@yukino.js/yukino 0.0.6 → 0.0.7

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.
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __yukinoCreateRequire } from "node:module";
3
3
  const require = __yukinoCreateRequire(import.meta.url);
4
- import{a as Rf}from"./chunk-SYLHBECV.js";import{a as If,b as _i,c as Mn,e as Of,f as xi}from"./chunk-WVT2D5AR.js";import{B as C,G as Ue,H as qr,J as Cf,K as Br,L as Rn,M as Wr,O as M,P as ki,Q as Cn,R as Ht,S as Is,T,U as ur,W as Mf,_ as Af,a as Tt,aa as Os,b as mf,c as wi,e as bi,f as ot,h as xf,k as Tf,l as Ef,n as $f,v as vi,w as Si,x as Pf}from"./chunk-E7FXB7TA.js";import{A as Sf,B as kf,C as _f,D as y,a as ff,d as Fe,e as it,f as gf,g as v,h as yf,i as V,k as Q,l as wf,m as bf,n as de,o as P,p as R,q as ge,r as ie,s as xc,t as Tc,u as re,v as at,w as A,x as le,y as vf,z as Ec}from"./chunk-IW5L5276.js";import{a as An,f as Nf,h as Df}from"./chunk-NAQRFHUX.js";import{a as cr,c as $,e as yi}from"./chunk-7MKA3SHV.js";var Zs=$(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.regexpCode=Y.getEsmExportName=Y.getProperty=Y.safeStringify=Y.stringify=Y.strConcat=Y.addCodeArg=Y.str=Y._=Y.nil=Y._Code=Y.Name=Y.IDENTIFIER=Y._CodeOrName=void 0;var Js=class{};Y._CodeOrName=Js;Y.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xr=class extends Js{constructor(e){if(super(),!Y.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}}};Y.Name=Xr;var yt=class extends Js{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 Xr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Y._Code=yt;Y.nil=new yt("");function vg(t,...e){let r=[t[0]],n=0;for(;n<e.length;)xu(r,e[n]),r.push(t[++n]);return new yt(r)}Y._=vg;var _u=new yt("+");function Sg(t,...e){let r=[Xs(t[0])],n=0;for(;n<e.length;)r.push(_u),xu(r,e[n]),r.push(_u,Xs(t[++n]));return iP(r),new yt(r)}Y.str=Sg;function xu(t,e){e instanceof yt?t.push(...e._items):e instanceof Xr?t.push(e):t.push(cP(e))}Y.addCodeArg=xu;function iP(t){let e=1;for(;e<t.length-1;){if(t[e]===_u){let r=aP(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function aP(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Xr||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 Xr))return`"${t}${e.slice(1)}`}function lP(t,e){return e.emptyStr()?t:t.emptyStr()?e:Sg`${t}${e}`}Y.strConcat=lP;function cP(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xs(Array.isArray(t)?t.join(","):t)}function uP(t){return new yt(Xs(t))}Y.stringify=uP;function Xs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Y.safeStringify=Xs;function dP(t){return typeof t=="string"&&Y.IDENTIFIER.test(t)?new yt(`.${t}`):vg`[${t}]`}Y.getProperty=dP;function hP(t){if(typeof t=="string"&&Y.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Y.getEsmExportName=hP;function pP(t){return new yt(t.toString())}Y.regexpCode=pP});var $u=$(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Je=Zs(),Tu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oa||(Xe.UsedValueState=oa={}));Xe.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var ia=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.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}}};Xe.Scope=ia;var aa=class extends Je.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(r)}[${n}]`}};Xe.ValueScopeName=aa;var fP=(0,Je._)`\n`,Eu=class extends ia{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fP:Je.nil}}get(){return this._scope}name(e){return new aa(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 u=a.get(i);if(u)return u}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,s.setValue(r,{property:o,itemIndex:c}),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,Je._)`${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=Je.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,oa.Started);let u=r(c);if(u){let d=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;o=(0,Je._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=s?.(c))o=(0,Je._)`${o}${u}${this.opts._n}`;else throw new Tu(c);l.set(c,oa.Completed)})}return o}};Xe.ValueScope=Eu});var F=$(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.or=U.and=U.not=U.CodeGen=U.operators=U.varKinds=U.ValueScopeName=U.ValueScope=U.Scope=U.Name=U.regexpCode=U.stringify=U.getProperty=U.nil=U.strConcat=U.str=U._=void 0;var H=Zs(),$t=$u(),yr=Zs();Object.defineProperty(U,"_",{enumerable:!0,get:function(){return yr._}});Object.defineProperty(U,"str",{enumerable:!0,get:function(){return yr.str}});Object.defineProperty(U,"strConcat",{enumerable:!0,get:function(){return yr.strConcat}});Object.defineProperty(U,"nil",{enumerable:!0,get:function(){return yr.nil}});Object.defineProperty(U,"getProperty",{enumerable:!0,get:function(){return yr.getProperty}});Object.defineProperty(U,"stringify",{enumerable:!0,get:function(){return yr.stringify}});Object.defineProperty(U,"regexpCode",{enumerable:!0,get:function(){return yr.regexpCode}});Object.defineProperty(U,"Name",{enumerable:!0,get:function(){return yr.Name}});var da=$u();Object.defineProperty(U,"Scope",{enumerable:!0,get:function(){return da.Scope}});Object.defineProperty(U,"ValueScope",{enumerable:!0,get:function(){return da.ValueScope}});Object.defineProperty(U,"ValueScopeName",{enumerable:!0,get:function(){return da.ValueScopeName}});Object.defineProperty(U,"varKinds",{enumerable:!0,get:function(){return da.varKinds}});U.operators={GT:new H._Code(">"),GTE:new H._Code(">="),LT:new H._Code("<"),LTE:new H._Code("<="),EQ:new H._Code("==="),NEQ:new H._Code("!=="),NOT:new H._Code("!"),OR:new H._Code("||"),AND:new H._Code("&&"),ADD:new H._Code("+")};var Yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Pu=class extends Yt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.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=qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof H._CodeOrName?this.rhs.names:{}}},la=class extends Yt{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 H.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof H.Name?{}:{...this.lhs.names};return ua(e,this.rhs)}},Ru=class extends la{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Cu=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mu=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Au=class extends Yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Iu=class extends Yt{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=qn(this.code,e,r),this}get names(){return this.code instanceof H._CodeOrName?this.code.names:{}}},Qs=class extends Yt{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)||(mP(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>en(e,r.names),{})}},Jt=class extends Qs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ou=class extends Qs{},Un=class extends Jt{};Un.kind="else";var Zr=class t extends Jt{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 Un(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(kg(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=qn(this.condition,e,r),this}get names(){let e=super.names;return ua(e,this.condition),this.else&&en(e,this.else.names),e}};Zr.kind="if";var Qr=class extends Jt{};Qr.kind="for";var Nu=class extends Qr{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=qn(this.iteration,e,r),this}get names(){return en(super.names,this.iteration.names)}},Du=class extends Qr{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?$t.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=ua(super.names,this.from);return ua(e,this.to)}},ca=class extends Qr{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=qn(this.iterable,e,r),this}get names(){return en(super.names,this.iterable.names)}},eo=class extends Jt{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)}};eo.kind="func";var to=class extends Qs{render(e){return"return "+super.render(e)}};to.kind="return";var zu=class extends Jt{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&&en(e,this.catch.names),this.finally&&en(e,this.finally.names),e}},ro=class extends Jt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ro.kind="catch";var no=class extends Jt{render(e){return"finally"+super.render(e)}};no.kind="finally";var ju=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ import{a as Rf}from"./chunk-HWDSXNX4.js";import{a as If,b as _i,c as Mn,e as Of,f as xi}from"./chunk-7PPWFSIC.js";import{$ as Af,B as C,H as Ue,I as qr,K as Cf,L as Br,M as Rn,N as Wr,P as M,Q as ki,R as Cn,S as Ht,T as Is,U as T,V as ur,X as Mf,a as Tt,b as mf,ba as Os,c as wi,e as bi,f as ot,h as xf,k as Tf,l as Ef,n as $f,v as vi,w as Si,x as Pf}from"./chunk-NG62ISUV.js";import{A as Sf,B as kf,C as _f,D as y,a as ff,d as Fe,e as it,f as gf,g as v,h as yf,i as V,k as Q,l as wf,m as bf,n as de,o as P,p as R,q as ge,r as ie,s as xc,t as Tc,u as re,v as at,w as A,x as le,y as vf,z as Ec}from"./chunk-IW5L5276.js";import{a as An,f as Nf,h as Df}from"./chunk-NAQRFHUX.js";import{a as cr,c as $,e as yi}from"./chunk-7MKA3SHV.js";var Zs=$(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.regexpCode=Y.getEsmExportName=Y.getProperty=Y.safeStringify=Y.stringify=Y.strConcat=Y.addCodeArg=Y.str=Y._=Y.nil=Y._Code=Y.Name=Y.IDENTIFIER=Y._CodeOrName=void 0;var Js=class{};Y._CodeOrName=Js;Y.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xr=class extends Js{constructor(e){if(super(),!Y.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}}};Y.Name=Xr;var yt=class extends Js{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 Xr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Y._Code=yt;Y.nil=new yt("");function vg(t,...e){let r=[t[0]],n=0;for(;n<e.length;)xu(r,e[n]),r.push(t[++n]);return new yt(r)}Y._=vg;var _u=new yt("+");function Sg(t,...e){let r=[Xs(t[0])],n=0;for(;n<e.length;)r.push(_u),xu(r,e[n]),r.push(_u,Xs(t[++n]));return iP(r),new yt(r)}Y.str=Sg;function xu(t,e){e instanceof yt?t.push(...e._items):e instanceof Xr?t.push(e):t.push(cP(e))}Y.addCodeArg=xu;function iP(t){let e=1;for(;e<t.length-1;){if(t[e]===_u){let r=aP(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function aP(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Xr||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 Xr))return`"${t}${e.slice(1)}`}function lP(t,e){return e.emptyStr()?t:t.emptyStr()?e:Sg`${t}${e}`}Y.strConcat=lP;function cP(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xs(Array.isArray(t)?t.join(","):t)}function uP(t){return new yt(Xs(t))}Y.stringify=uP;function Xs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Y.safeStringify=Xs;function dP(t){return typeof t=="string"&&Y.IDENTIFIER.test(t)?new yt(`.${t}`):vg`[${t}]`}Y.getProperty=dP;function hP(t){if(typeof t=="string"&&Y.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Y.getEsmExportName=hP;function pP(t){return new yt(t.toString())}Y.regexpCode=pP});var $u=$(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Je=Zs(),Tu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oa||(Xe.UsedValueState=oa={}));Xe.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var ia=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.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}}};Xe.Scope=ia;var aa=class extends Je.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(r)}[${n}]`}};Xe.ValueScopeName=aa;var fP=(0,Je._)`\n`,Eu=class extends ia{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fP:Je.nil}}get(){return this._scope}name(e){return new aa(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 u=a.get(i);if(u)return u}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,s.setValue(r,{property:o,itemIndex:c}),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,Je._)`${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=Je.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,oa.Started);let u=r(c);if(u){let d=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;o=(0,Je._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=s?.(c))o=(0,Je._)`${o}${u}${this.opts._n}`;else throw new Tu(c);l.set(c,oa.Completed)})}return o}};Xe.ValueScope=Eu});var F=$(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.or=U.and=U.not=U.CodeGen=U.operators=U.varKinds=U.ValueScopeName=U.ValueScope=U.Scope=U.Name=U.regexpCode=U.stringify=U.getProperty=U.nil=U.strConcat=U.str=U._=void 0;var H=Zs(),$t=$u(),yr=Zs();Object.defineProperty(U,"_",{enumerable:!0,get:function(){return yr._}});Object.defineProperty(U,"str",{enumerable:!0,get:function(){return yr.str}});Object.defineProperty(U,"strConcat",{enumerable:!0,get:function(){return yr.strConcat}});Object.defineProperty(U,"nil",{enumerable:!0,get:function(){return yr.nil}});Object.defineProperty(U,"getProperty",{enumerable:!0,get:function(){return yr.getProperty}});Object.defineProperty(U,"stringify",{enumerable:!0,get:function(){return yr.stringify}});Object.defineProperty(U,"regexpCode",{enumerable:!0,get:function(){return yr.regexpCode}});Object.defineProperty(U,"Name",{enumerable:!0,get:function(){return yr.Name}});var da=$u();Object.defineProperty(U,"Scope",{enumerable:!0,get:function(){return da.Scope}});Object.defineProperty(U,"ValueScope",{enumerable:!0,get:function(){return da.ValueScope}});Object.defineProperty(U,"ValueScopeName",{enumerable:!0,get:function(){return da.ValueScopeName}});Object.defineProperty(U,"varKinds",{enumerable:!0,get:function(){return da.varKinds}});U.operators={GT:new H._Code(">"),GTE:new H._Code(">="),LT:new H._Code("<"),LTE:new H._Code("<="),EQ:new H._Code("==="),NEQ:new H._Code("!=="),NOT:new H._Code("!"),OR:new H._Code("||"),AND:new H._Code("&&"),ADD:new H._Code("+")};var Yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Pu=class extends Yt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.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=qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof H._CodeOrName?this.rhs.names:{}}},la=class extends Yt{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 H.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof H.Name?{}:{...this.lhs.names};return ua(e,this.rhs)}},Ru=class extends la{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Cu=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mu=class extends Yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Au=class extends Yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Iu=class extends Yt{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=qn(this.code,e,r),this}get names(){return this.code instanceof H._CodeOrName?this.code.names:{}}},Qs=class extends Yt{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)||(mP(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>en(e,r.names),{})}},Jt=class extends Qs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ou=class extends Qs{},Un=class extends Jt{};Un.kind="else";var Zr=class t extends Jt{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 Un(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(kg(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=qn(this.condition,e,r),this}get names(){let e=super.names;return ua(e,this.condition),this.else&&en(e,this.else.names),e}};Zr.kind="if";var Qr=class extends Jt{};Qr.kind="for";var Nu=class extends Qr{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=qn(this.iteration,e,r),this}get names(){return en(super.names,this.iteration.names)}},Du=class extends Qr{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?$t.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=ua(super.names,this.from);return ua(e,this.to)}},ca=class extends Qr{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=qn(this.iterable,e,r),this}get names(){return en(super.names,this.iterable.names)}},eo=class extends Jt{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)}};eo.kind="func";var to=class extends Qs{render(e){return"return "+super.render(e)}};to.kind="return";var zu=class extends Jt{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&&en(e,this.catch.names),this.finally&&en(e,this.finally.names),e}},ro=class extends Jt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ro.kind="catch";var no=class extends Jt{render(e){return"finally"+super.render(e)}};no.kind="finally";var ju=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
5
  `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Ou]}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 Pu(e,o,n)),o}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new la(e,r,n))}add(e,r){return this._leafNode(new Ru(e,U.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==H.nil&&this._leafNode(new Iu(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,H.addCodeArg)(r,s));return r.push("}"),new H._Code(r)}if(e,r,n){if(this._blockNode(new Zr(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 Zr(e))}else(){return this._elseNode(new Un)}endIf(){return this._endBlockNode(Zr,Un)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Nu(e),r)}forRange(e,r,n,s,o=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new Du(o,i,r,n),()=>s(i))}forOf(e,r,n,s=$t.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof H.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,H._)`${i}.length`,a=>{this.var(o,(0,H._)`${i}[${a}]`),n(o)})}return this._for(new ca("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?$t.varKinds.var:$t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,H._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new ca("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(Qr)}label(e){return this._leafNode(new Cu(e))}break(e){return this._leafNode(new Mu(e))}return(e){let r=new to;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(to)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new zu;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new ro(o),r(o)}return n&&(this._currNode=s.finally=new no,this.code(n)),this._endBlockNode(ro,no)}throw(e){return this._leafNode(new Au(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=H.nil,n,s){return this._blockNode(new eo(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(eo)}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 Zr))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}};U.CodeGen=ju;function en(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ua(t,e){return e instanceof H._CodeOrName?en(t,e.names):t}function qn(t,e,r){if(t instanceof H.Name)return n(t);if(!s(t))return t;return new H._Code(t._items.reduce((o,i)=>(i instanceof H.Name&&(i=n(i)),i instanceof H._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 H._Code&&o._items.some(i=>i instanceof H.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function mP(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function kg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,H._)`!${Lu(t)}`}U.not=kg;var gP=_g(U.operators.AND);function yP(...t){return t.reduce(gP)}U.and=yP;var wP=_g(U.operators.OR);function bP(...t){return t.reduce(wP)}U.or=bP;function _g(t){return(e,r)=>e===H.nil?r:r===H.nil?e:(0,H._)`${Lu(e)} ${t} ${Lu(r)}`}function Lu(t){return t instanceof H.Name?t:(0,H._)`(${t})`}});var G=$(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var ee=F(),vP=Zs();function SP(t){let e={};for(let r of t)e[r]=!0;return e}q.toHash=SP;function kP(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Eg(t,e),!$g(e,t.self.RULES.all))}q.alwaysValidSchema=kP;function Eg(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]||Cg(t,`unknown keyword: "${o}"`)}q.checkUnknownRules=Eg;function $g(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}q.schemaHasRules=$g;function _P(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}q.schemaHasRulesButRef=_P;function xP({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ee._)`${r}`}return(0,ee._)`${t}${e}${(0,ee.getProperty)(n)}`}q.schemaRefOrVal=xP;function TP(t){return Pg(decodeURIComponent(t))}q.unescapeFragment=TP;function EP(t){return encodeURIComponent(Uu(t))}q.escapeFragment=EP;function Uu(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=Uu;function Pg(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=Pg;function $P(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}q.eachItem=$P;function xg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ee.Name?(o instanceof ee.Name?t(s,o,i):e(s,o,i),i):o instanceof ee.Name?(e(s,i,o),o):r(o,i);return a===ee.Name&&!(l instanceof ee.Name)?n(s,l):l}}q.mergeEvaluated={props:xg({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ee._)`${r} || {}`).code((0,ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ee._)`${r} || {}`),qu(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Rg}),items:xg({mergeNames:(t,e,r)=>t.if((0,ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Rg(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ee._)`{}`);return e!==void 0&&qu(t,r,e),r}q.evaluatedPropsToName=Rg;function qu(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ee._)`${e}${(0,ee.getProperty)(n)}`,!0))}q.setEvaluated=qu;var Tg={};function PP(t,e){return t.scopeValue("func",{ref:e,code:Tg[e.code]||(Tg[e.code]=new vP._Code(e.code))})}q.useFunc=PP;var Fu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fu||(q.Type=Fu={}));function RP(t,e,r){if(t instanceof ee.Name){let n=e===Fu.Num;return r?n?(0,ee._)`"[" + ${t} + "]"`:(0,ee._)`"['" + ${t} + "']"`:n?(0,ee._)`"/" + ${t}`:(0,ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ee.getProperty)(t).toString():"/"+Uu(t)}q.getErrorPath=RP;function Cg(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}q.checkStrictMode=Cg});var Xt=$(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var Ae=F(),CP={data:new Ae.Name("data"),valCxt:new Ae.Name("valCxt"),instancePath:new Ae.Name("instancePath"),parentData:new Ae.Name("parentData"),parentDataProperty:new Ae.Name("parentDataProperty"),rootData:new Ae.Name("rootData"),dynamicAnchors:new Ae.Name("dynamicAnchors"),vErrors:new Ae.Name("vErrors"),errors:new Ae.Name("errors"),this:new Ae.Name("this"),self:new Ae.Name("self"),scope:new Ae.Name("scope"),json:new Ae.Name("json"),jsonPos:new Ae.Name("jsonPos"),jsonLen:new Ae.Name("jsonLen"),jsonPart:new Ae.Name("jsonPart")};Bu.default=CP});var so=$(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.extendErrors=Ie.resetErrorsCount=Ie.reportExtraError=Ie.reportError=Ie.keyword$DataError=Ie.keywordError=void 0;var K=F(),ha=G(),Be=Xt();Ie.keywordError={message:({keyword:t})=>(0,K.str)`must pass "${t}" keyword validation`};Ie.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,K.str)`"${t}" keyword must be ${e} ($data)`:(0,K.str)`"${t}" keyword is invalid ($data)`};function MP(t,e=Ie.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Ig(t,e,r);n??(i||a)?Mg(o,l):Ag(s,(0,K._)`[${l}]`)}Ie.reportError=MP;function AP(t,e=Ie.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Ig(t,e,r);Mg(s,a),o||i||Ag(n,Be.default.vErrors)}Ie.reportExtraError=AP;function IP(t,e){t.assign(Be.default.errors,e),t.if((0,K._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,K._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ie.resetErrorsCount=IP;function OP({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,Be.default.errors,a=>{t.const(i,(0,K._)`${Be.default.vErrors}[${a}]`),t.if((0,K._)`${i}.instancePath === undefined`,()=>t.assign((0,K._)`${i}.instancePath`,(0,K.strConcat)(Be.default.instancePath,o.errorPath))),t.assign((0,K._)`${i}.schemaPath`,(0,K.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,K._)`${i}.schema`,r),t.assign((0,K._)`${i}.data`,n))})}Ie.extendErrors=OP;function Mg(t,e){let r=t.const("err",e);t.if((0,K._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,K._)`[${r}]`),(0,K._)`${Be.default.vErrors}.push(${r})`),t.code((0,K._)`${Be.default.errors}++`)}function Ag(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,K._)`new ${t.ValidationError}(${e})`):(r.assign((0,K._)`${n}.errors`,e),r.return(!1))}var tn={keyword:new K.Name("keyword"),schemaPath:new K.Name("schemaPath"),params:new K.Name("params"),propertyName:new K.Name("propertyName"),message:new K.Name("message"),schema:new K.Name("schema"),parentSchema:new K.Name("parentSchema")};function Ig(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,K._)`{}`:NP(t,e,r)}function NP(t,e,r={}){let{gen:n,it:s}=t,o=[DP(s,r),zP(t,r)];return jP(t,e,o),n.object(...o)}function DP({errorPath:t},{instancePath:e}){let r=e?(0,K.str)`${t}${(0,ha.getErrorPath)(e,ha.Type.Str)}`:t;return[Be.default.instancePath,(0,K.strConcat)(Be.default.instancePath,r)]}function zP({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,K.str)`${e}/${t}`;return r&&(s=(0,K.str)`${s}${(0,ha.getErrorPath)(r,ha.Type.Str)}`),[tn.schemaPath,s]}function jP(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([tn.keyword,s],[tn.params,typeof e=="function"?e(t):e||(0,K._)`{}`]),l.messages&&n.push([tn.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([tn.schema,i],[tn.parentSchema,(0,K._)`${u}${d}`],[Be.default.data,o]),c&&n.push([tn.propertyName,c])}});var Ng=$(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.boolOrEmptySchema=Bn.topBoolOrEmptySchema=void 0;var LP=so(),FP=F(),UP=Xt(),qP={message:"boolean schema is false"};function BP(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Og(t,!1):typeof r=="object"&&r.$async===!0?e.return(UP.default.data):(e.assign((0,FP._)`${n}.errors`,null),e.return(!0))}Bn.topBoolOrEmptySchema=BP;function WP(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Og(t)):r.var(e,!0)}Bn.boolOrEmptySchema=WP;function Og(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,LP.reportError)(s,qP,void 0,e)}});var Wu=$(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.getRules=Wn.isJSONType=void 0;var HP=["string","number","integer","boolean","null","object","array"],GP=new Set(HP);function KP(t){return typeof t=="string"&&GP.has(t)}Wn.isJSONType=KP;function VP(){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:{}}}Wn.getRules=VP});var Hu=$(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.shouldUseRule=wr.shouldUseGroup=wr.schemaHasRulesForType=void 0;function YP({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Dg(t,n)}wr.schemaHasRulesForType=YP;function Dg(t,e){return e.rules.some(r=>zg(t,r))}wr.shouldUseGroup=Dg;function zg(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))}wr.shouldUseRule=zg});var oo=$(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.reportTypeError=Oe.checkDataTypes=Oe.checkDataType=Oe.coerceAndCheckDataType=Oe.getJSONTypes=Oe.getSchemaTypes=Oe.DataType=void 0;var JP=Wu(),XP=Hu(),ZP=so(),L=F(),jg=G(),Hn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Hn||(Oe.DataType=Hn={}));function QP(t){let e=Lg(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}Oe.getSchemaTypes=QP;function Lg(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(JP.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Oe.getJSONTypes=Lg;function eR(t,e){let{gen:r,data:n,opts:s}=t,o=tR(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,XP.schemaHasRulesForType)(t,e[0]));if(i){let a=Ku(e,n,s.strictNumbers,Hn.Wrong);r.if(a,()=>{o.length?rR(t,e,o):Vu(t)})}return i}Oe.coerceAndCheckDataType=eR;var Fg=new Set(["string","number","integer","boolean","null"]);function tR(t,e){return e?t.filter(r=>Fg.has(r)||e==="array"&&r==="array"):[]}function rR(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,L._)`typeof ${s}`),a=n.let("coerced",(0,L._)`undefined`);o.coerceTypes==="array"&&n.if((0,L._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,L._)`${s}[0]`).assign(i,(0,L._)`typeof ${s}`).if(Ku(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,L._)`${a} !== undefined`);for(let c of r)(Fg.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Vu(t),n.endIf(),n.if((0,L._)`${a} !== undefined`,()=>{n.assign(s,a),nR(t,a)});function l(c){switch(c){case"string":n.elseIf((0,L._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,L._)`"" + ${s}`).elseIf((0,L._)`${s} === null`).assign(a,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${i} == "boolean" || ${s} === null
6
6
  || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,L._)`+${s}`);return;case"integer":n.elseIf((0,L._)`${i} === "boolean" || ${s} === null
7
7
  || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,L._)`+${s}`);return;case"boolean":n.elseIf((0,L._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,L._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,L._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,L._)`${i} === "string" || ${i} === "number"
8
8
  || ${i} === "boolean" || ${s} === null`).assign(a,(0,L._)`[${s}]`)}}}function nR({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,L._)`${e} !== undefined`,()=>t.assign((0,L._)`${e}[${r}]`,n))}function Gu(t,e,r,n=Hn.Correct){let s=n===Hn.Correct?L.operators.EQ:L.operators.NEQ,o;switch(t){case"null":return(0,L._)`${e} ${s} null`;case"array":o=(0,L._)`Array.isArray(${e})`;break;case"object":o=(0,L._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,L._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,L._)`typeof ${e} ${s} ${t}`}return n===Hn.Correct?o:(0,L.not)(o);function i(a=L.nil){return(0,L.and)((0,L._)`typeof ${e} == "number"`,a,r?(0,L._)`isFinite(${e})`:L.nil)}}Oe.checkDataType=Gu;function Ku(t,e,r,n){if(t.length===1)return Gu(t[0],e,r,n);let s,o=(0,jg.toHash)(t);if(o.array&&o.object){let i=(0,L._)`typeof ${e} != "object"`;s=o.null?i:(0,L._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=L.nil;o.number&&delete o.integer;for(let i in o)s=(0,L.and)(s,Gu(i,e,r,n));return s}Oe.checkDataTypes=Ku;var sR={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,L._)`{type: ${t}}`:(0,L._)`{type: ${e}}`};function Vu(t){let e=oR(t);(0,ZP.reportError)(e,sR)}Oe.reportTypeError=Vu;function oR(t){let{gen:e,data:r,schema:n}=t,s=(0,jg.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var qg=$(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.assignDefaults=void 0;var Gn=F(),iR=G();function aR(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Ug(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Ug(t,o,s.default))}pa.assignDefaults=aR;function Ug(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Gn._)`${o}${(0,Gn.getProperty)(e)}`;if(s){(0,iR.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Gn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Gn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,Gn._)`${a} = ${(0,Gn.stringify)(r)}`)}});var wt=$(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.validateUnion=Z.validateArray=Z.usePattern=Z.callValidateCode=Z.schemaProperties=Z.allSchemaProperties=Z.noPropertyInData=Z.propertyInData=Z.isOwnProperty=Z.hasPropFunc=Z.reportMissingProp=Z.checkMissingProp=Z.checkReportMissingProp=void 0;var se=F(),Yu=G(),br=Xt(),lR=G();function cR(t,e){let{gen:r,data:n,it:s}=t;r.if(Xu(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,se._)`${e}`},!0),t.error()})}Z.checkReportMissingProp=cR;function uR({gen:t,data:e,it:{opts:r}},n,s){return(0,se.or)(...n.map(o=>(0,se.and)(Xu(t,e,o,r.ownProperties),(0,se._)`${s} = ${o}`)))}Z.checkMissingProp=uR;function dR(t,e){t.setParams({missingProperty:e},!0),t.error()}Z.reportMissingProp=dR;function Bg(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,se._)`Object.prototype.hasOwnProperty`})}Z.hasPropFunc=Bg;function Ju(t,e,r){return(0,se._)`${Bg(t)}.call(${e}, ${r})`}Z.isOwnProperty=Ju;function hR(t,e,r,n){let s=(0,se._)`${e}${(0,se.getProperty)(r)} !== undefined`;return n?(0,se._)`${s} && ${Ju(t,e,r)}`:s}Z.propertyInData=hR;function Xu(t,e,r,n){let s=(0,se._)`${e}${(0,se.getProperty)(r)} === undefined`;return n?(0,se.or)(s,(0,se.not)(Ju(t,e,r))):s}Z.noPropertyInData=Xu;function Wg(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Z.allSchemaProperties=Wg;function pR(t,e){return Wg(e).filter(r=>!(0,Yu.alwaysValidSchema)(t,e[r]))}Z.schemaProperties=pR;function fR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,l,c){let u=c?(0,se._)`${t}, ${e}, ${n}${s}`:e,d=[[br.default.instancePath,(0,se.strConcat)(br.default.instancePath,o)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let h=(0,se._)`${u}, ${r.object(...d)}`;return l!==se.nil?(0,se._)`${a}.call(${l}, ${h})`:(0,se._)`${a}(${h})`}Z.callValidateCode=fR;var mR=(0,se._)`new RegExp`;function gR({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,se._)`${s.code==="new RegExp"?mR:(0,lR.useFunc)(t,s)}(${r}, ${n})`})}Z.usePattern=gR;function yR(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 l=e.const("len",(0,se._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:Yu.Type.Num},o),e.if((0,se.not)(o),a)})}}Z.validateArray=yR;function wR(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Yu.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{let u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(i,(0,se._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,se.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Z.validateUnion=wR});var Kg=$(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.validateKeywordUsage=Dt.validSchemaType=Dt.funcKeywordCode=Dt.macroKeywordCode=void 0;var We=F(),rn=Xt(),bR=wt(),vR=so();function SR(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Gg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let c=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Dt.macroKeywordCode=SR;function kR(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;xR(l,e);let c=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,u=Gg(n,s,c),d=n.let("valid");t.block$data(d,h),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function h(){if(e.errors===!1)f(),e.modifying&&Hg(t),g(()=>t.error());else{let w=e.async?p():m();e.modifying&&Hg(t),g(()=>_R(t,w))}}function p(){let w=n.let("ruleErrs",null);return n.try(()=>f((0,We._)`await `),b=>n.assign(d,!1).if((0,We._)`${b} instanceof ${l.ValidationError}`,()=>n.assign(w,(0,We._)`${b}.errors`),()=>n.throw(b))),w}function m(){let w=(0,We._)`${u}.errors`;return n.assign(w,null),f(We.nil),w}function f(w=e.async?(0,We._)`await `:We.nil){let b=l.opts.passContext?rn.default.this:rn.default.self,k=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${w}${(0,bR.callValidateCode)(t,u,b,k)}`,e.modifying)}function g(w){var b;n.if((0,We.not)((b=e.valid)!==null&&b!==void 0?b:d),w)}}Dt.funcKeywordCode=kR;function Hg(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function _R(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(rn.default.vErrors,(0,We._)`${rn.default.vErrors} === null ? ${e} : ${rn.default.vErrors}.concat(${e})`).assign(rn.default.errors,(0,We._)`${rn.default.vErrors}.length`),(0,vR.extendErrors)(t)},()=>t.error())}function xR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Gg(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,We.stringify)(r)})}function TR(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")}Dt.validSchemaType=TR;function ER({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 l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Dt.validateKeywordUsage=ER});var Yg=$(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.extendSubschemaMode=vr.extendSubschemaData=vr.getSubschema=void 0;var zt=F(),Vg=G();function $R(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,zt._)`${t.schemaPath}${(0,zt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,zt._)`${t.schemaPath}${(0,zt.getProperty)(e)}${(0,zt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Vg.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')}vr.getSubschema=$R;function PR(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:c,dataPathArr:u,opts:d}=e,h=a.let("data",(0,zt._)`${e.data}${(0,zt.getProperty)(r)}`,!0);l(h),t.errorPath=(0,zt.str)`${c}${(0,Vg.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zt._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(s!==void 0){let c=s instanceof zt.Name?s:a.let("data",s,!0);l(c),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}vr.extendSubschemaData=PR;function RR(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}vr.extendSubschemaMode=RR});var Zu=$((h9,Jg)=>{"use strict";Jg.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 Zg=$((p9,Xg)=>{"use strict";var Sr=Xg.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(){};fa(e,n,s,t,"",t)};Sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Sr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function fa(t,e,r,n,s,o,i,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Sr.arrayKeywords)for(var h=0;h<d.length;h++)fa(t,e,r,d[h],s+"/"+u+"/"+h,o,s,u,n,h)}else if(u in Sr.propsKeywords){if(d&&typeof d=="object")for(var p in d)fa(t,e,r,d[p],s+"/"+u+"/"+CR(p),o,s,u,n,p)}else(u in Sr.keywords||t.allKeys&&!(u in Sr.skipKeywords))&&fa(t,e,r,d,s+"/"+u,o,s,u,n)}r(n,s,o,i,a,l,c)}}function CR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var io=$(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var MR=G(),AR=Zu(),IR=Zg(),OR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function NR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qu(t):e?Qg(t)<=e:!1}Ze.inlineRef=NR;var DR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qu(t){for(let e in t){if(DR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Qu)||typeof r=="object"&&Qu(r))return!0}return!1}function Qg(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!OR.has(r)&&(typeof t[r]=="object"&&(0,MR.eachItem)(t[r],n=>e+=Qg(n)),e===1/0))return 1/0}return e}function ey(t,e="",r){r!==!1&&(e=Kn(e));let n=t.parse(e);return ty(t,n)}Ze.getFullPath=ey;function ty(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=ty;var zR=/#\/?$/;function Kn(t){return t?t.replace(zR,""):""}Ze.normalizeId=Kn;function jR(t,e,r){return r=Kn(r),t.resolve(e,r)}Ze.resolveUrl=jR;var LR=/^[a-z_][-a-z0-9._]*$/i;function FR(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Kn(t[r]||e),o={"":s},i=ey(n,s,!1),a={},l=new Set;return IR(t,{allKeys:!0},(d,h,p,m)=>{if(m===void 0)return;let f=i+h,g=o[m];typeof d[r]=="string"&&(g=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[h]=g;function w(k){let _=this.opts.uriResolver.resolve;if(k=Kn(g?_(g,k):k),l.has(k))throw u(k);l.add(k);let S=this.refs[k];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?c(d,S.schema,k):k!==Kn(f)&&(k[0]==="#"?(c(d,a[k],k),a[k]=d):this.refs[k]=f),k}function b(k){if(typeof k=="string"){if(!LR.test(k))throw new Error(`invalid anchor "${k}"`);w.call(this,`#${k}`)}}}),a;function c(d,h,p){if(h!==void 0&&!AR(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ze.getSchemaRefs=FR});var co=$(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.getData=kr.KeywordCxt=kr.validateFunctionCode=void 0;var iy=Ng(),ry=oo(),td=Hu(),ma=oo(),UR=qg(),lo=Kg(),ed=Yg(),I=F(),j=Xt(),qR=io(),Zt=G(),ao=so();function BR(t){if(cy(t)&&(uy(t),ly(t))){GR(t);return}ay(t,()=>(0,iy.topBoolOrEmptySchema)(t))}kr.validateFunctionCode=BR;function ay({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,I._)`${j.default.data}, ${j.default.valCxt}`,n.$async,()=>{t.code((0,I._)`"use strict"; ${ny(r,s)}`),HR(t,s),t.code(o)}):t.func(e,(0,I._)`${j.default.data}, ${WR(s)}`,n.$async,()=>t.code(ny(r,s)).code(o))}function WR(t){return(0,I._)`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${t.dynamicRef?(0,I._)`, ${j.default.dynamicAnchors}={}`:I.nil}}={}`}function HR(t,e){t.if(j.default.valCxt,()=>{t.var(j.default.instancePath,(0,I._)`${j.default.valCxt}.${j.default.instancePath}`),t.var(j.default.parentData,(0,I._)`${j.default.valCxt}.${j.default.parentData}`),t.var(j.default.parentDataProperty,(0,I._)`${j.default.valCxt}.${j.default.parentDataProperty}`),t.var(j.default.rootData,(0,I._)`${j.default.valCxt}.${j.default.rootData}`),e.dynamicRef&&t.var(j.default.dynamicAnchors,(0,I._)`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{t.var(j.default.instancePath,(0,I._)`""`),t.var(j.default.parentData,(0,I._)`undefined`),t.var(j.default.parentDataProperty,(0,I._)`undefined`),t.var(j.default.rootData,j.default.data),e.dynamicRef&&t.var(j.default.dynamicAnchors,(0,I._)`{}`)})}function GR(t){let{schema:e,opts:r,gen:n}=t;ay(t,()=>{r.$comment&&e.$comment&&hy(t),XR(t),n.let(j.default.vErrors,null),n.let(j.default.errors,0),r.unevaluated&&KR(t),dy(t),eC(t)})}function KR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,I._)`${r}.evaluated`),e.if((0,I._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,I._)`${t.evaluated}.props`,(0,I._)`undefined`)),e.if((0,I._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,I._)`${t.evaluated}.items`,(0,I._)`undefined`))}function ny(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,I._)`/*# sourceURL=${r} */`:I.nil}function VR(t,e){if(cy(t)&&(uy(t),ly(t))){YR(t,e);return}(0,iy.boolOrEmptySchema)(t,e)}function ly({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 cy(t){return typeof t.schema!="boolean"}function YR(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&hy(t),ZR(t),QR(t);let o=n.const("_errs",j.default.errors);dy(t,o),n.var(e,(0,I._)`${o} === ${j.default.errors}`)}function uy(t){(0,Zt.checkUnknownRules)(t),JR(t)}function dy(t,e){if(t.opts.jtd)return sy(t,[],!1,e);let r=(0,ry.getSchemaTypes)(t.schema),n=(0,ry.coerceAndCheckDataType)(t,r);sy(t,r,!n,e)}function JR(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Zt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function XR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Zt.checkStrictMode)(t,"default is ignored in the schema root")}function ZR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,qR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function QR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function hy({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,I._)`${j.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,I.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,I._)`${j.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function eC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,I._)`${j.default.errors} === 0`,()=>e.return(j.default.data),()=>e.throw((0,I._)`new ${s}(${j.default.vErrors})`)):(e.assign((0,I._)`${n}.errors`,j.default.vErrors),o.unevaluated&&tC(t),e.return((0,I._)`${j.default.errors} === 0`))}function tC({gen:t,evaluated:e,props:r,items:n}){r instanceof I.Name&&t.assign((0,I._)`${e}.props`,r),n instanceof I.Name&&t.assign((0,I._)`${e}.items`,n)}function sy(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Zt.schemaHasRulesButRef)(o,u))){s.block(()=>fy(t,"$ref",u.all.$ref.definition));return}l.jtd||rC(t,e),s.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,td.shouldUseGroup)(o,h)&&(h.type?(s.if((0,ma.checkDataType)(h.type,i,l.strictNumbers)),oy(t,h),e.length===1&&e[0]===h.type&&r&&(s.else(),(0,ma.reportTypeError)(t)),s.endIf()):oy(t,h),a||s.if((0,I._)`${j.default.errors} === ${n||0}`))}}function oy(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,UR.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,td.shouldUseRule)(n,o)&&fy(t,o.keyword,o.definition,e.type)})}function rC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(nC(t,e),t.opts.allowUnionTypes||sC(t,e),oC(t,t.dataTypes))}function nC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{py(t.dataTypes,r)||rd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),aC(t,e)}}function sC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rd(t,"use allowUnionTypes to allow union type keyword")}function oC(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,td.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>iC(e,i))&&rd(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function iC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function py(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function aC(t,e){let r=[];for(let n of t.dataTypes)py(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Zt.checkStrictMode)(t,e,t.opts.strictTypes)}var ga=class{constructor(e,r,n){if((0,lo.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,Zt.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",my(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,lo.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,I.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,I.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,I._)`${r} !== undefined && (${(0,I.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?ao.reportExtraError:ao.reportError)(this,this.def.error,r)}$dataError(){(0,ao.reportError)(this,this.def.$dataError||ao.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ao.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=I.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=I.nil,r=I.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,I.or)((0,I._)`${s} === undefined`,r)),e!==I.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==I.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,I.or)(i(),a());function i(){if(n.length){if(!(r instanceof I.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,I._)`${(0,ma.checkDataTypes)(l,r,o.opts.strictNumbers,ma.DataType.Wrong)}`}return I.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,I._)`!${l}(${r})`}return I.nil}}subschema(e,r){let n=(0,ed.getSubschema)(this.it,e);(0,ed.extendSubschemaData)(n,this.it,e),(0,ed.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return VR(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Zt.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Zt.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,I.Name)),!0}};kr.KeywordCxt=ga;function fy(t,e,r,n){let s=new ga(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,lo.funcKeywordCode)(s,r):"macro"in r?(0,lo.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,lo.funcKeywordCode)(s,r)}var lC=/^\/(?:[^~]|~0|~1)*$/,cC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function my(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return j.default.rootData;if(t[0]==="/"){if(!lC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=j.default.rootData}else{let c=cC.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(s=c[2],s==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!s)return o}let i=o,a=s.split("/");for(let c of a)c&&(o=(0,I._)`${o}${(0,I.getProperty)((0,Zt.unescapeJsonPointer)(c))}`,i=(0,I._)`${i} && ${o}`);return i;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}kr.getData=my});var ya=$(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};sd.default=nd});var uo=$(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var od=io(),id=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,od.resolveUrl)(e,r,n),this.missingSchema=(0,od.normalizeId)((0,od.getFullPath)(e,this.missingRef))}};ad.default=id});var ba=$(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.resolveSchema=bt.getCompilingSchema=bt.resolveRef=bt.compileSchema=bt.SchemaEnv=void 0;var Pt=F(),uC=ya(),nn=Xt(),Rt=io(),gy=G(),dC=co(),Vn=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,Rt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};bt.SchemaEnv=Vn;function cd(t){let e=yy.call(this,t);if(e)return e;let r=(0,Rt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new Pt.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:uC.default,code:(0,Pt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let c={gen:i,allErrors:this.opts.allErrors,data:nn.default.data,parentData:nn.default.parentData,parentDataProperty:nn.default.parentDataProperty,dataNames:[nn.default.data],dataPathArr:[Pt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Pt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Pt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Pt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,dC.validateFunctionCode)(c),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(nn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${nn.default.self}`,`${nn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:f}=c;p.evaluated={props:m instanceof Pt.Name?void 0:m,items:f instanceof Pt.Name?void 0:f,dynamicProps:m instanceof Pt.Name,dynamicItems:f instanceof Pt.Name},p.source&&(p.source.evaluated=(0,Pt.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}bt.compileSchema=cd;function hC(t,e,r){var n;r=(0,Rt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=mC.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 Vn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=pC.call(this,o)}bt.resolveRef=hC;function pC(t){return(0,Rt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:cd.call(this,t)}function yy(t){for(let e of this._compilations)if(fC(e,t))return e}bt.getCompilingSchema=yy;function fC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function mC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||wa.call(this,t,e)}function wa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Rt._getFullPath)(this.opts.uriResolver,r),s=(0,Rt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return ld.call(this,r,t);let o=(0,Rt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=wa.call(this,t,i);return typeof a?.schema!="object"?void 0:ld.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||cd.call(this,i),o===(0,Rt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,c=a[l];return c&&(s=(0,Rt.resolveUrl)(this.opts.uriResolver,s,c)),new Vn({schema:a,schemaId:l,root:t,baseId:s})}return ld.call(this,r,i)}}bt.resolveSchema=wa;var gC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ld(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 l=r[(0,gy.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!gC.has(a)&&c&&(e=(0,Rt.resolveUrl)(this.opts.uriResolver,e,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,gy.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Rt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=wa.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new Vn({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var wy=$((b9,yC)=>{yC.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 md=$((v9,Ty)=>{"use strict";var wC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dd=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),bC=RegExp.prototype.test.bind(/^\d*$/u),sn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),hd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),vy=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),pd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),vC=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Qe=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Qe[e]="%"+t[e>>4]+t[e&15]}function Ne(t){return t<2048?Qe[192|t>>6]+Qe[128|t&63]:t<65536?Qe[224|t>>12]+Qe[128|t>>6&63]+Qe[128|t&63]:Qe[240|t>>18]+Qe[128|t>>12&63]+Qe[128|t>>6&63]+Qe[128|t&63]}function SC(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 kC=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),_C=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),xC=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),TC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function EC(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!xC(t[e])){if(t[e]==="%"&&e+2<t.length&&sn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function by(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 $C(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 l=s[a];if(l==="")return;if(l.indexOf(".")!==-1){if(a!==s.length-1||e!==-1&&n.length===0||!dd(l))return;o+=2;continue}if(!kC(l))return;s[a]=parseInt(l,16).toString(16),o++}if(e===-1)return o!==8?void 0:by(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 by(i)}function ud(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&&_C(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(PC(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),!EC(s))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,o)}let i=$C(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(s?"%"+s:""),escapedHost:i+(s?"%25"+s:""),isIPV6:!0}}function PC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function RC(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 CC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},MC=/[@/?#:]/g,AC=/[@/?#]/g;function Sy(t,e){let r=e?AC:MC;return r.lastIndex=0,t.replace(r,n=>CC[n])}function ky(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&&hd(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function IC(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!=="."&&hd(i)?e+=i:e+="%"+o,r+=2;continue}}if(vy(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=xy(s)?n:Qe[s];else if(s<55296||s>57343)e+=Ne(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Ne(65536+(s-55296<<10)+(o-56320)),r++):e+=Ne(65533)}else e+=Ne(65533)}}return e}function OC(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),vy(o)&&(o!==":"||!n))r+=o;else{let i=t.charCodeAt(s);if(i<128)r+=Qe[i];else if(i<55296||i>57343)r+=Ne(i);else if(i<=56319&&s+1<t.length){let a=t.charCodeAt(s+1);a>=56320&&a<=57343?(r+=Ne(65536+(i-55296<<10)+(a-56320)),s++):r+=Ne(65533)}else r+=Ne(65533)}}return r}function fd(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+=Qe[o];else if(o<55296||o>57343)r+=Ne(o);else if(o<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Ne(65536+(o-55296<<10)+(i-56320)),n++):r+=Ne(65533)}else r+=Ne(65533)}}return r}function _y(t){return fd(t,vC)}function NC(t){return fd(t,pd)}function DC(t){return fd(t,pd)}function xy(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 zC(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));hd(i)?e+=i:e+="%"+o,r+=2;continue}}if(pd(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=xy(s)?n:Qe[s];else if(s<55296||s>57343)e+=Ne(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Ne(65536+(s-55296<<10)+(o-56320)),r++):e+=Ne(65533)}else e+=Ne(65533)}}return e}function jC(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 LC(t){let e=[];if(t.userinfo!==void 0&&(e.push(_y(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!dd(r)){let n=ud(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ky(r,!0),n=ud(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=Sy(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!bC(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}Ty.exports={nonSimpleDomain:TC,recomposeAuthority:LC,reescapeHostDelimiters:Sy,normalizePercentEncoding:ky,normalizePathEncoding:IC,serializePathEncoding:OC,normalizeQueryFragmentEncoding:zC,encodeUserinfo:_y,encodeQuery:NC,encodeFragment:DC,escapePreservingEscapes:jC,removeDotSegments:RC,isIPv4:dd,isUUID:wC,normalizeIPv6:ud,stringArrayToHexStripped:SC}});var Cy=$((S9,Ry)=>{"use strict";var{isUUID:FC}=md(),UC=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,qC=["http","https","ws","wss","urn","urn:uuid"];function BC(t){return qC.indexOf(t)!==-1}function gd(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 Ey(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function $y(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 WC(t){return t.secure=gd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function HC(t){if((t.port===(gd(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 GC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(UC);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=yd(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function KC(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=yd(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 VC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!FC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function YC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Py={scheme:"http",domainHost:!0,parse:Ey,serialize:$y},JC={scheme:"https",domainHost:Py.domainHost,parse:Ey,serialize:$y},va={scheme:"ws",domainHost:!0,parse:WC,serialize:HC},XC={scheme:"wss",domainHost:va.domainHost,parse:va.parse,serialize:va.serialize},ZC={scheme:"urn",parse:GC,serialize:KC,skipNormalize:!0},QC={scheme:"urn:uuid",parse:VC,serialize:YC,skipNormalize:!0},Sa={http:Py,https:JC,ws:va,wss:XC,urn:ZC,"urn:uuid":QC};Object.setPrototypeOf(Sa,null);function yd(t){return t&&(Sa[t]||Sa[t.toLowerCase()])||void 0}Ry.exports={wsIsSecure:gd,SCHEMES:Sa,isValidSchemeName:BC,getSchemeHandler:yd}});var By=$((k9,xa)=>{"use strict";var{normalizeIPv6:Ny,removeDotSegments:po,recomposeAuthority:eM,normalizePercentEncoding:wd,normalizePathEncoding:tM,serializePathEncoding:My,normalizeQueryFragmentEncoding:Ay,encodeQuery:rM,encodeFragment:nM,reescapeHostDelimiters:sM,isIPv4:Dy,nonSimpleDomain:oM}=md(),{SCHEMES:zy,getSchemeHandler:bd}=Cy(),jy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ly="URI scheme is malformed.";function Iy(t){let e=unescape(String(t));if(!jy.test(e))throw new TypeError(Ly);return e}function iM(t,e){return typeof t=="string"?t=fM(t,e):typeof t=="object"&&(t=_a(on(t,e),e)),t}function aM(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:l,malformedScheme:c}=ka(t,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:h,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:f}=ka(e,n);if(o||d||i||h||a||p||l||m||c||f)throw new Error(s.error||u.error||"URI is malformed.");let g=Fy(s,u,n,!0),w=bd(r&&r.scheme||g.scheme),b=g.host,k=b!==void 0&&b!==""&&(Dy(b)||Ny(b).isIPV6);Uy(g,r||{},w,k);let _=b&&b.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(b);if(g.error&&!_)throw new Error(g.error);return n.skipEscape=!0,on(g,n)}function Fy(t,e,r,n){let s={};return n||(t=_a(on(t,r),r),e=_a(on(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=po(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=po(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=po(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=po(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 lM(t,e,r){let n=Oy(t,r),s=Oy(e,r);return n!==void 0&&s!==void 0&&n===s}function on(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=Iy(r.scheme));let o=bd(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=wd(r.path):r.path=My(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=Iy(r.scheme),s.push(r.scheme,":"));let l=eM(r);if(l!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(l),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(c=po(c)),a&&(c=My(c,!0)),l===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),s.push(c)}return r.query!==void 0&&s.push("?",rM(r.query)),r.fragment!==void 0&&s.push("#",nM(r.fragment)),s.join("")}var cM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,uM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,dM=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function hM(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 ho(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 vd(t){return t[0]==="["&&t[t.length-1]==="]"}function pM(t){let e=t[4];return ho(t[3])||e!==void 0&&!vd(e)&&ho(e)||ho(t[6])||ho(t[7])||ho(t[8])}function Uy(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!vd(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&oM(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 ka(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,l=!1,c=!1,u=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(uM);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let h=t.match(dM);if(h!==null){let m=h[1],f=m.replace(/[\t\n\r]/g,"");f.length>=2&&(f.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):m.length!==f.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}let p=t.match(cM);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let g=unescape(n.scheme);jy.test(g)?n.scheme=g.toLowerCase():(n.error=n.error||Ly,c=!0)}o=pM(p),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=hM(n,p);if(m!==void 0&&(n.error=n.error||m,s=!0),n.host)if(Dy(n.host)===!1){let w=vd(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,k=Ny(n.host);u=k.isIPV6||k.isIPVFuture===!0,l=b&&(!w||k.error===!0),n.host=u?k.host:k.host.toLowerCase(),l&&(n.error=n.error||"URI host is malformed.",s=!0)}else u=!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 f=bd(r.scheme||n.scheme);if(l||(a=Uy(n,r,f,u)),t.indexOf("%")!==-1&&n.host!==void 0&&!l){let g=u?n.host:wd(n.host,!0);u||(g=wd(g.toLowerCase())),n.host=sM(g,u)}(!f||f&&!f.skipNormalize)&&(n.path&&(n.path=tM(n.path)),n.query&&(n.query=Ay(n.query)),n.fragment&&(n.fragment=Ay(n.fragment))),f&&f.parse&&(f.parse(n,r),f===zy.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:c}}function _a(t,e){return ka(t,e).parsed}function fM(t,e){return qy(t,e).normalized}function qy(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}=ka(t,e);return{normalized:n||s||o||i||a?t:on(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}}function Oy(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:on(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}=qy(r,e);return s||o||i||a||l?void 0:n}var Sd={SCHEMES:zy,normalize:iM,resolve:aM,resolveComponent:Fy,equal:lM,serialize:on,parse:_a};xa.exports=Sd;xa.exports.default=Sd;xa.exports.fastUri=Sd});var Hy=$(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Wy=By();Wy.code='require("ajv/dist/runtime/uri").default';kd.default=Wy});var Qy=$(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var mM=co();Object.defineProperty(Pe,"KeywordCxt",{enumerable:!0,get:function(){return mM.KeywordCxt}});var Yn=F();Object.defineProperty(Pe,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(Pe,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(Pe,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(Pe,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(Pe,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var gM=ya(),Jy=uo(),yM=Wu(),fo=ba(),wM=F(),mo=io(),Ta=oo(),xd=G(),Gy=wy(),bM=Hy(),Xy=(t,e)=>new RegExp(t,e);Xy.code="new RegExp";var vM=["removeAdditional","useDefaults","coerceTypes"],SM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kM={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."},_M={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ky=200;function xM(t){var e,r,n,s,o,i,a,l,c,u,d,h,p,m,f,g,w,b,k,_,S,x,E,N,D;let J=t.strict,_e=(e=t.code)===null||e===void 0?void 0:e.optimize,ue=_e===!0||_e===void 0?1:_e||0,B=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Xy,ne=(s=t.uriResolver)!==null&&s!==void 0?s:bM.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:J)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:J)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:J)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:J)!==null&&h!==void 0?h:"log",strictRequired:(m=(p=t.strictRequired)!==null&&p!==void 0?p:J)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ue,regExp:B}:{optimize:ue,regExp:B},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:Ky,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Ky,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(k=t.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(_=t.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(x=t.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(E=t.validateFormats)!==null&&E!==void 0?E:!0,unicodeRegExp:(N=t.unicodeRegExp)!==null&&N!==void 0?N:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:ne}}var go=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,...xM(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new wM.ValueScope({scope:{},prefixes:SM,es5:r,lines:n}),this.logger=CM(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yM.getRules)(),Vy.call(this,kM,e,"NOT SUPPORTED"),Vy.call(this,_M,e,"DEPRECATED","warn"),this._metaOpts=PM.call(this),e.formats&&EM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$M.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),TM.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Gy;n==="id"&&(s={...Gy},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(u,d){await o.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||i.call(this,h)}async function o(u){u&&!this.getSchema(u)&&await s.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Jy.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}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,mo.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=Yy.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new fo.SchemaEnv({schema:{},schemaId:n});if(r=fo.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=Yy.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,mo.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(AM.call(this,n,r),!r)return(0,xd.eachItem)(n,o=>_d.call(this,o)),this;OM.call(this,r);let s={...r,type:(0,Ta.getJSONTypes)(r.type),schemaType:(0,Ta.getJSONTypes)(r.schemaType)};return(0,xd.eachItem)(n,s.type.length===0?o=>_d.call(this,o,s):o=>s.type.forEach(i=>_d.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 l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=i[a];c&&u&&(i[a]=Zy(u))}}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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,mo.normalizeId)(i||n);let c=mo.getSchemaRefs.call(this,e,n);return l=new fo.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_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):fo.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{fo.compileSchema.call(this,e)}finally{this.opts=r}}};go.ValidationError=gM.default;go.MissingRefError=Jy.default;Pe.default=go;function Vy(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 Yy(t){return t=(0,mo.normalizeId)(t),this.schemas[t]||this.refs[t]}function TM(){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 EM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function $M(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 PM(){let t={...this.opts};for(let e of vM)delete t[e];return t}var RM={log(){},warn(){},error(){}};function CM(t){if(t===!1)return RM;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var MM=/^[a-z_$][a-z0-9_$:-]*$/i;function AM(t,e){let{RULES:r}=this;if((0,xd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!MM.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function _d(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:l})=>l===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,Ta.getJSONTypes)(e.type),schemaType:(0,Ta.getJSONTypes)(e.schemaType)}};e.before?IM.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function IM(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 OM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Zy(e)),t.validateSchema=this.compile(e,!0))}var NM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zy(t){return{anyOf:[t,NM]}}});var ew=$(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var DM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Td.default=DM});var sw=$(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.callRef=an.getValidate=void 0;var zM=uo(),tw=wt(),et=F(),Jn=Xt(),rw=ba(),Ea=G(),jM={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&s===c.baseId)return d();let u=rw.resolveRef.call(l,c,s,r);if(u===void 0)throw new zM.default(n.opts.uriResolver,s,r);if(u instanceof rw.SchemaEnv)return h(u);return p(u);function d(){if(o===c)return $a(t,i,o,o.$async);let m=e.scopeValue("root",{ref:c});return $a(t,(0,et._)`${m}.validate`,c,c.$async)}function h(m){let f=nw(t,m);$a(t,f,m,m.$async)}function p(m){let f=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,et.stringify)(m)}:{ref:m}),g=e.name("valid"),w=t.subschema({schema:m,dataTypes:[],schemaPath:et.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(w),t.ok(g)}}};function nw(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}an.getValidate=nw;function $a(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,c=l.passContext?Jn.default.this:et.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,et._)`await ${(0,tw.callValidateCode)(t,e,c)}`),p(e),i||s.assign(m,!0)},f=>{s.if((0,et._)`!(${f} instanceof ${o.ValidationError})`,()=>s.throw(f)),h(f),i||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,tw.callValidateCode)(t,e,c),()=>p(e),()=>h(e))}function h(m){let f=(0,et._)`${m}.errors`;s.assign(Jn.default.vErrors,(0,et._)`${Jn.default.vErrors} === null ? ${f} : ${Jn.default.vErrors}.concat(${f})`),s.assign(Jn.default.errors,(0,et._)`${Jn.default.vErrors}.length`)}function p(m){var f;if(!o.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Ea.mergeEvaluated.props(s,g.props,o.props));else{let w=s.var("props",(0,et._)`${m}.evaluated.props`);o.props=Ea.mergeEvaluated.props(s,w,o.props,et.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Ea.mergeEvaluated.items(s,g.items,o.items));else{let w=s.var("items",(0,et._)`${m}.evaluated.items`);o.items=Ea.mergeEvaluated.items(s,w,o.items,et.Name)}}}an.callRef=$a;an.default=jM});var ow=$(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var LM=ew(),FM=sw(),UM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",LM.default,FM.default];Ed.default=UM});var iw=$($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Pa=F(),_r=Pa.operators,Ra={maximum:{okStr:"<=",ok:_r.LTE,fail:_r.GT},minimum:{okStr:">=",ok:_r.GTE,fail:_r.LT},exclusiveMaximum:{okStr:"<",ok:_r.LT,fail:_r.GTE},exclusiveMinimum:{okStr:">",ok:_r.GT,fail:_r.LTE}},qM={message:({keyword:t,schemaCode:e})=>(0,Pa.str)`must be ${Ra[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pa._)`{comparison: ${Ra[t].okStr}, limit: ${e}}`},BM={keyword:Object.keys(Ra),type:"number",schemaType:"number",$data:!0,error:qM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Pa._)`${r} ${Ra[e].fail} ${n} || isNaN(${r})`)}};$d.default=BM});var aw=$(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var yo=F(),WM={message:({schemaCode:t})=>(0,yo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,yo._)`{multipleOf: ${t}}`},HM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:WM,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,yo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,yo._)`${i} !== parseInt(${i})`;t.fail$data((0,yo._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Pd.default=HM});var cw=$(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});function lw(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}Rd.default=lw;lw.code='require("ajv/dist/runtime/ucs2length").default'});var uw=$(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var ln=F(),GM=G(),KM=cw(),VM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ln.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ln._)`{limit: ${t}}`},YM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VM,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ln.operators.GT:ln.operators.LT,i=s.opts.unicode===!1?(0,ln._)`${r}.length`:(0,ln._)`${(0,GM.useFunc)(t.gen,KM.default)}(${r})`;t.fail$data((0,ln._)`${i} ${o} ${n}`)}};Cd.default=YM});var dw=$(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var JM=wt(),XM=G(),Xn=F(),ZM={message:({schemaCode:t})=>(0,Xn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Xn._)`{pattern: ${t}}`},QM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ZM,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:l}=i.opts.code,c=l.code==="new RegExp"?(0,Xn._)`new RegExp`:(0,XM.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Xn._)`${c}(${o}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Xn._)`!${u}`)}else{let l=(0,JM.usePattern)(t,s);t.fail$data((0,Xn._)`!${l}.test(${r})`)}}};Md.default=QM});var hw=$(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var wo=F(),eA={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,wo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,wo._)`{limit: ${t}}`},tA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:eA,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?wo.operators.GT:wo.operators.LT;t.fail$data((0,wo._)`Object.keys(${r}).length ${s} ${n}`)}};Ad.default=tA});var pw=$(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var bo=wt(),vo=F(),rA=G(),nA={message:({params:{missingProperty:t}})=>(0,vo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,vo._)`{missingProperty: ${t}}`},sA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:nA,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 l=r.length>=a.loopRequired;if(i.allErrors?c():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:m}=t.it;for(let f of r)if(p?.[f]===void 0&&!m.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,rA.checkStrictMode)(i,w,i.opts.strictRequired)}}function c(){if(l||o)t.block$data(vo.nil,d);else for(let p of r)(0,bo.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>h(p,m)),t.ok(m)}else e.if((0,bo.checkMissingProp)(t,r,p)),(0,bo.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,bo.noPropertyInData)(e,s,p,a.ownProperties),()=>t.error())})}function h(p,m){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,bo.propertyInData)(e,s,p,a.ownProperties)),e.if((0,vo.not)(m),()=>{t.error(),e.break()})},vo.nil)}}};Id.default=sA});var fw=$(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var So=F(),oA={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,So.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,So._)`{limit: ${t}}`},iA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:oA,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?So.operators.GT:So.operators.LT;t.fail$data((0,So._)`${r}.length ${s} ${n}`)}};Od.default=iA});var Ca=$(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var mw=Zu();mw.code='require("ajv/dist/runtime/equal").default';Nd.default=mw});var gw=$(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Dd=oo(),Re=F(),aA=G(),lA=Ca(),cA={message:({params:{i:t,j:e}})=>(0,Re.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Re._)`{i: ${t}, j: ${e}}`},uA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:cA,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let l=e.let("valid"),c=o.items?(0,Dd.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,Re._)`${i} === false`),t.ok(l);function u(){let m=e.let("i",(0,Re._)`${r}.length`),f=e.let("j");t.setParams({i:m,j:f}),e.assign(l,!0),e.if((0,Re._)`${m} > 1`,()=>(d()?h:p)(m,f))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function h(m,f){let g=e.name("item"),w=(0,Dd.checkDataTypes)(c,g,a.opts.strictNumbers,Dd.DataType.Wrong),b=e.const("indices",(0,Re._)`{}`);e.for((0,Re._)`;${m}--;`,()=>{e.let(g,(0,Re._)`${r}[${m}]`),e.if(w,(0,Re._)`continue`),c.length>1&&e.if((0,Re._)`typeof ${g} == "string"`,(0,Re._)`${g} += "_"`),e.if((0,Re._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(f,(0,Re._)`${b}[${g}]`),t.error(),e.assign(l,!1).break()}).code((0,Re._)`${b}[${g}] = ${m}`)})}function p(m,f){let g=(0,aA.useFunc)(e,lA.default),w=e.name("outer");e.label(w).for((0,Re._)`;${m}--;`,()=>e.for((0,Re._)`${f} = ${m}; ${f}--;`,()=>e.if((0,Re._)`${g}(${r}[${m}], ${r}[${f}])`,()=>{t.error(),e.assign(l,!1).break(w)})))}}};zd.default=uA});var yw=$(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var jd=F(),dA=G(),hA=Ca(),pA={message:"must be equal to constant",params:({schemaCode:t})=>(0,jd._)`{allowedValue: ${t}}`},fA={keyword:"const",$data:!0,error:pA,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,jd._)`!${(0,dA.useFunc)(e,hA.default)}(${r}, ${s})`):t.fail((0,jd._)`${o} !== ${r}`)}};Ld.default=fA});var ww=$(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ko=F(),mA=G(),gA=Ca(),yA={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ko._)`{allowedValues: ${t}}`},wA={keyword:"enum",schemaType:"array",$data:!0,error:yA,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,l,c=()=>l??(l=(0,mA.useFunc)(e,gA.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let p=e.const("vSchema",o);u=(0,ko.or)(...s.map((m,f)=>h(p,f)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,p=>e.if((0,ko._)`${c()}(${r}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,m){let f=s[m];return typeof f=="object"&&f!==null?(0,ko._)`${c()}(${r}, ${p}[${m}])`:(0,ko._)`${r} === ${f}`}}};Fd.default=wA});var bw=$(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var bA=iw(),vA=aw(),SA=uw(),kA=dw(),_A=hw(),xA=pw(),TA=fw(),EA=gw(),$A=yw(),PA=ww(),RA=[bA.default,vA.default,SA.default,kA.default,_A.default,xA.default,TA.default,EA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},$A.default,PA.default];Ud.default=RA});var Bd=$(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.validateAdditionalItems=void 0;var cn=F(),qd=G(),CA={message:({params:{len:t}})=>(0,cn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cn._)`{limit: ${t}}`},MA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:CA,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,qd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}vw(t,n)}};function vw(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,cn._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,cn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,qd.alwaysValidSchema)(i,n)){let c=r.var("valid",(0,cn._)`${a} <= ${e.length}`);r.if((0,cn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:qd.Type.Num},c),i.allErrors||r.if((0,cn.not)(c),()=>r.break())})}}_o.validateAdditionalItems=vw;_o.default=MA});var Wd=$(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.validateTuple=void 0;var Sw=F(),Ma=G(),AA=wt(),IA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return kw(t,"additionalItems",e);r.items=!0,!(0,Ma.alwaysValidSchema)(r,e)&&t.ok((0,AA.validateArray)(t))}};function kw(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;u(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ma.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,Sw._)`${o}.length`);r.forEach((d,h)=>{(0,Ma.alwaysValidSchema)(a,d)||(n.if((0,Sw._)`${c} > ${h}`,()=>t.subschema({keyword:i,schemaProp:h,dataProp:h},l)),t.ok(l))});function u(d){let{opts:h,errSchemaPath:p}=a,m=r.length,f=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(h.strictTuples&&!f){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Ma.checkStrictMode)(a,g,h.strictTuples)}}}xo.validateTuple=kw;xo.default=IA});var _w=$(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var OA=Wd(),NA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,OA.validateTuple)(t,"items")};Hd.default=NA});var Tw=$(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var xw=F(),DA=G(),zA=wt(),jA=Bd(),LA={message:({params:{len:t}})=>(0,xw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xw._)`{limit: ${t}}`},FA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:LA,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,DA.alwaysValidSchema)(n,e)&&(s?(0,jA.validateAdditionalItems)(t,s):t.ok((0,zA.validateArray)(t)))}};Gd.default=FA});var Ew=$(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var vt=F(),Aa=G(),UA={message:({params:{min:t,max:e}})=>e===void 0?(0,vt.str)`must contain at least ${t} valid item(s)`:(0,vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vt._)`{minContains: ${t}}`:(0,vt._)`{minContains: ${t}, maxContains: ${e}}`},qA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:UA,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:l,maxContains:c}=n;o.opts.next?(i=l===void 0?1:l,a=c):i=1;let u=e.const("len",(0,vt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Aa.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Aa.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Aa.alwaysValidSchema)(o,r)){let f=(0,vt._)`${u} >= ${i}`;a!==void 0&&(f=(0,vt._)`${f} && ${u} <= ${a}`),t.pass(f);return}o.items=!0;let d=e.name("valid");a===void 0&&i===1?p(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,vt._)`${s}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let f=e.name("_valid"),g=e.let("count",0);p(f,()=>e.if(f,()=>m(g)))}function p(f,g){e.forRange("i",0,u,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:Aa.Type.Num,compositeRule:!0},f),g()})}function m(f){e.code((0,vt._)`${f}++`),a===void 0?e.if((0,vt._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,vt._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,vt._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};Kd.default=qA});var Rw=$(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.validateSchemaDeps=jt.validatePropertyDeps=jt.error=void 0;var Vd=F(),BA=G(),To=wt();jt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Vd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Vd._)`{property: ${t},
9
9
  missingProperty: ${n},
10
10
  depsCount: ${e},
11
- deps: ${r}}`};var WA={keyword:"dependencies",type:"object",schemaType:"object",error:jt.error,code(t){let[e,r]=HA(t);$w(t,e),Pw(t,r)}};function HA({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 $w(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 l=(0,To.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(l,()=>{for(let c of a)(0,To.checkReportMissingProp)(t,c)}):(r.if((0,Vd._)`${l} && (${(0,To.checkMissingProp)(t,a,o)})`),(0,To.reportMissingProp)(t,o),r.else())}}jt.validatePropertyDeps=$w;function Pw(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,BA.alwaysValidSchema)(o,e[a])||(r.if((0,To.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}jt.validateSchemaDeps=Pw;jt.default=WA});var Mw=$(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Cw=F(),GA=G(),KA={message:"property name must be valid",params:({params:t})=>(0,Cw._)`{propertyName: ${t.propertyName}}`},VA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:KA,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,GA.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,Cw.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Yd.default=VA});var Xd=$(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Ia=wt(),Ct=F(),YA=Xt(),Oa=G(),JA={message:"must NOT have additional properties",params:({params:t})=>(0,Ct._)`{additionalProperty: ${t.additionalProperty}}`},XA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:JA,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:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Oa.alwaysValidSchema)(i,r))return;let c=(0,Ia.allSchemaProperties)(n.properties),u=(0,Ia.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Ct._)`${o} === ${YA.default.errors}`);function d(){e.forIn("key",s,g=>{!c.length&&!u.length?m(g):e.if(h(g),()=>m(g))})}function h(g){let w;if(c.length>8){let b=(0,Oa.schemaRefOrVal)(i,n.properties,"properties");w=(0,Ia.isOwnProperty)(e,b,g)}else c.length?w=(0,Ct.or)(...c.map(b=>(0,Ct._)`${g} === ${b}`)):w=Ct.nil;return u.length&&(w=(0,Ct.or)(w,...u.map(b=>(0,Ct._)`${(0,Ia.usePattern)(t,b)}.test(${g})`))),(0,Ct.not)(w)}function p(g){e.code((0,Ct._)`delete ${s}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Oa.alwaysValidSchema)(i,r)){let w=e.name("valid");l.removeAdditional==="failing"?(f(g,w,!1),e.if((0,Ct.not)(w),()=>{t.reset(),p(g)})):(f(g,w),a||e.if((0,Ct.not)(w),()=>e.break()))}}function f(g,w,b){let k={keyword:"additionalProperties",dataProp:g,dataPropType:Oa.Type.Str};b===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(k,w)}}};Jd.default=XA});var Ow=$(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var ZA=co(),Aw=wt(),Zd=G(),Iw=Xd(),QA={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&&Iw.default.code(new ZA.KeywordCxt(o,Iw.default,"additionalProperties"));let i=(0,Aw.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Zd.mergeEvaluated.props(e,(0,Zd.toHash)(i),o.props));let a=i.filter(d=>!(0,Zd.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,Aw.propertyInData)(e,s,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};Qd.default=QA});var jw=$(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Nw=wt(),Na=F(),Dw=G(),zw=G(),e1={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,Nw.allSchemaProperties)(r),l=a.filter(f=>(0,Dw.alwaysValidSchema)(o,r[f]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=i.strictSchema&&!i.allowMatchingProperties&&s.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Na.Name)&&(o.props=(0,zw.evaluatedPropsToName)(e,o.props));let{props:d}=o;h();function h(){for(let f of a)c&&p(f),o.allErrors?m(f):(e.var(u,!0),m(f),e.if(u))}function p(f){for(let g in c)new RegExp(f).test(g)&&(0,Dw.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",n,g=>{e.if((0,Na._)`${(0,Nw.usePattern)(t,f)}.test(${g})`,()=>{let w=l.includes(f);w||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:zw.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,Na._)`${d}[${g}]`,!0):!w&&!o.allErrors&&e.if((0,Na.not)(u),()=>e.break())})})}}};eh.default=e1});var Lw=$(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var t1=G(),r1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,t1.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"}};th.default=r1});var Fw=$(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var n1=wt(),s1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n1.validateUnion,error:{message:"must match a schema in anyOf"}};rh.default=s1});var Uw=$(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var Da=F(),o1=G(),i1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Da._)`{passingSchemas: ${t.passing}}`},a1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:i1,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),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(i,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let h;(0,o1.alwaysValidSchema)(s,u)?e.var(l,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,Da._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Da._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Da.Name)})})}}};nh.default=a1});var qw=$(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var l1=G(),c1={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,l1.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};sh.default=c1});var Hw=$(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var za=F(),Ww=G(),u1={message:({params:t})=>(0,za.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,za._)`{failingKeyword: ${t.ifClause}}`},d1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:u1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Ww.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Bw(n,"then"),o=Bw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else s?e.if(a,c("then")):e.if((0,za.not)(a),c("else"));t.pass(i,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(h,i),d?e.assign(d,(0,za._)`${u}`):t.setParams({ifClause:u})}}}};function Bw(t,e){let r=t.schema[e];return r!==void 0&&!(0,Ww.alwaysValidSchema)(t,r)}oh.default=d1});var Gw=$(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var h1=G(),p1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,h1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ih.default=p1});var Kw=$(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var f1=Bd(),m1=_w(),g1=Wd(),y1=Tw(),w1=Ew(),b1=Rw(),v1=Mw(),S1=Xd(),k1=Ow(),_1=jw(),x1=Lw(),T1=Fw(),E1=Uw(),$1=qw(),P1=Hw(),R1=Gw();function C1(t=!1){let e=[x1.default,T1.default,E1.default,$1.default,P1.default,R1.default,v1.default,S1.default,b1.default,k1.default,_1.default];return t?e.push(m1.default,y1.default):e.push(f1.default,g1.default),e.push(w1.default),e}ah.default=C1});var Vw=$(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var he=F(),M1={message:({schemaCode:t})=>(0,he.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,he._)`{format: ${t}}`},A1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:M1,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;s?h():p();function h(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),f=r.const("fDef",(0,he._)`${m}[${i}]`),g=r.let("fType"),w=r.let("format");r.if((0,he._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,he._)`${f}.type || "string"`).assign(w,(0,he._)`${f}.validate`),()=>r.assign(g,(0,he._)`"string"`).assign(w,f)),t.fail$data((0,he.or)(b(),k()));function b(){return l.strictSchema===!1?he.nil:(0,he._)`${i} && !${w}`}function k(){let _=u.$async?(0,he._)`(${f}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,he._)`${w}(${n})`,S=(0,he._)`(typeof ${w} == "function" ? ${_} : ${w}.test(${n}))`;return(0,he._)`${w} && ${w} !== true && ${g} === ${e} && !${S}`}}function p(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[f,g,w]=k(m);f===e&&t.pass(_());function b(){if(l.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function k(S){let x=S instanceof RegExp?(0,he.regexpCode)(S):l.code.formats?(0,he._)`${l.code.formats}${(0,he.getProperty)(o)}`:void 0,E=r.scopeValue("formats",{key:o,ref:S,code:x});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,he._)`${E}.validate`]:["string",S,E]}function _(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,he._)`await ${w}(${n})`}return typeof g=="function"?(0,he._)`${w}(${n})`:(0,he._)`${w}.test(${n})`}}}};lh.default=A1});var Yw=$(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var I1=Vw(),O1=[I1.default];ch.default=O1});var Jw=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Zw=$(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var N1=ow(),D1=bw(),z1=Kw(),j1=Yw(),Xw=Jw(),L1=[N1.default,D1.default,(0,z1.default)(),j1.default,Xw.metadataVocabulary,Xw.contentVocabulary];uh.default=L1});var eb=$(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.DiscrError=void 0;var Qw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Qw||(ja.DiscrError=Qw={}))});var rb=$(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var Qn=F(),dh=eb(),tb=ba(),F1=uo(),U1=G(),q1={message:({params:{discrError:t,tagName:e}})=>t===dh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},B1={keyword:"discriminator",type:"object",schemaType:"object",error:q1,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 l=e.let("valid",!1),c=e.const("tag",(0,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:dh.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let p=h();e.if(!1);for(let m in p)e.elseIf((0,Qn._)`${c} === ${m}`),e.assign(l,d(p[m]));e.else(),t.error(!1,{discrError:dh.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:p},m);return t.mergeEvaluated(f,Qn.Name),m}function h(){var p;let m={},f=w(s),g=!0;for(let _=0;_<i.length;_++){let S=i[_];if(S?.$ref&&!(0,U1.schemaHasRulesButRef)(S,o.self.RULES)){let E=S.$ref;if(S=tb.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,E),S instanceof tb.SchemaEnv&&(S=S.schema),S===void 0)throw new F1.default(o.opts.uriResolver,o.baseId,E)}let x=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||w(S)),b(x,_)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:_}){return Array.isArray(_)&&_.includes(a)}function b(_,S){if(_.const)k(_.const,S);else if(_.enum)for(let x of _.enum)k(x,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(_,S){if(typeof _!="string"||_ in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[_]=S}}}};hh.default=B1});var nb=$((u3,W1)=>{W1.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 fh=$((oe,ph)=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.MissingRefError=oe.ValidationError=oe.CodeGen=oe.Name=oe.nil=oe.stringify=oe.str=oe._=oe.KeywordCxt=oe.Ajv=void 0;var H1=Qy(),G1=Zw(),K1=rb(),sb=nb(),V1=["/properties"],La="http://json-schema.org/draft-07/schema",es=class extends H1.default{_addVocabularies(){super._addVocabularies(),G1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(K1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(sb,V1):sb;this.addMetaSchema(e,La,!1),this.refs["http://json-schema.org/schema"]=La}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(La)?La:void 0)}};oe.Ajv=es;ph.exports=oe=es;ph.exports.Ajv=es;Object.defineProperty(oe,"__esModule",{value:!0});oe.default=es;var Y1=co();Object.defineProperty(oe,"KeywordCxt",{enumerable:!0,get:function(){return Y1.KeywordCxt}});var ts=F();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return ts._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return ts.str}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return ts.stringify}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return ts.nil}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return ts.Name}});Object.defineProperty(oe,"CodeGen",{enumerable:!0,get:function(){return ts.CodeGen}});var J1=ya();Object.defineProperty(oe,"ValidationError",{enumerable:!0,get:function(){return J1.default}});var X1=uo();Object.defineProperty(oe,"MissingRefError",{enumerable:!0,get:function(){return X1.default}})});var hb=$(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.formatNames=Ft.fastFormats=Ft.fullFormats=void 0;function Lt(t,e){return{validate:t,compare:e}}Ft.fullFormats={date:Lt(lb,wh),time:Lt(gh(!0),bh),"date-time":Lt(ob(!0),ub),"iso-time":Lt(gh(),cb),"iso-date-time":Lt(ob(),db),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nI,"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:uI,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:sI,int32:{type:"number",validate:aI},int64:{type:"number",validate:lI},float:{type:"number",validate:ab},double:{type:"number",validate:ab},password:!0,binary:!0};Ft.fastFormats={...Ft.fullFormats,date:Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,wh),time:Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bh),"date-time":Lt(/^\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,ub),"iso-time":Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cb),"iso-date-time":Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,db),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ft.formatNames=Object.keys(Ft.fullFormats);function Z1(t){return t%4===0&&(t%100!==0||t%400===0)}var Q1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lb(t){let e=Q1.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&&Z1(r)?29:eI[n])}function wh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var mh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gh(t){return function(r){let n=mh.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let d=o-u*l,h=s-c*l-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&i<61}}function bh(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 cb(t,e){if(!(t&&e))return;let r=mh.exec(t),n=mh.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 yh=/t|\s/i;function ob(t){let e=gh(t);return function(n){let s=n.split(yh);return s.length===2&&lb(s[0])&&e(s[1])}}function ub(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function db(t,e){if(!(t&&e))return;let[r,n]=t.split(yh),[s,o]=e.split(yh),i=wh(r,s);if(i!==void 0)return i||bh(n,o)}var tI=/\/|:/,rI=/^(?:[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 nI(t){return tI.test(t)&&rI.test(t)}var ib=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function sI(t){return ib.lastIndex=0,ib.test(t)}var oI=-(2**31),iI=2**31-1;function aI(t){return Number.isInteger(t)&&t<=iI&&t>=oI}function lI(t){return Number.isInteger(t)}function ab(){return!0}var cI=/[^\\]\\Z/;function uI(t){if(cI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pb=$(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.formatLimitDefinition=void 0;var dI=fh(),Mt=F(),xr=Mt.operators,Fa={formatMaximum:{okStr:"<=",ok:xr.LTE,fail:xr.GT},formatMinimum:{okStr:">=",ok:xr.GTE,fail:xr.LT},formatExclusiveMaximum:{okStr:"<",ok:xr.LT,fail:xr.GTE},formatExclusiveMinimum:{okStr:">",ok:xr.GT,fail:xr.LTE}},hI={message:({keyword:t,schemaCode:e})=>(0,Mt.str)`should be ${Fa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Mt._)`{comparison: ${Fa[t].okStr}, limit: ${e}}`};rs.formatLimitDefinition={keyword:Object.keys(Fa),type:"string",schemaType:"string",$data:!0,error:hI,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new dI.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?c():u();function c(){let h=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Mt._)`${h}[${l.schemaCode}]`);t.fail$data((0,Mt.or)((0,Mt._)`typeof ${p} != "object"`,(0,Mt._)`${p} instanceof RegExp`,(0,Mt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=l.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${s}": format "${h}" does not define "compare" function`);let m=e.scopeValue("formats",{key:h,ref:p,code:i.code.formats?(0,Mt._)`${i.code.formats}${(0,Mt.getProperty)(h)}`:void 0});t.fail$data(d(m))}function d(h){return(0,Mt._)`${h}.compare(${r}, ${n}) ${Fa[s].fail} 0`}},dependencies:["format"]};var pI=t=>(t.addKeyword(rs.formatLimitDefinition),t);rs.default=pI});var yb=$((Eo,gb)=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var ns=hb(),fI=pb(),vh=F(),fb=new vh.Name("fullFormats"),mI=new vh.Name("fastFormats"),Sh=(t,e={keywords:!0})=>{if(Array.isArray(e))return mb(t,e,ns.fullFormats,fb),t;let[r,n]=e.mode==="fast"?[ns.fastFormats,mI]:[ns.fullFormats,fb],s=e.formats||ns.formatNames;return mb(t,s,r,n),e.keywords&&(0,fI.default)(t),t};Sh.get=(t,e="full")=>{let n=(e==="fast"?ns.fastFormats:ns.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function mb(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,vh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}gb.exports=Eo=Sh;Object.defineProperty(Eo,"__esModule",{value:!0});Eo.default=Sh});var Kb=$((G3,Gb)=>{"use strict";Gb.exports=Hb;Hb.sync=KI;var Bb=cr("fs");function GI(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&t.substr(-s.length).toLowerCase()===s)return!0}return!1}function Wb(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:GI(e,r)}function Hb(t,e,r){Bb.stat(t,function(n,s){r(n,n?!1:Wb(s,t,e))})}function KI(t,e){return Wb(Bb.statSync(t),t,e)}});var Zb=$((K3,Xb)=>{"use strict";Xb.exports=Yb;Yb.sync=VI;var Vb=cr("fs");function Yb(t,e,r){Vb.stat(t,function(n,s){r(n,n?!1:Jb(s,e))})}function VI(t,e){return Jb(Vb.statSync(t),e)}function Jb(t,e){return t.isFile()&&YI(t,e)}function YI(t,e){var r=t.mode,n=t.uid,s=t.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),i=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),u=a|l,d=r&c||r&l&&s===i||r&a&&n===o||r&u&&o===0;return d}});var ev=$((Y3,Qb)=>{"use strict";var V3=cr("fs"),Xa;process.platform==="win32"||global.TESTING_WINDOWS?Xa=Kb():Xa=Zb();Qb.exports=Uh;Uh.sync=JI;function Uh(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,s){Uh(t,e||{},function(o,i){o?s(o):n(i)})})}Xa(t,e||{},function(n,s){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,s=!1),r(n,s)})}function JI(t,e){try{return Xa.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var av=$((J3,iv)=>{"use strict";var ds=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",tv=cr("path"),XI=ds?";":":",rv=ev(),nv=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),sv=(t,e)=>{let r=e.colon||XI,n=t.match(/\//)||ds&&t.match(/\\/)?[""]:[...ds?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=ds?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=ds?s.split(r):[""];return ds&&t.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:n,pathExt:o,pathExtExe:s}},ov=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:s,pathExtExe:o}=sv(t,e),i=[],a=c=>new Promise((u,d)=>{if(c===n.length)return e.all&&i.length?u(i):d(nv(t));let h=n[c],p=/^".*"$/.test(h)?h.slice(1,-1):h,m=tv.join(p,t),f=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;u(l(f,c,0))}),l=(c,u,d)=>new Promise((h,p)=>{if(d===s.length)return h(a(u+1));let m=s[d];rv(c+m,{pathExt:o},(f,g)=>{if(!f&&g)if(e.all)i.push(c+m);else return h(c+m);return h(l(c,u,d+1))})});return r?a(0).then(c=>r(null,c),r):a(0)},ZI=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:s}=sv(t,e),o=[];for(let i=0;i<r.length;i++){let a=r[i],l=/^".*"$/.test(a)?a.slice(1,-1):a,c=tv.join(l,t),u=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+c:c;for(let d=0;d<n.length;d++){let h=u+n[d];try{if(rv.sync(h,{pathExt:s}))if(e.all)o.push(h);else return h}catch{}}}if(e.all&&o.length)return o;if(e.nothrow)return null;throw nv(t)};iv.exports=ov;ov.sync=ZI});var cv=$((X3,qh)=>{"use strict";var lv=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};qh.exports=lv;qh.exports.default=lv});var pv=$((Z3,hv)=>{"use strict";var uv=cr("path"),QI=av(),eO=cv();function dv(t,e){let r=t.options.env||process.env,n=process.cwd(),s=t.options.cwd!=null,o=s&&process.chdir!==void 0&&!process.chdir.disabled;if(o)try{process.chdir(t.options.cwd)}catch{}let i;try{i=QI.sync(t.command,{path:r[eO({env:r})],pathExt:e?uv.delimiter:void 0})}catch{}finally{o&&process.chdir(n)}return i&&(i=uv.resolve(s?t.options.cwd:"",i)),i}function tO(t){return dv(t)||dv(t,!0)}hv.exports=tO});var fv=$((Q3,Wh)=>{"use strict";var Bh=/([()\][%!^"`<>&|;, *?])/g;function rO(t){return t=t.replace(Bh,"^$1"),t}function nO(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Bh,"^$1"),e&&(t=t.replace(Bh,"^$1")),t}Wh.exports.command=rO;Wh.exports.argument=nO});var gv=$((eK,mv)=>{"use strict";mv.exports=/^#!(.*)/});var wv=$((tK,yv)=>{"use strict";var sO=gv();yv.exports=(t="")=>{let e=t.match(sO);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?n:n?`${s} ${n}`:s}});var vv=$((rK,bv)=>{"use strict";var Hh=cr("fs"),oO=wv();function iO(t){let r=Buffer.alloc(150),n;try{n=Hh.openSync(t,"r"),Hh.readSync(n,r,0,150,0),Hh.closeSync(n)}catch{}return oO(r.toString())}bv.exports=iO});var xv=$((nK,_v)=>{"use strict";var aO=cr("path"),Sv=pv(),kv=fv(),lO=vv(),cO=process.platform==="win32",uO=/\.(?:com|exe)$/i,dO=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function hO(t){t.file=Sv(t);let e=t.file&&lO(t.file);return e?(t.args.unshift(t.file),t.command=e,Sv(t)):t.file}function pO(t){if(!cO)return t;let e=hO(t),r=!uO.test(e);if(t.options.forceShell||r){let n=dO.test(e);t.command=aO.normalize(t.command),t.command=kv.command(t.command),t.args=t.args.map(o=>kv.argument(o,n));let s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function fO(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:pO(n)}_v.exports=fO});var $v=$((sK,Ev)=>{"use strict";var Gh=process.platform==="win32";function Kh(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function mO(t,e){if(!Gh)return;let r=t.emit;t.emit=function(n,s){if(n==="exit"){let o=Tv(s,e);if(o)return r.call(t,"error",o)}return r.apply(t,arguments)}}function Tv(t,e){return Gh&&t===1&&!e.file?Kh(e.original,"spawn"):null}function gO(t,e){return Gh&&t===1&&!e.file?Kh(e.original,"spawnSync"):null}Ev.exports={hookChildProcess:mO,verifyENOENT:Tv,verifyENOENTSync:gO,notFoundError:Kh}});var Cv=$((oK,hs)=>{"use strict";var Pv=cr("child_process"),Vh=xv(),Yh=$v();function Rv(t,e,r){let n=Vh(t,e,r),s=Pv.spawn(n.command,n.args,n.options);return Yh.hookChildProcess(s,n),s}function yO(t,e,r){let n=Vh(t,e,r),s=Pv.spawnSync(n.command,n.args,n.options);return s.error=s.error||Yh.verifyENOENTSync(s.status,n),s}hs.exports=Rv;hs.exports.spawn=Rv;hs.exports.sync=yO;hs.exports._parse=Vh;hs.exports._enoent=Yh});var Dv=$(Xh=>{"use strict";var Iv=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,_O=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Ov=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xO=/\\([\u000b\u0020-\u00ff])/g,TO=/([\\"])/g,Nv=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Xh.format=EO;Xh.parse=$O;function EO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Nv.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var s,o=Object.keys(e).sort(),i=0;i<o.length;i++){if(s=o[i],!Ov.test(s))throw new TypeError("invalid parameter name");n+="; "+s+"="+RO(e[s])}return n}function $O(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?PO(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!Nv.test(n))throw new TypeError("invalid media type");var s=new CO(n.toLowerCase());if(r!==-1){var o,i,a;for(Iv.lastIndex=r;i=Iv.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,o=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(xO,"$1"))),s.parameters[o]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return s}function PO(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function RO(t){var e=String(t);if(Ov.test(e))return e;if(e.length>0&&!_O.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(TO,"\\$1")+'"'}function CO(t){this.parameters=Object.create(null),this.type=t}});import{createHash as Tx}from"crypto";var zf=new WeakMap;function Ti(t){return performance.now()-t}function Ex(t){if(t)return Tx("sha256").update(t).digest("hex").slice(0,16)}function jf(t){return zf.get(t)??{model:"unknown",protocol:t.protocol??"unknown"}}function $x(t,e){let r=In(),n={cache_creation:t.cacheCreationInputTokens,cache_read:t.cacheReadInputTokens,input:t.inputTokens,output:t.outputTokens};for(let[s,o]of Object.entries(n))o>0&&r.recordMetric("yukino.llm.tokens","counter",o,{...e,"token.type":s})}function Ei(t,e){return zf.set(t,e),t}function Lf(t,e){let r=In(),n=jf(e),s=Ex(t),o={protocol:n.protocol,...s?{"session.hash":s}:{}};return r.recordMetric("yukino.agent.runs","counter",1,{protocol:n.protocol}),{observation:r.startObservation("agent","yukino.agent.run",o),protocol:n.protocol,startedAt:performance.now()}}function Ff(t,e){let r=In();t.observation.update({metadata:{outcome:e}}),t.observation.end(),r.recordMetric("yukino.agent.duration","histogram",Ti(t.startedAt),{outcome:e,protocol:t.protocol})}async function*Uf(t,e,r){let n=In(),s=jf(t),o={model:s.model,protocol:s.protocol},i=r.observation.startChild("generation","yukino.llm.generate",o),a=performance.now(),l,c="incomplete";n.recordMetric("yukino.llm.requests","counter",1,o);try{for await(let u of e){if(!l&&u.type!=="stream_end"&&(l=new Date,n.recordMetric("yukino.llm.time_to_first_token","histogram",Ti(a),o)),u.type==="stream_end"){c="completed";let d={cacheCreationInput:u.usage.cacheCreationInputTokens,cacheReadInput:u.usage.cacheReadInputTokens,input:u.usage.inputTokens,output:u.usage.outputTokens};i.update({completionStartTime:l,metadata:{outcome:c,protocol:s.protocol,stopReason:u.stopReason},model:s.model,usageDetails:d}),$x(u.usage,o)}yield u}}catch(u){throw c="error",i.recordException(u),i.update({metadata:{outcome:c,protocol:s.protocol}}),n.emitLog("yukino.llm.error","error",{"error.type":u instanceof Error?u.name:typeof u,...o}),u}finally{i.end(),n.recordMetric("yukino.llm.duration","histogram",Ti(a),{...o,outcome:c})}}async function qf(t,e,r){let n=In(),s={tool:t},o=r.observation.startChild("tool","yukino.tool.execute",s),i=performance.now(),a="error";n.recordMetric("yukino.tool.calls","counter",1,s);try{let l=await e();return a=l.isError?"error":"completed",o.update({level:l.isError?"ERROR":"DEFAULT",metadata:{outcome:a,tool:t},...l.isError?{statusMessage:"Tool returned an error"}:{}}),l}catch(l){throw o.recordException(l),n.emitLog("yukino.tool.error","error",{"error.type":l instanceof Error?l.name:typeof l,tool:t}),l}finally{o.end(),n.recordMetric("yukino.tool.duration","histogram",Ti(i),{outcome:a,tool:t})}}var Wf={end:()=>{},recordException:()=>{},startChild:()=>Wf,update:()=>{}},Pc={captureError:()=>{},emitLog:()=>{},flush:()=>Promise.resolve(),recordMetric:()=>{},setMode:()=>{},shutdown:()=>Promise.resolve(),startObservation:()=>Wf},Gt=Pc,Hf="unknown",On=null,$i=null,Bf=!1;function $c(t){return t?.split(",").map(e=>e.trim()).some(e=>e.length>0&&e!=="none")??!1}function Rx(){let t=process.env.OTEL_SDK_DISABLED?.toLowerCase()!=="true",e=$c(process.env.OTEL_TRACES_EXPORTER)||$c(process.env.OTEL_LOGS_EXPORTER)||$c(process.env.OTEL_METRICS_EXPORTER),r=!!(process.env.LANGFUSE_PUBLIC_KEY&&process.env.LANGFUSE_SECRET_KEY);return!!process.env.SENTRY_DSN||t&&(e||r)}function In(){return Gt}async function v2(){if(On)return On;if(Rx())return On=import("./providers-6UOA2HYN.js").then(async({createTelemetryRuntime:t})=>{Gt=await t(),Gt.setMode(Hf),process.once("beforeExit",()=>{Cx()})}).catch(()=>{Gt=Pc}),On}function S2(t){Hf=t,Gt.setMode(t)}function k2(t,e){Gt.captureError(t,e)}async function Cx(){await On,await Gt.flush()}async function Mx(){return $i||($i=(async()=>{await On,await Gt.shutdown(),Gt=Pc})(),$i)}function _2(t){if(Bf)return;Bf=!0;let e=(r,n)=>{let s=()=>{process.off(r,s),Promise.resolve(t?.(n)).catch(()=>{}).finally(()=>{Mx().finally(()=>{process.exit(n)})})};process.once(r,s)};e("SIGINT",130),e("SIGTERM",143)}import{createHash as Ax}from"crypto";import{existsSync as Pi,mkdirSync as Rc,readFileSync as Hr,unlinkSync as Ri,writeFileSync as Ns}from"fs";import{dirname as Gf,join as Ds,resolve as Ix}from"path";var Et=C({module:"file-history"}),Cc=100,Kf=60,Ox=y.object({backupPath:y.string(),time:y.string(),unavailable:y.literal(!0).optional()}),Nx=y.object({messageIndex:y.number(),userText:y.string(),backups:y.record(y.string(),Ox),timestamp:y.string(),sessionLineCount:y.number().optional()}),Dx=y.discriminatedUnion("state",[y.object({state:y.literal("existing"),backupPath:y.string()}),y.object({state:y.literal("absent")}),y.object({state:y.literal("unavailable")})]),zx=y.object({version:y.literal(1),trackedFiles:y.array(y.string()),snapshots:y.array(Nx),baselines:y.record(y.string(),Dx).optional(),nextSnapshotSeq:y.number().optional()});function Yf(t){return Ax("sha256").update(t).digest("hex").slice(0,16)}function jx(t,e){return`${Yf(t)}@s${String(e)}`}function Lx(t){return`${Yf(t)}@baseline`}function Ci(t,e){return Ds(t,".yukino","file-history",e)}var Vf=class{sessionDir;trackedFiles=new Set;baselines=new Map;snapshots=[];nextSnapshotSeq=0;constructor(e,r){this.sessionDir=Ci(e,r),Rc(this.sessionDir,{recursive:!0}),this.load()}trackEdit(e){let r=Ix(e);this.trackedFiles.has(r)||(this.baselines.set(r,this.captureBaseline(r)),this.trackedFiles.add(r)),this.save()}captureBaseline(e){let r;try{r=Hr(e)}catch(s){let o=y.looseObject({code:y.string().optional()}).safeParse(s);return o.success&&o.data.code==="ENOENT"?{state:"absent"}:(Et.error({err:s},"file-history baseline capture failed"),{state:"unavailable"})}let n=Ds(this.sessionDir,Lx(e));try{return Ns(n,r),{state:"existing",backupPath:n}}catch(s){return Et.error({err:s},"file-history baseline capture failed"),{state:"unavailable"}}}makeSnapshot(e,r,n){let s=r;s.length>Kf&&(s=s.slice(0,Kf)+"...");let o=new Date().toISOString(),i=this.nextSnapshotSeq;this.nextSnapshotSeq++;let a={};for(let l of this.trackedFiles){let c=Ds(this.sessionDir,jx(l,i));if(!Pi(l)){a[l]={backupPath:c,time:o};continue}try{Ns(c,Hr(l))}catch(u){Et.error({err:u},"file-history operation failed"),a[l]={backupPath:c,time:o,unavailable:!0};continue}a[l]={backupPath:c,time:o}}if(this.snapshots.push({messageIndex:e,userText:s,backups:a,timestamp:o,...n===void 0?{}:{sessionLineCount:n}}),this.snapshots.length>Cc){let l=this.snapshots.slice(0,this.snapshots.length-Cc);this.snapshots=this.snapshots.slice(this.snapshots.length-Cc),this.deleteBackups(l)}this.save()}rewind(e){if(e<0||e>=this.snapshots.length)throw new Error(`Invalid snapshot index: ${String(e)}`);let r=this.snapshots[e],n=[];for(let[a,l]of Object.entries(r.backups)){if(l.unavailable)continue;let c=null;try{c=Hr(l.backupPath)}catch{if(Pi(a))try{Ri(a),n.push(a)}catch(p){Et.error({err:p},"file-history operation failed")}continue}let u=null;try{u=Hr(a)}catch(p){Et.error({err:p},"file-history operation failed")}let d=c.toString(),h=u?.toString();if(d!==h)try{Rc(Gf(a),{recursive:!0}),Ns(a,c),n.push(a)}catch(p){Et.error({err:p},"file-history operation failed")}}let s=[...this.trackedFiles].filter(a=>!(a in r.backups)),o=new Set;for(let a of s){let l=this.baselines.get(a),c=!1;if(l?.state==="existing"){try{let u=Hr(l.backupPath),d=null;try{d=Hr(a)}catch{}(!d||!u.equals(d))&&(Rc(Gf(a),{recursive:!0}),Ns(a,u),n.push(a)),c=!0}catch(u){Et.error({err:u},"file-history baseline restore failed")}if(c)try{Ri(l.backupPath)}catch{}}else if(l?.state==="absent")if(!Pi(a))c=!0;else try{Ri(a),n.push(a),c=!0}catch(u){Et.error({err:u},"file-history baseline delete failed")}c?this.baselines.delete(a):o.add(a)}let i=this.snapshots.slice(e+1);return this.deleteBackups(i),this.snapshots=this.snapshots.slice(0,e+1),this.trackedFiles=new Set([...Object.keys(r.backups),...o]),this.save(),n}deleteBackups(e){for(let r of e)for(let n of Object.values(r.backups))try{Ri(n.backupPath)}catch{}}getSnapshots(){return[...this.snapshots]}hasSnapshots(){return this.snapshots.length>0}save(){let e={version:1,trackedFiles:[...this.trackedFiles],snapshots:this.snapshots,baselines:Object.fromEntries(this.baselines),nextSnapshotSeq:this.nextSnapshotSeq};try{Ns(Ds(this.sessionDir,"snapshots.json"),JSON.stringify(e,null,2),"utf-8")}catch(r){Et.error({err:r},"file-history operation failed")}}load(){let e=Ds(this.sessionDir,"snapshots.json");if(!Pi(e))return;let r;try{r=JSON.parse(Hr(e,"utf-8"))}catch(o){Et.error({err:o},"file-history operation failed");return}let n=it(zx,r);if(!n.success){Et.error({err:n.error},"file-history operation failed");return}let s=n.data;this.snapshots=s.snapshots,this.nextSnapshotSeq=s.nextSnapshotSeq??s.snapshots.length;for(let[o,i]of Object.entries(s.baselines??{}))this.baselines.set(o,i);if(s.trackedFiles.length>0)for(let o of s.trackedFiles)this.trackedFiles.add(o);else if(s.snapshots.length>0){let o=s.snapshots[s.snapshots.length-1];for(let i of Object.keys(o.backups))this.trackedFiles.add(i)}for(let o of this.trackedFiles)this.baselines.has(o)||this.baselines.set(o,{state:"unavailable"})}};import{readFileSync as rm,statSync as lT}from"fs";import{isAbsolute as cT,join as uT}from"path";import{readFileSync as eT,statSync as tT}from"fs";import{extname as rT}from"path";import Oc from"sharp";import{spawn as Fx}from"child_process";import{createHash as Ux}from"crypto";import{mkdir as Mc,readFile as Zf,rm as qx,writeFile as Bx}from"fs/promises";import{join as Qf}from"path";var Jf=5e3,Ac=32*1024*1024,Wx=16*1024,zs="The clipboard does not contain an image.",Xf=Buffer.from([137,80,78,71,13,10,26,10]);function Hx(t){return t.length>Xf.length&&t.subarray(0,8).equals(Xf)}function Gx(t){return`${Ux("sha256").update(t).digest("hex").slice(0,16)}.png`}async function Kx(t,e,r){if(!Hx(r))throw new Error("Clipboard data is not a PNG image.");if(r.length>Ac)throw new Error(`Clipboard image is too large (${String(r.length)} bytes, limit ${String(Ac)}).`);let n=Ci(t,e);await Mc(n,{recursive:!0});let s=Qf(n,Gx(r));return await Bx(s,r),s}function Ic(t,e,r){return new Promise((n,s)=>{let o=Fx(t,[...e],{shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:r?{...process.env,...r}:process.env}),i=!1,a=0,l=0,c=[],u=[],d=p=>{i||(i=!0,clearTimeout(h),p())},h=setTimeout(()=>{o.kill(),d(()=>{s(new Error(`${t} timed out after ${String(Jf)}ms.`))})},Jf);if(!o.stdout||!o.stderr){o.kill(),d(()=>{s(new Error(`${t} pipes were not created.`))});return}o.stdout.on("data",p=>{if(a+=p.length,a>Ac){o.kill(),d(()=>{s(new Error(`${t} produced more than the clipboard image byte limit.`))});return}c.push(p)}),o.stderr.on("data",p=>{let m=Wx-l;if(m>0){let f=p.subarray(0,m);l+=f.length,u.push(f)}}),o.on("error",p=>{d(()=>{s(p.code==="ENOENT"?new Error(`${t} is not installed or not on PATH.`):p)})}),o.on("close",p=>{d(()=>{n({code:p??1,stdout:Buffer.concat(c),stderr:Buffer.concat(u).toString("utf8").trim()})})})})}var Vx=["on run argv","set d to the clipboard as \xABclass PNGf\xBB","set f to open for access POSIX file (item 1 of argv) with write permission","set eof f to 0","write d to f","close access f","end run"];async function Yx(t){let e=[...Vx.flatMap(n=>["-e",n]),t],r=await Ic("/usr/bin/osascript",e);if(r.code!==0)throw r.stderr.includes("-1700")?new Error(zs):new Error(`osascript failed: ${r.stderr||`exit ${String(r.code)}`}`);return Zf(t)}async function Jx(){let t=[];if(process.env.WAYLAND_DISPLAY&&t.push({command:"wl-paste",args:["--no-newline","--type","image/png"],hint:"Install wl-clipboard (provides wl-paste)."}),process.env.DISPLAY&&t.push({command:"xclip",args:["-selection","clipboard","-t","image/png","-o"],hint:"Install xclip with your system package manager."}),t.length===0)throw new Error("No Wayland or X11 session found (WAYLAND_DISPLAY and DISPLAY are unset).");let e=new Error(zs);for(let r of t)try{let n=await Ic(r.command,r.args);if(n.code===0&&n.stdout.length>0)return n.stdout;let s=n.stderr.toLowerCase();e=s.includes("target")||s.includes("no suitable")||s.includes("nothing")?new Error(zs):new Error(`${r.command} failed: ${n.stderr||`exit ${String(n.code)}`}`)}catch(n){e=new Error(`${n instanceof Error?n.message:String(n)} ${r.hint}`.trim())}throw e}var Xx=["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing","$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($null -eq $img) { exit 3 }","$img.Save($env:YUKINO_CLIPBOARD_PATH, [System.Drawing.Imaging.ImageFormat]::Png)","$img.Dispose()"].join("; ");async function Zx(t){let e=await Ic("powershell.exe",["-NoProfile","-NonInteractive","-Sta","-Command",Xx],{YUKINO_CLIPBOARD_PATH:t});if(e.code===3)throw new Error(zs);if(e.code!==0)throw new Error(`powershell failed: ${e.stderr||`exit ${String(e.code)}`}`);return Zf(t)}async function D2(t,e){let r=Ci(t,e),n=Qf(r,`.clipboard-${String(process.pid)}.tmp`);try{let s;switch(process.platform){case"darwin":await Mc(r,{recursive:!0}),s=await Yx(n);break;case"linux":s=await Jx();break;case"win32":await Mc(r,{recursive:!0}),s=await Zx(n);break;default:return{ok:!1,reason:`Clipboard image paste is not supported on ${process.platform}.`}}return s.length===0?{ok:!1,reason:zs}:{ok:!0,value:await Kx(t,e,s)}}catch(s){return{ok:!1,reason:s instanceof Error?s.message:String(s)}}finally{await qx(n,{force:!0}).catch(()=>{})}}var nT=C({module:"images"});function tm(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var Dc=5*1024*1024,Mi=Dc*3/4,em=50*1024*1024,dr=2e3,zc=10,Gr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},sT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function oT(t){return sT[rT(t).toLowerCase()]??null}function Ai(t){return oT(t)!==null}function iT(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function Ii(t){let e=tT(t);if(!e.isFile())throw new Error(`Not a file: ${t}`);if(e.size>em)throw new Gr(`Image file is ${hr(e.size)} on disk; files over ${hr(em)} are not read. Please provide a smaller image.`);let r=eT(t),n=iT(r);if(!n)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let s=await js(r,n);return{mediaType:s.mediaType,data:s.data,sourcePath:t,byteLength:s.byteLength}}function Nc(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function hr(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function js(t,e){if(t.length===0)throw new Gr("Image file is empty (0 bytes)");if(t.length<=Mi)return Nc(t,e);try{return await aT(t,e)}catch(r){throw r instanceof Gr?r:(nT.warn({err:r},"sharp compression failed"),new Gr(`Image is ${hr(t.length)} raw (${hr(t.length*4/3)} base64-encoded, API limit ${hr(Dc)}) and compression failed. Please provide a smaller image.`))}}async function aT(t,e){let r=await Oc(t).metadata(),n=r.width??dr,s=r.height??dr;n>dr&&(s=Math.max(1,Math.round(s*dr/n)),n=dr),s>dr&&(n=Math.max(1,Math.round(n*dr/s)),s=dr);let o=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(o){let a=await Oc(t).resize(n,s,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=Mi)return Nc(a,"image/png")}for(let a of[80,60,40,20]){let l=await Oc(t).resize(n,s,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(l.length<=Mi)return Nc(l,"image/jpeg")}n=Math.max(1,Math.round(n/2)),s=Math.max(1,Math.round(s/2))}throw new Gr(`Unable to compress image (${hr(t.length)} raw) under the ${hr(Dc)} base64 API limit (raw bytes must be \u2264${hr(Mi)}). Please provide a smaller image.`)}var nm=C({module:"at-expand"}),sm=1e5,dT=1e7;function hT(t){let e=/^(.+)#L(\d+)(?:-(\d+))?$/.exec(t);if(!e)return{path:t};let r=Number.parseInt(e[2],10);return{path:e[1],lineStart:r,lineEnd:e[3]?Number.parseInt(e[3],10):r}}function pT(t,e,r){let n=t.split(`
11
+ deps: ${r}}`};var WA={keyword:"dependencies",type:"object",schemaType:"object",error:jt.error,code(t){let[e,r]=HA(t);$w(t,e),Pw(t,r)}};function HA({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 $w(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 l=(0,To.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(l,()=>{for(let c of a)(0,To.checkReportMissingProp)(t,c)}):(r.if((0,Vd._)`${l} && (${(0,To.checkMissingProp)(t,a,o)})`),(0,To.reportMissingProp)(t,o),r.else())}}jt.validatePropertyDeps=$w;function Pw(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,BA.alwaysValidSchema)(o,e[a])||(r.if((0,To.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}jt.validateSchemaDeps=Pw;jt.default=WA});var Mw=$(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Cw=F(),GA=G(),KA={message:"property name must be valid",params:({params:t})=>(0,Cw._)`{propertyName: ${t.propertyName}}`},VA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:KA,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,GA.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,Cw.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Yd.default=VA});var Xd=$(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Ia=wt(),Ct=F(),YA=Xt(),Oa=G(),JA={message:"must NOT have additional properties",params:({params:t})=>(0,Ct._)`{additionalProperty: ${t.additionalProperty}}`},XA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:JA,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:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Oa.alwaysValidSchema)(i,r))return;let c=(0,Ia.allSchemaProperties)(n.properties),u=(0,Ia.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Ct._)`${o} === ${YA.default.errors}`);function d(){e.forIn("key",s,g=>{!c.length&&!u.length?m(g):e.if(h(g),()=>m(g))})}function h(g){let w;if(c.length>8){let b=(0,Oa.schemaRefOrVal)(i,n.properties,"properties");w=(0,Ia.isOwnProperty)(e,b,g)}else c.length?w=(0,Ct.or)(...c.map(b=>(0,Ct._)`${g} === ${b}`)):w=Ct.nil;return u.length&&(w=(0,Ct.or)(w,...u.map(b=>(0,Ct._)`${(0,Ia.usePattern)(t,b)}.test(${g})`))),(0,Ct.not)(w)}function p(g){e.code((0,Ct._)`delete ${s}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Oa.alwaysValidSchema)(i,r)){let w=e.name("valid");l.removeAdditional==="failing"?(f(g,w,!1),e.if((0,Ct.not)(w),()=>{t.reset(),p(g)})):(f(g,w),a||e.if((0,Ct.not)(w),()=>e.break()))}}function f(g,w,b){let k={keyword:"additionalProperties",dataProp:g,dataPropType:Oa.Type.Str};b===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(k,w)}}};Jd.default=XA});var Ow=$(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var ZA=co(),Aw=wt(),Zd=G(),Iw=Xd(),QA={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&&Iw.default.code(new ZA.KeywordCxt(o,Iw.default,"additionalProperties"));let i=(0,Aw.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Zd.mergeEvaluated.props(e,(0,Zd.toHash)(i),o.props));let a=i.filter(d=>!(0,Zd.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,Aw.propertyInData)(e,s,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};Qd.default=QA});var jw=$(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Nw=wt(),Na=F(),Dw=G(),zw=G(),e1={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,Nw.allSchemaProperties)(r),l=a.filter(f=>(0,Dw.alwaysValidSchema)(o,r[f]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=i.strictSchema&&!i.allowMatchingProperties&&s.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Na.Name)&&(o.props=(0,zw.evaluatedPropsToName)(e,o.props));let{props:d}=o;h();function h(){for(let f of a)c&&p(f),o.allErrors?m(f):(e.var(u,!0),m(f),e.if(u))}function p(f){for(let g in c)new RegExp(f).test(g)&&(0,Dw.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",n,g=>{e.if((0,Na._)`${(0,Nw.usePattern)(t,f)}.test(${g})`,()=>{let w=l.includes(f);w||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:zw.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,Na._)`${d}[${g}]`,!0):!w&&!o.allErrors&&e.if((0,Na.not)(u),()=>e.break())})})}}};eh.default=e1});var Lw=$(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var t1=G(),r1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,t1.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"}};th.default=r1});var Fw=$(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var n1=wt(),s1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n1.validateUnion,error:{message:"must match a schema in anyOf"}};rh.default=s1});var Uw=$(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var Da=F(),o1=G(),i1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Da._)`{passingSchemas: ${t.passing}}`},a1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:i1,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),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(i,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let h;(0,o1.alwaysValidSchema)(s,u)?e.var(l,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,Da._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Da._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Da.Name)})})}}};nh.default=a1});var qw=$(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var l1=G(),c1={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,l1.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};sh.default=c1});var Hw=$(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var za=F(),Ww=G(),u1={message:({params:t})=>(0,za.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,za._)`{failingKeyword: ${t.ifClause}}`},d1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:u1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Ww.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Bw(n,"then"),o=Bw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else s?e.if(a,c("then")):e.if((0,za.not)(a),c("else"));t.pass(i,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(h,i),d?e.assign(d,(0,za._)`${u}`):t.setParams({ifClause:u})}}}};function Bw(t,e){let r=t.schema[e];return r!==void 0&&!(0,Ww.alwaysValidSchema)(t,r)}oh.default=d1});var Gw=$(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var h1=G(),p1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,h1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ih.default=p1});var Kw=$(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var f1=Bd(),m1=_w(),g1=Wd(),y1=Tw(),w1=Ew(),b1=Rw(),v1=Mw(),S1=Xd(),k1=Ow(),_1=jw(),x1=Lw(),T1=Fw(),E1=Uw(),$1=qw(),P1=Hw(),R1=Gw();function C1(t=!1){let e=[x1.default,T1.default,E1.default,$1.default,P1.default,R1.default,v1.default,S1.default,b1.default,k1.default,_1.default];return t?e.push(m1.default,y1.default):e.push(f1.default,g1.default),e.push(w1.default),e}ah.default=C1});var Vw=$(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var he=F(),M1={message:({schemaCode:t})=>(0,he.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,he._)`{format: ${t}}`},A1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:M1,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;s?h():p();function h(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),f=r.const("fDef",(0,he._)`${m}[${i}]`),g=r.let("fType"),w=r.let("format");r.if((0,he._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,he._)`${f}.type || "string"`).assign(w,(0,he._)`${f}.validate`),()=>r.assign(g,(0,he._)`"string"`).assign(w,f)),t.fail$data((0,he.or)(b(),k()));function b(){return l.strictSchema===!1?he.nil:(0,he._)`${i} && !${w}`}function k(){let _=u.$async?(0,he._)`(${f}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,he._)`${w}(${n})`,S=(0,he._)`(typeof ${w} == "function" ? ${_} : ${w}.test(${n}))`;return(0,he._)`${w} && ${w} !== true && ${g} === ${e} && !${S}`}}function p(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[f,g,w]=k(m);f===e&&t.pass(_());function b(){if(l.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function k(S){let x=S instanceof RegExp?(0,he.regexpCode)(S):l.code.formats?(0,he._)`${l.code.formats}${(0,he.getProperty)(o)}`:void 0,E=r.scopeValue("formats",{key:o,ref:S,code:x});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,he._)`${E}.validate`]:["string",S,E]}function _(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,he._)`await ${w}(${n})`}return typeof g=="function"?(0,he._)`${w}(${n})`:(0,he._)`${w}.test(${n})`}}}};lh.default=A1});var Yw=$(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var I1=Vw(),O1=[I1.default];ch.default=O1});var Jw=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Zw=$(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var N1=ow(),D1=bw(),z1=Kw(),j1=Yw(),Xw=Jw(),L1=[N1.default,D1.default,(0,z1.default)(),j1.default,Xw.metadataVocabulary,Xw.contentVocabulary];uh.default=L1});var eb=$(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.DiscrError=void 0;var Qw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Qw||(ja.DiscrError=Qw={}))});var rb=$(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var Qn=F(),dh=eb(),tb=ba(),F1=uo(),U1=G(),q1={message:({params:{discrError:t,tagName:e}})=>t===dh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},B1={keyword:"discriminator",type:"object",schemaType:"object",error:q1,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 l=e.let("valid",!1),c=e.const("tag",(0,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:dh.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let p=h();e.if(!1);for(let m in p)e.elseIf((0,Qn._)`${c} === ${m}`),e.assign(l,d(p[m]));e.else(),t.error(!1,{discrError:dh.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:p},m);return t.mergeEvaluated(f,Qn.Name),m}function h(){var p;let m={},f=w(s),g=!0;for(let _=0;_<i.length;_++){let S=i[_];if(S?.$ref&&!(0,U1.schemaHasRulesButRef)(S,o.self.RULES)){let E=S.$ref;if(S=tb.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,E),S instanceof tb.SchemaEnv&&(S=S.schema),S===void 0)throw new F1.default(o.opts.uriResolver,o.baseId,E)}let x=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||w(S)),b(x,_)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:_}){return Array.isArray(_)&&_.includes(a)}function b(_,S){if(_.const)k(_.const,S);else if(_.enum)for(let x of _.enum)k(x,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(_,S){if(typeof _!="string"||_ in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[_]=S}}}};hh.default=B1});var nb=$((u3,W1)=>{W1.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 fh=$((oe,ph)=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.MissingRefError=oe.ValidationError=oe.CodeGen=oe.Name=oe.nil=oe.stringify=oe.str=oe._=oe.KeywordCxt=oe.Ajv=void 0;var H1=Qy(),G1=Zw(),K1=rb(),sb=nb(),V1=["/properties"],La="http://json-schema.org/draft-07/schema",es=class extends H1.default{_addVocabularies(){super._addVocabularies(),G1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(K1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(sb,V1):sb;this.addMetaSchema(e,La,!1),this.refs["http://json-schema.org/schema"]=La}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(La)?La:void 0)}};oe.Ajv=es;ph.exports=oe=es;ph.exports.Ajv=es;Object.defineProperty(oe,"__esModule",{value:!0});oe.default=es;var Y1=co();Object.defineProperty(oe,"KeywordCxt",{enumerable:!0,get:function(){return Y1.KeywordCxt}});var ts=F();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return ts._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return ts.str}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return ts.stringify}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return ts.nil}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return ts.Name}});Object.defineProperty(oe,"CodeGen",{enumerable:!0,get:function(){return ts.CodeGen}});var J1=ya();Object.defineProperty(oe,"ValidationError",{enumerable:!0,get:function(){return J1.default}});var X1=uo();Object.defineProperty(oe,"MissingRefError",{enumerable:!0,get:function(){return X1.default}})});var hb=$(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.formatNames=Ft.fastFormats=Ft.fullFormats=void 0;function Lt(t,e){return{validate:t,compare:e}}Ft.fullFormats={date:Lt(lb,wh),time:Lt(gh(!0),bh),"date-time":Lt(ob(!0),ub),"iso-time":Lt(gh(),cb),"iso-date-time":Lt(ob(),db),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nI,"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:uI,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:sI,int32:{type:"number",validate:aI},int64:{type:"number",validate:lI},float:{type:"number",validate:ab},double:{type:"number",validate:ab},password:!0,binary:!0};Ft.fastFormats={...Ft.fullFormats,date:Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,wh),time:Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bh),"date-time":Lt(/^\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,ub),"iso-time":Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cb),"iso-date-time":Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,db),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ft.formatNames=Object.keys(Ft.fullFormats);function Z1(t){return t%4===0&&(t%100!==0||t%400===0)}var Q1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lb(t){let e=Q1.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&&Z1(r)?29:eI[n])}function wh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var mh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gh(t){return function(r){let n=mh.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let d=o-u*l,h=s-c*l-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&i<61}}function bh(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 cb(t,e){if(!(t&&e))return;let r=mh.exec(t),n=mh.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 yh=/t|\s/i;function ob(t){let e=gh(t);return function(n){let s=n.split(yh);return s.length===2&&lb(s[0])&&e(s[1])}}function ub(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function db(t,e){if(!(t&&e))return;let[r,n]=t.split(yh),[s,o]=e.split(yh),i=wh(r,s);if(i!==void 0)return i||bh(n,o)}var tI=/\/|:/,rI=/^(?:[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 nI(t){return tI.test(t)&&rI.test(t)}var ib=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function sI(t){return ib.lastIndex=0,ib.test(t)}var oI=-(2**31),iI=2**31-1;function aI(t){return Number.isInteger(t)&&t<=iI&&t>=oI}function lI(t){return Number.isInteger(t)}function ab(){return!0}var cI=/[^\\]\\Z/;function uI(t){if(cI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pb=$(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.formatLimitDefinition=void 0;var dI=fh(),Mt=F(),xr=Mt.operators,Fa={formatMaximum:{okStr:"<=",ok:xr.LTE,fail:xr.GT},formatMinimum:{okStr:">=",ok:xr.GTE,fail:xr.LT},formatExclusiveMaximum:{okStr:"<",ok:xr.LT,fail:xr.GTE},formatExclusiveMinimum:{okStr:">",ok:xr.GT,fail:xr.LTE}},hI={message:({keyword:t,schemaCode:e})=>(0,Mt.str)`should be ${Fa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Mt._)`{comparison: ${Fa[t].okStr}, limit: ${e}}`};rs.formatLimitDefinition={keyword:Object.keys(Fa),type:"string",schemaType:"string",$data:!0,error:hI,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new dI.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?c():u();function c(){let h=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Mt._)`${h}[${l.schemaCode}]`);t.fail$data((0,Mt.or)((0,Mt._)`typeof ${p} != "object"`,(0,Mt._)`${p} instanceof RegExp`,(0,Mt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=l.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${s}": format "${h}" does not define "compare" function`);let m=e.scopeValue("formats",{key:h,ref:p,code:i.code.formats?(0,Mt._)`${i.code.formats}${(0,Mt.getProperty)(h)}`:void 0});t.fail$data(d(m))}function d(h){return(0,Mt._)`${h}.compare(${r}, ${n}) ${Fa[s].fail} 0`}},dependencies:["format"]};var pI=t=>(t.addKeyword(rs.formatLimitDefinition),t);rs.default=pI});var yb=$((Eo,gb)=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var ns=hb(),fI=pb(),vh=F(),fb=new vh.Name("fullFormats"),mI=new vh.Name("fastFormats"),Sh=(t,e={keywords:!0})=>{if(Array.isArray(e))return mb(t,e,ns.fullFormats,fb),t;let[r,n]=e.mode==="fast"?[ns.fastFormats,mI]:[ns.fullFormats,fb],s=e.formats||ns.formatNames;return mb(t,s,r,n),e.keywords&&(0,fI.default)(t),t};Sh.get=(t,e="full")=>{let n=(e==="fast"?ns.fastFormats:ns.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function mb(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,vh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}gb.exports=Eo=Sh;Object.defineProperty(Eo,"__esModule",{value:!0});Eo.default=Sh});var Kb=$((G3,Gb)=>{"use strict";Gb.exports=Hb;Hb.sync=KI;var Bb=cr("fs");function GI(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&t.substr(-s.length).toLowerCase()===s)return!0}return!1}function Wb(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:GI(e,r)}function Hb(t,e,r){Bb.stat(t,function(n,s){r(n,n?!1:Wb(s,t,e))})}function KI(t,e){return Wb(Bb.statSync(t),t,e)}});var Zb=$((K3,Xb)=>{"use strict";Xb.exports=Yb;Yb.sync=VI;var Vb=cr("fs");function Yb(t,e,r){Vb.stat(t,function(n,s){r(n,n?!1:Jb(s,e))})}function VI(t,e){return Jb(Vb.statSync(t),e)}function Jb(t,e){return t.isFile()&&YI(t,e)}function YI(t,e){var r=t.mode,n=t.uid,s=t.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),i=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),u=a|l,d=r&c||r&l&&s===i||r&a&&n===o||r&u&&o===0;return d}});var ev=$((Y3,Qb)=>{"use strict";var V3=cr("fs"),Xa;process.platform==="win32"||global.TESTING_WINDOWS?Xa=Kb():Xa=Zb();Qb.exports=Uh;Uh.sync=JI;function Uh(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,s){Uh(t,e||{},function(o,i){o?s(o):n(i)})})}Xa(t,e||{},function(n,s){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,s=!1),r(n,s)})}function JI(t,e){try{return Xa.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var av=$((J3,iv)=>{"use strict";var ds=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",tv=cr("path"),XI=ds?";":":",rv=ev(),nv=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),sv=(t,e)=>{let r=e.colon||XI,n=t.match(/\//)||ds&&t.match(/\\/)?[""]:[...ds?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=ds?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=ds?s.split(r):[""];return ds&&t.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:n,pathExt:o,pathExtExe:s}},ov=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:s,pathExtExe:o}=sv(t,e),i=[],a=c=>new Promise((u,d)=>{if(c===n.length)return e.all&&i.length?u(i):d(nv(t));let h=n[c],p=/^".*"$/.test(h)?h.slice(1,-1):h,m=tv.join(p,t),f=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;u(l(f,c,0))}),l=(c,u,d)=>new Promise((h,p)=>{if(d===s.length)return h(a(u+1));let m=s[d];rv(c+m,{pathExt:o},(f,g)=>{if(!f&&g)if(e.all)i.push(c+m);else return h(c+m);return h(l(c,u,d+1))})});return r?a(0).then(c=>r(null,c),r):a(0)},ZI=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:s}=sv(t,e),o=[];for(let i=0;i<r.length;i++){let a=r[i],l=/^".*"$/.test(a)?a.slice(1,-1):a,c=tv.join(l,t),u=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+c:c;for(let d=0;d<n.length;d++){let h=u+n[d];try{if(rv.sync(h,{pathExt:s}))if(e.all)o.push(h);else return h}catch{}}}if(e.all&&o.length)return o;if(e.nothrow)return null;throw nv(t)};iv.exports=ov;ov.sync=ZI});var cv=$((X3,qh)=>{"use strict";var lv=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};qh.exports=lv;qh.exports.default=lv});var pv=$((Z3,hv)=>{"use strict";var uv=cr("path"),QI=av(),eO=cv();function dv(t,e){let r=t.options.env||process.env,n=process.cwd(),s=t.options.cwd!=null,o=s&&process.chdir!==void 0&&!process.chdir.disabled;if(o)try{process.chdir(t.options.cwd)}catch{}let i;try{i=QI.sync(t.command,{path:r[eO({env:r})],pathExt:e?uv.delimiter:void 0})}catch{}finally{o&&process.chdir(n)}return i&&(i=uv.resolve(s?t.options.cwd:"",i)),i}function tO(t){return dv(t)||dv(t,!0)}hv.exports=tO});var fv=$((Q3,Wh)=>{"use strict";var Bh=/([()\][%!^"`<>&|;, *?])/g;function rO(t){return t=t.replace(Bh,"^$1"),t}function nO(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Bh,"^$1"),e&&(t=t.replace(Bh,"^$1")),t}Wh.exports.command=rO;Wh.exports.argument=nO});var gv=$((eK,mv)=>{"use strict";mv.exports=/^#!(.*)/});var wv=$((tK,yv)=>{"use strict";var sO=gv();yv.exports=(t="")=>{let e=t.match(sO);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?n:n?`${s} ${n}`:s}});var vv=$((rK,bv)=>{"use strict";var Hh=cr("fs"),oO=wv();function iO(t){let r=Buffer.alloc(150),n;try{n=Hh.openSync(t,"r"),Hh.readSync(n,r,0,150,0),Hh.closeSync(n)}catch{}return oO(r.toString())}bv.exports=iO});var xv=$((nK,_v)=>{"use strict";var aO=cr("path"),Sv=pv(),kv=fv(),lO=vv(),cO=process.platform==="win32",uO=/\.(?:com|exe)$/i,dO=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function hO(t){t.file=Sv(t);let e=t.file&&lO(t.file);return e?(t.args.unshift(t.file),t.command=e,Sv(t)):t.file}function pO(t){if(!cO)return t;let e=hO(t),r=!uO.test(e);if(t.options.forceShell||r){let n=dO.test(e);t.command=aO.normalize(t.command),t.command=kv.command(t.command),t.args=t.args.map(o=>kv.argument(o,n));let s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function fO(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:pO(n)}_v.exports=fO});var $v=$((sK,Ev)=>{"use strict";var Gh=process.platform==="win32";function Kh(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function mO(t,e){if(!Gh)return;let r=t.emit;t.emit=function(n,s){if(n==="exit"){let o=Tv(s,e);if(o)return r.call(t,"error",o)}return r.apply(t,arguments)}}function Tv(t,e){return Gh&&t===1&&!e.file?Kh(e.original,"spawn"):null}function gO(t,e){return Gh&&t===1&&!e.file?Kh(e.original,"spawnSync"):null}Ev.exports={hookChildProcess:mO,verifyENOENT:Tv,verifyENOENTSync:gO,notFoundError:Kh}});var Cv=$((oK,hs)=>{"use strict";var Pv=cr("child_process"),Vh=xv(),Yh=$v();function Rv(t,e,r){let n=Vh(t,e,r),s=Pv.spawn(n.command,n.args,n.options);return Yh.hookChildProcess(s,n),s}function yO(t,e,r){let n=Vh(t,e,r),s=Pv.spawnSync(n.command,n.args,n.options);return s.error=s.error||Yh.verifyENOENTSync(s.status,n),s}hs.exports=Rv;hs.exports.spawn=Rv;hs.exports.sync=yO;hs.exports._parse=Vh;hs.exports._enoent=Yh});var Dv=$(Xh=>{"use strict";var Iv=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,_O=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Ov=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xO=/\\([\u000b\u0020-\u00ff])/g,TO=/([\\"])/g,Nv=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Xh.format=EO;Xh.parse=$O;function EO(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Nv.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var s,o=Object.keys(e).sort(),i=0;i<o.length;i++){if(s=o[i],!Ov.test(s))throw new TypeError("invalid parameter name");n+="; "+s+"="+RO(e[s])}return n}function $O(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?PO(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!Nv.test(n))throw new TypeError("invalid media type");var s=new CO(n.toLowerCase());if(r!==-1){var o,i,a;for(Iv.lastIndex=r;i=Iv.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,o=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(xO,"$1"))),s.parameters[o]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return s}function PO(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function RO(t){var e=String(t);if(Ov.test(e))return e;if(e.length>0&&!_O.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(TO,"\\$1")+'"'}function CO(t){this.parameters=Object.create(null),this.type=t}});import{createHash as Tx}from"crypto";var zf=new WeakMap;function Ti(t){return performance.now()-t}function Ex(t){if(t)return Tx("sha256").update(t).digest("hex").slice(0,16)}function jf(t){return zf.get(t)??{model:"unknown",protocol:t.protocol??"unknown"}}function $x(t,e){let r=In(),n={cache_creation:t.cacheCreationInputTokens,cache_read:t.cacheReadInputTokens,input:t.inputTokens,output:t.outputTokens};for(let[s,o]of Object.entries(n))o>0&&r.recordMetric("yukino.llm.tokens","counter",o,{...e,"token.type":s})}function Ei(t,e){return zf.set(t,e),t}function Lf(t,e){let r=In(),n=jf(e),s=Ex(t),o={protocol:n.protocol,...s?{"session.hash":s}:{}};return r.recordMetric("yukino.agent.runs","counter",1,{protocol:n.protocol}),{observation:r.startObservation("agent","yukino.agent.run",o),protocol:n.protocol,startedAt:performance.now()}}function Ff(t,e){let r=In();t.observation.update({metadata:{outcome:e}}),t.observation.end(),r.recordMetric("yukino.agent.duration","histogram",Ti(t.startedAt),{outcome:e,protocol:t.protocol})}async function*Uf(t,e,r){let n=In(),s=jf(t),o={model:s.model,protocol:s.protocol},i=r.observation.startChild("generation","yukino.llm.generate",o),a=performance.now(),l,c="incomplete";n.recordMetric("yukino.llm.requests","counter",1,o);try{for await(let u of e){if(!l&&u.type!=="stream_end"&&(l=new Date,n.recordMetric("yukino.llm.time_to_first_token","histogram",Ti(a),o)),u.type==="stream_end"){c="completed";let d={cacheCreationInput:u.usage.cacheCreationInputTokens,cacheReadInput:u.usage.cacheReadInputTokens,input:u.usage.inputTokens,output:u.usage.outputTokens};i.update({completionStartTime:l,metadata:{outcome:c,protocol:s.protocol,stopReason:u.stopReason},model:s.model,usageDetails:d}),$x(u.usage,o)}yield u}}catch(u){throw c="error",i.recordException(u),i.update({metadata:{outcome:c,protocol:s.protocol}}),n.emitLog("yukino.llm.error","error",{"error.type":u instanceof Error?u.name:typeof u,...o}),u}finally{i.end(),n.recordMetric("yukino.llm.duration","histogram",Ti(a),{...o,outcome:c})}}async function qf(t,e,r){let n=In(),s={tool:t},o=r.observation.startChild("tool","yukino.tool.execute",s),i=performance.now(),a="error";n.recordMetric("yukino.tool.calls","counter",1,s);try{let l=await e();return a=l.isError?"error":"completed",o.update({level:l.isError?"ERROR":"DEFAULT",metadata:{outcome:a,tool:t},...l.isError?{statusMessage:"Tool returned an error"}:{}}),l}catch(l){throw o.recordException(l),n.emitLog("yukino.tool.error","error",{"error.type":l instanceof Error?l.name:typeof l,tool:t}),l}finally{o.end(),n.recordMetric("yukino.tool.duration","histogram",Ti(i),{outcome:a,tool:t})}}var Wf={end:()=>{},recordException:()=>{},startChild:()=>Wf,update:()=>{}},Pc={captureError:()=>{},emitLog:()=>{},flush:()=>Promise.resolve(),recordMetric:()=>{},setMode:()=>{},shutdown:()=>Promise.resolve(),startObservation:()=>Wf},Gt=Pc,Hf="unknown",On=null,$i=null,Bf=!1;function $c(t){return t?.split(",").map(e=>e.trim()).some(e=>e.length>0&&e!=="none")??!1}function Rx(){let t=process.env.OTEL_SDK_DISABLED?.toLowerCase()!=="true",e=$c(process.env.OTEL_TRACES_EXPORTER)||$c(process.env.OTEL_LOGS_EXPORTER)||$c(process.env.OTEL_METRICS_EXPORTER),r=!!(process.env.LANGFUSE_PUBLIC_KEY&&process.env.LANGFUSE_SECRET_KEY);return!!process.env.SENTRY_DSN||t&&(e||r)}function In(){return Gt}async function v2(){if(On)return On;if(Rx())return On=import("./providers-YG2HYIG6.js").then(async({createTelemetryRuntime:t})=>{Gt=await t(),Gt.setMode(Hf),process.once("beforeExit",()=>{Cx()})}).catch(()=>{Gt=Pc}),On}function S2(t){Hf=t,Gt.setMode(t)}function k2(t,e){Gt.captureError(t,e)}async function Cx(){await On,await Gt.flush()}async function Mx(){return $i||($i=(async()=>{await On,await Gt.shutdown(),Gt=Pc})(),$i)}function _2(t){if(Bf)return;Bf=!0;let e=(r,n)=>{let s=()=>{process.off(r,s),Promise.resolve(t?.(n)).catch(()=>{}).finally(()=>{Mx().finally(()=>{process.exit(n)})})};process.once(r,s)};e("SIGINT",130),e("SIGTERM",143)}import{createHash as Ax}from"crypto";import{existsSync as Pi,mkdirSync as Rc,readFileSync as Hr,unlinkSync as Ri,writeFileSync as Ns}from"fs";import{dirname as Gf,join as Ds,resolve as Ix}from"path";var Et=C({module:"file-history"}),Cc=100,Kf=60,Ox=y.object({backupPath:y.string(),time:y.string(),unavailable:y.literal(!0).optional()}),Nx=y.object({messageIndex:y.number(),userText:y.string(),backups:y.record(y.string(),Ox),timestamp:y.string(),sessionLineCount:y.number().optional()}),Dx=y.discriminatedUnion("state",[y.object({state:y.literal("existing"),backupPath:y.string()}),y.object({state:y.literal("absent")}),y.object({state:y.literal("unavailable")})]),zx=y.object({version:y.literal(1),trackedFiles:y.array(y.string()),snapshots:y.array(Nx),baselines:y.record(y.string(),Dx).optional(),nextSnapshotSeq:y.number().optional()});function Yf(t){return Ax("sha256").update(t).digest("hex").slice(0,16)}function jx(t,e){return`${Yf(t)}@s${String(e)}`}function Lx(t){return`${Yf(t)}@baseline`}function Ci(t,e){return Ds(t,".yukino","file-history",e)}var Vf=class{sessionDir;trackedFiles=new Set;baselines=new Map;snapshots=[];nextSnapshotSeq=0;constructor(e,r){this.sessionDir=Ci(e,r),Rc(this.sessionDir,{recursive:!0}),this.load()}trackEdit(e){let r=Ix(e);this.trackedFiles.has(r)||(this.baselines.set(r,this.captureBaseline(r)),this.trackedFiles.add(r)),this.save()}captureBaseline(e){let r;try{r=Hr(e)}catch(s){let o=y.looseObject({code:y.string().optional()}).safeParse(s);return o.success&&o.data.code==="ENOENT"?{state:"absent"}:(Et.error({err:s},"file-history baseline capture failed"),{state:"unavailable"})}let n=Ds(this.sessionDir,Lx(e));try{return Ns(n,r),{state:"existing",backupPath:n}}catch(s){return Et.error({err:s},"file-history baseline capture failed"),{state:"unavailable"}}}makeSnapshot(e,r,n){let s=r;s.length>Kf&&(s=s.slice(0,Kf)+"...");let o=new Date().toISOString(),i=this.nextSnapshotSeq;this.nextSnapshotSeq++;let a={};for(let l of this.trackedFiles){let c=Ds(this.sessionDir,jx(l,i));if(!Pi(l)){a[l]={backupPath:c,time:o};continue}try{Ns(c,Hr(l))}catch(u){Et.error({err:u},"file-history operation failed"),a[l]={backupPath:c,time:o,unavailable:!0};continue}a[l]={backupPath:c,time:o}}if(this.snapshots.push({messageIndex:e,userText:s,backups:a,timestamp:o,...n===void 0?{}:{sessionLineCount:n}}),this.snapshots.length>Cc){let l=this.snapshots.slice(0,this.snapshots.length-Cc);this.snapshots=this.snapshots.slice(this.snapshots.length-Cc),this.deleteBackups(l)}this.save()}rewind(e){if(e<0||e>=this.snapshots.length)throw new Error(`Invalid snapshot index: ${String(e)}`);let r=this.snapshots[e],n=[];for(let[a,l]of Object.entries(r.backups)){if(l.unavailable)continue;let c=null;try{c=Hr(l.backupPath)}catch{if(Pi(a))try{Ri(a),n.push(a)}catch(p){Et.error({err:p},"file-history operation failed")}continue}let u=null;try{u=Hr(a)}catch(p){Et.error({err:p},"file-history operation failed")}let d=c.toString(),h=u?.toString();if(d!==h)try{Rc(Gf(a),{recursive:!0}),Ns(a,c),n.push(a)}catch(p){Et.error({err:p},"file-history operation failed")}}let s=[...this.trackedFiles].filter(a=>!(a in r.backups)),o=new Set;for(let a of s){let l=this.baselines.get(a),c=!1;if(l?.state==="existing"){try{let u=Hr(l.backupPath),d=null;try{d=Hr(a)}catch{}(!d||!u.equals(d))&&(Rc(Gf(a),{recursive:!0}),Ns(a,u),n.push(a)),c=!0}catch(u){Et.error({err:u},"file-history baseline restore failed")}if(c)try{Ri(l.backupPath)}catch{}}else if(l?.state==="absent")if(!Pi(a))c=!0;else try{Ri(a),n.push(a),c=!0}catch(u){Et.error({err:u},"file-history baseline delete failed")}c?this.baselines.delete(a):o.add(a)}let i=this.snapshots.slice(e+1);return this.deleteBackups(i),this.snapshots=this.snapshots.slice(0,e+1),this.trackedFiles=new Set([...Object.keys(r.backups),...o]),this.save(),n}deleteBackups(e){for(let r of e)for(let n of Object.values(r.backups))try{Ri(n.backupPath)}catch{}}getSnapshots(){return[...this.snapshots]}hasSnapshots(){return this.snapshots.length>0}save(){let e={version:1,trackedFiles:[...this.trackedFiles],snapshots:this.snapshots,baselines:Object.fromEntries(this.baselines),nextSnapshotSeq:this.nextSnapshotSeq};try{Ns(Ds(this.sessionDir,"snapshots.json"),JSON.stringify(e,null,2),"utf-8")}catch(r){Et.error({err:r},"file-history operation failed")}}load(){let e=Ds(this.sessionDir,"snapshots.json");if(!Pi(e))return;let r;try{r=JSON.parse(Hr(e,"utf-8"))}catch(o){Et.error({err:o},"file-history operation failed");return}let n=it(zx,r);if(!n.success){Et.error({err:n.error},"file-history operation failed");return}let s=n.data;this.snapshots=s.snapshots,this.nextSnapshotSeq=s.nextSnapshotSeq??s.snapshots.length;for(let[o,i]of Object.entries(s.baselines??{}))this.baselines.set(o,i);if(s.trackedFiles.length>0)for(let o of s.trackedFiles)this.trackedFiles.add(o);else if(s.snapshots.length>0){let o=s.snapshots[s.snapshots.length-1];for(let i of Object.keys(o.backups))this.trackedFiles.add(i)}for(let o of this.trackedFiles)this.baselines.has(o)||this.baselines.set(o,{state:"unavailable"})}};import{readFileSync as rm,statSync as lT}from"fs";import{isAbsolute as cT,join as uT}from"path";import{readFileSync as eT,statSync as tT}from"fs";import{extname as rT}from"path";import Oc from"sharp";import{spawn as Fx}from"child_process";import{createHash as Ux}from"crypto";import{mkdir as Mc,readFile as Zf,rm as qx,writeFile as Bx}from"fs/promises";import{join as Qf}from"path";var Jf=5e3,Ac=32*1024*1024,Wx=16*1024,zs="The clipboard does not contain an image.",Xf=Buffer.from([137,80,78,71,13,10,26,10]);function Hx(t){return t.length>Xf.length&&t.subarray(0,8).equals(Xf)}function Gx(t){return`${Ux("sha256").update(t).digest("hex").slice(0,16)}.png`}async function Kx(t,e,r){if(!Hx(r))throw new Error("Clipboard data is not a PNG image.");if(r.length>Ac)throw new Error(`Clipboard image is too large (${String(r.length)} bytes, limit ${String(Ac)}).`);let n=Ci(t,e);await Mc(n,{recursive:!0});let s=Qf(n,Gx(r));return await Bx(s,r),s}function Ic(t,e,r){return new Promise((n,s)=>{let o=Fx(t,[...e],{shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:r?{...process.env,...r}:process.env}),i=!1,a=0,l=0,c=[],u=[],d=p=>{i||(i=!0,clearTimeout(h),p())},h=setTimeout(()=>{o.kill(),d(()=>{s(new Error(`${t} timed out after ${String(Jf)}ms.`))})},Jf);if(!o.stdout||!o.stderr){o.kill(),d(()=>{s(new Error(`${t} pipes were not created.`))});return}o.stdout.on("data",p=>{if(a+=p.length,a>Ac){o.kill(),d(()=>{s(new Error(`${t} produced more than the clipboard image byte limit.`))});return}c.push(p)}),o.stderr.on("data",p=>{let m=Wx-l;if(m>0){let f=p.subarray(0,m);l+=f.length,u.push(f)}}),o.on("error",p=>{d(()=>{s(p.code==="ENOENT"?new Error(`${t} is not installed or not on PATH.`):p)})}),o.on("close",p=>{d(()=>{n({code:p??1,stdout:Buffer.concat(c),stderr:Buffer.concat(u).toString("utf8").trim()})})})})}var Vx=["on run argv","set d to the clipboard as \xABclass PNGf\xBB","set f to open for access POSIX file (item 1 of argv) with write permission","set eof f to 0","write d to f","close access f","end run"];async function Yx(t){let e=[...Vx.flatMap(n=>["-e",n]),t],r=await Ic("/usr/bin/osascript",e);if(r.code!==0)throw r.stderr.includes("-1700")?new Error(zs):new Error(`osascript failed: ${r.stderr||`exit ${String(r.code)}`}`);return Zf(t)}async function Jx(){let t=[];if(process.env.WAYLAND_DISPLAY&&t.push({command:"wl-paste",args:["--no-newline","--type","image/png"],hint:"Install wl-clipboard (provides wl-paste)."}),process.env.DISPLAY&&t.push({command:"xclip",args:["-selection","clipboard","-t","image/png","-o"],hint:"Install xclip with your system package manager."}),t.length===0)throw new Error("No Wayland or X11 session found (WAYLAND_DISPLAY and DISPLAY are unset).");let e=new Error(zs);for(let r of t)try{let n=await Ic(r.command,r.args);if(n.code===0&&n.stdout.length>0)return n.stdout;let s=n.stderr.toLowerCase();e=s.includes("target")||s.includes("no suitable")||s.includes("nothing")?new Error(zs):new Error(`${r.command} failed: ${n.stderr||`exit ${String(n.code)}`}`)}catch(n){e=new Error(`${n instanceof Error?n.message:String(n)} ${r.hint}`.trim())}throw e}var Xx=["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing","$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($null -eq $img) { exit 3 }","$img.Save($env:YUKINO_CLIPBOARD_PATH, [System.Drawing.Imaging.ImageFormat]::Png)","$img.Dispose()"].join("; ");async function Zx(t){let e=await Ic("powershell.exe",["-NoProfile","-NonInteractive","-Sta","-Command",Xx],{YUKINO_CLIPBOARD_PATH:t});if(e.code===3)throw new Error(zs);if(e.code!==0)throw new Error(`powershell failed: ${e.stderr||`exit ${String(e.code)}`}`);return Zf(t)}async function D2(t,e){let r=Ci(t,e),n=Qf(r,`.clipboard-${String(process.pid)}.tmp`);try{let s;switch(process.platform){case"darwin":await Mc(r,{recursive:!0}),s=await Yx(n);break;case"linux":s=await Jx();break;case"win32":await Mc(r,{recursive:!0}),s=await Zx(n);break;default:return{ok:!1,reason:`Clipboard image paste is not supported on ${process.platform}.`}}return s.length===0?{ok:!1,reason:zs}:{ok:!0,value:await Kx(t,e,s)}}catch(s){return{ok:!1,reason:s instanceof Error?s.message:String(s)}}finally{await qx(n,{force:!0}).catch(()=>{})}}var nT=C({module:"images"});function tm(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var Dc=5*1024*1024,Mi=Dc*3/4,em=50*1024*1024,dr=2e3,zc=10,Gr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},sT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function oT(t){return sT[rT(t).toLowerCase()]??null}function Ai(t){return oT(t)!==null}function iT(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function Ii(t){let e=tT(t);if(!e.isFile())throw new Error(`Not a file: ${t}`);if(e.size>em)throw new Gr(`Image file is ${hr(e.size)} on disk; files over ${hr(em)} are not read. Please provide a smaller image.`);let r=eT(t),n=iT(r);if(!n)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let s=await js(r,n);return{mediaType:s.mediaType,data:s.data,sourcePath:t,byteLength:s.byteLength}}function Nc(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function hr(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function js(t,e){if(t.length===0)throw new Gr("Image file is empty (0 bytes)");if(t.length<=Mi)return Nc(t,e);try{return await aT(t,e)}catch(r){throw r instanceof Gr?r:(nT.warn({err:r},"sharp compression failed"),new Gr(`Image is ${hr(t.length)} raw (${hr(t.length*4/3)} base64-encoded, API limit ${hr(Dc)}) and compression failed. Please provide a smaller image.`))}}async function aT(t,e){let r=await Oc(t).metadata(),n=r.width??dr,s=r.height??dr;n>dr&&(s=Math.max(1,Math.round(s*dr/n)),n=dr),s>dr&&(n=Math.max(1,Math.round(n*dr/s)),s=dr);let o=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(o){let a=await Oc(t).resize(n,s,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=Mi)return Nc(a,"image/png")}for(let a of[80,60,40,20]){let l=await Oc(t).resize(n,s,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(l.length<=Mi)return Nc(l,"image/jpeg")}n=Math.max(1,Math.round(n/2)),s=Math.max(1,Math.round(s/2))}throw new Gr(`Unable to compress image (${hr(t.length)} raw) under the ${hr(Dc)} base64 API limit (raw bytes must be \u2264${hr(Mi)}). Please provide a smaller image.`)}var nm=C({module:"at-expand"}),sm=1e5,dT=1e7;function hT(t){let e=/^(.+)#L(\d+)(?:-(\d+))?$/.exec(t);if(!e)return{path:t};let r=Number.parseInt(e[2],10);return{path:e[1],lineStart:r,lineEnd:e[3]?Number.parseInt(e[3],10):r}}function pT(t,e,r){let n=t.split(`
12
12
  `),s=Math.max(1,e),o=Math.min(n.length,Math.max(r,s));return n.slice(s-1,o).join(`
13
13
  `)}function fT(t){let e=/(?:^|\s)(?:'@([^']+)'|"@([^"]+)"|@"([^"]+)"|@'([^']+)'|@([^\s]+))/g;return[...t.matchAll(e)].map(r=>r[1]??r[2]??r[3]??r[4]??r[5])}async function G2(t,e){let r=fT(t);if(r.length===0)return t;let n="",s=new Set,o=[];for(let a of r){if(s.has(a))continue;s.add(a);let{path:l,lineStart:c,lineEnd:u}=hT(a),d=cT(l)?l:uT(e,l);try{let h=lT(d);if(!h.isFile())continue;if(Ai(d)){if(o.length>=zc){n+=`
14
14
 
@@ -168,7 +168,7 @@ ${n}`)].filter(Boolean).join(`
168
168
  `);this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,e)}async*run(){let e=Lf(this.sessionId,this.client);this.restoreContext();let r=this.registry.getAllSchemas(this.client.protocol??"anthropic",this.toolFilter),n=this.registry.listVisibleToolNames(this.client.protocol??"anthropic",this.toolFilter),s=!1,o=0,i=0,a=0;await this.fireLifecycle("session_start");try{let l=!0;for(;l;){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(a++,this.maxIterations>0&&a>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let c="",u=[],d=[],h="end_turn",p=null;if(this.checker.mode==="plan"){let f=Bi(this.workDir);this.checker.planFilePath=f,this.conversation.addSystemReminder(Fm(f,Lm(this.workDir),a))}this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(Um(a));let m=this.registry.getDeferredToolNames();if(m.length>0&&(m.length!==this.announcedDeferred.length||m.some((g,w)=>g!==this.announcedDeferred[w])||!this.conversation.hasReminderContaining(Zm))){let g=Zm+' Their schemas are NOT loaded - use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas';g+=this.registry.mcpLoadingMode==="dispatch"?", then invoke them with the McpCall tool":" before calling them",this.conversation.addSystemReminder(g+`:
169
169
  `+m.join(`
170
170
  `)),this.announcedDeferred=m}if(this.hookEngine)for(let f of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(f);if(this.notificationFn)for(let f of this.notificationFn())this.conversation.addSystemReminder(f);if(this.skillDeltaFn){let f=this.skillDeltaFn();f&&this.conversation.addSystemReminder(`The following skills became available:
171
- `+f)}await this.fireLifecycle("turn_start");try{await this.fireLifecycle("pre_send");for(let g of this.hookEngine?.drainNotifications()??[])this.conversation.addSystemReminder(g);let f=await Rm(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,n,r,this.sessionFilePath,this.abortSignal);if(f.message&&(yield{type:"compact",message:f.message,boundary:f.boundary}),f.compacted&&this.restoreContext(),this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}try{let g=Uf(this.client,this.client.stream(this.conversation,r,this.abortSignal),e);for await(let w of g){if(this.abortSignal?.aborted){l=!1;break}switch(w.type){case"text_delta":c+=w.text,yield{type:"stream_text",text:w.text};break;case"thinking_delta":yield{type:"thinking_text",text:w.text};break;case"thinking_complete":u.push({thinking:w.thinking,signature:w.signature}),yield{type:"thinking_complete",thinking:w.thinking,signature:w.signature};break;case"tool_call_start":break;case"tool_call_complete":d.push({toolUseId:w.toolId,toolName:w.toolName,arguments:w.arguments,...w.parseError?{parseError:w.parseError}:{},...w.providerItemId?{providerItemId:w.providerItemId}:{}}),yield{type:"tool_use",toolName:w.toolName,toolId:w.toolId,args:w.arguments};break;case"stream_end":h=w.stopReason,p=w.usage,yield{type:"usage",usage:w.usage};break}}}catch(g){if(this.abortSignal?.aborted){(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(g instanceof Os)try{let w=await Cm(this.conversation,this.client,this.recoveryState,n,r,this.sessionFilePath,this.abortSignal);if(!w.compacted){yield{type:"error",error:g};return}this.conversation.clearUsageAnchor(),this.restoreContext(),yield{type:"compact",message:"Auto-compacted due to context length: "+w.message,boundary:w.boundary};continue}catch{yield{type:"error",error:g};return}if(g instanceof Af){if(i>=EE){yield{type:"error",error:g};return}i++;let w=PE(g.retryAfter);if(yield{type:"retry",reason:"rate limited",delay:w},await this.interruptibleSleep(w)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"error",error:g instanceof Error?g:new Error(M(g))};return}if(i=0,this.abortSignal?.aborted){(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",c),h==="max_tokens"){let g=Math.min(TE,this.contextWindow);if(!s&&this.maxOutput<g&&this.client.setMaxOutputTokens){this.client.setMaxOutputTokens?.(g),this.maxOutput=g,s=!0,(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else if(o<Jm){o++,(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces.")),yield{type:"retry",reason:`max_tokens recovery ${String(o)}/${String(Jm)}`,delay:0};continue}}else o=0;if((c||u.length>0||d.length>0)&&(this.conversation.addAssistantFull(c,u,d),this.persistLastMessage()),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),d.length>0){let g=await this.executeTools(d,e);for(let _ of g)yield _;let w=new Set;for(let _ of d)Km(_.toolName,_.arguments,this.workDir,this.sessionId)&&w.add(_.toolUseId);let b=[];for(let _ of g)if(_.type==="tool_result"){let S={toolUseId:_.toolId,content:_.output,..._.contentBlocks?.length?{contentBlocks:_.contentBlocks}:{},isError:_.isError};if(S.content.length>$E&&!w.has(_.toolId)){let x=Ym(this.workDir,this.sessionId,_.toolId,S.content);x!==S.content&&Kc(S,x),w.add(_.toolId)}b.push(S)}Vm(b,this.workDir,this.sessionId,w);let k=d.some(_=>{if(_.toolName!=="ExitPlanMode")return!1;let S=g.find(x=>x.type==="tool_result"&&x.toolId===_.toolUseId);return S?.type==="tool_result"&&!S.isError});if(this.conversation.addToolResultsMessage(b),this.persistLastMessage(),this.abortSignal?.aborted){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"interrupted"};return}if(this.memoryRecallPromise&&!this.memoryRecallConsumed&&this.memoryRecallSettled){let _=this.memoryRecallValue;_?.reminder&&(this.conversation.addSystemReminder(_.reminder),this.onMemoriesSurfaced?.(_.paths)),this.memoryRecallConsumed=!0}if(k){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},yield*this.deliverSteering()}else{if((yield*this.deliverSteering()).length>0){yield{type:"turn_complete"};continue}if(l=!1,this.fileHistory){let w=c.length>60?c.slice(0,60)+"...":c;this.fileHistory.makeSnapshot(this.conversation.len(),w,xm(this.sessionFilePath))}if(yield{type:"loop_complete",stopReason:h},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}finally{await this.fireLifecycle("turn_end")}}}finally{try{await this.fireLifecycle("session_end")}finally{Ff(e,this.abortSignal?.aborted?"interrupted":"completed")}}}async fireLifecycle(e,r){if(!this.hookEngine)return;let n=await this.hookEngine.fire(e,{event:e,message:r},{workDir:this.workDir,abortSignal:this.abortSignal});for(let s of n)s.output&&this.hookEngine.recordNotification(s.output)}interruptibleSleep(e){return new Promise(r=>{if(this.abortSignal?.aborted){r(!0);return}let n=()=>{clearTimeout(s),r(!0)},s=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",n),r(!1)},e);this.abortSignal?.addEventListener("abort",n,{once:!0})})}async executeTools(e,r){let n=[],s=this.partitionToolCalls(e);for(let o of s){let i=await this.executeBatch(o.blocks,o.concurrent&&o.blocks.length>1,r);n.push(...i)}return n}partitionToolCalls(e){let r=[];for(let n of e){let s=this.registry.get(n.toolName),o=s?s.isConcurrencySafe?.(n.arguments??{})??s.category==="read":!1;o&&r.length>0&&r[r.length-1].concurrent?r[r.length-1].blocks.push(n):r.push({concurrent:o,blocks:[n]})}return r}async executeBatch(e,r,n){let s=[],o=new Wi(this.registry,{workDir:this.workDir,sessionId:this.sessionId,taskManager:this.taskManager,abortSignal:this.abortSignal,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache,permissionChecker:this.checker,onPermissionRequest:this.onPermissionRequest},n);for(let i of e){if(i.parseError){if(o.submit(i.toolUseId,i.toolName,i.arguments,i.parseError),!r){let h=await o.collectResults();for(let p of h)await this.processToolResult(p,e,s)}continue}if(this.abortSignal?.aborted){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:"Error: command interrupted",isError:!0,elapsed:0});continue}if(this.toolFilter&&!this.toolFilter(i.toolName)){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Tool '${i.toolName}' is not available to this agent.`,isError:!0,elapsed:0});continue}if(this.hookEngine){let h=await this.hookEngine.firePreToolHooks(i.toolName,i.arguments,{workDir:this.workDir,abortSignal:this.abortSignal});if(h.rejected){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Rejected by hook: ${h.reason}`,isError:!0,elapsed:0});continue}}let a=this.registry.get(i.toolName),l=a?.category??"command",c=a instanceof xi?a.resolveTarget(i.arguments):void 0;if(c&&(!this.registry.get(c.name)||this.toolFilter&&!this.toolFilter(c.name))){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Tool '${c.name}' is not available to this agent.`,isError:!0,elapsed:0});continue}let u=[this.checker.check(i.toolName,l,i.arguments)];c&&u.push(this.checker.check(c.name,c.category,Wr(i.arguments.arguments??{})));let d=u.find(h=>h.effect==="deny")??u.find(h=>h.effect==="ask")??u[0];if(d.effect==="deny"){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Permission denied: ${d.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(d.effect==="ask"&&!this.onPermissionRequest){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:"Permission required, but this agent has no approval handler. The tool was not executed.",isError:!0,elapsed:0});continue}if(d.effect==="ask"&&this.onPermissionRequest){let h;try{h=await this.onPermissionRequest(i.toolName,i.arguments,d,i.toolUseId),h==="allowAlways"&&!this.abortSignal?.aborted&&this.checker.allowAlways(i.toolName,i.arguments)}catch(p){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Permission request failed: ${M(p)}. The tool was not executed.`,isError:!0,elapsed:0});continue}if(h==="deny"){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:Mf,isError:!0,elapsed:0});continue}}if(o.submit(i.toolUseId,i.toolName,i.arguments),!r){let h=await o.collectResults();for(let p of h)await this.processToolResult(p,e,s)}}if(r){let i=await o.collectResults();for(let a of i)await this.processToolResult(a,e,s)}return s}async processToolResult(e,r,n){if(!e.result.isError&&e.toolName==="ReadFile"&&!e.result.contentBlocks?.length){let s=r.find(i=>i.toolUseId===e.toolId),o=T(s?.arguments??{},"file_path");o&&this.recoveryState.recordFileRead(o,e.result.output)}if(n.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,...e.result.contentBlocks?.length?{contentBlocks:e.result.contentBlocks}:{},isError:e.result.isError,elapsed:e.elapsed}),this.hookEngine){let s=r.find(i=>i.toolUseId===e.toolId)?.arguments,o=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,args:s,filePath:T(s??{},"file_path",T(s??{},"path","")),message:e.result.output},{workDir:this.workDir,abortSignal:this.abortSignal});for(let i of o)i.output&&this.hookEngine.recordNotification(i.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let r=e[e.length-1];Wc(this.workDir,this.sessionId,{role:r.role,content:r.content,timestamp:Math.floor(Date.now()/1e3),...r.toolUses?.length?{tool_uses:ji(r.toolUses)}:{},...r.toolResults?.length?{tool_results:Li(r.toolResults)}:{}})}};function PE(t){if(!t?.trim())return 5e3;let e=t.trim();if(/^\d+(?:\.\d+)?$/.test(e))return Math.min(Number(e)*1e3,Xm);let r=/^[A-Za-z]{3},/.test(e)?Date.parse(e):NaN;return Number.isFinite(r)?Math.min(Math.max(0,r-Date.now()),Xm):5e3}async function Fs(t,e){switch(t.protocol){case"anthropic":{let{AnthropicClient:r}=await import("./anthropic-3TRLGKHZ.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}case"openai":{let{OpenAIClient:r}=await import("./openai-PYPO6SKD.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}case"openai-compat":{let{OpenAICompatClient:r}=await import("./openai-PYPO6SKD.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}default:throw new Error(`Unknown protocol: ${String(t.protocol)}`)}}import{isDeepStrictEqual as DO}from"util";var jn="2025-11-25";var Qm=[jn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fr="io.modelcontextprotocol/related-task",Ki="2.0",ye=vf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),eg=ie([v(),V().int()]),tg=v(),uW=ge({ttl:V().optional(),pollInterval:V().optional()}),CE=R({ttl:V().optional()}),ME=R({taskId:v()}),Jc=ge({progressToken:eg.optional(),[fr]:ME.optional()}),lt=R({_meta:Jc.optional()}),Us=lt.extend({task:CE.optional()}),rg=t=>Us.safeParse(t).success,Te=R({method:v(),params:lt.loose().optional()}),mt=R({_meta:Jc.optional()}),gt=R({method:v(),params:mt.loose().optional()}),Ee=ge({_meta:Jc.optional()}),Vi=ie([v(),V().int()]),ng=R({jsonrpc:A(Ki),id:Vi,...Te.shape}).strict(),qs=t=>ng.safeParse(t).success,sg=R({jsonrpc:A(Ki),...gt.shape}).strict(),og=t=>sg.safeParse(t).success,Xc=R({jsonrpc:A(Ki),id:Vi,result:Ee}).strict(),Vr=t=>Xc.safeParse(t).success;var z;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(z||(z={}));var Zc=R({jsonrpc:A(Ki),id:Vi.optional(),error:R({code:V().int(),message:v(),data:de().optional()})}).strict();var ig=t=>Zc.safeParse(t).success;var mr=ie([ng,sg,Xc,Zc]),dW=ie([Xc,Zc]),Yr=Ee.strict(),AE=mt.extend({requestId:Vi.optional(),reason:v().optional()}),Yi=gt.extend({method:A("notifications/cancelled"),params:AE}),IE=R({src:v(),mimeType:v().optional(),sizes:P(v()).optional(),theme:at(["light","dark"]).optional()}),Bs=R({icons:P(IE).optional()}),zn=R({name:v(),title:v().optional()}),ag=zn.extend({...zn.shape,...Bs.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),OE=Tc(R({applyDefaults:Q().optional()}),re(v(),de())),NE=Ec(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Tc(R({form:OE.optional(),url:ye.optional()}),re(v(),de()).optional())),DE=ge({list:ye.optional(),cancel:ye.optional(),requests:ge({sampling:ge({createMessage:ye.optional()}).optional(),elicitation:ge({create:ye.optional()}).optional()}).optional()}),zE=ge({list:ye.optional(),cancel:ye.optional(),requests:ge({tools:ge({call:ye.optional()}).optional()}).optional()}),jE=R({experimental:re(v(),ye).optional(),sampling:R({context:ye.optional(),tools:ye.optional()}).optional(),elicitation:NE.optional(),roots:R({listChanged:Q().optional()}).optional(),tasks:DE.optional(),extensions:re(v(),ye).optional()}),LE=lt.extend({protocolVersion:v(),capabilities:jE,clientInfo:ag}),FE=Te.extend({method:A("initialize"),params:LE});var UE=R({experimental:re(v(),ye).optional(),logging:ye.optional(),completions:ye.optional(),prompts:R({listChanged:Q().optional()}).optional(),resources:R({subscribe:Q().optional(),listChanged:Q().optional()}).optional(),tools:R({listChanged:Q().optional()}).optional(),tasks:zE.optional(),extensions:re(v(),ye).optional()}),Qc=Ee.extend({protocolVersion:v(),capabilities:UE,serverInfo:ag,instructions:v().optional()}),lg=gt.extend({method:A("notifications/initialized"),params:mt.optional()}),cg=t=>lg.safeParse(t).success,Ji=Te.extend({method:A("ping"),params:lt.optional()}),qE=R({progress:V(),total:le(V()),message:le(v())}),BE=R({...mt.shape,...qE.shape,progressToken:eg}),Xi=gt.extend({method:A("notifications/progress"),params:BE}),WE=lt.extend({cursor:tg.optional()}),Ws=Te.extend({params:WE.optional()}),Hs=Ee.extend({nextCursor:tg.optional()}),HE=at(["working","input_required","completed","failed","cancelled"]),Gs=R({taskId:v(),status:HE,ttl:ie([V(),wf()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:le(V()),statusMessage:le(v())}),Jr=Ee.extend({task:Gs}),GE=mt.merge(Gs),Ks=gt.extend({method:A("notifications/tasks/status"),params:GE}),Zi=Te.extend({method:A("tasks/get"),params:lt.extend({taskId:v()})}),Qi=Ee.merge(Gs),ea=Te.extend({method:A("tasks/result"),params:lt.extend({taskId:v()})}),hW=Ee.loose(),ta=Ws.extend({method:A("tasks/list")}),ra=Hs.extend({tasks:P(Gs)}),na=Te.extend({method:A("tasks/cancel"),params:lt.extend({taskId:v()})}),ug=Ee.merge(Gs),dg=R({uri:v(),mimeType:le(v()),_meta:re(v(),de()).optional()}),hg=dg.extend({text:v()}),eu=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),pg=dg.extend({blob:eu}),Vs=at(["user","assistant"]),Ln=R({audience:P(Vs).optional(),priority:V().min(0).max(1).optional(),lastModified:kf.datetime({offset:!0}).optional()}),fg=R({...zn.shape,...Bs.shape,uri:v(),description:le(v()),mimeType:le(v()),size:le(V()),annotations:Ln.optional(),_meta:le(ge({}))}),KE=R({...zn.shape,...Bs.shape,uriTemplate:v(),description:le(v()),mimeType:le(v()),annotations:Ln.optional(),_meta:le(ge({}))}),VE=Ws.extend({method:A("resources/list")}),tu=Hs.extend({resources:P(fg)}),YE=Ws.extend({method:A("resources/templates/list")}),ru=Hs.extend({resourceTemplates:P(KE)}),nu=lt.extend({uri:v()}),JE=nu,XE=Te.extend({method:A("resources/read"),params:JE}),su=Ee.extend({contents:P(ie([hg,pg]))}),ou=gt.extend({method:A("notifications/resources/list_changed"),params:mt.optional()}),ZE=nu,QE=Te.extend({method:A("resources/subscribe"),params:ZE}),e$=nu,t$=Te.extend({method:A("resources/unsubscribe"),params:e$}),r$=mt.extend({uri:v()}),n$=gt.extend({method:A("notifications/resources/updated"),params:r$}),s$=R({name:v(),description:le(v()),required:le(Q())}),o$=R({...zn.shape,...Bs.shape,description:le(v()),arguments:le(P(s$)),_meta:le(ge({}))}),i$=Ws.extend({method:A("prompts/list")}),iu=Hs.extend({prompts:P(o$)}),a$=lt.extend({name:v(),arguments:re(v(),v()).optional()}),l$=Te.extend({method:A("prompts/get"),params:a$}),au=R({type:A("text"),text:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),lu=R({type:A("image"),data:eu,mimeType:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),cu=R({type:A("audio"),data:eu,mimeType:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),c$=R({type:A("tool_use"),name:v(),id:v(),input:re(v(),de()),_meta:re(v(),de()).optional()}),u$=R({type:A("resource"),resource:ie([hg,pg]),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),d$=fg.extend({type:A("resource_link")}),uu=ie([au,lu,cu,d$,u$]),h$=R({role:Vs,content:uu}),du=Ee.extend({description:v().optional(),messages:P(h$)}),hu=gt.extend({method:A("notifications/prompts/list_changed"),params:mt.optional()}),p$=R({title:v().optional(),readOnlyHint:Q().optional(),destructiveHint:Q().optional(),idempotentHint:Q().optional(),openWorldHint:Q().optional()}),f$=R({taskSupport:at(["required","optional","forbidden"]).optional()}),mg=R({...zn.shape,...Bs.shape,description:v().optional(),inputSchema:R({type:A("object"),properties:re(v(),ye).optional(),required:P(v()).optional()}).catchall(de()),outputSchema:R({type:A("object"),properties:re(v(),ye).optional(),required:P(v()).optional()}).catchall(de()).optional(),annotations:p$.optional(),execution:f$.optional(),_meta:re(v(),de()).optional()}),m$=Ws.extend({method:A("tools/list")}),pu=Hs.extend({tools:P(mg)}),Fn=Ee.extend({content:P(uu).default([]),structuredContent:re(v(),de()).optional(),isError:Q().optional()}),pW=Fn.or(Ee.extend({toolResult:de()})),g$=Us.extend({name:v(),arguments:re(v(),de()).optional()}),y$=Te.extend({method:A("tools/call"),params:g$}),fu=gt.extend({method:A("notifications/tools/list_changed"),params:mt.optional()}),gg=R({autoRefresh:Q().default(!0),debounceMs:V().int().nonnegative().default(300)}),yg=at(["debug","info","notice","warning","error","critical","alert","emergency"]),w$=lt.extend({level:yg}),b$=Te.extend({method:A("logging/setLevel"),params:w$}),v$=mt.extend({level:yg,logger:v().optional(),data:de()}),S$=gt.extend({method:A("notifications/message"),params:v$}),k$=R({name:v().optional()}),_$=R({hints:P(k$).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),x$=R({mode:at(["auto","required","none"]).optional()}),T$=R({type:A("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:P(uu).default([]),structuredContent:R({}).loose().optional(),isError:Q().optional(),_meta:re(v(),de()).optional()}),E$=xc("type",[au,lu,cu]),Gi=xc("type",[au,lu,cu,c$,T$]),$$=R({role:Vs,content:ie([Gi,P(Gi)]),_meta:re(v(),de()).optional()}),P$=Us.extend({messages:P($$),modelPreferences:_$.optional(),systemPrompt:v().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:P(v()).optional(),metadata:ye.optional(),tools:P(mg).optional(),toolChoice:x$.optional()}),mu=Te.extend({method:A("sampling/createMessage"),params:P$}),gu=Ee.extend({model:v(),stopReason:le(at(["endTurn","stopSequence","maxTokens"]).or(v())),role:Vs,content:E$}),yu=Ee.extend({model:v(),stopReason:le(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Vs,content:ie([Gi,P(Gi)])}),R$=R({type:A("boolean"),title:v().optional(),description:v().optional(),default:Q().optional()}),C$=R({type:A("string"),title:v().optional(),description:v().optional(),minLength:V().optional(),maxLength:V().optional(),format:at(["email","uri","date","date-time"]).optional(),default:v().optional()}),M$=R({type:at(["number","integer"]),title:v().optional(),description:v().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),A$=R({type:A("string"),title:v().optional(),description:v().optional(),enum:P(v()),default:v().optional()}),I$=R({type:A("string"),title:v().optional(),description:v().optional(),oneOf:P(R({const:v(),title:v()})),default:v().optional()}),O$=R({type:A("string"),title:v().optional(),description:v().optional(),enum:P(v()),enumNames:P(v()).optional(),default:v().optional()}),N$=ie([A$,I$]),D$=R({type:A("array"),title:v().optional(),description:v().optional(),minItems:V().optional(),maxItems:V().optional(),items:R({type:A("string"),enum:P(v())}),default:P(v()).optional()}),z$=R({type:A("array"),title:v().optional(),description:v().optional(),minItems:V().optional(),maxItems:V().optional(),items:R({anyOf:P(R({const:v(),title:v()}))}),default:P(v()).optional()}),j$=ie([D$,z$]),L$=ie([O$,N$,j$]),F$=ie([L$,R$,C$,M$]),U$=Us.extend({mode:A("form").optional(),message:v(),requestedSchema:R({type:A("object"),properties:re(v(),F$),required:P(v()).optional()})}),q$=Us.extend({mode:A("url"),message:v(),elicitationId:v(),url:v().url()}),B$=ie([U$,q$]),wu=Te.extend({method:A("elicitation/create"),params:B$}),W$=mt.extend({elicitationId:v()}),H$=gt.extend({method:A("notifications/elicitation/complete"),params:W$}),bu=Ee.extend({action:at(["accept","decline","cancel"]),content:Ec(t=>t===null?void 0:t,re(v(),ie([v(),V(),Q(),P(v())])).optional())}),G$=R({type:A("ref/resource"),uri:v()});var K$=R({type:A("ref/prompt"),name:v()}),V$=lt.extend({ref:ie([K$,G$]),argument:R({name:v(),value:v()}),context:R({arguments:re(v(),v()).optional()}).optional()}),Y$=Te.extend({method:A("completion/complete"),params:V$});var vu=Ee.extend({completion:ge({values:P(v()).max(100),total:le(V().int()),hasMore:le(Q())})}),J$=R({uri:v().startsWith("file://"),name:v().optional(),_meta:re(v(),de()).optional()}),X$=Te.extend({method:A("roots/list"),params:lt.optional()}),Z$=Ee.extend({roots:P(J$)}),Q$=gt.extend({method:A("notifications/roots/list_changed"),params:mt.optional()}),fW=ie([Ji,FE,Y$,b$,l$,i$,VE,YE,XE,QE,t$,y$,m$,Zi,ea,ta,na]),mW=ie([Yi,Xi,lg,Q$,Ks]),gW=ie([Yr,gu,yu,bu,Z$,Qi,ra,Jr]),yW=ie([Ji,mu,wu,X$,Zi,ea,ta,na]),wW=ie([Yi,Xi,S$,n$,ou,fu,hu,Ks,H$]),bW=ie([Yr,Qc,vu,du,iu,tu,ru,su,Fn,pu,Qi,ra,Jr]),O=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===z.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Yc(s.elicitations,r)}return new t(e,r,n)}},Yc=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(z.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function gr(t){return t==="completed"||t==="failed"||t==="cancelled"}var ZW=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Su(t){let r=wi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ku(t,e){let r=Tt(t,e);if(!r.success)throw r.error;return r.data}var oP=6e4,sa=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(Yi,r=>{this._oncancel(r)}),this.setNotificationHandler(Xi,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 O(z.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(ea,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 l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{let d=l,h=new O(d.error.code,d.error.message,d.error.data);u(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new O(z.InvalidParams,`Task not found: ${o}`);if(!gr(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(gr(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[fr]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(ta,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 O(z.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(na,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(z.InvalidParams,`Task not found: ${r.params.taskId}`);if(gr(s.status))throw new O(z.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 O(z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof O?s:new O(z.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),O.fromError(z.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),Vr(o)||ig(o)?this._onresponse(o):qs(o)?this._onrequest(o,i):og(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=O.fromError(z.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?.[fr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:z.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(u).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=rg(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,c={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(u,d)},sendRequest:async(u,d,h)=>{if(i.signal.aborted)throw new O(z.ConnectionClosed,"Request was cancelled");let p={...h,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let m=p.relatedTask?.taskId??o;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async u=>{if(i.signal.aborted)return;let d={result:u,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 u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:z.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).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(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vr(e))n(e);else{let i=new O(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(Vr(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),Vr(e))s(e);else{let i=O.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 O?i:new O(z.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Jr,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},gr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new O(z.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(z.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(z.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=b=>{u(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 h=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),a&&(p.params={...p.params,task:a}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[fr]:l}});let m=b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let k=b instanceof O?b:new O(z.RequestTimeout,String(b));u(k)};this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let k=Tt(r,b.result);k.success?c(k.data):u(k.error)}catch(k){u(k)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let f=n?.timeout??oP,g=()=>m(O.fromError(z.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(h,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let w=l?.taskId;if(w){let b=k=>{let _=this._responseHandlers.get(h);_?_(k):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,b),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(h),u(k)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(h),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qi,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},ra,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ug,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||{},[fr]: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||{},[fr]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[fr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Su(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=ku(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=Su(e);this._notificationHandlers.set(n,s=>{let o=ku(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"&&qs(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new O(z.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 O(z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new O(z.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 O(z.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 l=Ks.parse({method:"notifications/tasks/status",params:a});await this.notification(l),gr(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 O(z.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(gr(a.status))throw new O(z.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 l=await n.getTask(s,r);if(l){let c=Ks.parse({method:"notifications/tasks/status",params:l});await this.notification(c),gr(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function wg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bg(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];wg(i)&&wg(o)?r[s]={...i,...o}:r[s]=o}return r}var wb=yi(fh(),1),bb=yi(yb(),1);function gI(){let t=new wb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bb.default)(t),t}var Ua=class{constructor(e){this._ajv=e??gI()}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 qa=class{constructor(e){this._client=e}async*callToolStream(e,r=Fn,n){let s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},i=s.requestStream({method:"tools/call",params:e},r,o),a=s.getToolOutputValidator(e.name);for await(let l of i){if(l.type==="result"&&a){let c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new O(z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{let u=a(c.structuredContent);if(!u.valid){yield{type:"error",error:new O(z.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof O){yield{type:"error",error:u};return}yield{type:"error",error:new O(z.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function vb(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 Sb(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}}function Ba(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let s of Object.keys(n)){let o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Ba(o,r[s])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ba(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ba(r,e)}}function yI(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Wa=class extends sa{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ua,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",fu,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",hu,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ou,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new qa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=bg(this._capabilities,e)}setRequestHandler(e,r){let s=wi(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=bi(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");let i=o;if(i==="elicitation/create"){let a=async(l,c)=>{let u=Tt(wu,l);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new O(z.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:h,supportsUrlMode:p}=yI(this._capabilities.elicitation);if(d.mode==="form"&&!h)throw new O(z.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new O(z.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(l,c));if(d.task){let b=Tt(Jr,m);if(!b.success){let k=b.error instanceof Error?b.error.message:String(b.error);throw new O(z.InvalidParams,`Invalid task creation result: ${k}`)}return b.data}let f=Tt(bu,m);if(!f.success){let b=f.error instanceof Error?f.error.message:String(f.error);throw new O(z.InvalidParams,`Invalid elicitation result: ${b}`)}let g=f.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ba(w,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(l,c)=>{let u=Tt(mu,l);if(!u.success){let g=u.error instanceof Error?u.error.message:String(u.error);throw new O(z.InvalidParams,`Invalid sampling request: ${g}`)}let{params:d}=u.data,h=await Promise.resolve(r(l,c));if(d.task){let g=Tt(Jr,h);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new O(z.InvalidParams,`Invalid task creation result: ${w}`)}return g.data}let m=d.tools||d.toolChoice?yu:gu,f=Tt(m,h);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new O(z.InvalidParams,`Invalid sampling result: ${g}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:jn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Qc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Qm.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){vb(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Sb(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Yr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},vu,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Yr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},du,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},iu,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},tu,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ru,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},su,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Yr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Yr,r)}async callTool(e,r=Fn,n){if(this.isToolTaskRequired(e.name))throw new O(z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new O(z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{let i=o(s.structuredContent);if(!i.valid)throw new O(z.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof O?i:new O(z.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},pu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){let o=gg.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=o.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{let d=await s();l(null,d)}catch(d){let h=d instanceof Error?d:new Error(String(d));l(h,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let h=setTimeout(c,a);this._listChangedDebounceTimers.set(e,h)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var $o=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},kb=10,wI=13,un=32;function kh(t){}function Ha(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=kh,onError:r=kh,onRetry:n=kh,onComment:s,maxBufferSize:o}=t,i=[],a=0,l=!0,c,u="",d=0,h,p=!1;function m(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let N=g(S);N!==""&&(i.push(N),a=N.length),f();return}if(S.indexOf(`
171
+ `+f)}await this.fireLifecycle("turn_start");try{await this.fireLifecycle("pre_send");for(let g of this.hookEngine?.drainNotifications()??[])this.conversation.addSystemReminder(g);let f=await Rm(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,n,r,this.sessionFilePath,this.abortSignal);if(f.message&&(yield{type:"compact",message:f.message,boundary:f.boundary}),f.compacted&&this.restoreContext(),this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}try{let g=Uf(this.client,this.client.stream(this.conversation,r,this.abortSignal),e);for await(let w of g){if(this.abortSignal?.aborted){l=!1;break}switch(w.type){case"text_delta":c+=w.text,yield{type:"stream_text",text:w.text};break;case"thinking_delta":yield{type:"thinking_text",text:w.text};break;case"thinking_complete":u.push({thinking:w.thinking,signature:w.signature}),yield{type:"thinking_complete",thinking:w.thinking,signature:w.signature};break;case"tool_call_start":break;case"tool_call_complete":d.push({toolUseId:w.toolId,toolName:w.toolName,arguments:w.arguments,...w.parseError?{parseError:w.parseError}:{},...w.providerItemId?{providerItemId:w.providerItemId}:{}}),yield{type:"tool_use",toolName:w.toolName,toolId:w.toolId,args:w.arguments};break;case"stream_end":h=w.stopReason,p=w.usage,yield{type:"usage",usage:w.usage};break}}}catch(g){if(this.abortSignal?.aborted){(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(g instanceof Os)try{let w=await Cm(this.conversation,this.client,this.recoveryState,n,r,this.sessionFilePath,this.abortSignal);if(!w.compacted){yield{type:"error",error:g};return}this.conversation.clearUsageAnchor(),this.restoreContext(),yield{type:"compact",message:"Auto-compacted due to context length: "+w.message,boundary:w.boundary};continue}catch{yield{type:"error",error:g};return}if(g instanceof Af){if(i>=EE){yield{type:"error",error:g};return}i++;let w=PE(g.retryAfter);if(yield{type:"retry",reason:"rate limited",delay:w},await this.interruptibleSleep(w)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"error",error:g instanceof Error?g:new Error(M(g))};return}if(i=0,this.abortSignal?.aborted){(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",c),h==="max_tokens"){let g=Math.min(TE,this.contextWindow);if(!s&&this.maxOutput<g&&this.client.setMaxOutputTokens){this.client.setMaxOutputTokens?.(g),this.maxOutput=g,s=!0,(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else if(o<Jm){o++,(c||u.length>0)&&(this.conversation.addAssistantFull(c,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces.")),yield{type:"retry",reason:`max_tokens recovery ${String(o)}/${String(Jm)}`,delay:0};continue}}else o=0;if((c||u.length>0||d.length>0)&&(this.conversation.addAssistantFull(c,u,d),this.persistLastMessage()),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),d.length>0){let g=await this.executeTools(d,e);for(let _ of g)yield _;let w=new Set;for(let _ of d)Km(_.toolName,_.arguments,this.workDir,this.sessionId)&&w.add(_.toolUseId);let b=[];for(let _ of g)if(_.type==="tool_result"){let S={toolUseId:_.toolId,content:_.output,..._.contentBlocks?.length?{contentBlocks:_.contentBlocks}:{},isError:_.isError};if(S.content.length>$E&&!w.has(_.toolId)){let x=Ym(this.workDir,this.sessionId,_.toolId,S.content);x!==S.content&&Kc(S,x),w.add(_.toolId)}b.push(S)}Vm(b,this.workDir,this.sessionId,w);let k=d.some(_=>{if(_.toolName!=="ExitPlanMode")return!1;let S=g.find(x=>x.type==="tool_result"&&x.toolId===_.toolUseId);return S?.type==="tool_result"&&!S.isError});if(this.conversation.addToolResultsMessage(b),this.persistLastMessage(),this.abortSignal?.aborted){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"interrupted"};return}if(this.memoryRecallPromise&&!this.memoryRecallConsumed&&this.memoryRecallSettled){let _=this.memoryRecallValue;_?.reminder&&(this.conversation.addSystemReminder(_.reminder),this.onMemoriesSurfaced?.(_.paths)),this.memoryRecallConsumed=!0}if(k){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},yield*this.deliverSteering()}else{if((yield*this.deliverSteering()).length>0){yield{type:"turn_complete"};continue}if(l=!1,this.fileHistory){let w=c.length>60?c.slice(0,60)+"...":c;this.fileHistory.makeSnapshot(this.conversation.len(),w,xm(this.sessionFilePath))}if(yield{type:"loop_complete",stopReason:h},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}finally{await this.fireLifecycle("turn_end")}}}finally{try{await this.fireLifecycle("session_end")}finally{Ff(e,this.abortSignal?.aborted?"interrupted":"completed")}}}async fireLifecycle(e,r){if(!this.hookEngine)return;let n=await this.hookEngine.fire(e,{event:e,message:r},{workDir:this.workDir,abortSignal:this.abortSignal});for(let s of n)s.output&&this.hookEngine.recordNotification(s.output)}interruptibleSleep(e){return new Promise(r=>{if(this.abortSignal?.aborted){r(!0);return}let n=()=>{clearTimeout(s),r(!0)},s=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",n),r(!1)},e);this.abortSignal?.addEventListener("abort",n,{once:!0})})}async executeTools(e,r){let n=[],s=this.partitionToolCalls(e);for(let o of s){let i=await this.executeBatch(o.blocks,o.concurrent&&o.blocks.length>1,r);n.push(...i)}return n}partitionToolCalls(e){let r=[];for(let n of e){let s=this.registry.get(n.toolName),o=s?s.isConcurrencySafe?.(n.arguments??{})??s.category==="read":!1;o&&r.length>0&&r[r.length-1].concurrent?r[r.length-1].blocks.push(n):r.push({concurrent:o,blocks:[n]})}return r}async executeBatch(e,r,n){let s=[],o=new Wi(this.registry,{workDir:this.workDir,sessionId:this.sessionId,taskManager:this.taskManager,abortSignal:this.abortSignal,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache,permissionChecker:this.checker,onPermissionRequest:this.onPermissionRequest},n);for(let i of e){if(i.parseError){if(o.submit(i.toolUseId,i.toolName,i.arguments,i.parseError),!r){let h=await o.collectResults();for(let p of h)await this.processToolResult(p,e,s)}continue}if(this.abortSignal?.aborted){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:"Error: command interrupted",isError:!0,elapsed:0});continue}if(this.toolFilter&&!this.toolFilter(i.toolName)){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Tool '${i.toolName}' is not available to this agent.`,isError:!0,elapsed:0});continue}if(this.hookEngine){let h=await this.hookEngine.firePreToolHooks(i.toolName,i.arguments,{workDir:this.workDir,abortSignal:this.abortSignal});if(h.rejected){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Rejected by hook: ${h.reason}`,isError:!0,elapsed:0});continue}}let a=this.registry.get(i.toolName),l=a?.category??"command",c=a instanceof xi?a.resolveTarget(i.arguments):void 0;if(c&&(!this.registry.get(c.name)||this.toolFilter&&!this.toolFilter(c.name))){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Tool '${c.name}' is not available to this agent.`,isError:!0,elapsed:0});continue}let u=[this.checker.check(i.toolName,l,i.arguments)];c&&u.push(this.checker.check(c.name,c.category,Wr(i.arguments.arguments??{})));let d=u.find(h=>h.effect==="deny")??u.find(h=>h.effect==="ask")??u[0];if(d.effect==="deny"){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Permission denied: ${d.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(d.effect==="ask"&&!this.onPermissionRequest){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:"Permission required, but this agent has no approval handler. The tool was not executed.",isError:!0,elapsed:0});continue}if(d.effect==="ask"&&this.onPermissionRequest){let h;try{h=await this.onPermissionRequest(i.toolName,i.arguments,d,i.toolUseId),h==="allowAlways"&&!this.abortSignal?.aborted&&this.checker.allowAlways(i.toolName,i.arguments)}catch(p){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:`Permission request failed: ${M(p)}. The tool was not executed.`,isError:!0,elapsed:0});continue}if(h==="deny"){s.push({type:"tool_result",toolName:i.toolName,toolId:i.toolUseId,output:Mf,isError:!0,elapsed:0});continue}}if(o.submit(i.toolUseId,i.toolName,i.arguments),!r){let h=await o.collectResults();for(let p of h)await this.processToolResult(p,e,s)}}if(r){let i=await o.collectResults();for(let a of i)await this.processToolResult(a,e,s)}return s}async processToolResult(e,r,n){if(!e.result.isError&&e.toolName==="ReadFile"&&!e.result.contentBlocks?.length){let s=r.find(i=>i.toolUseId===e.toolId),o=T(s?.arguments??{},"file_path");o&&this.recoveryState.recordFileRead(o,e.result.output)}if(n.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,...e.result.contentBlocks?.length?{contentBlocks:e.result.contentBlocks}:{},isError:e.result.isError,elapsed:e.elapsed}),this.hookEngine){let s=r.find(i=>i.toolUseId===e.toolId)?.arguments,o=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,args:s,filePath:T(s??{},"file_path",T(s??{},"path","")),message:e.result.output},{workDir:this.workDir,abortSignal:this.abortSignal});for(let i of o)i.output&&this.hookEngine.recordNotification(i.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let r=e[e.length-1];Wc(this.workDir,this.sessionId,{role:r.role,content:r.content,timestamp:Math.floor(Date.now()/1e3),...r.toolUses?.length?{tool_uses:ji(r.toolUses)}:{},...r.toolResults?.length?{tool_results:Li(r.toolResults)}:{}})}};function PE(t){if(!t?.trim())return 5e3;let e=t.trim();if(/^\d+(?:\.\d+)?$/.test(e))return Math.min(Number(e)*1e3,Xm);let r=/^[A-Za-z]{3},/.test(e)?Date.parse(e):NaN;return Number.isFinite(r)?Math.min(Math.max(0,r-Date.now()),Xm):5e3}async function Fs(t,e){switch(t.protocol){case"anthropic":{let{AnthropicClient:r}=await import("./anthropic-WK6EYMUE.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}case"openai":{let{OpenAIClient:r}=await import("./openai-RYXW7AKZ.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}case"openai-compat":{let{OpenAICompatClient:r}=await import("./openai-RYXW7AKZ.js");return Ei(new r(t,e),{model:t.model,protocol:t.protocol})}default:throw new Error(`Unknown protocol: ${String(t.protocol)}`)}}import{isDeepStrictEqual as DO}from"util";var jn="2025-11-25";var Qm=[jn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fr="io.modelcontextprotocol/related-task",Ki="2.0",ye=vf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),eg=ie([v(),V().int()]),tg=v(),uW=ge({ttl:V().optional(),pollInterval:V().optional()}),CE=R({ttl:V().optional()}),ME=R({taskId:v()}),Jc=ge({progressToken:eg.optional(),[fr]:ME.optional()}),lt=R({_meta:Jc.optional()}),Us=lt.extend({task:CE.optional()}),rg=t=>Us.safeParse(t).success,Te=R({method:v(),params:lt.loose().optional()}),mt=R({_meta:Jc.optional()}),gt=R({method:v(),params:mt.loose().optional()}),Ee=ge({_meta:Jc.optional()}),Vi=ie([v(),V().int()]),ng=R({jsonrpc:A(Ki),id:Vi,...Te.shape}).strict(),qs=t=>ng.safeParse(t).success,sg=R({jsonrpc:A(Ki),...gt.shape}).strict(),og=t=>sg.safeParse(t).success,Xc=R({jsonrpc:A(Ki),id:Vi,result:Ee}).strict(),Vr=t=>Xc.safeParse(t).success;var z;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(z||(z={}));var Zc=R({jsonrpc:A(Ki),id:Vi.optional(),error:R({code:V().int(),message:v(),data:de().optional()})}).strict();var ig=t=>Zc.safeParse(t).success;var mr=ie([ng,sg,Xc,Zc]),dW=ie([Xc,Zc]),Yr=Ee.strict(),AE=mt.extend({requestId:Vi.optional(),reason:v().optional()}),Yi=gt.extend({method:A("notifications/cancelled"),params:AE}),IE=R({src:v(),mimeType:v().optional(),sizes:P(v()).optional(),theme:at(["light","dark"]).optional()}),Bs=R({icons:P(IE).optional()}),zn=R({name:v(),title:v().optional()}),ag=zn.extend({...zn.shape,...Bs.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),OE=Tc(R({applyDefaults:Q().optional()}),re(v(),de())),NE=Ec(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Tc(R({form:OE.optional(),url:ye.optional()}),re(v(),de()).optional())),DE=ge({list:ye.optional(),cancel:ye.optional(),requests:ge({sampling:ge({createMessage:ye.optional()}).optional(),elicitation:ge({create:ye.optional()}).optional()}).optional()}),zE=ge({list:ye.optional(),cancel:ye.optional(),requests:ge({tools:ge({call:ye.optional()}).optional()}).optional()}),jE=R({experimental:re(v(),ye).optional(),sampling:R({context:ye.optional(),tools:ye.optional()}).optional(),elicitation:NE.optional(),roots:R({listChanged:Q().optional()}).optional(),tasks:DE.optional(),extensions:re(v(),ye).optional()}),LE=lt.extend({protocolVersion:v(),capabilities:jE,clientInfo:ag}),FE=Te.extend({method:A("initialize"),params:LE});var UE=R({experimental:re(v(),ye).optional(),logging:ye.optional(),completions:ye.optional(),prompts:R({listChanged:Q().optional()}).optional(),resources:R({subscribe:Q().optional(),listChanged:Q().optional()}).optional(),tools:R({listChanged:Q().optional()}).optional(),tasks:zE.optional(),extensions:re(v(),ye).optional()}),Qc=Ee.extend({protocolVersion:v(),capabilities:UE,serverInfo:ag,instructions:v().optional()}),lg=gt.extend({method:A("notifications/initialized"),params:mt.optional()}),cg=t=>lg.safeParse(t).success,Ji=Te.extend({method:A("ping"),params:lt.optional()}),qE=R({progress:V(),total:le(V()),message:le(v())}),BE=R({...mt.shape,...qE.shape,progressToken:eg}),Xi=gt.extend({method:A("notifications/progress"),params:BE}),WE=lt.extend({cursor:tg.optional()}),Ws=Te.extend({params:WE.optional()}),Hs=Ee.extend({nextCursor:tg.optional()}),HE=at(["working","input_required","completed","failed","cancelled"]),Gs=R({taskId:v(),status:HE,ttl:ie([V(),wf()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:le(V()),statusMessage:le(v())}),Jr=Ee.extend({task:Gs}),GE=mt.merge(Gs),Ks=gt.extend({method:A("notifications/tasks/status"),params:GE}),Zi=Te.extend({method:A("tasks/get"),params:lt.extend({taskId:v()})}),Qi=Ee.merge(Gs),ea=Te.extend({method:A("tasks/result"),params:lt.extend({taskId:v()})}),hW=Ee.loose(),ta=Ws.extend({method:A("tasks/list")}),ra=Hs.extend({tasks:P(Gs)}),na=Te.extend({method:A("tasks/cancel"),params:lt.extend({taskId:v()})}),ug=Ee.merge(Gs),dg=R({uri:v(),mimeType:le(v()),_meta:re(v(),de()).optional()}),hg=dg.extend({text:v()}),eu=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),pg=dg.extend({blob:eu}),Vs=at(["user","assistant"]),Ln=R({audience:P(Vs).optional(),priority:V().min(0).max(1).optional(),lastModified:kf.datetime({offset:!0}).optional()}),fg=R({...zn.shape,...Bs.shape,uri:v(),description:le(v()),mimeType:le(v()),size:le(V()),annotations:Ln.optional(),_meta:le(ge({}))}),KE=R({...zn.shape,...Bs.shape,uriTemplate:v(),description:le(v()),mimeType:le(v()),annotations:Ln.optional(),_meta:le(ge({}))}),VE=Ws.extend({method:A("resources/list")}),tu=Hs.extend({resources:P(fg)}),YE=Ws.extend({method:A("resources/templates/list")}),ru=Hs.extend({resourceTemplates:P(KE)}),nu=lt.extend({uri:v()}),JE=nu,XE=Te.extend({method:A("resources/read"),params:JE}),su=Ee.extend({contents:P(ie([hg,pg]))}),ou=gt.extend({method:A("notifications/resources/list_changed"),params:mt.optional()}),ZE=nu,QE=Te.extend({method:A("resources/subscribe"),params:ZE}),e$=nu,t$=Te.extend({method:A("resources/unsubscribe"),params:e$}),r$=mt.extend({uri:v()}),n$=gt.extend({method:A("notifications/resources/updated"),params:r$}),s$=R({name:v(),description:le(v()),required:le(Q())}),o$=R({...zn.shape,...Bs.shape,description:le(v()),arguments:le(P(s$)),_meta:le(ge({}))}),i$=Ws.extend({method:A("prompts/list")}),iu=Hs.extend({prompts:P(o$)}),a$=lt.extend({name:v(),arguments:re(v(),v()).optional()}),l$=Te.extend({method:A("prompts/get"),params:a$}),au=R({type:A("text"),text:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),lu=R({type:A("image"),data:eu,mimeType:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),cu=R({type:A("audio"),data:eu,mimeType:v(),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),c$=R({type:A("tool_use"),name:v(),id:v(),input:re(v(),de()),_meta:re(v(),de()).optional()}),u$=R({type:A("resource"),resource:ie([hg,pg]),annotations:Ln.optional(),_meta:re(v(),de()).optional()}),d$=fg.extend({type:A("resource_link")}),uu=ie([au,lu,cu,d$,u$]),h$=R({role:Vs,content:uu}),du=Ee.extend({description:v().optional(),messages:P(h$)}),hu=gt.extend({method:A("notifications/prompts/list_changed"),params:mt.optional()}),p$=R({title:v().optional(),readOnlyHint:Q().optional(),destructiveHint:Q().optional(),idempotentHint:Q().optional(),openWorldHint:Q().optional()}),f$=R({taskSupport:at(["required","optional","forbidden"]).optional()}),mg=R({...zn.shape,...Bs.shape,description:v().optional(),inputSchema:R({type:A("object"),properties:re(v(),ye).optional(),required:P(v()).optional()}).catchall(de()),outputSchema:R({type:A("object"),properties:re(v(),ye).optional(),required:P(v()).optional()}).catchall(de()).optional(),annotations:p$.optional(),execution:f$.optional(),_meta:re(v(),de()).optional()}),m$=Ws.extend({method:A("tools/list")}),pu=Hs.extend({tools:P(mg)}),Fn=Ee.extend({content:P(uu).default([]),structuredContent:re(v(),de()).optional(),isError:Q().optional()}),pW=Fn.or(Ee.extend({toolResult:de()})),g$=Us.extend({name:v(),arguments:re(v(),de()).optional()}),y$=Te.extend({method:A("tools/call"),params:g$}),fu=gt.extend({method:A("notifications/tools/list_changed"),params:mt.optional()}),gg=R({autoRefresh:Q().default(!0),debounceMs:V().int().nonnegative().default(300)}),yg=at(["debug","info","notice","warning","error","critical","alert","emergency"]),w$=lt.extend({level:yg}),b$=Te.extend({method:A("logging/setLevel"),params:w$}),v$=mt.extend({level:yg,logger:v().optional(),data:de()}),S$=gt.extend({method:A("notifications/message"),params:v$}),k$=R({name:v().optional()}),_$=R({hints:P(k$).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),x$=R({mode:at(["auto","required","none"]).optional()}),T$=R({type:A("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:P(uu).default([]),structuredContent:R({}).loose().optional(),isError:Q().optional(),_meta:re(v(),de()).optional()}),E$=xc("type",[au,lu,cu]),Gi=xc("type",[au,lu,cu,c$,T$]),$$=R({role:Vs,content:ie([Gi,P(Gi)]),_meta:re(v(),de()).optional()}),P$=Us.extend({messages:P($$),modelPreferences:_$.optional(),systemPrompt:v().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:P(v()).optional(),metadata:ye.optional(),tools:P(mg).optional(),toolChoice:x$.optional()}),mu=Te.extend({method:A("sampling/createMessage"),params:P$}),gu=Ee.extend({model:v(),stopReason:le(at(["endTurn","stopSequence","maxTokens"]).or(v())),role:Vs,content:E$}),yu=Ee.extend({model:v(),stopReason:le(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Vs,content:ie([Gi,P(Gi)])}),R$=R({type:A("boolean"),title:v().optional(),description:v().optional(),default:Q().optional()}),C$=R({type:A("string"),title:v().optional(),description:v().optional(),minLength:V().optional(),maxLength:V().optional(),format:at(["email","uri","date","date-time"]).optional(),default:v().optional()}),M$=R({type:at(["number","integer"]),title:v().optional(),description:v().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),A$=R({type:A("string"),title:v().optional(),description:v().optional(),enum:P(v()),default:v().optional()}),I$=R({type:A("string"),title:v().optional(),description:v().optional(),oneOf:P(R({const:v(),title:v()})),default:v().optional()}),O$=R({type:A("string"),title:v().optional(),description:v().optional(),enum:P(v()),enumNames:P(v()).optional(),default:v().optional()}),N$=ie([A$,I$]),D$=R({type:A("array"),title:v().optional(),description:v().optional(),minItems:V().optional(),maxItems:V().optional(),items:R({type:A("string"),enum:P(v())}),default:P(v()).optional()}),z$=R({type:A("array"),title:v().optional(),description:v().optional(),minItems:V().optional(),maxItems:V().optional(),items:R({anyOf:P(R({const:v(),title:v()}))}),default:P(v()).optional()}),j$=ie([D$,z$]),L$=ie([O$,N$,j$]),F$=ie([L$,R$,C$,M$]),U$=Us.extend({mode:A("form").optional(),message:v(),requestedSchema:R({type:A("object"),properties:re(v(),F$),required:P(v()).optional()})}),q$=Us.extend({mode:A("url"),message:v(),elicitationId:v(),url:v().url()}),B$=ie([U$,q$]),wu=Te.extend({method:A("elicitation/create"),params:B$}),W$=mt.extend({elicitationId:v()}),H$=gt.extend({method:A("notifications/elicitation/complete"),params:W$}),bu=Ee.extend({action:at(["accept","decline","cancel"]),content:Ec(t=>t===null?void 0:t,re(v(),ie([v(),V(),Q(),P(v())])).optional())}),G$=R({type:A("ref/resource"),uri:v()});var K$=R({type:A("ref/prompt"),name:v()}),V$=lt.extend({ref:ie([K$,G$]),argument:R({name:v(),value:v()}),context:R({arguments:re(v(),v()).optional()}).optional()}),Y$=Te.extend({method:A("completion/complete"),params:V$});var vu=Ee.extend({completion:ge({values:P(v()).max(100),total:le(V().int()),hasMore:le(Q())})}),J$=R({uri:v().startsWith("file://"),name:v().optional(),_meta:re(v(),de()).optional()}),X$=Te.extend({method:A("roots/list"),params:lt.optional()}),Z$=Ee.extend({roots:P(J$)}),Q$=gt.extend({method:A("notifications/roots/list_changed"),params:mt.optional()}),fW=ie([Ji,FE,Y$,b$,l$,i$,VE,YE,XE,QE,t$,y$,m$,Zi,ea,ta,na]),mW=ie([Yi,Xi,lg,Q$,Ks]),gW=ie([Yr,gu,yu,bu,Z$,Qi,ra,Jr]),yW=ie([Ji,mu,wu,X$,Zi,ea,ta,na]),wW=ie([Yi,Xi,S$,n$,ou,fu,hu,Ks,H$]),bW=ie([Yr,Qc,vu,du,iu,tu,ru,su,Fn,pu,Qi,ra,Jr]),O=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===z.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Yc(s.elicitations,r)}return new t(e,r,n)}},Yc=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(z.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function gr(t){return t==="completed"||t==="failed"||t==="cancelled"}var ZW=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Su(t){let r=wi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ku(t,e){let r=Tt(t,e);if(!r.success)throw r.error;return r.data}var oP=6e4,sa=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(Yi,r=>{this._oncancel(r)}),this.setNotificationHandler(Xi,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 O(z.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(ea,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 l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{let d=l,h=new O(d.error.code,d.error.message,d.error.data);u(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new O(z.InvalidParams,`Task not found: ${o}`);if(!gr(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(gr(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[fr]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(ta,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 O(z.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(na,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new O(z.InvalidParams,`Task not found: ${r.params.taskId}`);if(gr(s.status))throw new O(z.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 O(z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof O?s:new O(z.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),O.fromError(z.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),Vr(o)||ig(o)?this._onresponse(o):qs(o)?this._onrequest(o,i):og(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=O.fromError(z.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?.[fr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:z.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(u).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=rg(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,c={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(u,d)},sendRequest:async(u,d,h)=>{if(i.signal.aborted)throw new O(z.ConnectionClosed,"Request was cancelled");let p={...h,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let m=p.relatedTask?.taskId??o;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async u=>{if(i.signal.aborted)return;let d={result:u,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 u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:z.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).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(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vr(e))n(e);else{let i=new O(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(Vr(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),Vr(e))s(e);else{let i=O.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 O?i:new O(z.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Jr,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},gr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new O(z.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(z.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(z.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=b=>{u(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 h=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),a&&(p.params={...p.params,task:a}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[fr]:l}});let m=b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let k=b instanceof O?b:new O(z.RequestTimeout,String(b));u(k)};this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let k=Tt(r,b.result);k.success?c(k.data):u(k.error)}catch(k){u(k)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let f=n?.timeout??oP,g=()=>m(O.fromError(z.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(h,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let w=l?.taskId;if(w){let b=k=>{let _=this._responseHandlers.get(h);_?_(k):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,b),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(h),u(k)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(h),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qi,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},ra,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ug,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||{},[fr]: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||{},[fr]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[fr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Su(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=ku(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=Su(e);this._notificationHandlers.set(n,s=>{let o=ku(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"&&qs(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new O(z.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 O(z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new O(z.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 O(z.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 l=Ks.parse({method:"notifications/tasks/status",params:a});await this.notification(l),gr(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 O(z.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(gr(a.status))throw new O(z.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 l=await n.getTask(s,r);if(l){let c=Ks.parse({method:"notifications/tasks/status",params:l});await this.notification(c),gr(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function wg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bg(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];wg(i)&&wg(o)?r[s]={...i,...o}:r[s]=o}return r}var wb=yi(fh(),1),bb=yi(yb(),1);function gI(){let t=new wb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bb.default)(t),t}var Ua=class{constructor(e){this._ajv=e??gI()}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 qa=class{constructor(e){this._client=e}async*callToolStream(e,r=Fn,n){let s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},i=s.requestStream({method:"tools/call",params:e},r,o),a=s.getToolOutputValidator(e.name);for await(let l of i){if(l.type==="result"&&a){let c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new O(z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{let u=a(c.structuredContent);if(!u.valid){yield{type:"error",error:new O(z.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof O){yield{type:"error",error:u};return}yield{type:"error",error:new O(z.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function vb(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 Sb(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}}function Ba(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let s of Object.keys(n)){let o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Ba(o,r[s])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ba(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ba(r,e)}}function yI(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Wa=class extends sa{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ua,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",fu,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",hu,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ou,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new qa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=bg(this._capabilities,e)}setRequestHandler(e,r){let s=wi(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=bi(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");let i=o;if(i==="elicitation/create"){let a=async(l,c)=>{let u=Tt(wu,l);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new O(z.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:h,supportsUrlMode:p}=yI(this._capabilities.elicitation);if(d.mode==="form"&&!h)throw new O(z.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new O(z.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(l,c));if(d.task){let b=Tt(Jr,m);if(!b.success){let k=b.error instanceof Error?b.error.message:String(b.error);throw new O(z.InvalidParams,`Invalid task creation result: ${k}`)}return b.data}let f=Tt(bu,m);if(!f.success){let b=f.error instanceof Error?f.error.message:String(f.error);throw new O(z.InvalidParams,`Invalid elicitation result: ${b}`)}let g=f.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Ba(w,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(l,c)=>{let u=Tt(mu,l);if(!u.success){let g=u.error instanceof Error?u.error.message:String(u.error);throw new O(z.InvalidParams,`Invalid sampling request: ${g}`)}let{params:d}=u.data,h=await Promise.resolve(r(l,c));if(d.task){let g=Tt(Jr,h);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new O(z.InvalidParams,`Invalid task creation result: ${w}`)}return g.data}let m=d.tools||d.toolChoice?yu:gu,f=Tt(m,h);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new O(z.InvalidParams,`Invalid sampling result: ${g}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:jn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Qc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Qm.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){vb(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Sb(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Yr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},vu,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Yr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},du,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},iu,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},tu,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ru,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},su,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Yr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Yr,r)}async callTool(e,r=Fn,n){if(this.isToolTaskRequired(e.name))throw new O(z.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new O(z.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{let i=o(s.structuredContent);if(!i.valid)throw new O(z.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof O?i:new O(z.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},pu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){let o=gg.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=o.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{let d=await s();l(null,d)}catch(d){let h=d instanceof Error?d:new Error(String(d));l(h,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let h=setTimeout(c,a);this._listChangedDebounceTimers.set(e,h)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var $o=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},kb=10,wI=13,un=32;function kh(t){}function Ha(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=kh,onError:r=kh,onRetry:n=kh,onComment:s,maxBufferSize:o}=t,i=[],a=0,l=!0,c,u="",d=0,h,p=!1;function m(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let N=g(S);N!==""&&(i.push(N),a=N.length),f();return}if(S.indexOf(`
172
172
  `)===-1&&S.indexOf("\r")===-1){i.push(S),a+=S.length,f();return}i.push(S);let x=i.join("");i.length=0,a=0;let E=g(x);E!==""&&(i.push(E),a=E.length),f()}function f(){o!==void 0&&(a+u.length<=o||(p=!0,i.length=0,a=0,c=void 0,u="",d=0,h=void 0,r(new $o(`Buffered data exceeded max buffer size of ${o} characters`,{type:"max-buffer-size-exceeded"}))))}function g(S){let x=0;if(S.indexOf("\r")===-1){let E=S.indexOf(`
173
173
  `,x);for(;E!==-1;){if(x===E){d>0&&e({id:c,event:h,data:u}),c=void 0,u="",d=0,h=void 0,x=E+1,E=S.indexOf(`
174
174
  `,x);continue}let N=S.charCodeAt(x);if(_b(S,x,N)){let D=S.charCodeAt(x+5)===un?x+6:x+5,J=S.slice(D,E);if(d===0&&S.charCodeAt(E+1)===kb){e({id:c,event:h,data:J}),c=void 0,u="",h=void 0,x=E+2,E=S.indexOf(`
@@ -955,7 +955,7 @@ Binary files /dev/null and b/${t} differ
955
955
 
956
956
  ${Wt(O_,{diff:r.diffText,existing_code:e.existingCode,comment:e.content})}`,o;try{o=await Fr(t,s,n)}catch(l){if(n?.aborted)throw l;return!1}let i=hq(o);if(!i||i===e.existingCode)return!1;let a=e.existingCode;return e.existingCode=i,pi(e,r)?(e.resolution="llm",!0):(e.existingCode=a,!1)}var fq="You are a precise assistant. Follow the instructions exactly and output only what is requested.",mq=50,gq=100,yq=50,wq=3,bq=2;function vq(t,e,r){if(r&&(t||e))throw new Error("--commit cannot be combined with --from/--to");if(t&&!e||!t&&e)throw new Error("--from and --to must be used together");for(let n of[t,e,r])if(n?.startsWith("-"))throw new Error(`invalid ref "${n}": refs must not start with "-"`)}function Sq(t){let e=0,r=0;for(let n of t){let s=n.insertions+n.deletions;e+=s,s>r&&(r=s)}return{total:e,maxFile:r}}function kq(){}async function QX(t,e){let{workDir:r,abortSignal:n}=t,s=t.onProgress??kq,o=t.maxConcurrency??wq,i=t.maxRounds??bq,a=t.background??"";vq(t.from,t.to,t.commit);let l={from:t.from,to:t.to,commit:t.commit},c=sx(l),u={mode:c,comments:[],filesReviewed:0,filesChanged:0,groups:[],excluded:[],filteredOut:0,aborted:!1};s({phase:"diff",message:"Collecting git diffs\u2026"});let d=await nx({workDir:r,mode:c,from:t.from,to:t.to,commit:t.commit,abortSignal:n});if(u.filesChanged=d.length,d.length===0)return s({phase:"done",message:"No changes found.",progress:1}),u;let h=vi(e.provider),p=Si(e.provider),m=Math.floor(h*j_),f=F_(d,{excludePatterns:t.excludePatterns,fileTokenLimit:m}),g=U_(f);if(u.excluded=g.excluded,g.selectedCount===0)return s({phase:"done",message:g.tooLargeCount>0?`${String(g.tooLargeCount)} file(s) exceeded the size limit; nothing left to review.`:"No reviewable files changed. Skipping review.",progress:1}),u;let w=g.selectedCount;s({phase:"selection",message:`${String(d.length)} file(s) changed, reviewing ${String(w)}`});let b=await Fs({...e.provider,thinking:"off"},fq);s({phase:"grouping",message:"Grouping files\u2026"});let k=await B_(g.selected,{client:b,abortSignal:n,tokenBudget:m,onFallback:B=>{s({phase:"grouping",message:`Grouping fell back to deterministic chunking (${B})`})}});u.groups=k.map(B=>({label:B.label,files:B.diffs.map(ne=>ne.newPath)}));let _=new Map;for(let B of g.retained)B.newPath&&B.newPath!=="/dev/null"&&_.set(B.newPath,B),B.oldPath&&B.oldPath!=="/dev/null"&&_.set(B.oldPath,B);let S=()=>g.retained,x=new Date().toISOString().slice(0,16).replace("T"," "),E=[],N=0,D=0,J=async B=>{let ne=B.label,ht={label:ne,files:B.diffs.map(Le=>Le.newPath),completed:!1,comments:[]},lr=new hc;try{await _q(B,{workDir:r,provider:e.provider,utilClient:b,collector:lr,diffByPath:_,allDiffs:S,currentDate:x,background:a,maxRounds:i,skipFilter:t.skipFilter??!1,abortSignal:n,contextWindow:h,maxOutput:p,onPhase:(Le,te)=>{s({phase:Le,message:`[${ne}] ${te}`})},onFiltered:Le=>{D+=Le},onToolEvent:t.onToolEvent}),ht.completed=!0}catch(Le){n?.aborted||(ht.error=Le instanceof Error?Le.message:String(Le))}finally{ht.comments=lr.all(),N++,s({phase:"review",message:`Group ${String(N)}/${String(k.length)} done (${ne})`,progress:N/k.length})}E.push(ht)},_e=[...k],ue=[];for(let B=0;B<Math.min(o,_e.length);B++)ue.push((async()=>{for(;_e.length>0;){let ne=_e.shift();if(!ne||n?.aborted)return;await J(ne)}})());return await Promise.all(ue),n?.aborted&&(u.aborted=!0),u.comments=Tq(E.flatMap(B=>B.comments)),u.filteredOut=D,u.filesReviewed=E.filter(B=>B.completed).reduce((B,ne)=>B+ne.files.length,0),s({phase:"done",message:u.aborted?`Review aborted: ${String(u.comments.length)} finding(s) collected before the interrupt`:`Review complete: ${String(u.comments.length)} finding(s) across ${String(k.length)} group(s)`,progress:1}),u}async function _q(t,e){let{abortSignal:r}=e,n=gc(t.diffs),s=K_(e.allDiffs(),t.diffs),{total:o,maxFile:i}=Sq(t.diffs),a=await Fs({...e.provider},R_),l="";if(i>=mq||t.diffs.length>=2&&o>=gq){e.onPhase("plan","Planning review\u2026");try{let d=`${$_}
957
957
 
958
- ${Wt(P_,{change_files:s,diffs:n,current_system_date_time:e.currentDate,requirement_background:e.background})}`;l=await Fr(e.utilClient,d,r)}catch(d){if(r?.aborted)throw d;l=""}}let u=[];for(let d=1;d<=e.maxRounds;d++){r?.throwIfAborted();let h=d>1?"":l,p=e.collector.snapshot();e.onPhase("review",`Review round ${String(d)}/${String(e.maxRounds)}\u2026`);let m=J_({changeFiles:s,diffs:n,currentDateTime:e.currentDate,background:e.background,planGuidance:h,confirmedComments:Y_(u)}),f=await cx(t,e,{message:m,agentClient:a}),g=e.collector.since(p);!f&&g.length===0&&(e.onPhase("review","No review activity; retrying with a nudge\u2026"),f=await cx(t,e,{message:m+N_,agentClient:a}),g=e.collector.since(p));let w=g;if(!e.skipFilter&&g.length>0){e.onPhase("filter",`Fact-checking ${String(g.length)} finding(s)\u2026`);let b=await X_(xq(t.diffs,g,e.diffByPath),g,{client:e.utilClient,abortSignal:r});b.size>0&&(e.collector.removeAt([...b].map(k=>p+k)),e.onFiltered(b.size),w=g.filter((k,_)=>!b.has(_)))}if(u.push(...w),w.length===0||u.length>=V_)break}}function xq(t,e,r){let n=new Set;for(let o of t)n.add(o.oldPath),n.add(o.newPath);let s=[...t];for(let o of e){if(n.has(o.path))continue;let i=r.get(o.path);i&&!s.includes(i)&&(s.push(i),n.add(o.path))}return s}async function cx(t,e,r){let n=new An;n.register(new pc({collector:e.collector,groupDiffs:t.diffs,groupLabel:t.label,resolve:async c=>{for(let u of c){let d=e.diffByPath.get(u.path),h=d?pi(u,d):!1;h||(h=ax(u,e.allDiffs())!==null),!h&&d&&await lx(e.utilClient,u,d,e.abortSignal)}}})),n.register(new fc(e.diffByPath)),n.register(new jr),n.register(new zr),n.register(new Or);let s=new qe;s.addUserMessage(r.message);let o=new pr({client:r.agentClient,registry:n,checker:new Ut(e.workDir,"default"),conversation:s,workDir:e.workDir,maxIterations:yq,abortSignal:e.abortSignal,fileStateCache:new Pr,contextWindow:e.contextWindow,maxOutput:e.maxOutput}),i=`review:${pq()}:`,a=new Map,l=!1;try{for await(let c of o.run()){if(c.type==="tool_use"&&(l=!0,a.set(c.toolId,{toolName:c.toolName,startedAt:Date.now()}),e.onToolEvent?.({...c,toolId:i+c.toolId})),c.type==="tool_result"&&(a.delete(c.toolId),e.onToolEvent?.({...c,toolId:i+c.toolId})),c.type==="error")throw c.error;c.type==="loop_complete"&&c.stopReason==="interrupted"&&e.abortSignal?.throwIfAborted()}}finally{let c=Date.now();for(let[u,d]of a)e.onToolEvent?.({type:"tool_result",toolName:d.toolName,toolId:i+u,output:e.abortSignal?.aborted?"Review tool call interrupted.":"Review tool call did not complete.",isError:!0,elapsed:(c-d.startedAt)/1e3})}return l}function Tq(t){let e=new Set,r=[];for(let s of t){let o=`${s.path}:${String(s.startLine)}:${s.content}`;e.has(o)||(e.add(o),r.push(s))}let n={critical:0,high:1,medium:2,low:3};return r.sort((s,o)=>s.path!==o.path?s.path.localeCompare(o.path):s.startLine!==o.startLine?s.startLine-o.startLine:(n[s.severity]??9)-(n[o.severity]??9))}var af=class{commands=new Map;register(e){if(this.commands.has(e.name))throw new Error(`Command '${e.name}' already registered`);this.commands.set(e.name,e)}find(e){return this.commands.get(e)}complete(e){let r=e.toLowerCase();return[...this.commands.values()].filter(n=>n.name.toLowerCase().startsWith(r))}listCommands(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};function rZ(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trim(),r=e.search(/\s/),n=r===-1?e:e.slice(0,r);return n.includes("/")?null:r===-1?{name:n,args:""}:{name:n,args:e.slice(r+1).trim()}}function nZ(){let t=new af;return t.register({name:"login",type:"local_ui",description:"Configure, save, and activate LLM provider",handler:()=>"login"}),t.register({name:"help",type:"local",description:"Show available commands",handler:e=>{if(e.args){let s=t.find(e.args);return s?`/${s.name} \u2014 ${s.description}
958
+ ${Wt(P_,{change_files:s,diffs:n,current_system_date_time:e.currentDate,requirement_background:e.background})}`;l=await Fr(e.utilClient,d,r)}catch(d){if(r?.aborted)throw d;l=""}}let u=[];for(let d=1;d<=e.maxRounds;d++){r?.throwIfAborted();let h=d>1?"":l,p=e.collector.snapshot();e.onPhase("review",`Review round ${String(d)}/${String(e.maxRounds)}\u2026`);let m=J_({changeFiles:s,diffs:n,currentDateTime:e.currentDate,background:e.background,planGuidance:h,confirmedComments:Y_(u)}),f=await cx(t,e,{message:m,agentClient:a}),g=e.collector.since(p);!f&&g.length===0&&(e.onPhase("review","No review activity; retrying with a nudge\u2026"),f=await cx(t,e,{message:m+N_,agentClient:a}),g=e.collector.since(p));let w=g;if(!e.skipFilter&&g.length>0){e.onPhase("filter",`Fact-checking ${String(g.length)} finding(s)\u2026`);let b=await X_(xq(t.diffs,g,e.diffByPath),g,{client:e.utilClient,abortSignal:r});b.size>0&&(e.collector.removeAt([...b].map(k=>p+k)),e.onFiltered(b.size),w=g.filter((k,_)=>!b.has(_)))}if(u.push(...w),w.length===0||u.length>=V_)break}}function xq(t,e,r){let n=new Set;for(let o of t)n.add(o.oldPath),n.add(o.newPath);let s=[...t];for(let o of e){if(n.has(o.path))continue;let i=r.get(o.path);i&&!s.includes(i)&&(s.push(i),n.add(o.path))}return s}async function cx(t,e,r){let n=new An;n.register(new pc({collector:e.collector,groupDiffs:t.diffs,groupLabel:t.label,resolve:async c=>{for(let u of c){let d=e.diffByPath.get(u.path),h=d?pi(u,d):!1;h||(h=ax(u,e.allDiffs())!==null),!h&&d&&await lx(e.utilClient,u,d,e.abortSignal)}}})),n.register(new fc(e.diffByPath)),n.register(new jr),n.register(new zr),n.register(new Or);let s=new qe;s.addUserMessage(r.message);let o=new pr({client:r.agentClient,registry:n,checker:new Ut(e.workDir,"default"),conversation:s,workDir:e.workDir,maxIterations:yq,abortSignal:e.abortSignal,fileStateCache:new Pr,contextWindow:e.contextWindow,maxOutput:e.maxOutput}),i=`review:${pq()}:`,a=new Map,l=!1;try{for await(let c of o.run()){if(c.type==="tool_use"&&(l=!0,a.set(c.toolId,{toolName:c.toolName,startedAt:Date.now()}),e.onToolEvent?.({...c,toolId:i+c.toolId})),c.type==="tool_result"&&(a.delete(c.toolId),e.onToolEvent?.({...c,toolId:i+c.toolId})),c.type==="error")throw c.error;c.type==="loop_complete"&&c.stopReason==="interrupted"&&e.abortSignal?.throwIfAborted()}}finally{let c=Date.now();for(let[u,d]of a)e.onToolEvent?.({type:"tool_result",toolName:d.toolName,toolId:i+u,output:e.abortSignal?.aborted?"Review tool call interrupted.":"Review tool call did not complete.",isError:!0,elapsed:(c-d.startedAt)/1e3})}return l}function Tq(t){let e=new Set,r=[];for(let s of t){let o=`${s.path}:${String(s.startLine)}:${s.content}`;e.has(o)||(e.add(o),r.push(s))}let n={critical:0,high:1,medium:2,low:3};return r.sort((s,o)=>s.path!==o.path?s.path.localeCompare(o.path):s.startLine!==o.startLine?s.startLine-o.startLine:(n[s.severity]??9)-(n[o.severity]??9))}var af=class{commands=new Map;register(e){if(this.commands.has(e.name))throw new Error(`Command '${e.name}' already registered`);this.commands.set(e.name,e)}find(e){return this.commands.get(e)}complete(e){let r=e.toLowerCase();return[...this.commands.values()].filter(n=>n.name.toLowerCase().startsWith(r))}listCommands(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};function rZ(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trim(),r=e.search(/\s/),n=r===-1?e:e.slice(0,r);return n.includes("/")?null:r===-1?{name:n,args:""}:{name:n,args:e.slice(r+1).trim()}}function nZ(){let t=new af;return t.register({name:"login",type:"local_ui",description:"Configure, save, and activate LLM provider",handler:()=>"login"}),t.register({name:"model",type:"local_ui",description:"Switch the model of the current provider",handler:()=>"model"}),t.register({name:"help",type:"local",description:"Show available commands",handler:e=>{if(e.args){let s=t.find(e.args);return s?`/${s.name} \u2014 ${s.description}
959
959
  `:`Unknown command: ${e.args}`}let r=t.listCommands().filter(s=>!s.isSkill),n=`Available commands:
960
960
 
961
961
  `;return n+=r.map(s=>` /${s.name}