@aventurevc/mcp-server 0.8.206 → 0.8.207

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{B as e,E as t,H as n,L as r,O as i,R as a,V as o,c as s,d as c,l,n as u,t as d,z as f}from"../chunks/esm-CFkfzPrU.js";import{t as p}from"../chunks/commander-BB7CDPLs.js";import{A as m,C as h,D as g,E as _,F as v,G as y,I as b,K as x,N as S,O as C,P as w,T,V as E,W as D,Z as O,a as k,ct as A,d as j,et as ee,f as te,h as M,i as N,j as ne,k as re,l as ie,o as ae,p as oe,q as se,s as ce,t as le,tt as ue,u as de,ut as fe,vt as pe,w as me,x as he}from"../chunks/logging-Dg0n6y4b.js";import{A as ge,D as _e,E as ve,F as ye,I as be,L as xe,M as Se,N as Ce,P as we,S as Te,_ as Ee,b as De,j as Oe,k as ke}from"../chunks/tool-policy-DkhiYpLq.js";import{A as Ae,D as je,E as P,S as F,T as I,_ as L,b as R,c as Me,d as Ne,f as Pe,g as z,h as Fe,i as Ie,k as Le,l as B,m as Re,o as V,p as ze,r as Be,s as Ve,u as H,v as U,w as W,x as He,y as G}from"../chunks/person-owner-BJgNYLKX.js";import{$ as Ue,$n as We,$t as Ge,A as Ke,An as qe,Ar as Je,At as Ye,B as Xe,Bn as Ze,Bt as Qe,C as $e,Cn as et,Cr as tt,Ct as nt,D as rt,Dn as it,Dr as at,Dt as ot,E as st,En as ct,Er as lt,Et as ut,F as dt,Fn as ft,Ft as pt,G as mt,Gn as ht,Gt as gt,H as _t,Hn as vt,Hr as yt,Ht as bt,I as xt,In as St,Ir as Ct,It as wt,J as Tt,Jn as Et,Jt as Dt,K as Ot,Kn as kt,Kt as At,L as jt,Ln as Mt,Lr as Nt,Lt as Pt,M as Ft,Mn as It,Mr as Lt,Mt as Rt,N as zt,Nn as Bt,Nr as Vt,Nt as Ht,O as Ut,On as Wt,Or as Gt,Ot as Kt,Pn as qt,Pr as Jt,Pt as Yt,Q as Xt,Qn as Zt,Qt,R as $t,Rn as en,Rr as tn,Rt as nn,S as rn,Sn as an,Sr as on,St as sn,T as cn,Tn as ln,Tr as un,Tt as dn,U as fn,Un as pn,Ur as mn,Ut as hn,V as gn,Vn as _n,Vr as vn,Vt as yn,W as bn,Wn as xn,Wt as Sn,X as Cn,Xn as wn,Xt as Tn,Y as En,Yn as Dn,Yt as On,Z as kn,Zn as An,Zt as jn,_ as Mn,_n as Nn,_r as Pn,_t as Fn,a as In,an as Ln,ar as Rn,at as zn,b as Bn,bn as Vn,br as Hn,bt as Un,c as Wn,cn as Gn,cr as Kn,ct as qn,d as Jn,dn as Yn,dr as Xn,dt as Zn,en as Qn,er as $n,et as er,f as tr,fn as nr,fr as rr,ft as ir,g as ar,gn as or,gr as sr,gt as cr,h as lr,hn as ur,hr as dr,ht as fr,i as pr,in as mr,ir as hr,it as gr,j as _r,jn as vr,jt as yr,k as br,kn as xr,kr as Sr,kt as Cr,l as wr,ln as Tr,lr as Er,lt as Dr,m as Or,mn as kr,mr as Ar,mt as jr,n as Mr,nn as Nr,nr as Pr,nt as Fr,o as Ir,on as Lr,or as Rr,ot as zr,p as Br,pn as Vr,pr as Hr,pt as Ur,q as Wr,qn as Gr,qt as Kr,r as qr,rn as Jr,rr as Yr,rt as Xr,s as Zr,sn as Qr,sr as $r,st as ei,t as ti,tn as ni,tr as ri,tt as ii,u as ai,un as oi,ur as si,ut as ci,v as li,vn as ui,vr as di,w as fi,wn as pi,wr as mi,wt as hi,x as gi,xn as _i,xr as vi,xt as yi,y as bi,yn as xi,yr as Si,yt as Ci,z as wi,zn as Ti,zr as Ei,zt as Di}from"../chunks/dist-CkrxZGUz.js";import{c as Oi,d as ki,i as Ai,p as ji,r as Mi,u as Ni}from"../chunks/result-envelope-BhUzhqlb.js";import{a as Pi}from"../chunks/package-DPDX5zmx.js";import{t as Fi}from"../chunks/provider-catalog-BMIyz1UJ.js";import{C as Ii,_ as Li,b as Ri,f as zi,h as Bi,i as Vi,m as Hi,p as Ui,r as Wi,t as Gi,v as Ki,x as qi,y as Ji}from"../chunks/contract-DJ_CoOxY.js";import{n as Yi,t as Xi}from"../chunks/mcp-generation-contract-CwV6ilRb.js";import Zi from"crypto";import{Readable as Qi}from"stream";import{Buffer as $i}from"node:buffer";import{fileURLToPath as ea}from"node:url";import{isIP as ta,isIPv4 as na,isIPv6 as ra}from"node:net";import{createHash as ia,randomUUID as aa,timingSafeEqual as oa}from"node:crypto";var sa={name:`metric_data_point`,countItems:e=>{let t=0;for(let n of e.scopeMetrics)for(let e of n.metrics)t+=e.dataPoints.length;return t}},ca,la=a((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(ca||={})})),K,ua,da=a((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(K||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(ua||={})}));function fa(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function pa(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function ma(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new va(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function ha(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ga(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}function _a(e,t){return e.toLowerCase()===t.toLowerCase()}var va,ya=a((()=>{va=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),ba,xa=a((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(ba||={})})),Sa,Ca=a((()=>{xa(),Sa=class{kind=ba.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function wa(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Ta,Ea,Da=a((()=>{xa(),da(),ya(),Ta=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=wa(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=ga(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Ea=class{kind=ba.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Ta(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]+a[e];let s=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(s=Math.min(n.min,r.min),c=Math.max(n.max,r.max)):n.hasMinMax?(s=n.min,c=n.max):r.hasMinMax&&(s=r.min,c=r.max)),new Ta(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:s,max:c})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=a[e]-i[e];return new Ta(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:ua.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}})),Oa,ka,Aa=a((()=>{Oa=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new ka,t=0,n=0,r=0){this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=r}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}},ka=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}}));function ja(e){return Ba.setFloat64(0,e),{hi:Ba.getUint32(0),lo:Ba.getUint32(4)}}function Ma(e){let{hi:t}=ja(e);return((t&Pa)>>20)-Ia}function Na(e){let{hi:t,lo:n}=ja(e);return(t&Fa)===0&&n===0}var Pa,Fa,Ia,La,Ra,za,Ba,Va=a((()=>{Pa=2146435072,Fa=1048575,Ia=1023,La=-1022,Ra=Ia,za=2**-1022,Ba=new DataView(new ArrayBuffer(8))}));function Ha(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Ua(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Wa=a((()=>{})),Ga,Ka=a((()=>{Ga=class extends Error{}})),qa,Ja=a((()=>{Va(),Wa(),Ka(),qa=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<za?this._minNormalLowerBoundaryIndex():Ma(e)+(Na(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Ga(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Ga(`overflow: ${e} is > maximum lower boundary: ${n}`);return Ha(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=La>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Ra>>this._shift}}})),Ya,Xa=a((()=>{Va(),Wa(),Ka(),Ya=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=Ha(Math.LOG2E,e),this._inverseFactor=Ha(Math.LN2,-e)}mapToIndex(e){if(e<=za)return this._minNormalLowerBoundaryIndex()-1;if(Na(e))return(Ma(e)<<this._scale)-1;let t=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return t>=n?n:t}lowerBoundary(e){let t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Ga(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return za;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Ga(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return La<<this._scale}_maxNormalLowerBoundaryIndex(){return(Ra+1<<this._scale)-1}}}));function Za(e){if(e>$a||e<Qa)throw new Ga(`expected scale >= ${Qa} && <= ${$a}, got: ${e}`);return eo[e+10]}var Qa,$a,eo,to=a((()=>{Ja(),Xa(),Ka(),Qa=-10,$a=20,eo=Array.from({length:31},(e,t)=>t>10?new Ya(t-10):new qa(t-10))})),no,ro,io,ao,oo,so,co=a((()=>{xa(),da(),u(),Aa(),to(),Wa(),no=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}low;high;constructor(e,t){this.low=e,this.high=t}},ro=20,io=160,ao=2,oo=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=io,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Oa,u=new Oa,d=Za(ro)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=u,this._mapping=d,this._maxSize<ao&&(l.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
2
+ import{B as e,E as t,H as n,L as r,O as i,R as a,V as o,c as s,d as c,l,n as u,t as d,z as f}from"../chunks/esm-CFkfzPrU.js";import{t as p}from"../chunks/commander-BB7CDPLs.js";import{A as m,C as h,D as g,E as _,F as v,G as y,I as b,K as x,N as S,O as C,P as w,T,V as E,W as D,Z as O,a as k,ct as A,d as j,et as ee,f as te,h as M,i as N,j as ne,k as re,l as ie,o as ae,p as oe,q as se,s as ce,t as le,tt as ue,u as de,ut as fe,vt as pe,w as me,x as he}from"../chunks/logging-B804Egte.js";import{A as ge,D as _e,E as ve,F as ye,I as be,L as xe,M as Se,N as Ce,P as we,S as Te,_ as Ee,b as De,j as Oe,k as ke}from"../chunks/tool-policy-CFolhIHo.js";import{A as Ae,D as je,E as P,S as F,T as I,_ as L,b as R,c as Me,d as Ne,f as Pe,g as z,h as Fe,i as Ie,k as Le,l as B,m as Re,o as V,p as ze,r as Be,s as Ve,u as H,v as U,w as W,x as He,y as G}from"../chunks/person-owner-BJgNYLKX.js";import{$ as Ue,$n as We,$t as Ge,A as Ke,An as qe,Ar as Je,At as Ye,B as Xe,Bn as Ze,Bt as Qe,C as $e,Cn as et,Cr as tt,Ct as nt,D as rt,Dn as it,Dr as at,Dt as ot,E as st,En as ct,Er as lt,Et as ut,F as dt,Fn as ft,Ft as pt,G as mt,Gn as ht,Gt as gt,H as _t,Hn as vt,Ht as yt,I as bt,In as xt,Ir as St,It as Ct,J as wt,Jn as Tt,Jr as Et,Jt as Dt,K as Ot,Kn as kt,Kr as At,Kt as jt,L as Mt,Ln as Nt,Lr as Pt,Lt as Ft,M as It,Mn as Lt,Mr as Rt,Mt as zt,N as Bt,Nn as Vt,Nr as Ht,Nt as Ut,O as Wt,On as Gt,Or as Kt,Ot as qt,Pn as Jt,Pr as Yt,Pt as Xt,Q as Zt,Qn as Qt,Qt as $t,R as en,Rn as tn,Rr as nn,Rt as rn,S as an,Sn as on,Sr as sn,St as cn,T as ln,Tn as un,Tr as dn,Tt as fn,U as pn,Un as mn,Ut as hn,V as gn,Vn as _n,Vr as vn,Vt as yn,W as bn,Wn as xn,Wt as Sn,X as Cn,Xn as wn,Xt as Tn,Y as En,Yn as Dn,Yt as On,Z as kn,Zn as An,Zt as jn,_ as Mn,_n as Nn,_r as Pn,_t as Fn,a as In,an as Ln,ar as Rn,at as zn,b as Bn,bn as Vn,br as Hn,bt as Un,c as Wn,cn as Gn,cr as Kn,ct as qn,d as Jn,dn as Yn,dr as Xn,dt as Zn,en as Qn,er as $n,et as er,f as tr,fn as nr,fr as rr,ft as ir,g as ar,gn as or,gr as sr,gt as cr,h as lr,hn as ur,hr as dr,ht as fr,i as pr,in as mr,ir as hr,it as gr,j as _r,jn as vr,jt as yr,k as br,kn as xr,kr as Sr,kt as Cr,l as wr,ln as Tr,lr as Er,lt as Dr,m as Or,mn as kr,mr as Ar,mt as jr,n as Mr,nn as Nr,nr as Pr,nt as Fr,o as Ir,on as Lr,or as Rr,ot as zr,p as Br,pn as Vr,pr as Hr,pt as Ur,q as Wr,qn as Gr,qr as Kr,qt as qr,r as Jr,rn as Yr,rr as Xr,rt as Zr,s as Qr,sn as $r,sr as ei,st as ti,t as ni,tn as ri,tr as ii,tt as ai,u as oi,un as si,ur as ci,ut as li,v as ui,vn as di,vr as fi,w as pi,wn as mi,wr as hi,wt as gi,x as _i,xn as vi,xr as yi,xt as bi,y as xi,yn as Si,yr as Ci,yt as wi,z as Ti,zn as Ei,zr as Di,zt as Oi}from"../chunks/dist-xUtpL3iS.js";import{f as ki,i as Ai,l as ji,r as Mi,s as Ni,u as Pi}from"../chunks/result-envelope-BKs-tese.js";import{a as Fi}from"../chunks/package-DPDX5zmx.js";import{t as Ii}from"../chunks/provider-catalog-8OOstDRa.js";import{_ as Li,b as Ri,f as zi,h as Bi,i as Vi,m as Hi,p as Ui,r as Wi,t as Gi,v as Ki,x as qi,y as Ji}from"../chunks/contract-BGyWTcJb.js";import{n as Yi,t as Xi}from"../chunks/mcp-generation-contract-CwV6ilRb.js";import Zi from"crypto";import{Readable as Qi}from"stream";import{Buffer as $i}from"node:buffer";import{fileURLToPath as ea}from"node:url";import{isIP as ta,isIPv4 as na,isIPv6 as ra}from"node:net";import{createHash as ia,randomUUID as aa,timingSafeEqual as oa}from"node:crypto";var sa={name:`metric_data_point`,countItems:e=>{let t=0;for(let n of e.scopeMetrics)for(let e of n.metrics)t+=e.dataPoints.length;return t}},ca,la=a((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(ca||={})})),K,ua,da=a((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(K||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(ua||={})}));function fa(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function pa(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function ma(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new va(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function ha(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ga(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}function _a(e,t){return e.toLowerCase()===t.toLowerCase()}var va,ya=a((()=>{va=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),ba,xa=a((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(ba||={})})),Sa,Ca=a((()=>{xa(),Sa=class{kind=ba.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function wa(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Ta,Ea,Da=a((()=>{xa(),da(),ya(),Ta=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=wa(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=ga(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Ea=class{kind=ba.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Ta(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]+a[e];let s=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(s=Math.min(n.min,r.min),c=Math.max(n.max,r.max)):n.hasMinMax?(s=n.min,c=n.max):r.hasMinMax&&(s=r.min,c=r.max)),new Ta(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:s,max:c})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=a[e]-i[e];return new Ta(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:ua.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}})),Oa,ka,Aa=a((()=>{Oa=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new ka,t=0,n=0,r=0){this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=r}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}},ka=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}}));function ja(e){return Ba.setFloat64(0,e),{hi:Ba.getUint32(0),lo:Ba.getUint32(4)}}function Ma(e){let{hi:t}=ja(e);return((t&Pa)>>20)-Ia}function Na(e){let{hi:t,lo:n}=ja(e);return(t&Fa)===0&&n===0}var Pa,Fa,Ia,La,Ra,za,Ba,Va=a((()=>{Pa=2146435072,Fa=1048575,Ia=1023,La=-1022,Ra=Ia,za=2**-1022,Ba=new DataView(new ArrayBuffer(8))}));function Ha(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Ua(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Wa=a((()=>{})),Ga,Ka=a((()=>{Ga=class extends Error{}})),qa,Ja=a((()=>{Va(),Wa(),Ka(),qa=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<za?this._minNormalLowerBoundaryIndex():Ma(e)+(Na(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Ga(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Ga(`overflow: ${e} is > maximum lower boundary: ${n}`);return Ha(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=La>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Ra>>this._shift}}})),Ya,Xa=a((()=>{Va(),Wa(),Ka(),Ya=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=Ha(Math.LOG2E,e),this._inverseFactor=Ha(Math.LN2,-e)}mapToIndex(e){if(e<=za)return this._minNormalLowerBoundaryIndex()-1;if(Na(e))return(Ma(e)<<this._scale)-1;let t=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return t>=n?n:t}lowerBoundary(e){let t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Ga(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return za;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Ga(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return La<<this._scale}_maxNormalLowerBoundaryIndex(){return(Ra+1<<this._scale)-1}}}));function Za(e){if(e>$a||e<Qa)throw new Ga(`expected scale >= ${Qa} && <= ${$a}, got: ${e}`);return eo[e+10]}var Qa,$a,eo,to=a((()=>{Ja(),Xa(),Ka(),Qa=-10,$a=20,eo=Array.from({length:31},(e,t)=>t>10?new Ya(t-10):new qa(t-10))})),no,ro,io,ao,oo,so,co=a((()=>{xa(),da(),u(),Aa(),to(),Wa(),no=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}low;high;constructor(e,t){this.low=e,this.high=t}},ro=20,io=160,ao=2,oo=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=io,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Oa,u=new Oa,d=Za(ro)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=u,this._mapping=d,this._maxSize<ao&&(l.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
3
3
  changing to the minimum size of: ${ao}`),this._maxSize=ao)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){if(Number.isFinite(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new e(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,n){let r=this._mapping.mapToIndex(t),i=!1,a=0,o=0;if(e.length===0?(e.indexStart=r,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):r<e.indexStart&&e.indexEnd-r>=this._maxSize?(i=!0,o=r,a=e.indexEnd):r>e.indexEnd&&r-e.indexStart>=this._maxSize&&(i=!0,o=e.indexStart,a=r),i){let e=this._changeScale(a,o);this._downscale(e),r=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,r,n)}_incrementIndexBy(e,t,n){if(n===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){let n=e.indexEnd-t;n>=e.backing.length&&this._grow(e,n+1),e.indexStart=t}else if(t>e.indexEnd){let n=t-e.indexStart;n>=e.backing.length&&this._grow(e,n+1),e.indexEnd=t}let r=t-e.indexBase;r<0&&(r+=e.backing.length),e.incrementBucket(r,n)}_grow(e,t){let n=e.backing.length,r=e.indexBase-e.indexStart,i=n-r,a=Ua(t);a>this._maxSize&&(a=this._maxSize);let o=a-r;e.backing.growTo(a,i,o)}_changeScale(e,t){let n=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n}_downscale(e){if(e===0)return;if(e<0)throw Error(`impossible change of scale: ${this.scale}`);let t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Za(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=no.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=no.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(r.high,r.low))}_highLowAtScale(e,t,n){if(e.length===0)return new no(0,-1);let r=t-n;return new no(e.indexStart>>r,e.indexEnd>>r)}_mergeBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++)this._incrementIndexBy(e,i+t>>a,n.at(t))}_diffBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++){let r=(i+t>>a)-e.indexBase;r<0&&(r+=e.backing.length),e.decrementBucket(r,n.at(t))}e.trim()}},so=class{kind=ba.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new oo(e,this._maxSize,this._recordMinMax)}merge(e,t){let n=t.clone();return n.merge(e),n}diff(e,t){let n=t.clone();return n.diff(e),n}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:ua.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}})),lo,uo,fo=a((()=>{xa(),v(),da(),lo=class{startTime;_current;sampleTime;constructor(e,t=0,n=[0,0]){this.startTime=e,this._current=t,this.sampleTime=n}record(e){this._current=e,this.sampleTime=O(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},uo=class{kind=ba.LAST_VALUE;createAccumulation(e){return new lo(e)}merge(e,t){let n=x(t.sampleTime)>=x(e.sampleTime)?t:e;return new lo(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=x(t.sampleTime)>=x(e.sampleTime)?t:e;return new lo(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:ua.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),po,mo,ho=a((()=>{xa(),da(),po=class{startTime;monotonic;_current;reset;constructor(e,t,n=0,r=!1){this.startTime=e,this.monotonic=t,this._current=n,this.reset=r}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},mo=class{kind=ba.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new po(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new po(t.startTime,this.monotonic,r,t.reset):new po(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new po(t.startTime,this.monotonic,r,!0):new po(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:ua.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),go=a((()=>{Ca(),Da(),co(),fo(),ho()})),_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko=a((()=>{u(),go(),da(),_o=class e{static DEFAULT_INSTANCE=new Sa;createAggregator(t){return e.DEFAULT_INSTANCE}},vo=class e{static MONOTONIC_INSTANCE=new mo(!0);static NON_MONOTONIC_INSTANCE=new mo(!1);createAggregator(t){switch(t.type){case K.COUNTER:case K.OBSERVABLE_COUNTER:case K.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},yo=class e{static DEFAULT_INSTANCE=new uo;createAggregator(t){return e.DEFAULT_INSTANCE}},bo=class e{static DEFAULT_INSTANCE=new Ea([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}},xo=class{_boundaries;_recordMinMax;constructor(e,t=!0){if(e==null)throw Error(`ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array`);e=e.concat(),e=e.sort((e,t)=>e-t);let n=e.lastIndexOf(-1/0),r=e.indexOf(1/0);r===-1&&(r=void 0),this._boundaries=e.slice(n+1,r),this._recordMinMax=t}createAggregator(e){return new Ea(this._boundaries,this._recordMinMax)}},So=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new so(this._maxSize,this._recordMinMax)}},Co=class{_resolve(e){switch(e.type){case K.COUNTER:case K.UP_DOWN_COUNTER:case K.OBSERVABLE_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:return To;case K.GAUGE:case K.OBSERVABLE_GAUGE:return Eo;case K.HISTOGRAM:return e.advice.explicitBucketBoundaries?new xo(e.advice.explicitBucketBoundaries):Do}return l.warn(`Unable to recognize instrument type: ${e.type}`),wo}createAggregator(e){return this._resolve(e).createAggregator(e)}},wo=new _o,To=new vo,Eo=new yo,Do=new bo,new So,Oo=new Co}));function Ao(e){switch(e.type){case jo.DEFAULT:return Oo;case jo.DROP:return wo;case jo.SUM:return To;case jo.LAST_VALUE:return Eo;case jo.EXPONENTIAL_HISTOGRAM:{let t=e;return new So(t.options?.maxSize,t.options?.recordMinMax)}case jo.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?Do:new xo(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var jo,Mo=a((()=>{ko(),(function(e){e[e.DEFAULT=0]=`DEFAULT`,e[e.DROP=1]=`DROP`,e[e.SUM=2]=`SUM`,e[e.LAST_VALUE=3]=`LAST_VALUE`,e[e.EXPLICIT_BUCKET_HISTOGRAM=4]=`EXPLICIT_BUCKET_HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=5]=`EXPONENTIAL_HISTOGRAM`})(jo||={})})),No,Po,Fo=a((()=>{la(),Mo(),No=e=>({type:jo.DEFAULT}),Po=e=>ca.CUMULATIVE})),Io,Lo,Ro,zo,Bo,Vo=a((()=>{Io=`otel.component.name`,Lo=`otel.component.type`,Ro=`periodic_metric_reader`,zo=`otel.sdk.metric_reader.collection.duration`,Bo=`error.type`})),Ho,Uo,Wo=a((()=>{Vo(),Ho=new Map,Uo=class{collectionDuration;standardAttrs;constructor(e,t){let n=Ho.get(e)??0;Ho.set(e,n+1),this.standardAttrs={[Lo]:e,[Io]:`${e}/${n}`},this.collectionDuration=t.createHistogram(zo,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[Bo]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}}})),Go,Ko=a((()=>{Go=`2.11.0`})),qo,Jo=a((()=>{u(),ya(),Fo(),Wo(),Ko(),v(),qo=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_selfObsMetrics;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;_otelComponentType;constructor(e){this._aggregationSelector=e?.aggregationSelector??No,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??Po,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new Uo(this._otelComponentType,i())}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}_setSelfObsMeterProvider(e){let t=e.getMeter(`@opentelemetry/sdk-metrics`,Go);this._selfObsMetrics=new Uo(this._otelComponentType,t)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw Error(`MetricReader is not bound to a MetricProducer`);if(this._shutdown)throw Error(`MetricReader is shutdown`);let t=D(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=D(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=se(y(t,i));return this._selfObsMetrics.recordCollection(o,a.length>0?a[0].name??`collect_error`:void 0),{resourceMetrics:{resource:n.resourceMetrics.resource,scopeMetrics:n.resourceMetrics.scopeMetrics.concat(r.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:a}}async shutdown(e){if(this._shutdown){l.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await ma(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){l.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await ma(this.onForceFlush(),e.timeoutMillis)}}}));function Yo(e,t){if(!Number.isInteger(t)||t<=0)throw Error(`maxExportBatchSize must be a positive integer`);let n=[],r=0,i=[];function a(){i.length>0&&(n.push({resource:e.resource,scopeMetrics:i}),i=[],r=0)}for(let n of e.scopeMetrics){let e=null;for(let o of n.metrics){let s=o.dataPoints;if(s.length===0){e||(e={scope:n.scope,metrics:[]},i.push(e)),e.metrics.push(o);continue}let c=0;for(;c<s.length;){let l=t-r,u=Math.min(l,s.length-c);e||(e={scope:n.scope,metrics:[]},i.push(e));let d={...o,dataPoints:s.slice(c,c+u)};e.metrics.push(d),c+=u,r+=u,r===t&&(a(),e=null)}}}return a(),n}var Xo=a((()=>{})),Zo,Qo=a((()=>{u(),v(),Jo(),ya(),da(),Xo(),Vo(),Zo=class extends qo{_interval;_exporter;_exportInterval;_exportTimeout;_maxExportBatchSize;_ongoingExportPromise=null;constructor(e){let{exporter:t,exportIntervalMillis:n=6e4,metricProducers:r,cardinalityLimits:i,maxExportBatchSize:a}=e,{exportTimeoutMillis:o=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),otelComponentType:Ro,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...i};switch(e){case K.COUNTER:return t.counter??t.default;case K.GAUGE:return t.gauge??t.default;case K.HISTOGRAM:return t.histogram??t.default;case K.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case K.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case K.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case K.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),n<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(o<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(a!==void 0&&(!Number.isInteger(a)||a<=0))throw Error(`maxExportBatchSize must be a positive integer`);if(n<o){if(`exportIntervalMillis`in e&&`exportTimeoutMillis`in e)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);l.info(`Timeout of ${o} exceeds the interval of ${n}. Clamping timeout to interval duration.`),o=n}this._exportInterval=n,this._exportTimeout=o,this._exporter=t,this._maxExportBatchSize=a}async _runOnce(){try{await this._doRun()}catch(e){fe(e)}}async _doRun(){if(this._ongoingExportPromise){l.debug(`PeriodicExportingMetricReader: export already in progress, skipping`);return}let e=async()=>{let{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&l.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){l.debug(`Error while resolving async portion of resource: `,e),fe(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?Yo(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await ma(b._export(this._exporter,e),this._exportTimeout);t.code!==E.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof va){l.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}l.error(`PeriodicExportingMetricReader: metrics export threw error`,e),r=e instanceof Error?e:Error(String(e))}if(r)throw r};this._ongoingExportPromise=e();try{await this._ongoingExportPromise}finally{this._ongoingExportPromise=null}}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!=`number`&&this._interval.unref()}async onForceFlush(){await this._awaitOngoingExport(),this._ongoingExportPromise?await this._awaitOngoingExport():await this._runOnce(),await this._exporter.forceFlush()}async _awaitOngoingExport(){if(this._ongoingExportPromise){l.debug(`PeriodicExportingMetricReader: export already in progress, awaiting ongoing export`);try{await this._ongoingExportPromise}catch{}}}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}})),$o,es=a((()=>{v(),$o=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){if(this._shutdown){setTimeout(()=>t({code:E.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>t({code:E.SUCCESS}),0)}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}})),ts,ns=a((()=>{v(),Fo(),ts=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??Po}export(t,n){if(this._shutdown){n({code:E.FAILED});return}return e._sendMetrics(t,n)}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(let t of e.scopeMetrics)for(let e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:E.SUCCESS})}}})),rs,is=a((()=>{rs=class{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(n=>this._matchInstrument(n.instrumentSelector,e)&&this._matchMeter(n.meterSelector,t))}_matchInstrument(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))}}}));function as(e,n,r){return cs(e)||l.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:n,description:r?.description??``,unit:r?.unit??``,valueType:r?.valueType??t.DOUBLE,advice:r?.advice??{}}}function os(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function ss(e,t){return _a(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function cs(e){return ls.test(e)}var ls,us=a((()=>{u(),ya(),ls=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function ds(e){return e instanceof _s}var fs,ps,ms,hs,gs,_s,vs,ys,bs,xs=a((()=>{u(),fs=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,n={},r){if(typeof e!=`number`){l.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===t.INT&&!Number.isInteger(e)&&(l.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,n,r,Date.now())}},ps=class extends fs{add(e,t,n){this._record(e,t,n)}},ms=class extends fs{add(e,t,n){if(e<0){l.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},hs=class extends fs{record(e,t,n){this._record(e,t,n)}},gs=class extends fs{record(e,t,n){if(e<0){l.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},_s=class{_metricStorages;_descriptor;_observableRegistry;constructor(e,t,n){this._descriptor=e,this._metricStorages=t,this._observableRegistry=n}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}},vs=class extends _s{},ys=class extends _s{},bs=class extends _s{}})),Ss,Cs=a((()=>{us(),xs(),da(),Ss=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){let n=as(e,K.GAUGE,t),r=this._meterSharedState.registerMetricStorage(n);return new hs(r,n)}createHistogram(e,t){let n=as(e,K.HISTOGRAM,t),r=this._meterSharedState.registerMetricStorage(n);return new gs(r,n)}createCounter(e,t){let n=as(e,K.COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new ms(r,n)}createUpDownCounter(e,t){let n=as(e,K.UP_DOWN_COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new ps(r,n)}createObservableGauge(e,t){let n=as(e,K.OBSERVABLE_GAUGE,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new ys(n,r,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=as(e,K.OBSERVABLE_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new vs(n,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=as(e,K.OBSERVABLE_UP_DOWN_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new bs(n,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),ws,Ts=a((()=>{us(),ws=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=as(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),Es,Ds,Os=a((()=>{ya(),Es=class{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){let n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);let r=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r),r}set(e,t,n){n??=this._hash(e),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){let e=this._keyMap.entries(),t=e.next();for(;t.done!==!0;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){let e=this._valueMap.entries(),t=e.next();for(;t.done!==!0;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}},Ds=class extends Es{constructor(){super(fa)}}})),ks,As=a((()=>{v(),ya(),Os(),ks=class{_activeCollectionStorage=new Ds;_cumulativeMemoStorage=new Ds;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=fa(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=O(n);if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(i))?.record(e);return}r=this._aggregator.createAccumulation(i),this._activeCollectionStorage.set(t,r)}r?.record(e)}batchCumulate(e,t){for(let[n,r,i]of e.entries()){let e=n,a=i,o=this._aggregator.createAccumulation(t);o?.record(r);let s=o;if(this._cumulativeMemoStorage.has(e,a)){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,a=this._overflowHashCode,this._cumulativeMemoStorage.has(e,a))){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}if(this._activeCollectionStorage.has(e,a)){let t=this._activeCollectionStorage.get(e,a);s=this._aggregator.merge(t,s)}this._cumulativeMemoStorage.set(e,o,a),this._activeCollectionStorage.set(e,s,a)}}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new Ds,e}}}));function js(e){return Array.from(e.entries())}var Ms,Ns=a((()=>{la(),Os(),Ms=class e{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(t,n,r,i){this._stashAccumulations(r);let a=this._getMergedUnreportedAccumulations(t),o=a,s;if(this._reportHistory.has(t)){let n=this._reportHistory.get(t),r=n.collectionTime;s=n.aggregationTemporality,o=s===ca.CUMULATIVE?e.merge(n.accumulations,a,this._aggregator):e.calibrateStartTime(n.accumulations,a,r)}else s=t.selectAggregationTemporality(n.type);this._reportHistory.set(t,{accumulations:o,collectionTime:i,aggregationTemporality:s});let c=js(o);if(c.length!==0)return this._aggregator.toMetricData(n,s,c,i)}_stashAccumulations(e){let t=this._unreportedAccumulations.keys();for(let n of t){let t=this._unreportedAccumulations.get(n);t===void 0&&(t=[],this._unreportedAccumulations.set(n,t)),t.push(e)}}_getMergedUnreportedAccumulations(t){let n=new Ds,r=this._unreportedAccumulations.get(t);if(this._unreportedAccumulations.set(t,[]),r===void 0)return n;for(let t of r)n=e.merge(n,t,this._aggregator);return n}static merge(e,t,n){let r=e,i=t.entries(),a=i.next();for(;a.done!==!0;){let[t,o,s]=a.value;if(e.has(t,s)){let i=e.get(t,s),a=n.merge(i,o);r.set(t,a,s)}else r.set(t,o,s);a=i.next()}return r}static calibrateStartTime(e,t,n){for(let[r,i]of e.keys())t.get(r,i)?.setStartTime(n);return t}}})),Ps,Fs=a((()=>{Ts(),As(),Ns(),Os(),Ps=class extends ws{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new ks(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ms(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new Ds;for(let[t,r]of e.entries())n.set(this._attributesProcessor.process(t),r);this._deltaMetricStorage.batchCumulate(n,t)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}}));function Is(e,t){let n=``;return e.unit!==t.unit&&(n+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(n+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(n+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(n+=`\t- Description '${e.description}' does not match '${t.description}'\n`),n}function Ls(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function Rs(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function zs(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'`}function Bs(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'
4
4
  \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${r}
5
5
  \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${r}`}function Vs(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:Bs(e,t):zs(e,t):Rs(e,t):Ls(e,t)}var Hs=a((()=>{})),Us,Ws=a((()=>{us(),u(),Hs(),Us=class e{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new e}getStorages(e){let t=[];for(let e of this._sharedRegistry.values())t=t.concat(e);let n=this._perCollectorRegistry.get(e);if(n!=null)for(let e of n.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let n=this._perCollectorRegistry.get(e);n??(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)}findOrUpdateCompatibleStorage(e){let t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){let n=this._perCollectorRegistry.get(e);if(n===void 0)return null;let r=n.get(t.name);return r===void 0?null:this._findOrUpdateCompatibleStorage(t,r)}_registerStorage(e,t){let n=e.getInstrumentDescriptor(),r=t.get(n.name);if(r===void 0){t.set(n.name,[e]);return}r.push(e)}_findOrUpdateCompatibleStorage(e,t){let n=null;for(let r of t){let t=r.getInstrumentDescriptor();ss(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),l.warn(`A view or instrument with the name `,e.name,` has already been registered, but has a different description and is incompatible with another registered view.
@@ -8,7 +8,7 @@ import{B as e,E as t,H as n,L as r,O as i,R as a,V as o,c as s,d as c,l,n as u,t
8
8
  To resolve the conflict:`,Vs(t,e))),n=r):l.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
9
9
  `,`Details:
10
10
  `,Is(t,e),`To resolve the conflict:
11
- `,Vs(t,e))}return n}}})),Gs,Ks=a((()=>{u(),Gs=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=c.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}}})),qs,Js,Ys=a((()=>{u(),Os(),xs(),qs=class{_buffer=new Ds;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){l.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.INT&&!Number.isInteger(e)&&(l.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},Js=class{_buffer=new Map;observe(e,n,r={}){if(!ds(e))return;let i=this._buffer.get(e);if(i??(i=new Ds,this._buffer.set(e,i)),typeof n!=`number`){l.warn(`non-number value provided to metric ${e._descriptor.name}: ${n}`);return}e._descriptor.valueType===t.INT&&!Number.isInteger(n)&&(l.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),n=Math.trunc(n),!Number.isInteger(n))||i.set(r,n)}}})),Xs,Zs=a((()=>{u(),xs(),Ys(),ya(),Xs=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(ds));if(n.size===0){l.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(ds)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new qs(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=ma(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Js,a=Promise.resolve(n(i));t!=null&&(a=ma(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&ha(n.instruments,t))}}})),Qs,$s=a((()=>{u(),Ts(),As(),Ns(),Qs=class extends ws{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new ks(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ms(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??c.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),ec,tc=a((()=>{us(),Cs(),Fs(),Ws(),Ks(),Zs(),$s(),ec=class{metricStorageRegistry=new Us;observableRegistry=new Xs;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Ss(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,Qs);return t.length===1?t[0]:new Gs(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Ps)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=os(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}}})),nc,rc=a((()=>{ya(),is(),tc(),Mo(),nc=class{viewRegistry=new rs;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=pa(e),n=this.meterSharedStates.get(t);return n??(n=new ec(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Ao(n.selectAggregation(e))]);return t}}})),ic,ac=a((()=>{v(),ic=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=O(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),oc,sc,cc,lc=a((()=>{oc=/[\^$\\.+?()[\]{}|]/g,sc=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(oc,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},cc=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}}));function uc(){return vc}function dc(e){return new hc(e)}function fc(e){return new gc(e)}function pc(e){return new _c(e)}var mc,hc,gc,_c,vc,yc=a((()=>{mc=class{process(e,t){return e}},hc=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},gc=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._allowedAttributeNames.has(t)&&(n[t]=e[t]);return n}},_c=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&!this._deniedAttributeNames.has(t)&&(n[t]=e[t]);return n}},vc=new mc})),bc,xc=a((()=>{lc(),bc=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new sc(e?.name??`*`),this._type=e?.type,this._unitFilter=new cc(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),Sc,Cc=a((()=>{lc(),Sc=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new cc(e?.name),this._versionFilter=new cc(e?.version),this._schemaUrlFilter=new cc(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}}));function wc(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function Tc(e){if(wc(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||sc.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var Ec,Dc=a((()=>{lc(),yc(),xc(),Cc(),Mo(),Ec=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){Tc(e),this.attributesProcessor=e.attributesProcessors==null?uc():dc(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Ao(e.aggregation??{type:jo.DEFAULT}),this.instrumentSelector=new bc({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Sc({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),Oc,kc=a((()=>{u(),m(),Jo(),rc(),ac(),Dc(),Oc=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new nc(e?.resource??ne()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new Ec(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new ic(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof qo&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(l.warn(`A shutdown MeterProvider cannot provide a Meter`),i()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){l.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){l.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),Ac=f({AggregationTemporality:()=>ca,AggregationType:()=>jo,ConsoleMetricExporter:()=>ts,DataPointType:()=>ua,InMemoryMetricExporter:()=>$o,InstrumentType:()=>K,MeterProvider:()=>Oc,MetricReader:()=>qo,PeriodicExportingMetricReader:()=>Zo,TimeoutError:()=>va,createAllowListAttributesProcessor:()=>fc,createDenyListAttributesProcessor:()=>pc}),jc=a((()=>{la(),da(),Jo(),Qo(),es(),ns(),kc(),Mo(),yc(),ya()})),Mc;(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(Mc||={}),u(),jc();function Nc(e,t){let n=C(e.resource,t);return{resource:n,schemaUrl:n.schemaUrl,scopeMetrics:Pc(e.scopeMetrics,t)}}function Pc(e,t){return Array.from(e.map(e=>({scope:g(e.scope,t),metrics:e.metrics.map(e=>Fc(e,t)),schemaUrl:e.scope.schemaUrl})))}function Fc(e,t){let n={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},r=Bc(e.aggregationTemporality);switch(e.dataPointType){case ua.SUM:n.sum={aggregationTemporality:r,isMonotonic:e.isMonotonic,dataPoints:Lc(e,t)};break;case ua.GAUGE:n.gauge={dataPoints:Lc(e,t)};break;case ua.HISTOGRAM:n.histogram={aggregationTemporality:r,dataPoints:Rc(e,t)};break;case ua.EXPONENTIAL_HISTOGRAM:n.exponentialHistogram={aggregationTemporality:r,dataPoints:zc(e,t)}}return n}function Ic(e,n,r){let i={attributes:re(e.attributes,r),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(n){case t.INT:i.asInt=e.value;break;case t.DOUBLE:i.asDouble=e.value}return i}function Lc(e,t){return e.dataPoints.map(n=>Ic(n,e.descriptor.valueType,t))}function Rc(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:re(e.attributes,t),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function zc(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:re(e.attributes,t),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Bc(e){switch(e){case ca.DELTA:return Mc.AGGREGATION_TEMPORALITY_DELTA;case ca.CUMULATIVE:return Mc.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Vc(e,t){return{resourceMetrics:e.map(e=>Nc(e,t))}}u();var Hc={serializeRequest:e=>{let t=Vc([e],_);return new TextEncoder().encode(JSON.stringify(t))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;try{return JSON.parse(t.decode(e))}catch(e){return l.warn(`Failed to parse metrics export response: ${e.message}. Returning empty response`),{}}}};function Uc(){let e,t;return async()=>(e===void 0&&(e=await(t??=Wc().finally(()=>{t=void 0}))),e)}async function Wc(){let e=`getAuthProviderCatalog`,t=await vn(he(),{method:`GET`,path:Je(e,{}),headers:{},operationId:e},Fi).catch(e=>{ae({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:le(e),fields:{requestId:_e()},error:e})});if(t===void 0)return;if(!t.ok||t.redirect){ae({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:`the API did not return an OAuth provider catalog`,fields:{requestId:_e()}});return}let n=t.data.oauthClient;if(n==null){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published no OAuth client; retrying on the next request that needs one`,fields:{requestId:_e()}});return}let r=n.mcpResource;if(r==null){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an OAuth client without an MCP resource indicator, so this server has no resource to advertise or audience to verify; retrying on the next request that needs one`,fields:{requestId:_e()}});return}if(!URL.canParse(r)){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an unusable MCP resource indicator: ${r}`,fields:{requestId:_e()}});return}let i=new URL(r);return k({component:`aventure-mcp-server`,event:`oauth_discovery_ready`,fields:{requestId:_e(),resource:i.href,authorizationServer:n.authorizationServer}}),{client:n,resourceUrl:i}}var Gc=2e3,Kc={userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,graphQL:{document:!1,variables:!1},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!1,frameContextLines:0},qc;async function Jc(){let e=Zc(process.env.SENTRY_DSN),t=Zc(process.env.SENTRY_RELEASE);if(e===void 0||t===void 0)return;let n=await import(`../chunks/esm-B_HfoRSQ.js`);n.init({dsn:e,environment:ce()[`deployment.environment.name`],release:t,dataCollection:Kc,beforeBreadcrumb:()=>null,beforeSend:e=>{let t=e.tags?.failure;return delete e.request,delete e.user,delete e.breadcrumbs,delete e.contexts,delete e.extra,delete e.transaction,delete e.tags,(t===`authentication_unavailable`||t===`server_start_failed`||t===`transport_error`)&&(e.tags={failure:t}),e}}),qc=n}function Yc(e,t){qc?.captureException(e,{tags:{failure:t}})}async function Xc(){let e=qc;qc=void 0,e!==void 0&&await e.close(Gc)}function Zc(e){return e?.trim()||void 0}var Qc=r(((e,t)=>{var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(e==null)throw TypeError(`Object.assign cannot be called with null or undefined`);return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String(`abc`);if(e[5]=`de`,Object.getOwnPropertyNames(e)[0]===`5`)return!1;for(var t={},n=0;n<10;n++)t[`_`+String.fromCharCode(n)]=n;if(Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(``)!==`0123456789`)return!1;var r={};return`abcdefghijklmnopqrst`.split(``).forEach(function(e){r[e]=e}),Object.keys(Object.assign({},r)).join(``)===`abcdefghijklmnopqrst`}catch{return!1}}t.exports=o()?Object.assign:function(e,t){for(var o,s=a(e),c,l=1;l<arguments.length;l++){for(var u in o=Object(arguments[l]),o)r.call(o,u)&&(s[u]=o[u]);if(n){c=n(o);for(var d=0;d<c.length;d++)i.call(o,c[d])&&(s[c[d]]=o[c[d]])}}return s}})),$c=r(((e,t)=>{t.exports=a,t.exports.append=r;var n=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function r(e,t){if(typeof e!=`string`)throw TypeError(`header argument is required`);if(!t)throw TypeError(`field argument is required`);for(var r=Array.isArray(t)?t:i(String(t)),a=0;a<r.length;a++)if(!n.test(r[a]))throw TypeError(`field argument contains an invalid header name`);if(e===`*`)return e;var o=e,s=i(e.toLowerCase());if(r.indexOf(`*`)!==-1||s.indexOf(`*`)!==-1)return`*`;for(var c=0;c<r.length;c++){var l=r[c].toLowerCase();s.indexOf(l)===-1&&(s.push(l),o=o?o+`, `+r[c]:r[c])}return o}function i(e){for(var t=0,n=[],r=0,i=0,a=e.length;i<a;i++)switch(e.charCodeAt(i)){case 32:r===t&&(r=t=i+1);break;case 44:n.push(e.substring(r,t)),r=t=i+1;break;default:t=i+1}return n.push(e.substring(r,t)),n}function a(e,t){if(!e||!e.getHeader||!e.setHeader)throw TypeError(`res argument is required`);var n=e.getHeader(`Vary`)||``;(n=r(Array.isArray(n)?n.join(`, `):String(n),t))&&e.setHeader(`Vary`,n)}})),el=r(((e,t)=>{(function(){var e=Qc(),n=$c(),r={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,preflightContinue:!1,optionsSuccessStatus:204};function i(e){return typeof e==`string`||e instanceof String}function a(e,t){if(Array.isArray(t)){for(var n=0;n<t.length;++n)if(a(e,t[n]))return!0;return!1}return i(t)?e===t:t instanceof RegExp?t.test(e):!!t}function o(e,t){var n=t.headers.origin,r=[],o;return!e.origin||e.origin===`*`?r.push([{key:`Access-Control-Allow-Origin`,value:`*`}]):i(e.origin)?(r.push([{key:`Access-Control-Allow-Origin`,value:e.origin}]),r.push([{key:`Vary`,value:`Origin`}])):(o=a(n,e.origin),r.push([{key:`Access-Control-Allow-Origin`,value:o?n:!1}]),r.push([{key:`Vary`,value:`Origin`}])),r}function s(e){var t=e.methods;return t.join&&(t=e.methods.join(`,`)),{key:`Access-Control-Allow-Methods`,value:t}}function c(e){return e.credentials===!0?{key:`Access-Control-Allow-Credentials`,value:`true`}:null}function l(e,t){var n=e.allowedHeaders||e.headers,r=[];return n?n.join&&(n=n.join(`,`)):(n=t.headers[`access-control-request-headers`],r.push([{key:`Vary`,value:`Access-Control-Request-Headers`}])),n&&n.length&&r.push([{key:`Access-Control-Allow-Headers`,value:n}]),r}function u(e){var t=e.exposedHeaders;if(t)t.join&&(t=t.join(`,`));else return null;return t&&t.length?{key:`Access-Control-Expose-Headers`,value:t}:null}function d(e){var t=(typeof e.maxAge==`number`||e.maxAge)&&e.maxAge.toString();return t&&t.length?{key:`Access-Control-Max-Age`,value:t}:null}function f(e,t){for(var r=0,i=e.length;r<i;r++){var a=e[r];a&&(Array.isArray(a)?f(a,t):a.key===`Vary`&&a.value?n(t,a.value):a.value&&t.setHeader(a.key,a.value))}}function p(e,t,n,r){var i=[];(t.method&&t.method.toUpperCase&&t.method.toUpperCase())===`OPTIONS`?(i.push(o(e,t)),i.push(c(e)),i.push(s(e)),i.push(l(e,t)),i.push(d(e)),i.push(u(e)),f(i,n),e.preflightContinue?r():(n.statusCode=e.optionsSuccessStatus,n.setHeader(`Content-Length`,`0`),n.end())):(i.push(o(e,t)),i.push(c(e)),i.push(u(e)),f(i,n),r())}function m(t){var n=null;return n=typeof t==`function`?t:function(e,n){n(null,t)},function(t,i,a){n(t,function(n,o){if(n)a(n);else{var s=e({},r,o),c=null;s.origin&&typeof s.origin==`function`?c=s.origin:s.origin&&(c=function(e,t){t(null,s.origin)}),c?c(t.headers.origin,function(e,n){e||!n?a(e):(s.origin=n,p(s,t,i,a))}):a()}})}}t.exports=m})()})),tl=r(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),nl=r(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=tl(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),rl=r(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=nl()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),il=r(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),al=r(((t,n)=>{var r=e(`os`),i=e(`tty`),a=il(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1);function c(){if(`FORCE_COLOR`in o)return o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(o.FORCE_COLOR,10),3)}function l(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function u(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let i=c();i!==void 0&&(s=i);let l=n?s:i;if(l===0)return 0;if(n){if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(o.TERM===`dumb`)return u;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`,`DRONE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:u;if(`TEAMCITY_VERSION`in o)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION);if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=Number.parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:u}function d(e,t={}){return l(u(e,{streamIsTTY:e&&e.isTTY,...t}))}n.exports={supportsColor:d,stdout:d({isTTY:i.isatty(1)}),stderr:d({isTTY:i.isatty(2)})}})),ol=r(((t,n)=>{var r=e(`tty`),i=e(`util`);t.init=d,t.log=c,t.formatArgs=o,t.save=l,t.load=u,t.useColors=a,t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let e=al();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
11
+ `,Vs(t,e))}return n}}})),Gs,Ks=a((()=>{u(),Gs=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=c.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}}})),qs,Js,Ys=a((()=>{u(),Os(),xs(),qs=class{_buffer=new Ds;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){l.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.INT&&!Number.isInteger(e)&&(l.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},Js=class{_buffer=new Map;observe(e,n,r={}){if(!ds(e))return;let i=this._buffer.get(e);if(i??(i=new Ds,this._buffer.set(e,i)),typeof n!=`number`){l.warn(`non-number value provided to metric ${e._descriptor.name}: ${n}`);return}e._descriptor.valueType===t.INT&&!Number.isInteger(n)&&(l.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),n=Math.trunc(n),!Number.isInteger(n))||i.set(r,n)}}})),Xs,Zs=a((()=>{u(),xs(),Ys(),ya(),Xs=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(ds));if(n.size===0){l.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(ds)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new qs(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=ma(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Js,a=Promise.resolve(n(i));t!=null&&(a=ma(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&ha(n.instruments,t))}}})),Qs,$s=a((()=>{u(),Ts(),As(),Ns(),Qs=class extends ws{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new ks(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ms(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??c.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),ec,tc=a((()=>{us(),Cs(),Fs(),Ws(),Ks(),Zs(),$s(),ec=class{metricStorageRegistry=new Us;observableRegistry=new Xs;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Ss(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,Qs);return t.length===1?t[0]:new Gs(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Ps)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=os(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}}})),nc,rc=a((()=>{ya(),is(),tc(),Mo(),nc=class{viewRegistry=new rs;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=pa(e),n=this.meterSharedStates.get(t);return n??(n=new ec(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Ao(n.selectAggregation(e))]);return t}}})),ic,ac=a((()=>{v(),ic=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=O(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),oc,sc,cc,lc=a((()=>{oc=/[\^$\\.+?()[\]{}|]/g,sc=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(oc,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},cc=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}}));function uc(){return vc}function dc(e){return new hc(e)}function fc(e){return new gc(e)}function pc(e){return new _c(e)}var mc,hc,gc,_c,vc,yc=a((()=>{mc=class{process(e,t){return e}},hc=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},gc=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._allowedAttributeNames.has(t)&&(n[t]=e[t]);return n}},_c=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&!this._deniedAttributeNames.has(t)&&(n[t]=e[t]);return n}},vc=new mc})),bc,xc=a((()=>{lc(),bc=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new sc(e?.name??`*`),this._type=e?.type,this._unitFilter=new cc(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),Sc,Cc=a((()=>{lc(),Sc=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new cc(e?.name),this._versionFilter=new cc(e?.version),this._schemaUrlFilter=new cc(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}}));function wc(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function Tc(e){if(wc(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||sc.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var Ec,Dc=a((()=>{lc(),yc(),xc(),Cc(),Mo(),Ec=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){Tc(e),this.attributesProcessor=e.attributesProcessors==null?uc():dc(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Ao(e.aggregation??{type:jo.DEFAULT}),this.instrumentSelector=new bc({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Sc({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),Oc,kc=a((()=>{u(),m(),Jo(),rc(),ac(),Dc(),Oc=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new nc(e?.resource??ne()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new Ec(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new ic(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof qo&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(l.warn(`A shutdown MeterProvider cannot provide a Meter`),i()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){l.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){l.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),Ac=f({AggregationTemporality:()=>ca,AggregationType:()=>jo,ConsoleMetricExporter:()=>ts,DataPointType:()=>ua,InMemoryMetricExporter:()=>$o,InstrumentType:()=>K,MeterProvider:()=>Oc,MetricReader:()=>qo,PeriodicExportingMetricReader:()=>Zo,TimeoutError:()=>va,createAllowListAttributesProcessor:()=>fc,createDenyListAttributesProcessor:()=>pc}),jc=a((()=>{la(),da(),Jo(),Qo(),es(),ns(),kc(),Mo(),yc(),ya()})),Mc;(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(Mc||={}),u(),jc();function Nc(e,t){let n=C(e.resource,t);return{resource:n,schemaUrl:n.schemaUrl,scopeMetrics:Pc(e.scopeMetrics,t)}}function Pc(e,t){return Array.from(e.map(e=>({scope:g(e.scope,t),metrics:e.metrics.map(e=>Fc(e,t)),schemaUrl:e.scope.schemaUrl})))}function Fc(e,t){let n={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},r=Bc(e.aggregationTemporality);switch(e.dataPointType){case ua.SUM:n.sum={aggregationTemporality:r,isMonotonic:e.isMonotonic,dataPoints:Lc(e,t)};break;case ua.GAUGE:n.gauge={dataPoints:Lc(e,t)};break;case ua.HISTOGRAM:n.histogram={aggregationTemporality:r,dataPoints:Rc(e,t)};break;case ua.EXPONENTIAL_HISTOGRAM:n.exponentialHistogram={aggregationTemporality:r,dataPoints:zc(e,t)}}return n}function Ic(e,n,r){let i={attributes:re(e.attributes,r),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(n){case t.INT:i.asInt=e.value;break;case t.DOUBLE:i.asDouble=e.value}return i}function Lc(e,t){return e.dataPoints.map(n=>Ic(n,e.descriptor.valueType,t))}function Rc(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:re(e.attributes,t),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function zc(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:re(e.attributes,t),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Bc(e){switch(e){case ca.DELTA:return Mc.AGGREGATION_TEMPORALITY_DELTA;case ca.CUMULATIVE:return Mc.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Vc(e,t){return{resourceMetrics:e.map(e=>Nc(e,t))}}u();var Hc={serializeRequest:e=>{let t=Vc([e],_);return new TextEncoder().encode(JSON.stringify(t))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;try{return JSON.parse(t.decode(e))}catch(e){return l.warn(`Failed to parse metrics export response: ${e.message}. Returning empty response`),{}}}};function Uc(){let e,t;return async()=>(e===void 0&&(e=await(t??=Wc().finally(()=>{t=void 0}))),e)}async function Wc(){let e=`getAuthProviderCatalog`,t=await At(he(),{method:`GET`,path:Je(e,{}),headers:{},operationId:e},Ii).catch(e=>{ae({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:le(e),fields:{requestId:_e()},error:e})});if(t===void 0)return;if(!t.ok||t.redirect){ae({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:`the API did not return an OAuth provider catalog`,fields:{requestId:_e()}});return}let n=t.data.oauthClient;if(n==null){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published no OAuth client; retrying on the next request that needs one`,fields:{requestId:_e()}});return}let r=n.mcpResource;if(r==null){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an OAuth client without an MCP resource indicator, so this server has no resource to advertise or audience to verify; retrying on the next request that needs one`,fields:{requestId:_e()}});return}if(!URL.canParse(r)){ae({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an unusable MCP resource indicator: ${r}`,fields:{requestId:_e()}});return}let i=new URL(r);return k({component:`aventure-mcp-server`,event:`oauth_discovery_ready`,fields:{requestId:_e(),resource:i.href,authorizationServer:n.authorizationServer}}),{client:n,resourceUrl:i}}var Gc=2e3,Kc={userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,graphQL:{document:!1,variables:!1},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!1,frameContextLines:0},qc;async function Jc(){let e=Zc(process.env.SENTRY_DSN),t=Zc(process.env.SENTRY_RELEASE);if(e===void 0||t===void 0)return;let n=await import(`../chunks/esm-B_HfoRSQ.js`);n.init({dsn:e,environment:ce()[`deployment.environment.name`],release:t,dataCollection:Kc,beforeBreadcrumb:()=>null,beforeSend:e=>{let t=e.tags?.failure;return delete e.request,delete e.user,delete e.breadcrumbs,delete e.contexts,delete e.extra,delete e.transaction,delete e.tags,(t===`authentication_unavailable`||t===`server_start_failed`||t===`transport_error`)&&(e.tags={failure:t}),e}}),qc=n}function Yc(e,t){qc?.captureException(e,{tags:{failure:t}})}async function Xc(){let e=qc;qc=void 0,e!==void 0&&await e.close(Gc)}function Zc(e){return e?.trim()||void 0}var Qc=r(((e,t)=>{var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(e==null)throw TypeError(`Object.assign cannot be called with null or undefined`);return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String(`abc`);if(e[5]=`de`,Object.getOwnPropertyNames(e)[0]===`5`)return!1;for(var t={},n=0;n<10;n++)t[`_`+String.fromCharCode(n)]=n;if(Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(``)!==`0123456789`)return!1;var r={};return`abcdefghijklmnopqrst`.split(``).forEach(function(e){r[e]=e}),Object.keys(Object.assign({},r)).join(``)===`abcdefghijklmnopqrst`}catch{return!1}}t.exports=o()?Object.assign:function(e,t){for(var o,s=a(e),c,l=1;l<arguments.length;l++){for(var u in o=Object(arguments[l]),o)r.call(o,u)&&(s[u]=o[u]);if(n){c=n(o);for(var d=0;d<c.length;d++)i.call(o,c[d])&&(s[c[d]]=o[c[d]])}}return s}})),$c=r(((e,t)=>{t.exports=a,t.exports.append=r;var n=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function r(e,t){if(typeof e!=`string`)throw TypeError(`header argument is required`);if(!t)throw TypeError(`field argument is required`);for(var r=Array.isArray(t)?t:i(String(t)),a=0;a<r.length;a++)if(!n.test(r[a]))throw TypeError(`field argument contains an invalid header name`);if(e===`*`)return e;var o=e,s=i(e.toLowerCase());if(r.indexOf(`*`)!==-1||s.indexOf(`*`)!==-1)return`*`;for(var c=0;c<r.length;c++){var l=r[c].toLowerCase();s.indexOf(l)===-1&&(s.push(l),o=o?o+`, `+r[c]:r[c])}return o}function i(e){for(var t=0,n=[],r=0,i=0,a=e.length;i<a;i++)switch(e.charCodeAt(i)){case 32:r===t&&(r=t=i+1);break;case 44:n.push(e.substring(r,t)),r=t=i+1;break;default:t=i+1}return n.push(e.substring(r,t)),n}function a(e,t){if(!e||!e.getHeader||!e.setHeader)throw TypeError(`res argument is required`);var n=e.getHeader(`Vary`)||``;(n=r(Array.isArray(n)?n.join(`, `):String(n),t))&&e.setHeader(`Vary`,n)}})),el=r(((e,t)=>{(function(){var e=Qc(),n=$c(),r={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,preflightContinue:!1,optionsSuccessStatus:204};function i(e){return typeof e==`string`||e instanceof String}function a(e,t){if(Array.isArray(t)){for(var n=0;n<t.length;++n)if(a(e,t[n]))return!0;return!1}return i(t)?e===t:t instanceof RegExp?t.test(e):!!t}function o(e,t){var n=t.headers.origin,r=[],o;return!e.origin||e.origin===`*`?r.push([{key:`Access-Control-Allow-Origin`,value:`*`}]):i(e.origin)?(r.push([{key:`Access-Control-Allow-Origin`,value:e.origin}]),r.push([{key:`Vary`,value:`Origin`}])):(o=a(n,e.origin),r.push([{key:`Access-Control-Allow-Origin`,value:o?n:!1}]),r.push([{key:`Vary`,value:`Origin`}])),r}function s(e){var t=e.methods;return t.join&&(t=e.methods.join(`,`)),{key:`Access-Control-Allow-Methods`,value:t}}function c(e){return e.credentials===!0?{key:`Access-Control-Allow-Credentials`,value:`true`}:null}function l(e,t){var n=e.allowedHeaders||e.headers,r=[];return n?n.join&&(n=n.join(`,`)):(n=t.headers[`access-control-request-headers`],r.push([{key:`Vary`,value:`Access-Control-Request-Headers`}])),n&&n.length&&r.push([{key:`Access-Control-Allow-Headers`,value:n}]),r}function u(e){var t=e.exposedHeaders;if(t)t.join&&(t=t.join(`,`));else return null;return t&&t.length?{key:`Access-Control-Expose-Headers`,value:t}:null}function d(e){var t=(typeof e.maxAge==`number`||e.maxAge)&&e.maxAge.toString();return t&&t.length?{key:`Access-Control-Max-Age`,value:t}:null}function f(e,t){for(var r=0,i=e.length;r<i;r++){var a=e[r];a&&(Array.isArray(a)?f(a,t):a.key===`Vary`&&a.value?n(t,a.value):a.value&&t.setHeader(a.key,a.value))}}function p(e,t,n,r){var i=[];(t.method&&t.method.toUpperCase&&t.method.toUpperCase())===`OPTIONS`?(i.push(o(e,t)),i.push(c(e)),i.push(s(e)),i.push(l(e,t)),i.push(d(e)),i.push(u(e)),f(i,n),e.preflightContinue?r():(n.statusCode=e.optionsSuccessStatus,n.setHeader(`Content-Length`,`0`),n.end())):(i.push(o(e,t)),i.push(c(e)),i.push(u(e)),f(i,n),r())}function m(t){var n=null;return n=typeof t==`function`?t:function(e,n){n(null,t)},function(t,i,a){n(t,function(n,o){if(n)a(n);else{var s=e({},r,o),c=null;s.origin&&typeof s.origin==`function`?c=s.origin:s.origin&&(c=function(e,t){t(null,s.origin)}),c?c(t.headers.origin,function(e,n){e||!n?a(e):(s.origin=n,p(s,t,i,a))}):a()}})}}t.exports=m})()})),tl=r(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),nl=r(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=tl(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),rl=r(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=nl()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),il=r(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),al=r(((t,n)=>{var r=e(`os`),i=e(`tty`),a=il(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1);function c(){if(`FORCE_COLOR`in o)return o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(o.FORCE_COLOR,10),3)}function l(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function u(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let i=c();i!==void 0&&(s=i);let l=n?s:i;if(l===0)return 0;if(n){if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(o.TERM===`dumb`)return u;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`,`DRONE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:u;if(`TEAMCITY_VERSION`in o)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION);if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=Number.parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:u}function d(e,t={}){return l(u(e,{streamIsTTY:e&&e.isTTY,...t}))}n.exports={supportsColor:d,stdout:d({isTTY:i.isatty(1)}),stderr:d({isTTY:i.isatty(2)})}})),ol=r(((t,n)=>{var r=e(`tty`),i=e(`util`);t.init=d,t.log=c,t.formatArgs=o,t.save=l,t.load=u,t.useColors=a,t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let e=al();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
12
12
  `).join(`
13
13
  `+a),e.push(i+`m+`+n.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+t+` `+e[0]}function s(){return t.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...e){return process.stderr.write(i.formatWithOptions(t.inspectOpts,...e)+`
14
14
  `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(e){e.inspectOpts={};let n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]}n.exports=nl()(t);var{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
@@ -58,21 +58,21 @@ return fn.apply(this, arguments)
58
58
  <pre>`+t+`</pre>
59
59
  </body>
60
60
  </html>
61
- `}function f(){return function(){this.error(404)}}function p(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var t=a.original(this.req);t.path=null,t.pathname=u(t.pathname+`/`);var n=r(c.format(t)),o=d(`Redirecting`,`Redirecting to `+i(n));e.statusCode=301,e.setHeader(`Content-Type`,`text/html; charset=UTF-8`),e.setHeader(`Content-Length`,Buffer.byteLength(o)),e.setHeader(`Content-Security-Policy`,`default-src 'none'`),e.setHeader(`X-Content-Type-Options`,`nosniff`),e.setHeader(`Location`,n),e.end(o)}}})),ef=r(((t,n)=>{var r=_d(),i=e(`node:events`).EventEmitter,a=vd(),o=Ld(),s=Id(),c=qd(),l=Qd();t=n.exports=u;function u(){var e=function(t,n,r){e.handle(t,n,r)};return a(e,i.prototype,!1),a(e,o,!1),e.request=Object.create(c,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(l,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}t.application=o,t.request=c,t.response=l,t.Route=s.Route,t.Router=s,t.json=r.json,t.raw=r.raw,t.static=$d(),t.text=r.text,t.urlencoded=r.urlencoded})),tf=r(((e,t)=>{t.exports=ef()})),nf=n(el(),1),rf=n(tf(),1),af=Object.create,of=Object.defineProperty,sf=Object.getOwnPropertyDescriptor,cf=Object.getOwnPropertyNames,lf=Object.getPrototypeOf,uf=Object.prototype.hasOwnProperty,q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),df=(e,t)=>{let n={};for(var r in e)of(n,r,{get:e[r],enumerable:!0});return t&&of(n,Symbol.toStringTag,{value:`Module`}),n},ff=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=cf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!uf.call(e,s)&&s!==n&&of(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=sf(t,s))||r.enumerable});return e},pf=(e,t,n)=>(n=e==null?{}:af(lf(e)),ff(t||!e||!e.__esModule?of(n,`default`,{value:e,enumerable:!0}):n,e)),mf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),hf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),gf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),_f=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function vf(e){return typeof e==`string`&&hf.has(e.replace(/#$/,``))}function yf(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(mf.has(n))return`2020-12`;if(hf.has(n))return`2019-09`;if(gf.has(n)||_f.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var bf=Symbol.for(`mcp.sdk.errorBrands`);function xf(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,bf,{value:n,enumerable:!1,configurable:!0})}function Sf(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,bf)){let n=t[bf];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Cf=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InvalidRedirectUri=`invalid_redirect_uri`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e.InvalidDpopProof=`invalid_dpop_proof`,e.UseDpopNonce=`use_dpop_nonce`,e}({}),wf=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,xf(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},J=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),Y=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n,r){super(t,r),this.code=e,this.data=n,this.name=`SdkError`,xf(this,new.target)}};(class extends Y{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n,r){super(e,t,n,r),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});var Tf={};function Ef(e){return Object.hasOwn(Tf,e)?Tf[e]:void 0}function Df(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Of(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function kf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Af(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(Df(i)&&Df(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Of(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}var jf=`2026-07-28`,Mf=[jf];function Nf(e){return e>=jf}function Pf(e){return e.filter(e=>!Nf(e))}function Ff(e){return e.filter(e=>Nf(e))}function If(e){let t=e.structuredContent;return t===void 0||typeof t==`object`&&t&&!Array.isArray(t)||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}var Lf=[`task`,`inputRequests`,`requestState`];function Rf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||Lf.some(t=>t in e)?e:{...e,content:[]}}function zf(){let e=Fe(()=>I([W(),U(),H(),Ve(),F(W(),e),B(e)])),t=F(W(),e),n=I([W(),U().int()]),r=W(),i=G({ttl:U().optional()}),a=G({taskId:W()}),o=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=G({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=G({method:W(),params:s.loose().optional()}),u=G({_meta:o.optional()}),d=G({method:W(),params:u.loose().optional()}),f=L({_meta:o.optional()}),p=I([W(),U().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:W().optional()}),g=d.extend({method:z(`notifications/cancelled`),params:h}),_=G({src:W(),mimeType:W().optional(),sizes:B(W()).optional(),theme:V([`light`,`dark`]).optional()}),v=G({icons:B(_).optional()}),y=G({name:W(),title:W().optional()}),b=y.extend({...y.shape,...v.shape,version:W(),websiteUrl:W().optional(),description:W().optional()}),x=Re(G({applyDefaults:H().optional()}),t),S=He(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Re(G({form:x.optional(),url:t.optional()}),t.optional())),C=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),w=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),T=G({experimental:F(W(),t).optional(),sampling:G({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:G({listChanged:H().optional()}).optional(),tasks:C.optional(),extensions:F(W(),t).optional()}),E=s.extend({protocolVersion:W(),capabilities:T,clientInfo:b}),D=l.extend({method:z(`initialize`),params:E}),O=G({experimental:F(W(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:G({listChanged:H().optional()}).optional(),resources:G({subscribe:H().optional(),listChanged:H().optional()}).optional(),tools:G({listChanged:H().optional()}).optional(),tasks:w.optional(),extensions:F(W(),t).optional()}),k=f.extend({protocolVersion:W(),capabilities:O,serverInfo:b,instructions:W().optional()}),A=d.extend({method:z(`notifications/initialized`),params:u.optional()}),j=l.extend({method:z(`ping`),params:s.optional()}),ee=G({progress:U(),total:R(U()),message:R(W())}),te=G({...u.shape,...ee.shape,progressToken:n}),M=d.extend({method:z(`notifications/progress`),params:te}),N=s.extend({cursor:r.optional()}),ne=l.extend({params:N.optional()}),re=f.extend({nextCursor:r.optional()}),ie=G({uri:W(),mimeType:R(W()),_meta:F(W(),P()).optional()}),ae=ie.extend({text:W()}),oe=W().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),se=ie.extend({blob:oe}),ce=V([`user`,`assistant`]),le=G({audience:B(ce).optional(),priority:U().min(0).max(1).optional(),lastModified:Ie({offset:!0}).optional()}),ue=G({...y.shape,...v.shape,uri:W(),description:R(W()),mimeType:R(W()),size:R(U()),annotations:le.optional(),_meta:R(L({}))}),de=G({...y.shape,...v.shape,uriTemplate:W(),description:R(W()),mimeType:R(W()),annotations:le.optional(),_meta:R(L({}))}),fe=ne.extend({method:z(`resources/list`)}),pe=re.extend({resources:B(ue)}),me=ne.extend({method:z(`resources/templates/list`)}),he=re.extend({resourceTemplates:B(de)}),ge=s.extend({uri:W()}),_e=ge,ve=l.extend({method:z(`resources/read`),params:_e}),ye=f.extend({contents:B(I([ae,se]))}),be=d.extend({method:z(`notifications/resources/list_changed`),params:u.optional()}),xe=ge,Se=l.extend({method:z(`resources/subscribe`),params:xe}),Ce=ge,we=l.extend({method:z(`resources/unsubscribe`),params:Ce}),Te=u.extend({uri:W()}),Ee=d.extend({method:z(`notifications/resources/updated`),params:Te}),De=G({name:W(),description:R(W()),required:R(H())}),Oe=G({...y.shape,...v.shape,description:R(W()),arguments:R(B(De)),_meta:R(L({}))}),ke=ne.extend({method:z(`prompts/list`)}),Ae=re.extend({prompts:B(Oe)}),je=s.extend({name:W(),arguments:F(W(),W()).optional()}),Me=l.extend({method:z(`prompts/get`),params:je}),Pe=G({type:z(`text`),text:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),Le=G({type:z(`image`),data:oe,mimeType:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),ze=G({type:z(`audio`),data:oe,mimeType:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),Be=G({type:z(`tool_use`),name:W(),id:W(),input:F(W(),P()),_meta:F(W(),P()).optional()}),Ue=G({type:z(`resource`),resource:I([ae,se]),annotations:le.optional(),_meta:F(W(),P()).optional()}),We=ue.extend({type:z(`resource_link`)}),Ge=I([Pe,Le,ze,We,Ue]),Ke=G({role:ce,content:Ge}),qe=f.extend({description:W().optional(),messages:B(Ke)}),Je=d.extend({method:z(`notifications/prompts/list_changed`),params:u.optional()}),Ye=G({title:W().optional(),readOnlyHint:H().optional(),destructiveHint:H().optional(),idempotentHint:H().optional(),openWorldHint:H().optional()}),Xe=G({taskSupport:V([`required`,`optional`,`forbidden`]).optional()}),Ze=G({...y.shape,...v.shape,description:W().optional(),inputSchema:G({type:z(`object`),properties:F(W(),e).optional(),required:B(W()).optional()}).catchall(P()),outputSchema:G({type:z(`object`),properties:F(W(),e).optional(),required:B(W()).optional()}).catchall(P()).optional(),annotations:Ye.optional(),execution:Xe.optional(),_meta:F(W(),P()).optional()}),Qe=ne.extend({method:z(`tools/list`)}),$e=re.extend({tools:B(Ze)}),et=f.extend({content:B(Ge),structuredContent:F(W(),P()).optional(),isError:H().optional()}),tt=c.extend({name:W(),arguments:F(W(),P()).optional()}),nt=l.extend({method:z(`tools/call`),params:tt}),rt=d.extend({method:z(`notifications/tools/list_changed`),params:u.optional()}),it=V([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),at=s.extend({level:it}),ot=l.extend({method:z(`logging/setLevel`),params:at}),st=u.extend({level:it,logger:W().optional(),data:P()}),ct=d.extend({method:z(`notifications/message`),params:st}),lt=G({name:W().optional()}),ut=G({hints:B(lt).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),dt=G({mode:V([`auto`,`required`,`none`]).optional()}),ft=G({type:z(`tool_result`),toolUseId:W().describe(`The unique identifier for the corresponding tool call.`),content:B(Ge),structuredContent:G({}).loose().optional(),isError:H().optional(),_meta:F(W(),P()).optional()}),pt=Ne(`type`,[Pe,Le,ze]),mt=Ne(`type`,[Pe,Le,ze,Be,ft]),ht=G({role:ce,content:I([mt,B(mt)]),_meta:F(W(),P()).optional()}),gt=c.extend({messages:B(ht),modelPreferences:ut.optional(),systemPrompt:W().optional(),includeContext:V([`none`,`thisServer`,`allServers`]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:B(W()).optional(),metadata:t.optional(),tools:B(Ze).optional(),toolChoice:dt.optional()}),_t=l.extend({method:z(`sampling/createMessage`),params:gt}),vt=f.extend({model:W(),stopReason:R(V([`endTurn`,`stopSequence`,`maxTokens`]).or(W())),role:ce,content:pt}),yt=f.extend({model:W(),stopReason:R(V([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(W())),role:ce,content:I([mt,B(mt)])}),bt=G({type:z(`boolean`),title:W().optional(),description:W().optional(),default:H().optional()}),xt=G({type:z(`string`),title:W().optional(),description:W().optional(),minLength:U().optional(),maxLength:U().optional(),format:V([`email`,`uri`,`date`,`date-time`]).optional(),default:W().optional()}),St=G({type:V([`number`,`integer`]),title:W().optional(),description:W().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),Ct=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),default:W().optional()}),wt=G({type:z(`string`),title:W().optional(),description:W().optional(),oneOf:B(G({const:W(),title:W()})),default:W().optional()}),Tt=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),enumNames:B(W()).optional(),default:W().optional()}),Et=I([Ct,wt]),Dt=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({type:z(`string`),enum:B(W())}),default:B(W()).optional()}),Ot=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({anyOf:B(G({const:W(),title:W()}))}),default:B(W()).optional()}),kt=I([Dt,Ot]),At=I([Tt,Et,kt]),jt=I([At,bt,xt,St]),Mt=c.extend({mode:z(`form`).optional(),message:W(),requestedSchema:G({type:z(`object`),properties:F(W(),jt),required:B(W()).optional()}).catchall(P())}),Nt=c.extend({mode:z(`url`),message:W(),elicitationId:W(),url:W().url()}),Pt=I([Mt,Nt]),Ft=l.extend({method:z(`elicitation/create`),params:Pt}),It=u.extend({elicitationId:W()}),Lt=d.extend({method:z(`notifications/elicitation/complete`),params:It}),Rt=f.extend({action:V([`accept`,`decline`,`cancel`]),content:He(e=>e===null?void 0:e,F(W(),I([W(),U(),H(),B(W())])).optional())}),zt=G({type:z(`ref/resource`),uri:W()}),Bt=G({type:z(`ref/prompt`),name:W()}),Vt=s.extend({ref:I([Bt,zt]),argument:G({name:W(),value:W()}),context:G({arguments:F(W(),W()).optional()}).optional()}),Ht=l.extend({method:z(`completion/complete`),params:Vt}),Ut=f.extend({completion:L({values:B(W()).max(100),total:R(U().int()),hasMore:R(H())})}),Wt=G({uri:W().startsWith(`file://`),name:W().optional(),_meta:F(W(),P()).optional()}),Gt=l.extend({method:z(`roots/list`),params:s.optional()}),Kt=f.extend({roots:B(Wt)}),qt=d.extend({method:z(`notifications/roots/list_changed`),params:u.optional()}),Jt=L({ttl:U().optional(),pollInterval:U().optional()}),Yt=V([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xt=G({taskId:W(),status:Yt,ttl:I([U(),Ve()]),createdAt:W(),lastUpdatedAt:W(),pollInterval:R(U()),statusMessage:R(W())}),Zt=f.extend({task:Xt}),Qt=u.merge(Xt),$t=d.extend({method:z(`notifications/tasks/status`),params:Qt}),en=l.extend({method:z(`tasks/get`),params:s.extend({taskId:W()})}),tn=f.merge(Xt),nn=l.extend({method:z(`tasks/result`),params:s.extend({taskId:W()})}),rn=f.loose(),an=ne.extend({method:z(`tasks/list`)}),on=re.extend({tasks:B(Xt)}),sn=l.extend({method:z(`tasks/cancel`),params:s.extend({taskId:W()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:v,BaseMetadataSchema:y,ImplementationSchema:b,ClientTasksCapabilitySchema:C,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:T,InitializeRequestParamsSchema:E,InitializeRequestSchema:D,ServerCapabilitiesSchema:O,InitializeResultSchema:k,InitializedNotificationSchema:A,PingRequestSchema:j,ProgressSchema:ee,ProgressNotificationParamsSchema:te,ProgressNotificationSchema:M,PaginatedRequestParamsSchema:N,PaginatedRequestSchema:ne,PaginatedResultSchema:re,ResourceContentsSchema:ie,TextResourceContentsSchema:ae,BlobResourceContentsSchema:se,RoleSchema:ce,AnnotationsSchema:le,ResourceSchema:ue,ResourceTemplateSchema:de,ListResourcesRequestSchema:fe,ListResourcesResultSchema:pe,ListResourceTemplatesRequestSchema:me,ListResourceTemplatesResultSchema:he,ResourceRequestParamsSchema:ge,ReadResourceRequestParamsSchema:_e,ReadResourceRequestSchema:ve,ReadResourceResultSchema:ye,ResourceListChangedNotificationSchema:be,SubscribeRequestParamsSchema:xe,SubscribeRequestSchema:Se,UnsubscribeRequestParamsSchema:Ce,UnsubscribeRequestSchema:we,ResourceUpdatedNotificationParamsSchema:Te,ResourceUpdatedNotificationSchema:Ee,PromptArgumentSchema:De,PromptSchema:Oe,ListPromptsRequestSchema:ke,ListPromptsResultSchema:Ae,GetPromptRequestParamsSchema:je,GetPromptRequestSchema:Me,TextContentSchema:Pe,ImageContentSchema:Le,AudioContentSchema:ze,ToolUseContentSchema:Be,EmbeddedResourceSchema:Ue,ResourceLinkSchema:We,ContentBlockSchema:Ge,PromptMessageSchema:Ke,GetPromptResultSchema:qe,PromptListChangedNotificationSchema:Je,ToolAnnotationsSchema:Ye,ToolExecutionSchema:Xe,ToolSchema:Ze,ListToolsRequestSchema:Qe,ListToolsResultSchema:$e,CallToolResultSchema:et,CallToolRequestParamsSchema:tt,CallToolRequestSchema:nt,ToolListChangedNotificationSchema:rt,LoggingLevelSchema:it,SetLevelRequestParamsSchema:at,SetLevelRequestSchema:ot,LoggingMessageNotificationParamsSchema:st,LoggingMessageNotificationSchema:ct,ModelHintSchema:lt,ModelPreferencesSchema:ut,ToolChoiceSchema:dt,ToolResultContentSchema:ft,SamplingContentSchema:pt,SamplingMessageContentBlockSchema:mt,SamplingMessageSchema:ht,CreateMessageRequestParamsSchema:gt,CreateMessageRequestSchema:_t,CreateMessageResultSchema:vt,CreateMessageResultWithToolsSchema:yt,BooleanSchemaSchema:bt,StringSchemaSchema:xt,NumberSchemaSchema:St,UntitledSingleSelectEnumSchemaSchema:Ct,TitledSingleSelectEnumSchemaSchema:wt,LegacyTitledEnumSchemaSchema:Tt,SingleSelectEnumSchemaSchema:Et,UntitledMultiSelectEnumSchemaSchema:Dt,TitledMultiSelectEnumSchemaSchema:Ot,MultiSelectEnumSchemaSchema:kt,EnumSchemaSchema:At,PrimitiveSchemaDefinitionSchema:jt,ElicitRequestFormParamsSchema:Mt,ElicitRequestURLParamsSchema:Nt,ElicitRequestParamsSchema:Pt,ElicitRequestSchema:Ft,ElicitationCompleteNotificationParamsSchema:It,ElicitationCompleteNotificationSchema:Lt,ElicitResultSchema:Rt,ResourceTemplateReferenceSchema:zt,PromptReferenceSchema:Bt,CompleteRequestParamsSchema:Vt,CompleteRequestSchema:Ht,CompleteResultSchema:Ut,RootSchema:Wt,ListRootsRequestSchema:Gt,ListRootsResultSchema:Kt,RootsListChangedNotificationSchema:qt,TaskCreationParamsSchema:Jt,TaskStatusSchema:Yt,TaskSchema:Xt,CreateTaskResultSchema:Zt,TaskStatusNotificationParamsSchema:Qt,TaskStatusNotificationSchema:$t,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Xt),ClientRequestSchema:I([j,D,Ht,ot,Me,ke,fe,me,ve,Se,we,nt,Qe,en,nn,an,sn]),ClientNotificationSchema:I([g,M,A,qt,$t]),ClientResultSchema:I([m,vt,yt,Rt,Kt,tn,on,Zt]),ServerRequestSchema:I([j,_t,Ft,Gt,en,nn,an,sn]),ServerNotificationSchema:I([g,M,ct,Ee,be,rt,Je,$t,Lt]),ServerResultSchema:I([m,k,Ut,qe,Ae,pe,he,ye,et,$e,tn,on,Zt]),CallToolResultWireSchema:P().superRefine((e,t)=>{if(typeof e==`object`&&e&&!Array.isArray(e)&&e.content===void 0){for(let n of Lf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Rf).pipe(et)}}var Bf;function Vf(){return Bf??=zf()}function Hf(e){return e.type!==`object`}var Uf=new Set([`const`,`enum`,`default`,`examples`]),Wf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Gf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Kf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Gf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=vf(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Gf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:i[o]=Uf.has(o)?s:Wf.has(o)?r(s,!0):r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}var qf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Yf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Xf;function Zf(){if(Xf)return Xf;let e=Vf();return Xf={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Xf}function Qf(e){return Object.prototype.hasOwnProperty.call(qf,e)}function $f(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function ep(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function tp(e){return ep(e)?Zf().resultSchemas[e]:void 0}function np(e){return Qf(e)?Zf().requestSchemas[e]:void 0}function rp(e){return $f(e)?Zf().notificationSchemas[e]:void 0}Object.keys(qf),Object.keys(Jf);function ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ap(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var op={ok:!1,reason:`not-in-era`};function sp(e){return ip(e)&&ip(e.outputSchema)&&Hf(e.outputSchema)}function cp(e){return e}var lp={era:`2025-11-25`,hasRequestMethod:Qf,hasNotificationMethod:$f,validateRequest:(e,t)=>ap(np(e),t),validateResult:(e,t)=>ap(tp(e),t),validateNotification:(e,t)=>ap(rp(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>op,validateInputResponse:()=>op,samplingResultVariant:((e,t)=>{let n=Vf();return ap(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=If(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&Hf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(ip(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:cp(e)}}return{kind:`complete`,result:cp(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>sp(e))?t:{...t,tools:n.map(e=>sp(e)?{...e,outputSchema:Kf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function up(){let e=Fe(()=>I([W(),U(),H(),Ve(),F(W(),e),B(e)])),t=F(W(),e),n=I([W(),U().int()]),r=W(),i=I([W(),U().int()]),a=V([`user`,`assistant`]),o=V([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=W().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=G({ttl:U().optional()}),l=G({taskId:W()}),u=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=G({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=G({_meta:u.optional()}),m=G({method:W(),params:p.loose().optional()}),h=G({src:W(),mimeType:W().optional(),sizes:B(W()).optional(),theme:V([`light`,`dark`]).optional()}),g=G({icons:B(h).optional()}),_=G({name:W(),title:W().optional()}),v=_.extend({..._.shape,...g.shape,version:W(),websiteUrl:W().optional(),description:W().optional()}),y=Re(G({applyDefaults:H().optional()}),t),b=He(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Re(G({form:y.optional(),url:t.optional()}),t.optional())),x=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),S=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),C=G({experimental:F(W(),t).optional(),sampling:G({context:t.optional(),tools:t.optional()}).optional(),elicitation:b.optional(),roots:G({listChanged:H().optional()}).optional(),tasks:x.optional(),extensions:F(W(),t).optional()}),w=G({experimental:F(W(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:G({listChanged:H().optional()}).optional(),resources:G({subscribe:H().optional(),listChanged:H().optional()}).optional(),tools:G({listChanged:H().optional()}).optional(),tasks:S.optional(),extensions:F(W(),t).optional()}),T=G({progress:U(),total:R(U()),message:R(W())}),E=G({...p.shape,...T.shape,progressToken:n}),D=m.extend({method:z(`notifications/progress`),params:E}),O=p.extend({level:o,logger:W().optional(),data:P()}),k=m.extend({method:z(`notifications/message`),params:O}),A=G({uri:W(),mimeType:R(W()),_meta:F(W(),P()).optional()}),j=A.extend({text:W()}),ee=A.extend({blob:s}),te=G({audience:B(a).optional(),priority:U().min(0).max(1).optional(),lastModified:Ie({offset:!0}).optional()}),M=G({..._.shape,...g.shape,uri:W(),description:R(W()),mimeType:R(W()),size:R(U()),annotations:te.optional(),_meta:R(L({}))}),N=G({..._.shape,...g.shape,uriTemplate:W(),description:R(W()),mimeType:R(W()),annotations:te.optional(),_meta:R(L({}))}),ne=m.extend({method:z(`notifications/resources/list_changed`),params:p.optional()}),re=p.extend({uri:W()}),ie=m.extend({method:z(`notifications/resources/updated`),params:re}),ae=G({name:W(),description:R(W()),required:R(H())}),oe=G({..._.shape,...g.shape,description:R(W()),arguments:R(B(ae)),_meta:R(L({}))}),se=m.extend({method:z(`notifications/prompts/list_changed`),params:p.optional()}),ce=G({type:z(`text`),text:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),le=G({type:z(`image`),data:s,mimeType:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),ue=G({type:z(`audio`),data:s,mimeType:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),de=G({type:z(`tool_use`),name:W(),id:W(),input:F(W(),P()),_meta:F(W(),P()).optional()}),fe=G({type:z(`resource`),resource:I([j,ee]),annotations:te.optional(),_meta:F(W(),P()).optional()}),pe=M.extend({type:z(`resource_link`)}),me=I([ce,le,ue,pe,fe]),he=G({role:a,content:me}),ge=G({title:W().optional(),readOnlyHint:H().optional(),destructiveHint:H().optional(),idempotentHint:H().optional(),openWorldHint:H().optional()}),_e=m.extend({method:z(`notifications/tools/list_changed`),params:p.optional()}),ve=G({name:W().optional()}),ye=G({hints:B(ve).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),be=G({mode:V([`auto`,`required`,`none`]).optional()}),xe=G({type:z(`boolean`),title:W().optional(),description:W().optional(),default:H().optional()}),Se=G({type:z(`string`),title:W().optional(),description:W().optional(),minLength:U().optional(),maxLength:U().optional(),format:V([`email`,`uri`,`date`,`date-time`]).optional(),default:W().optional()}),Ce=G({type:V([`number`,`integer`]),title:W().optional(),description:W().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),we=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),default:W().optional()}),Te=G({type:z(`string`),title:W().optional(),description:W().optional(),oneOf:B(G({const:W(),title:W()})),default:W().optional()}),Ee=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),enumNames:B(W()).optional(),default:W().optional()}),De=I([we,Te]),Oe=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({type:z(`string`),enum:B(W())}),default:B(W()).optional()}),ke=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({anyOf:B(G({const:W(),title:W()}))}),default:B(W()).optional()}),Ae=I([Oe,ke]),je=I([Ee,De,Ae]),Me=I([je,xe,Se,Ce]),Ne=f.extend({mode:z(`form`).optional(),message:W(),requestedSchema:G({type:z(`object`),properties:F(W(),Me),required:B(W()).optional()}).catchall(P())}),Pe=G({type:z(`ref/resource`),uri:W()}),Le=G({type:z(`ref/prompt`),name:W()}),ze=G({uri:W().startsWith(`file://`),name:W().optional(),_meta:F(W(),P()).optional()}),Be=C.shape,Ue=G({experimental:Be.experimental,sampling:Be.sampling,elicitation:Be.elicitation,roots:Be.roots,extensions:Be.extensions}),We=w.shape,Ge=G({experimental:We.experimental,logging:We.logging,completions:We.completions,prompts:We.prompts,resources:We.resources,tools:We.tools,extensions:We.extensions}),Ke=L({progressToken:n.optional(),[Qn]:W(),[ai]:v.optional(),[wr]:Ue,[Ci]:o.optional()}),qe=G({..._.shape,...g.shape,description:W().optional(),inputSchema:L({$schema:W().optional(),type:z(`object`)}),outputSchema:L({$schema:W().optional()}).optional(),annotations:ge.optional(),_meta:F(W(),P()).optional()}),Je=G({type:z(`tool_result`),toolUseId:W(),content:B(me),structuredContent:P().optional(),isError:H().optional(),_meta:F(W(),P()).optional()}),Ye=I([ce,le,ue,de,Je]),Xe=G({role:a,content:I([Ye,B(Ye)]),_meta:F(W(),P()).optional()}),Ze=W(),Qe=L({[St]:v.optional().catch(void 0)}),$e=Qe.optional();function et(e){return L({_meta:$e,resultType:Ze.default(`complete`),...e})}let tt=et({}),nt=et({nextCursor:r.optional()}),rt=et({content:B(me),structuredContent:P().optional(),isError:H().optional()}),it=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),tools:B(qe),nextCursor:r.optional()}),at=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),prompts:B(oe),nextCursor:r.optional()}),ot=et({description:W().optional(),messages:B(he)}),st=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resources:B(M),nextCursor:r.optional()}),ct=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resourceTemplates:B(N),nextCursor:r.optional()}),lt=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),contents:B(I([j,ee]))}),ut=et({completion:G({values:B(W()).max(100),total:U().int().optional(),hasMore:H().optional()}).loose()}),dt=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`])}),ft=et({ttlMs:U().int().min(0).catch(0),cacheScope:V([`public`,`private`]).catch(`private`),supportedVersions:B(W()),capabilities:Ge,instructions:W().optional()}),pt=G({messages:B(Xe),modelPreferences:ye.optional(),systemPrompt:W().optional(),includeContext:V([`none`,`thisServer`,`allServers`]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:B(W()).optional(),metadata:t.optional(),tools:B(qe).optional(),toolChoice:be.optional()}),mt=G({method:z(`sampling/createMessage`),params:pt}),ht=G({method:z(`roots/list`),params:G({_meta:F(W(),P()).optional()}).optional()}),gt=G({...Xe.shape,model:W(),stopReason:W().optional()}),_t=G({roots:B(ze)}),vt=G({action:V([`accept`,`decline`,`cancel`]),content:F(W(),I([W(),U(),H(),B(W())])).optional()}),yt=G({mode:z(`url`),message:W(),url:W().url()}),bt=I([Ne,yt]),xt=G({method:z(`elicitation/create`),params:bt}),Ct=I([mt,ht,xt]),wt=I([gt,_t,vt]),Tt=F(W(),Ct),Et=F(W(),wt),Dt=et({inputRequests:Tt.optional(),requestState:W().optional()}),Ot={inputResponses:Et.optional(),requestState:W().optional()},kt=G({_meta:Ke,...Ot}),At=L({progressToken:n.optional()});function jt(e,t){return G({method:z(e),params:G({_meta:Ke,...t})})}function Mt(e,t){return G({method:z(e),params:G({_meta:At.optional(),...t}).optional()})}let Nt={name:W(),arguments:F(W(),P()).optional(),...Ot},Pt={cursor:r.optional()},Ft=jt(`tools/call`,Nt),It=jt(`tools/list`,Pt),Lt=jt(`prompts/list`,Pt),Rt=jt(`prompts/get`,{name:W(),arguments:F(W(),W()).optional(),...Ot}),zt=jt(`resources/list`,Pt),Bt=jt(`resources/templates/list`,Pt),Vt=jt(`resources/read`,{uri:W(),...Ot}),Ht={ref:I([Le,Pe]),argument:G({name:W(),value:W()}),context:G({arguments:F(W(),W()).optional()}).optional()},Ut=jt(`completion/complete`,Ht),Wt=jt(`server/discover`,{}),Gt=G({toolsListChanged:H().optional(),promptsListChanged:H().optional(),resourcesListChanged:H().optional(),resourceSubscriptions:B(W()).optional()}),Kt={notifications:Gt},qt=jt(`subscriptions/listen`,Kt),Jt=Qe.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=L({_meta:Jt,resultType:Ze.default(`complete`)}),Xt={"tools/call":Mt(`tools/call`,Nt),"tools/list":Mt(`tools/list`,Pt),"prompts/get":Mt(`prompts/get`,{name:W(),arguments:F(W(),W()).optional()}),"prompts/list":Mt(`prompts/list`,Pt),"resources/list":Mt(`resources/list`,Pt),"resources/templates/list":Mt(`resources/templates/list`,Pt),"resources/read":Mt(`resources/read`,{uri:W()}),"completion/complete":Mt(`completion/complete`,Ht),"server/discover":Mt(`server/discover`,{}),"subscriptions/listen":Mt(`subscriptions/listen`,Kt)};function Zt(e){return L({_meta:$e,...e})}let Qt={"tools/call":Zt({content:B(me),structuredContent:P().optional(),isError:H().optional()}),"tools/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),tools:B(qe),nextCursor:r.optional()}),"prompts/get":Zt({description:W().optional(),messages:B(he)}),"prompts/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),prompts:B(oe),nextCursor:r.optional()}),"resources/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resources:B(M),nextCursor:r.optional()}),"resources/templates/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resourceTemplates:B(N),nextCursor:r.optional()}),"resources/read":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),contents:B(I([j,ee]))}),"completion/complete":Zt({completion:G({values:B(W()).max(100),total:U().int().optional(),hasMore:H().optional()}).loose()}),"server/discover":Zt({ttlMs:U().int().min(0).catch(0),cacheScope:V([`public`,`private`]).catch(`private`),supportedVersions:B(W()),capabilities:Ge,instructions:W().optional()}),"subscriptions/listen":Zt({})},$t=L({"io.modelcontextprotocol/subscriptionId":i.optional()}),en=G({method:z(`notifications/subscriptions/acknowledged`),params:G({_meta:$t.optional(),notifications:Gt})}),tn=G({_meta:$t.optional(),requestId:i,reason:W().optional()}),nn=G({method:z(`notifications/cancelled`),params:tn}),rn={"notifications/cancelled":nn,"notifications/progress":D,"notifications/message":k,"notifications/resources/updated":ie,"notifications/resources/list_changed":ne,"notifications/tools/list_changed":_e,"notifications/prompts/list_changed":se,"notifications/subscriptions/acknowledged":en},an=e=>G({jsonrpc:z(`2.0`),id:I([W(),U().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:v,ClientTasksCapabilitySchema:x,ServerTasksCapabilitySchema:S,ClientCapabilitiesSchema:C,ServerCapabilitiesSchema:w,ProgressSchema:T,ProgressNotificationParamsSchema:E,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:O,LoggingMessageNotificationSchema:k,ResourceContentsSchema:A,TextResourceContentsSchema:j,BlobResourceContentsSchema:ee,AnnotationsSchema:te,ResourceSchema:M,ResourceTemplateSchema:N,ResourceListChangedNotificationSchema:ne,ResourceUpdatedNotificationParamsSchema:re,ResourceUpdatedNotificationSchema:ie,PromptArgumentSchema:ae,PromptSchema:oe,PromptListChangedNotificationSchema:se,TextContentSchema:ce,ImageContentSchema:le,AudioContentSchema:ue,ToolUseContentSchema:de,EmbeddedResourceSchema:fe,ResourceLinkSchema:pe,ContentBlockSchema:me,PromptMessageSchema:he,ToolAnnotationsSchema:ge,ToolListChangedNotificationSchema:_e,ModelHintSchema:ve,ModelPreferencesSchema:ye,ToolChoiceSchema:be,BooleanSchemaSchema:xe,StringSchemaSchema:Se,NumberSchemaSchema:Ce,UntitledSingleSelectEnumSchemaSchema:we,TitledSingleSelectEnumSchemaSchema:Te,LegacyTitledEnumSchemaSchema:Ee,SingleSelectEnumSchemaSchema:De,UntitledMultiSelectEnumSchemaSchema:Oe,TitledMultiSelectEnumSchemaSchema:ke,MultiSelectEnumSchemaSchema:Ae,EnumSchemaSchema:je,PrimitiveSchemaDefinitionSchema:Me,ElicitRequestFormParamsSchema:Ne,ResourceTemplateReferenceSchema:Pe,PromptReferenceSchema:Le,RootSchema:ze,ClientCapabilities2026Schema:Ue,ServerCapabilities2026Schema:Ge,RequestMetaEnvelopeSchema:Ke,ToolSchema:qe,ToolResultContentSchema:Je,SamplingMessageContentBlockSchema:Ye,SamplingMessageSchema:Xe,ResultTypeSchema:Ze,ResultMetaSchema:Qe,ResultSchema:tt,PaginatedResultSchema:nt,CallToolResultSchema:rt,ListToolsResultSchema:it,ListPromptsResultSchema:at,GetPromptResultSchema:ot,ListResourcesResultSchema:st,ListResourceTemplatesResultSchema:ct,ReadResourceResultSchema:lt,CompleteResultSchema:ut,CacheableResultSchema:dt,DiscoverResultSchema:ft,CreateMessageRequestParamsSchema:pt,CreateMessageRequestSchema:mt,ListRootsRequestSchema:ht,CreateMessageResultSchema:gt,ListRootsResultSchema:_t,ElicitResultSchema:vt,ElicitRequestURLParamsSchema:yt,ElicitRequestParamsSchema:bt,ElicitRequestSchema:xt,InputRequestSchema:Ct,InputResponseSchema:wt,InputRequestsSchema:Tt,InputResponsesSchema:Et,InputRequiredResultSchema:Dt,InputResponseRequestParamsSchema:kt,CallToolRequestSchema:Ft,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Qt,NotificationMetaSchema:$t,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:rn,JSONRPCResultResponseSchema:an(tt),CallToolResultResponseSchema:an(I([rt,Dt])),ListToolsResultResponseSchema:an(it),ListPromptsResultResponseSchema:an(at),GetPromptResultResponseSchema:an(I([ot,Dt])),ListResourcesResultResponseSchema:an(st),ListResourceTemplatesResultResponseSchema:an(ct),ReadResourceResultResponseSchema:an(I([lt,Dt])),CompleteResultResponseSchema:an(ut),DiscoverResultResponseSchema:an(ft),SubscriptionsListenResultResponseSchema:an(Yt)}}var dp;function fp(){return dp??=up()}var pp=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function mp(e){return pp.includes(e)}var hp=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function gp(e,t){if(t===void 0)return e;let n=e[hp];if(n===void 0)return{...e,[hp]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[hp]:r}}function _p(e){return e[hp]}function vp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function yp(e){return e===`public`||e===`private`}function bp(e,t){if(e.ttlMs!==void 0&&!vp(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!yp(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}var X=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),Z=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,xf(this,new.target)}static fromError(t,n,r){if(t===X.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sp(e.elicitations,n)}if(t===X.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Cp({supported:e.supported,requested:e.requested},n)}if(t===X.InvalidParams||t===X.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===X.ResourceNotFound||Object.keys(e).length===1))return new xp(e.uri,n)}if(t===X.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new wp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},xp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Sp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Cp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},wp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Tp=0,Ep=`private`,Dp=[`tools/call`,`prompts/get`,`resources/read`];function Op(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||Dp.includes(e))return t;throw new Z(X.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function kp(e,t){let n=_p(t);if(t.resultType!==`complete`||!mp(e))return n===void 0?t:Pp(t);let r=t,i=vp(r.ttlMs)?r.ttlMs:Mp(n),a=yp(r.cacheScope)?r.cacheScope:Np(n),o={...r,ttlMs:i,cacheScope:a};return delete o[hp],o}function Ap(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[St]:t}}:!Ap(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[St]:t}}}function Mp(e){return e!==void 0&&vp(e.ttlMs)?e.ttlMs:Tp}function Np(e){return e!==void 0&&yp(e.cacheScope)?e.cacheScope:Ep}function Pp(e){let t={...e};return delete t[hp],t}var Fp=[`elicitation/create`,`sampling/createMessage`,`roots/list`],Ip;function Lp(){if(Ip)return Ip;let e=fp();return Ip={request:{"elicitation/create":G({method:z(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":G({method:z(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":G({method:z(`roots/list`),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Ip}function Rp(e){return Fp.includes(e)}function zp(e){return Rp(e)?Lp().request[e]:void 0}function Bp(e){return Rp(e)?Lp().response[e]:void 0}var Vp={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Hp={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Up(e){return Object.prototype.hasOwnProperty.call(Vp,e)}function Wp(e){return Object.prototype.hasOwnProperty.call(Hp,e)}function Gp(e){return Object.prototype.hasOwnProperty.call(Vp,e)}function Kp(e){return Up(e)?fp().dispatchRequestSchemas[e]:void 0}function qp(e){return Gp(e)?fp().dispatchResultSchemas[e]:void 0}function Jp(e){return Wp(e)?fp().notificationSchemas2026[e]:void 0}Object.keys(Vp),Object.keys(Hp);function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var Zp={ok:!1,reason:`not-in-era`},Qp=[Qn,wr];function $p(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>Yp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!Yp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(Yp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}var em={era:`2026-07-28`,hasRequestMethod:Up,hasNotificationMethod:Wp,hasInputRequestMethod:e=>zp(e)!==void 0,validateRequest:(e,t)=>Xp(Kp(e),t),validateResult:(e,t)=>Xp(qp(e),t),validateNotification:(e,t)=>Xp(Jp(e),t),validateInputRequest:(e,t)=>Xp(zp(e),t),validateInputResponse:(e,t)=>Xp(Bp(e),t),samplingResultVariant:()=>Zp,outboundEnvelope(e){return{[Qn]:e.protocolVersion,[ai]:e.clientInfo,[wr]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Qp)n in e||t.push({key:n,problem:`missing`});let n=fp().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>If(e),inputRequestSchema:zp,decodeResult(e,t){if(!Yp(t))return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=Yp(n)?n:{},i=t.requestState,a=t._meta===void 0?void 0:fp().ResultMetaSchema.safeParse(t._meta),o=a?.success?a.data:void 0;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i},...o!==void 0&&{_meta:o}}}if(n!==`complete`)return{kind:`invalid`,error:new Y(J.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=nm(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return jp(kp(e,Op(e,$p(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=fp().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},tm;function nm(){if(tm)return tm;let e=fp();return tm={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},tm}var rm=`2026-07-28`;function im(e){return e!==void 0&&Nf(e)?em:lp}function am(e){return e.revision===void 0?e.era===`modern`?em.era:lp.era:im(e.revision).era}function om(e){return lm.some(t=>t.hasRequestMethod(e))}function sm(e){return lm.some(t=>t.hasNotificationMethod(e))}function cm(e){return e===`tasks/get`||e===`tasks/cancel`}var lm=[lp,em];function um(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dm(e){if(!um(e))return;let t=e._meta;return um(t)?t:void 0}function fm(e){let t=dm(e);return t!==void 0&&`io.modelcontextprotocol/protocolVersion`in t}function pm(e){let t=dm(e)?.[Qn];return typeof t==`string`?t:void 0}function mm(e){return im(rm).validateEnvelopeMeta(e)}var hm=df({AnnotationsSchema:()=>qr,AudioContentSchema:()=>pr,BaseMetadataSchema:()=>In,BaseRequestParamsSchema:()=>Ir,BlobResourceContentsSchema:()=>Zr,BooleanSchemaSchema:()=>Wn,CallToolRequestParamsSchema:()=>Jn,CallToolRequestSchema:()=>tr,CallToolResultSchema:()=>Br,CancelTaskRequestSchema:()=>Or,CancelTaskResultSchema:()=>lr,CancelledNotificationParamsSchema:()=>ar,CancelledNotificationSchema:()=>Mn,ClientCapabilitiesSchema:()=>li,ClientNotificationSchema:()=>bi,ClientRequestSchema:()=>Bn,ClientResultSchema:()=>gi,ClientTasksCapabilitySchema:()=>rn,CompatibilityCallToolResultSchema:()=>$e,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>cn,CompleteResultSchema:()=>st,ContentBlockSchema:()=>rt,CreateMessageRequestParamsSchema:()=>Ut,CreateMessageRequestSchema:()=>br,CreateMessageResultSchema:()=>Ke,CreateMessageResultWithToolsSchema:()=>_r,CreateTaskResultSchema:()=>Ft,CursorSchema:()=>zt,DiscoverRequestSchema:()=>dt,DiscoverResultSchema:()=>xt,ElicitRequestFormParamsSchema:()=>jt,ElicitRequestParamsSchema:()=>$t,ElicitRequestSchema:()=>wi,ElicitRequestURLParamsSchema:()=>Xe,ElicitResultSchema:()=>gn,ElicitationCompleteNotificationParamsSchema:()=>_t,ElicitationCompleteNotificationSchema:()=>fn,EmbeddedResourceSchema:()=>bn,EmptyResultSchema:()=>mt,EnumSchemaSchema:()=>Ot,GetPromptRequestParamsSchema:()=>Wr,GetPromptRequestSchema:()=>Tt,GetPromptResultSchema:()=>En,GetTaskPayloadRequestSchema:()=>Cn,GetTaskPayloadResultSchema:()=>kn,GetTaskRequestSchema:()=>Xt,GetTaskResultSchema:()=>Ue,IconSchema:()=>er,IconsSchema:()=>ii,ImageContentSchema:()=>Xr,ImplementationSchema:()=>gr,InitializeRequestParamsSchema:()=>zn,InitializeRequestSchema:()=>zr,InitializeResultSchema:()=>ei,InitializedNotificationSchema:()=>qn,JSONArraySchema:()=>Dr,JSONObjectSchema:()=>ci,JSONRPCErrorResponseSchema:()=>Zn,JSONRPCMessageSchema:()=>ir,JSONRPCNotificationSchema:()=>Ur,JSONRPCRequestSchema:()=>jr,JSONRPCResponseSchema:()=>fr,JSONRPCResultResponseSchema:()=>cr,JSONValueSchema:()=>Fn,LegacyTitledEnumSchemaSchema:()=>Un,ListChangedOptionsBaseSchema:()=>yi,ListPromptsRequestSchema:()=>sn,ListPromptsResultSchema:()=>nt,ListResourceTemplatesRequestSchema:()=>hi,ListResourceTemplatesResultSchema:()=>dn,ListResourcesRequestSchema:()=>ut,ListResourcesResultSchema:()=>ot,ListRootsRequestSchema:()=>Kt,ListRootsResultSchema:()=>Cr,ListTasksRequestSchema:()=>Ye,ListTasksResultSchema:()=>yr,ListToolsRequestSchema:()=>Rt,ListToolsResultSchema:()=>Ht,LoggingLevelSchema:()=>Yt,LoggingMessageNotificationParamsSchema:()=>pt,LoggingMessageNotificationSchema:()=>wt,ModelHintSchema:()=>Pt,ModelPreferencesSchema:()=>nn,MultiSelectEnumSchemaSchema:()=>Di,NotificationSchema:()=>Qe,NotificationsParamsSchema:()=>yn,NumberSchemaSchema:()=>bt,PaginatedRequestParamsSchema:()=>ni,PaginatedRequestSchema:()=>Nr,PaginatedResultSchema:()=>Jr,PingRequestSchema:()=>mr,PrimitiveSchemaDefinitionSchema:()=>Ln,ProgressNotificationParamsSchema:()=>Lr,ProgressNotificationSchema:()=>Qr,ProgressSchema:()=>Gn,ProgressTokenSchema:()=>Tr,PromptArgumentSchema:()=>oi,PromptListChangedNotificationSchema:()=>Yn,PromptMessageSchema:()=>nr,PromptReferenceSchema:()=>Vr,PromptSchema:()=>kr,ReadResourceRequestParamsSchema:()=>ur,ReadResourceRequestSchema:()=>or,ReadResourceResultSchema:()=>Nn,RelatedTaskMetadataSchema:()=>ui,RequestIdSchema:()=>xi,RequestMetaSchema:()=>Vn,RequestSchema:()=>_i,ResourceContentsSchema:()=>an,ResourceLinkSchema:()=>et,ResourceListChangedNotificationSchema:()=>pi,ResourceRequestParamsSchema:()=>ln,ResourceSchema:()=>ct,ResourceTemplateReferenceSchema:()=>it,ResourceTemplateSchema:()=>Wt,ResourceUpdatedNotificationParamsSchema:()=>xr,ResourceUpdatedNotificationSchema:()=>qe,ResultMetaObjectSchema:()=>vr,ResultSchema:()=>It,RoleSchema:()=>Bt,RootSchema:()=>qt,RootsListChangedNotificationSchema:()=>ft,SamplingContentSchema:()=>Ti,SamplingMessageContentBlockSchema:()=>Ze,SamplingMessageSchema:()=>_n,ServerCapabilitiesSchema:()=>vt,ServerNotificationSchema:()=>pn,ServerRequestSchema:()=>xn,ServerResultSchema:()=>ht,ServerTasksCapabilitySchema:()=>kt,SetLevelRequestParamsSchema:()=>Gr,SetLevelRequestSchema:()=>Et,SingleSelectEnumSchemaSchema:()=>Dn,StringSchemaSchema:()=>wn,SubscribeRequestParamsSchema:()=>An,SubscribeRequestSchema:()=>Zt,SubscriptionFilterSchema:()=>We,SubscriptionsAcknowledgedNotificationParamsSchema:()=>$n,SubscriptionsAcknowledgedNotificationSchema:()=>ri,SubscriptionsListenRequestParamsSchema:()=>Pr,SubscriptionsListenRequestSchema:()=>Yr,SubscriptionsListenResultMetaSchema:()=>hr,SubscriptionsListenResultSchema:()=>Rn,TaskAugmentedRequestParamsSchema:()=>$r,TaskCreationParamsSchema:()=>Kn,TaskMetadataSchema:()=>Er,TaskSchema:()=>si,TaskStatusNotificationParamsSchema:()=>Xn,TaskStatusNotificationSchema:()=>rr,TaskStatusSchema:()=>Hr,TextContentSchema:()=>Ar,TextResourceContentsSchema:()=>dr,TitledMultiSelectEnumSchemaSchema:()=>sr,TitledSingleSelectEnumSchemaSchema:()=>Pn,ToolAnnotationsSchema:()=>di,ToolChoiceSchema:()=>Si,ToolExecutionSchema:()=>Hn,ToolListChangedNotificationSchema:()=>vi,ToolResultContentSchema:()=>on,ToolSchema:()=>tt,ToolUseContentSchema:()=>mi,UnsubscribeRequestParamsSchema:()=>un,UnsubscribeRequestSchema:()=>lt,UntitledMultiSelectEnumSchemaSchema:()=>at,UntitledSingleSelectEnumSchemaSchema:()=>Gt}),gm=e=>jr.safeParse(e).success,_m=e=>Ur.safeParse(e).success,vm=e=>cr.safeParse(e).success,ym=e=>Zn.safeParse(e).success,bm=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`,xm=e=>zr.safeParse(e).success;function Sm(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cm(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var wm=`Mcp-Param-`,Tm=`x-mcp-header`,Em=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Dm=new Set([`string`,`integer`,`boolean`,`number`]);function Om(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(Tm in o){if(!a||i.length===0)return`${jm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[Tm];if(typeof e!=`string`||e.length===0)return`${jm(i)}: x-mcp-header MUST be a non-empty string`;if(!Em.test(e))return`${jm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!Dm.has(r))return`${jm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of km){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&Am.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}var km=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],Am=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function jm(e){return e.length===0?`<root>`:e.join(`.`)}var Mm=`=?base64?`,Nm=`?=`,Pm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fm=/^-?\d+(\.\d+)?$/;function Im(e){if(typeof e==`string`)return e;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function Lm(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.codePointAt(e);return new TextDecoder(`utf-8`,{fatal:!0}).decode(n)}function Rm(e){if(!(e.startsWith(Mm)&&e.endsWith(Nm)))return e;let t=e.slice(9,e.length-2);if(Pm.test(t))try{return Lm(t)}catch{return}}function zm(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Bm(e,t,n){for(let r of e){let e=`${wm}${r.headerName}`,i=n.get(e),a=zm(t,r.path);if(a==null)continue;let o=Im(a);if(o===void 0)continue;if(i===null)return Vm(`param-header-missing`,e,`the body carries ${jm(r.path)}=${JSON.stringify(a)} but the ${e} header is absent`);let s=Rm(i);if(s===void 0)return Vm(`param-header-invalid-encoding`,e,`the ${e} header carries an invalid Base64 sentinel value`);if(!((r.type===`integer`||r.type===`number`)&&Fm.test(s)&&typeof a==`number`?Number(s)===a:s===o))return Vm(`param-header-mismatch`,e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${jm(r.path)}=${JSON.stringify(a)}`)}}function Vm(e,t,n){return{kind:`reject`,rung:`param-header-validation`,cell:e,httpStatus:400,code:Hm,message:`Bad Request: the request headers and body disagree: ${n}`,data:{mismatch:{header:t,body:n}},settled:!0}}var Hm=-32020;X.InvalidRequest,X.UnsupportedProtocolVersion,X.InvalidParams,X.MethodNotFound,X.InvalidParams,X.MissingRequiredClientCapability;var Um={[X.ParseError]:400,[X.InvalidRequest]:400,[X.MethodNotFound]:404,[X.UnsupportedProtocolVersion]:400,[X.MissingRequiredClientCapability]:400,[Hm]:400};function Wm(e,t){return t===`in-band`?e===X.MissingRequiredClientCapability?400:200:Um[e]??400}function Gm(e,t,n,r,i){return{kind:`reject`,rung:e,cell:t,httpStatus:n,code:r.code,message:r.message,...r.data!==void 0&&{data:r.data},settled:i}}function Km(e,t,n,r=`era-classification`){return Gm(r,e,400,new Z(Hm,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}}),!0)}var qm={"tools/call":`name`,"prompts/get":`name`,"resources/read":`uri`,"tasks/get":`taskId`,"tasks/update":`taskId`,"tasks/cancel":`taskId`};function Jm(e,t){let n=Object.hasOwn(qm,e)?qm[e]:void 0;if(n===void 0)return;let r=Zm(t)?t[n]:void 0;return{field:n,value:typeof r==`string`?r:void 0}}function Ym(e){let t=0;for(;t<e.length;){let n=e.codePointAt(t);if(n!==9&&n!==32)break;t+=1}let n=e.length;for(;n>t;){let t=e.codePointAt(n-1);if(t!==9&&t!==32)break;--n}return t===0&&n===e.length?e:e.slice(t,n)}function Xm(e,t){if(t.messageKind!==`request`)return;let n=t.message.method;if(e.protocolVersionHeader===void 0){let e=t.classification.revision;return Km(`version-header-missing`,`(missing)`,e===void 0?`the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent`:`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,`standard-header-validation`)}if(e.mcpMethodHeader===void 0)return Km(`method-header-missing`,`(missing)`,`the body names method ${n} but the required Mcp-Method header is absent`,`standard-header-validation`);let r=Jm(n,t.message.params);if(r===void 0)return;let{field:i,value:a}=r;if(e.mcpNameHeader===void 0)return a===void 0?void 0:Km(`name-header-missing`,`(missing)`,`the body carries params.${i}="${a}" but the required Mcp-Name header is absent`,`standard-header-validation`);let o=Ym(e.mcpNameHeader),s=Rm(o);if(s===void 0)return Km(`name-header-invalid-encoding`,o,`the Mcp-Name header carries an invalid Base64 sentinel value`,`standard-header-validation`);if(a!==void 0&&s!==a)return Km(`name-header-mismatch`,o,`the body carries params.${i}="${a}" but the Mcp-Name header names "${s}"`,`standard-header-validation`)}function Zm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qm(e){return e===void 0?{era:`modern`}:{era:Nf(e)?`modern`:`legacy`,revision:e}}function $m(e){if(!fm(e))return!1;let t=pm(e);if(t===void 0||!Nf(t))return!1;let n=dm(e);return n!==void 0&&mm(n).length===0}function eh(e){if(e.length===0)return Gm(`jsonrpc-shape`,`empty-batch`,400,new Z(X.InvalidRequest,`Bad Request: empty JSON-RPC batch`),!0);for(let t of e){if(fm(Zm(t)?t.params:void 0))return Gm(`jsonrpc-shape`,`batch-with-modern-element`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later`),!0);if(!(gm(t)||_m(t)||vm(t)||ym(t)))return Gm(`jsonrpc-shape`,`batch-with-invalid-element`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batch contains an invalid message`),!0)}return{kind:`legacy`,reason:`batch`}}function th(e,t){let n=t.params,r=t.method,i=e.protocolVersionHeader,a=i!==void 0&&Nf(i);if(r===`initialize`&&!$m(n)){if(a)return Km(`initialize-with-modern-header`,i,`an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header`);let e=Zm(n)&&typeof n.protocolVersion==`string`?n.protocolVersion:void 0;return{kind:`legacy`,reason:`initialize`,...e!==void 0&&{requestedVersion:e}}}if(fm(n)){let a=dm(n),o=(a===void 0?[]:mm(a))[0];if(o!==void 0)return Gm(`envelope`,`envelope-invalid`,400,new Z(X.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=pm(n);return i!==void 0&&s!==void 0&&i!==s?Km(`header-body-version-mismatch`,i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`method-header-mismatch`,e.mcpMethodHeader,`the body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`request`,message:t,classification:Qm(s)}}if(a){let e=dm(n),t=mm(e??{}).filter(e=>e.problem===`missing`).map(e=>e.key),r=e===void 0?[`_meta`]:t.length>0?t:[Qn];return Gm(`envelope`,`modern-header-without-claim`,400,new Z(X.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${r.join(`, `)}`,{envelope:{missing:r}}),!0)}return{kind:`legacy`,reason:`no-claim`,...i!==void 0&&{requestedVersion:i}}}function nh(e,t){let n=t.params,r=t.method,i=e.protocolVersionHeader,a=i!==void 0&&Nf(i);if(fm(n)){let a=pm(n);if(a===void 0){let e=dm(n),t=(e===void 0?[]:mm(e)).find(e=>e.key===`io.modelcontextprotocol/protocolVersion`)??{key:`io.modelcontextprotocol/protocolVersion`,problem:`expected a protocol version string`};return Gm(`envelope`,`notification-envelope-invalid`,400,new Z(X.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(i!==void 0&&i!==a)return Km(`notification-header-body-version-mismatch`,i,`the notification envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let o=Qm(a);return o.era===`modern`&&e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`notification-method-header-mismatch`,e.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`notification`,message:t,classification:o}}return a?e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`notification-method-header-mismatch`,e.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`notification`,message:t,classification:{era:`modern`,revision:i}}:{kind:`legacy`,reason:`notification`,...i!==void 0&&{requestedVersion:i}}}function rh(e){if(e={...e,...e.protocolVersionHeader!==void 0&&{protocolVersionHeader:Ym(e.protocolVersionHeader)},...e.mcpMethodHeader!==void 0&&{mcpMethodHeader:Ym(e.mcpMethodHeader)},...e.mcpNameHeader!==void 0&&{mcpNameHeader:Ym(e.mcpNameHeader)}},e.httpMethod.toUpperCase()!==`POST`)return{kind:`legacy`,reason:`http-method`};let t=e.body;return Array.isArray(t)?eh(t):vm(t)||ym(t)?{kind:`legacy`,reason:`response`}:Zm(t)&&gm(t)?th(e,t):Zm(t)&&_m(t)?nh(e,t):Gm(`jsonrpc-shape`,`invalid-json-rpc-body`,400,new Z(X.InvalidRequest,`Bad Request: the request body is not a valid JSON-RPC message`),!0)}function ih(e,t){switch(e.reason){case`http-method`:return Gm(`http-method`,`modern-only-method-not-allowed`,405,new Z(-32e3,`Method not allowed.`),!0);case`batch`:return Gm(`jsonrpc-shape`,`modern-only-batch-not-supported`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batches are not supported by this endpoint`),!0);case`response`:return Gm(`jsonrpc-shape`,`modern-only-response-post`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC responses cannot be posted to this endpoint`),!0);case`notification`:return;case`initialize`:case`no-claim`:{let n=e.requestedVersion;return Gm(`era-classification`,`modern-only-missing-envelope`,400,n===void 0?new Z(X.UnsupportedProtocolVersion,`Unsupported protocol version: the request did not name a protocol version`,{supported:[...t]}):new Cp({supported:[...t],requested:n}),!0)}}}function ah(e,t){return Le(e,t)}function oh(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function sh(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}var ch=!1,lh=`draft-2020-12`;function uh(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:lh});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);ch||(ch=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=Ae(e,{target:lh,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&dh(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function dh(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||dh(e)))}return!1}function fh(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function ph(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>fh(e)).join(`, `)}:{success:!0,data:n.value}}function mh(e){let t=Ae(e,{target:lh,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}var hh=/\\\.\\d\{(\d+)\}/;function gh(e){let t=hh.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>Ie({local:e,offset:t,precision:n}))))}function _h(e,t){let n;switch(e){case`email`:n=[Pe()];break;case`uri`:n=[je()];break;case`date`:n=[Be()];break;case`date-time`:n=gh(t)}return new Set(n.map(e=>mh(e)).filter(e=>e!==void 0))}function vh(e,t,n){return n!==`zod`||_h(e,t).has(t)}function yh(e){let t=uh(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function bh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xh(e){try{return uh(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Z(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}var Sh=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function Ch(e){return Sh.has(e)||e.startsWith(`x-`)}var wh=new Set([`$schema`,...Object.keys(jt.shape.requestedSchema.shape)]),Th={string:oh([wn,Gt,Pn,Un]),number:oh([bt]),integer:oh([bt]),boolean:oh([Wn]),array:oh([at,sr])},Eh=new Set(wn.shape.format.unwrap().options);function Dh(e,t,n,r){if(!bh(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Th,e.type)?Th[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||Ch(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Eh.has(e.format)?(typeof s!=`string`||!vh(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function Oh(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&bh(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Dh(n,`properties.${e}`,t,r)])):wh.has(i)?n[i]=a:Ch(i)||r.push(i);if(r.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function kh(e,t){if(!bh(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!ah(Ln,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Ah(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Ah(e,t[r],`${n}[${r}]`)):!bh(e)||!bh(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Ah(r,t[e],i):Ch(e)?[]:[i]})}function jh(e){if(!sh(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=Oh(xh(e.requestedSchema),t),r=ah(jt.shape.requestedSchema,n);if(!r.success)throw new Z(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${kh(n,r.error.message)}`);let i=Ah(n,r.data);if(i.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Mh(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Mh,{elicit(e){try{return{method:`elicitation/create`,params:jh(e)}}catch(e){throw e instanceof Z?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Nh(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Ph(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Fh(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}var Ih=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),Lh={IdJagTokenExchangeResponseSchema:Fr,OAuthClientInformationFullSchema:hn,OAuthClientInformationSchema:Sn,OAuthClientMetadataSchema:gt,OAuthClientRegistrationErrorSchema:At,OAuthErrorResponseSchema:Kr,OAuthMetadataSchema:Dt,OAuthProtectedResourceMetadataSchema:On,OAuthTokenRevocationRequestSchema:Tn,OAuthTokensSchema:jn,OpenIdProviderDiscoveryMetadataSchema:Qt,OpenIdProviderMetadataSchema:Ge},Rh={},zh={};function Bh(e,t){let n=e.slice(0,-6);Rh[n]=t,zh[n]=e=>t.safeParse(e).success}for(let e of Ih)Bh(e,hm[e]);for(let[e,t]of Object.entries(Lh))Bh(e,t);Object.freeze(Rh),Object.freeze(zh);function Vh(e){switch(e){case`initialize`:case`notifications/initialized`:return im(void 0);case`server/discover`:return im(rm);default:return}}var Hh=[Qn,ai,wr,Ci],Uh=[`inputResponses`,`requestState`];function Wh(e,t){let n=e.params;if(!Qh(n))return{message:e,lifted:{}};let r=n._meta,i=Qh(r)?Hh.filter(e=>e in r):[],a=t===`request`?Uh.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&Qh(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function Gh(e,t){let n=e.validateResult(t,void 0);if(n.ok||n.reason!==`not-in-era`)return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function Kh(e){return()=>e}var qh=Kh(void 0);function Jh(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:Kh(t)}}}var Yh;function Xh(e,t){Yh(e,t)}var Zh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Yh=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??en,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),vm(e)||ym(e)?this._onresponse(e):gm(e)?this._onrequest(e,t):_m(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new Y(J.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=Wh(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=am(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(sm(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;(i!==void 0||a!==void 0)&&Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=Wh(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=am(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(om(n.method)&&!i.hasRequestMethod(n.method)&&!(cm(n.method)&&this._customSchemaRequestMethods.has(n.method))){o(X.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(X.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(X.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:tg(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?qh:Kh(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),sh(t))return u(e,t,n);let i=Gh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(X.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:X.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),vm(e)?n(e):n(Z.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(sh(t))return cm(e.method)||this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n);this._assertOutboundRequestInEra(r,e.method);let i=Gh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return im(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Vh(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(om(t)&&!e.hasRequestMethod(t))throw new Y(J.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),v=!1,y=e=>{v||(this._progressHandlers.delete(h),m===void 0?t.method!==`initialize`&&this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof Y?e:new Y(J.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(v=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(ng(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;ph(n,o).then(e=>{e.success?d(e.data):f(new Y(J.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>y(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let b=r?.timeout??6e4;this._setupTimeout(h,b,r?.maxTotalTimeout,()=>y(new Y(J.RequestTimeout,`Request timed out`,{timeout:b})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new Y(J.NotConnected,`Not connected`);if(sm(t.method)&&!e.hasNotificationMethod(t.method))throw new Y(J.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&n?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!om(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await ph(t.params,{...r.params});if(!a.success)throw new Z(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);typeof t==`function`?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!sm(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await ph(t.params,{...r.params});if(!i.success)throw new Z(X.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Qh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $h(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Qh(a)&&Qh(i)?{...a,...i}:i}return n}function eg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tg(e){let t={},n=[];if(!eg(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!eg(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function ng(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var rg=pf(q((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))(),1);function ig(e){if(e)try{return rg.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function ag(e){return e===`application/json`||ig(e)===`application/json`}var og=/^[A-Za-z0-9._-]{1,128}$/;function sg(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!og.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function cg(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function lg(e){let t=sg(e);return cg(e,t.warnings),t.isValid}function ug(e){return typeof e==`object`&&!!e&&`_zod`in e}function dg(e){return typeof e==`object`&&!!e&&!(`_zod`in e)&&`_def`in e&&typeof e._def?.typeName==`string`}function fg(e){if(typeof e!=`object`||!e||sh(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(e=>ug(e))}function pg(e){if(e!==void 0){if(fg(e))return G(e);if(typeof e==`object`&&e&&!sh(e)&&Object.values(e).some(e=>dg(e)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!sh(e))throw TypeError(`inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).`);return e}}var mg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{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(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),hg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=mg();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Q=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=mg(),n=hg();var r=mg();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=hg();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
61
+ `}function f(){return function(){this.error(404)}}function p(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var t=a.original(this.req);t.path=null,t.pathname=u(t.pathname+`/`);var n=r(c.format(t)),o=d(`Redirecting`,`Redirecting to `+i(n));e.statusCode=301,e.setHeader(`Content-Type`,`text/html; charset=UTF-8`),e.setHeader(`Content-Length`,Buffer.byteLength(o)),e.setHeader(`Content-Security-Policy`,`default-src 'none'`),e.setHeader(`X-Content-Type-Options`,`nosniff`),e.setHeader(`Location`,n),e.end(o)}}})),ef=r(((t,n)=>{var r=_d(),i=e(`node:events`).EventEmitter,a=vd(),o=Ld(),s=Id(),c=qd(),l=Qd();t=n.exports=u;function u(){var e=function(t,n,r){e.handle(t,n,r)};return a(e,i.prototype,!1),a(e,o,!1),e.request=Object.create(c,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(l,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}t.application=o,t.request=c,t.response=l,t.Route=s.Route,t.Router=s,t.json=r.json,t.raw=r.raw,t.static=$d(),t.text=r.text,t.urlencoded=r.urlencoded})),tf=r(((e,t)=>{t.exports=ef()})),nf=n(el(),1),rf=n(tf(),1),af=Object.create,of=Object.defineProperty,sf=Object.getOwnPropertyDescriptor,cf=Object.getOwnPropertyNames,lf=Object.getPrototypeOf,uf=Object.prototype.hasOwnProperty,q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),df=(e,t)=>{let n={};for(var r in e)of(n,r,{get:e[r],enumerable:!0});return t&&of(n,Symbol.toStringTag,{value:`Module`}),n},ff=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=cf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!uf.call(e,s)&&s!==n&&of(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=sf(t,s))||r.enumerable});return e},pf=(e,t,n)=>(n=e==null?{}:af(lf(e)),ff(t||!e||!e.__esModule?of(n,`default`,{value:e,enumerable:!0}):n,e)),mf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),hf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),gf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),_f=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function vf(e){return typeof e==`string`&&hf.has(e.replace(/#$/,``))}function yf(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(mf.has(n))return`2020-12`;if(hf.has(n))return`2019-09`;if(gf.has(n)||_f.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var bf=Symbol.for(`mcp.sdk.errorBrands`);function xf(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,bf,{value:n,enumerable:!1,configurable:!0})}function Sf(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,bf)){let n=t[bf];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Cf=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InvalidRedirectUri=`invalid_redirect_uri`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e.InvalidDpopProof=`invalid_dpop_proof`,e.UseDpopNonce=`use_dpop_nonce`,e}({}),wf=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,xf(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},J=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),Y=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n,r){super(t,r),this.code=e,this.data=n,this.name=`SdkError`,xf(this,new.target)}};(class extends Y{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n,r){super(e,t,n,r),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});var Tf={};function Ef(e){return Object.hasOwn(Tf,e)?Tf[e]:void 0}function Df(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Of(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function kf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Af(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(Df(i)&&Df(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Of(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}var jf=`2026-07-28`,Mf=[jf];function Nf(e){return e>=jf}function Pf(e){return e.filter(e=>!Nf(e))}function Ff(e){return e.filter(e=>Nf(e))}function If(e){let t=e.structuredContent;return t===void 0||typeof t==`object`&&t&&!Array.isArray(t)||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}var Lf=[`task`,`inputRequests`,`requestState`];function Rf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||Lf.some(t=>t in e)?e:{...e,content:[]}}function zf(){let e=Fe(()=>I([W(),U(),H(),Ve(),F(W(),e),B(e)])),t=F(W(),e),n=I([W(),U().int()]),r=W(),i=G({ttl:U().optional()}),a=G({taskId:W()}),o=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=G({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=G({method:W(),params:s.loose().optional()}),u=G({_meta:o.optional()}),d=G({method:W(),params:u.loose().optional()}),f=L({_meta:o.optional()}),p=I([W(),U().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:W().optional()}),g=d.extend({method:z(`notifications/cancelled`),params:h}),_=G({src:W(),mimeType:W().optional(),sizes:B(W()).optional(),theme:V([`light`,`dark`]).optional()}),v=G({icons:B(_).optional()}),y=G({name:W(),title:W().optional()}),b=y.extend({...y.shape,...v.shape,version:W(),websiteUrl:W().optional(),description:W().optional()}),x=Re(G({applyDefaults:H().optional()}),t),S=He(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Re(G({form:x.optional(),url:t.optional()}),t.optional())),C=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),w=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),T=G({experimental:F(W(),t).optional(),sampling:G({context:t.optional(),tools:t.optional()}).optional(),elicitation:S.optional(),roots:G({listChanged:H().optional()}).optional(),tasks:C.optional(),extensions:F(W(),t).optional()}),E=s.extend({protocolVersion:W(),capabilities:T,clientInfo:b}),D=l.extend({method:z(`initialize`),params:E}),O=G({experimental:F(W(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:G({listChanged:H().optional()}).optional(),resources:G({subscribe:H().optional(),listChanged:H().optional()}).optional(),tools:G({listChanged:H().optional()}).optional(),tasks:w.optional(),extensions:F(W(),t).optional()}),k=f.extend({protocolVersion:W(),capabilities:O,serverInfo:b,instructions:W().optional()}),A=d.extend({method:z(`notifications/initialized`),params:u.optional()}),j=l.extend({method:z(`ping`),params:s.optional()}),ee=G({progress:U(),total:R(U()),message:R(W())}),te=G({...u.shape,...ee.shape,progressToken:n}),M=d.extend({method:z(`notifications/progress`),params:te}),N=s.extend({cursor:r.optional()}),ne=l.extend({params:N.optional()}),re=f.extend({nextCursor:r.optional()}),ie=G({uri:W(),mimeType:R(W()),_meta:F(W(),P()).optional()}),ae=ie.extend({text:W()}),oe=W().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),se=ie.extend({blob:oe}),ce=V([`user`,`assistant`]),le=G({audience:B(ce).optional(),priority:U().min(0).max(1).optional(),lastModified:Ie({offset:!0}).optional()}),ue=G({...y.shape,...v.shape,uri:W(),description:R(W()),mimeType:R(W()),size:R(U()),annotations:le.optional(),_meta:R(L({}))}),de=G({...y.shape,...v.shape,uriTemplate:W(),description:R(W()),mimeType:R(W()),annotations:le.optional(),_meta:R(L({}))}),fe=ne.extend({method:z(`resources/list`)}),pe=re.extend({resources:B(ue)}),me=ne.extend({method:z(`resources/templates/list`)}),he=re.extend({resourceTemplates:B(de)}),ge=s.extend({uri:W()}),_e=ge,ve=l.extend({method:z(`resources/read`),params:_e}),ye=f.extend({contents:B(I([ae,se]))}),be=d.extend({method:z(`notifications/resources/list_changed`),params:u.optional()}),xe=ge,Se=l.extend({method:z(`resources/subscribe`),params:xe}),Ce=ge,we=l.extend({method:z(`resources/unsubscribe`),params:Ce}),Te=u.extend({uri:W()}),Ee=d.extend({method:z(`notifications/resources/updated`),params:Te}),De=G({name:W(),description:R(W()),required:R(H())}),Oe=G({...y.shape,...v.shape,description:R(W()),arguments:R(B(De)),_meta:R(L({}))}),ke=ne.extend({method:z(`prompts/list`)}),Ae=re.extend({prompts:B(Oe)}),je=s.extend({name:W(),arguments:F(W(),W()).optional()}),Me=l.extend({method:z(`prompts/get`),params:je}),Pe=G({type:z(`text`),text:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),Le=G({type:z(`image`),data:oe,mimeType:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),ze=G({type:z(`audio`),data:oe,mimeType:W(),annotations:le.optional(),_meta:F(W(),P()).optional()}),Be=G({type:z(`tool_use`),name:W(),id:W(),input:F(W(),P()),_meta:F(W(),P()).optional()}),Ue=G({type:z(`resource`),resource:I([ae,se]),annotations:le.optional(),_meta:F(W(),P()).optional()}),We=ue.extend({type:z(`resource_link`)}),Ge=I([Pe,Le,ze,We,Ue]),Ke=G({role:ce,content:Ge}),qe=f.extend({description:W().optional(),messages:B(Ke)}),Je=d.extend({method:z(`notifications/prompts/list_changed`),params:u.optional()}),Ye=G({title:W().optional(),readOnlyHint:H().optional(),destructiveHint:H().optional(),idempotentHint:H().optional(),openWorldHint:H().optional()}),Xe=G({taskSupport:V([`required`,`optional`,`forbidden`]).optional()}),Ze=G({...y.shape,...v.shape,description:W().optional(),inputSchema:G({type:z(`object`),properties:F(W(),e).optional(),required:B(W()).optional()}).catchall(P()),outputSchema:G({type:z(`object`),properties:F(W(),e).optional(),required:B(W()).optional()}).catchall(P()).optional(),annotations:Ye.optional(),execution:Xe.optional(),_meta:F(W(),P()).optional()}),Qe=ne.extend({method:z(`tools/list`)}),$e=re.extend({tools:B(Ze)}),et=f.extend({content:B(Ge),structuredContent:F(W(),P()).optional(),isError:H().optional()}),tt=c.extend({name:W(),arguments:F(W(),P()).optional()}),nt=l.extend({method:z(`tools/call`),params:tt}),rt=d.extend({method:z(`notifications/tools/list_changed`),params:u.optional()}),it=V([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),at=s.extend({level:it}),ot=l.extend({method:z(`logging/setLevel`),params:at}),st=u.extend({level:it,logger:W().optional(),data:P()}),ct=d.extend({method:z(`notifications/message`),params:st}),lt=G({name:W().optional()}),ut=G({hints:B(lt).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),dt=G({mode:V([`auto`,`required`,`none`]).optional()}),ft=G({type:z(`tool_result`),toolUseId:W().describe(`The unique identifier for the corresponding tool call.`),content:B(Ge),structuredContent:G({}).loose().optional(),isError:H().optional(),_meta:F(W(),P()).optional()}),pt=Ne(`type`,[Pe,Le,ze]),mt=Ne(`type`,[Pe,Le,ze,Be,ft]),ht=G({role:ce,content:I([mt,B(mt)]),_meta:F(W(),P()).optional()}),gt=c.extend({messages:B(ht),modelPreferences:ut.optional(),systemPrompt:W().optional(),includeContext:V([`none`,`thisServer`,`allServers`]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:B(W()).optional(),metadata:t.optional(),tools:B(Ze).optional(),toolChoice:dt.optional()}),_t=l.extend({method:z(`sampling/createMessage`),params:gt}),vt=f.extend({model:W(),stopReason:R(V([`endTurn`,`stopSequence`,`maxTokens`]).or(W())),role:ce,content:pt}),yt=f.extend({model:W(),stopReason:R(V([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(W())),role:ce,content:I([mt,B(mt)])}),bt=G({type:z(`boolean`),title:W().optional(),description:W().optional(),default:H().optional()}),xt=G({type:z(`string`),title:W().optional(),description:W().optional(),minLength:U().optional(),maxLength:U().optional(),format:V([`email`,`uri`,`date`,`date-time`]).optional(),default:W().optional()}),St=G({type:V([`number`,`integer`]),title:W().optional(),description:W().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),Ct=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),default:W().optional()}),wt=G({type:z(`string`),title:W().optional(),description:W().optional(),oneOf:B(G({const:W(),title:W()})),default:W().optional()}),Tt=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),enumNames:B(W()).optional(),default:W().optional()}),Et=I([Ct,wt]),Dt=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({type:z(`string`),enum:B(W())}),default:B(W()).optional()}),Ot=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({anyOf:B(G({const:W(),title:W()}))}),default:B(W()).optional()}),kt=I([Dt,Ot]),At=I([Tt,Et,kt]),jt=I([At,bt,xt,St]),Mt=c.extend({mode:z(`form`).optional(),message:W(),requestedSchema:G({type:z(`object`),properties:F(W(),jt),required:B(W()).optional()}).catchall(P())}),Nt=c.extend({mode:z(`url`),message:W(),elicitationId:W(),url:W().url()}),Pt=I([Mt,Nt]),Ft=l.extend({method:z(`elicitation/create`),params:Pt}),It=u.extend({elicitationId:W()}),Lt=d.extend({method:z(`notifications/elicitation/complete`),params:It}),Rt=f.extend({action:V([`accept`,`decline`,`cancel`]),content:He(e=>e===null?void 0:e,F(W(),I([W(),U(),H(),B(W())])).optional())}),zt=G({type:z(`ref/resource`),uri:W()}),Bt=G({type:z(`ref/prompt`),name:W()}),Vt=s.extend({ref:I([Bt,zt]),argument:G({name:W(),value:W()}),context:G({arguments:F(W(),W()).optional()}).optional()}),Ht=l.extend({method:z(`completion/complete`),params:Vt}),Ut=f.extend({completion:L({values:B(W()).max(100),total:R(U().int()),hasMore:R(H())})}),Wt=G({uri:W().startsWith(`file://`),name:W().optional(),_meta:F(W(),P()).optional()}),Gt=l.extend({method:z(`roots/list`),params:s.optional()}),Kt=f.extend({roots:B(Wt)}),qt=d.extend({method:z(`notifications/roots/list_changed`),params:u.optional()}),Jt=L({ttl:U().optional(),pollInterval:U().optional()}),Yt=V([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xt=G({taskId:W(),status:Yt,ttl:I([U(),Ve()]),createdAt:W(),lastUpdatedAt:W(),pollInterval:R(U()),statusMessage:R(W())}),Zt=f.extend({task:Xt}),Qt=u.merge(Xt),$t=d.extend({method:z(`notifications/tasks/status`),params:Qt}),en=l.extend({method:z(`tasks/get`),params:s.extend({taskId:W()})}),tn=f.merge(Xt),nn=l.extend({method:z(`tasks/result`),params:s.extend({taskId:W()})}),rn=f.loose(),an=ne.extend({method:z(`tasks/list`)}),on=re.extend({tasks:B(Xt)}),sn=l.extend({method:z(`tasks/cancel`),params:s.extend({taskId:W()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:v,BaseMetadataSchema:y,ImplementationSchema:b,ClientTasksCapabilitySchema:C,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:T,InitializeRequestParamsSchema:E,InitializeRequestSchema:D,ServerCapabilitiesSchema:O,InitializeResultSchema:k,InitializedNotificationSchema:A,PingRequestSchema:j,ProgressSchema:ee,ProgressNotificationParamsSchema:te,ProgressNotificationSchema:M,PaginatedRequestParamsSchema:N,PaginatedRequestSchema:ne,PaginatedResultSchema:re,ResourceContentsSchema:ie,TextResourceContentsSchema:ae,BlobResourceContentsSchema:se,RoleSchema:ce,AnnotationsSchema:le,ResourceSchema:ue,ResourceTemplateSchema:de,ListResourcesRequestSchema:fe,ListResourcesResultSchema:pe,ListResourceTemplatesRequestSchema:me,ListResourceTemplatesResultSchema:he,ResourceRequestParamsSchema:ge,ReadResourceRequestParamsSchema:_e,ReadResourceRequestSchema:ve,ReadResourceResultSchema:ye,ResourceListChangedNotificationSchema:be,SubscribeRequestParamsSchema:xe,SubscribeRequestSchema:Se,UnsubscribeRequestParamsSchema:Ce,UnsubscribeRequestSchema:we,ResourceUpdatedNotificationParamsSchema:Te,ResourceUpdatedNotificationSchema:Ee,PromptArgumentSchema:De,PromptSchema:Oe,ListPromptsRequestSchema:ke,ListPromptsResultSchema:Ae,GetPromptRequestParamsSchema:je,GetPromptRequestSchema:Me,TextContentSchema:Pe,ImageContentSchema:Le,AudioContentSchema:ze,ToolUseContentSchema:Be,EmbeddedResourceSchema:Ue,ResourceLinkSchema:We,ContentBlockSchema:Ge,PromptMessageSchema:Ke,GetPromptResultSchema:qe,PromptListChangedNotificationSchema:Je,ToolAnnotationsSchema:Ye,ToolExecutionSchema:Xe,ToolSchema:Ze,ListToolsRequestSchema:Qe,ListToolsResultSchema:$e,CallToolResultSchema:et,CallToolRequestParamsSchema:tt,CallToolRequestSchema:nt,ToolListChangedNotificationSchema:rt,LoggingLevelSchema:it,SetLevelRequestParamsSchema:at,SetLevelRequestSchema:ot,LoggingMessageNotificationParamsSchema:st,LoggingMessageNotificationSchema:ct,ModelHintSchema:lt,ModelPreferencesSchema:ut,ToolChoiceSchema:dt,ToolResultContentSchema:ft,SamplingContentSchema:pt,SamplingMessageContentBlockSchema:mt,SamplingMessageSchema:ht,CreateMessageRequestParamsSchema:gt,CreateMessageRequestSchema:_t,CreateMessageResultSchema:vt,CreateMessageResultWithToolsSchema:yt,BooleanSchemaSchema:bt,StringSchemaSchema:xt,NumberSchemaSchema:St,UntitledSingleSelectEnumSchemaSchema:Ct,TitledSingleSelectEnumSchemaSchema:wt,LegacyTitledEnumSchemaSchema:Tt,SingleSelectEnumSchemaSchema:Et,UntitledMultiSelectEnumSchemaSchema:Dt,TitledMultiSelectEnumSchemaSchema:Ot,MultiSelectEnumSchemaSchema:kt,EnumSchemaSchema:At,PrimitiveSchemaDefinitionSchema:jt,ElicitRequestFormParamsSchema:Mt,ElicitRequestURLParamsSchema:Nt,ElicitRequestParamsSchema:Pt,ElicitRequestSchema:Ft,ElicitationCompleteNotificationParamsSchema:It,ElicitationCompleteNotificationSchema:Lt,ElicitResultSchema:Rt,ResourceTemplateReferenceSchema:zt,PromptReferenceSchema:Bt,CompleteRequestParamsSchema:Vt,CompleteRequestSchema:Ht,CompleteResultSchema:Ut,RootSchema:Wt,ListRootsRequestSchema:Gt,ListRootsResultSchema:Kt,RootsListChangedNotificationSchema:qt,TaskCreationParamsSchema:Jt,TaskStatusSchema:Yt,TaskSchema:Xt,CreateTaskResultSchema:Zt,TaskStatusNotificationParamsSchema:Qt,TaskStatusNotificationSchema:$t,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Xt),ClientRequestSchema:I([j,D,Ht,ot,Me,ke,fe,me,ve,Se,we,nt,Qe,en,nn,an,sn]),ClientNotificationSchema:I([g,M,A,qt,$t]),ClientResultSchema:I([m,vt,yt,Rt,Kt,tn,on,Zt]),ServerRequestSchema:I([j,_t,Ft,Gt,en,nn,an,sn]),ServerNotificationSchema:I([g,M,ct,Ee,be,rt,Je,$t,Lt]),ServerResultSchema:I([m,k,Ut,qe,Ae,pe,he,ye,et,$e,tn,on,Zt]),CallToolResultWireSchema:P().superRefine((e,t)=>{if(typeof e==`object`&&e&&!Array.isArray(e)&&e.content===void 0){for(let n of Lf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Rf).pipe(et)}}var Bf;function Vf(){return Bf??=zf()}function Hf(e){return e.type!==`object`}var Uf=new Set([`const`,`enum`,`default`,`examples`]),Wf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Gf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Kf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Gf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=vf(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Gf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:i[o]=Uf.has(o)?s:Wf.has(o)?r(s,!0):r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}var qf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Yf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Xf;function Zf(){if(Xf)return Xf;let e=Vf();return Xf={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Xf}function Qf(e){return Object.prototype.hasOwnProperty.call(qf,e)}function $f(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function ep(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function tp(e){return ep(e)?Zf().resultSchemas[e]:void 0}function np(e){return Qf(e)?Zf().requestSchemas[e]:void 0}function rp(e){return $f(e)?Zf().notificationSchemas[e]:void 0}Object.keys(qf),Object.keys(Jf);function ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ap(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var op={ok:!1,reason:`not-in-era`};function sp(e){return ip(e)&&ip(e.outputSchema)&&Hf(e.outputSchema)}function cp(e){return e}var lp={era:`2025-11-25`,hasRequestMethod:Qf,hasNotificationMethod:$f,validateRequest:(e,t)=>ap(np(e),t),validateResult:(e,t)=>ap(tp(e),t),validateNotification:(e,t)=>ap(rp(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>op,validateInputResponse:()=>op,samplingResultVariant:((e,t)=>{let n=Vf();return ap(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=If(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&Hf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(ip(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:cp(e)}}return{kind:`complete`,result:cp(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>sp(e))?t:{...t,tools:n.map(e=>sp(e)?{...e,outputSchema:Kf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function up(){let e=Fe(()=>I([W(),U(),H(),Ve(),F(W(),e),B(e)])),t=F(W(),e),n=I([W(),U().int()]),r=W(),i=I([W(),U().int()]),a=V([`user`,`assistant`]),o=V([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=W().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=G({ttl:U().optional()}),l=G({taskId:W()}),u=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=G({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=G({_meta:u.optional()}),m=G({method:W(),params:p.loose().optional()}),h=G({src:W(),mimeType:W().optional(),sizes:B(W()).optional(),theme:V([`light`,`dark`]).optional()}),g=G({icons:B(h).optional()}),_=G({name:W(),title:W().optional()}),v=_.extend({..._.shape,...g.shape,version:W(),websiteUrl:W().optional(),description:W().optional()}),y=Re(G({applyDefaults:H().optional()}),t),b=He(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Re(G({form:y.optional(),url:t.optional()}),t.optional())),x=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),S=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),C=G({experimental:F(W(),t).optional(),sampling:G({context:t.optional(),tools:t.optional()}).optional(),elicitation:b.optional(),roots:G({listChanged:H().optional()}).optional(),tasks:x.optional(),extensions:F(W(),t).optional()}),w=G({experimental:F(W(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:G({listChanged:H().optional()}).optional(),resources:G({subscribe:H().optional(),listChanged:H().optional()}).optional(),tools:G({listChanged:H().optional()}).optional(),tasks:S.optional(),extensions:F(W(),t).optional()}),T=G({progress:U(),total:R(U()),message:R(W())}),E=G({...p.shape,...T.shape,progressToken:n}),D=m.extend({method:z(`notifications/progress`),params:E}),O=p.extend({level:o,logger:W().optional(),data:P()}),k=m.extend({method:z(`notifications/message`),params:O}),A=G({uri:W(),mimeType:R(W()),_meta:F(W(),P()).optional()}),j=A.extend({text:W()}),ee=A.extend({blob:s}),te=G({audience:B(a).optional(),priority:U().min(0).max(1).optional(),lastModified:Ie({offset:!0}).optional()}),M=G({..._.shape,...g.shape,uri:W(),description:R(W()),mimeType:R(W()),size:R(U()),annotations:te.optional(),_meta:R(L({}))}),N=G({..._.shape,...g.shape,uriTemplate:W(),description:R(W()),mimeType:R(W()),annotations:te.optional(),_meta:R(L({}))}),ne=m.extend({method:z(`notifications/resources/list_changed`),params:p.optional()}),re=p.extend({uri:W()}),ie=m.extend({method:z(`notifications/resources/updated`),params:re}),ae=G({name:W(),description:R(W()),required:R(H())}),oe=G({..._.shape,...g.shape,description:R(W()),arguments:R(B(ae)),_meta:R(L({}))}),se=m.extend({method:z(`notifications/prompts/list_changed`),params:p.optional()}),ce=G({type:z(`text`),text:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),le=G({type:z(`image`),data:s,mimeType:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),ue=G({type:z(`audio`),data:s,mimeType:W(),annotations:te.optional(),_meta:F(W(),P()).optional()}),de=G({type:z(`tool_use`),name:W(),id:W(),input:F(W(),P()),_meta:F(W(),P()).optional()}),fe=G({type:z(`resource`),resource:I([j,ee]),annotations:te.optional(),_meta:F(W(),P()).optional()}),pe=M.extend({type:z(`resource_link`)}),me=I([ce,le,ue,pe,fe]),he=G({role:a,content:me}),ge=G({title:W().optional(),readOnlyHint:H().optional(),destructiveHint:H().optional(),idempotentHint:H().optional(),openWorldHint:H().optional()}),_e=m.extend({method:z(`notifications/tools/list_changed`),params:p.optional()}),ve=G({name:W().optional()}),ye=G({hints:B(ve).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),be=G({mode:V([`auto`,`required`,`none`]).optional()}),xe=G({type:z(`boolean`),title:W().optional(),description:W().optional(),default:H().optional()}),Se=G({type:z(`string`),title:W().optional(),description:W().optional(),minLength:U().optional(),maxLength:U().optional(),format:V([`email`,`uri`,`date`,`date-time`]).optional(),default:W().optional()}),Ce=G({type:V([`number`,`integer`]),title:W().optional(),description:W().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),we=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),default:W().optional()}),Te=G({type:z(`string`),title:W().optional(),description:W().optional(),oneOf:B(G({const:W(),title:W()})),default:W().optional()}),Ee=G({type:z(`string`),title:W().optional(),description:W().optional(),enum:B(W()),enumNames:B(W()).optional(),default:W().optional()}),De=I([we,Te]),Oe=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({type:z(`string`),enum:B(W())}),default:B(W()).optional()}),ke=G({type:z(`array`),title:W().optional(),description:W().optional(),minItems:U().optional(),maxItems:U().optional(),items:G({anyOf:B(G({const:W(),title:W()}))}),default:B(W()).optional()}),Ae=I([Oe,ke]),je=I([Ee,De,Ae]),Me=I([je,xe,Se,Ce]),Ne=f.extend({mode:z(`form`).optional(),message:W(),requestedSchema:G({type:z(`object`),properties:F(W(),Me),required:B(W()).optional()}).catchall(P())}),Pe=G({type:z(`ref/resource`),uri:W()}),Le=G({type:z(`ref/prompt`),name:W()}),ze=G({uri:W().startsWith(`file://`),name:W().optional(),_meta:F(W(),P()).optional()}),Be=C.shape,Ue=G({experimental:Be.experimental,sampling:Be.sampling,elicitation:Be.elicitation,roots:Be.roots,extensions:Be.extensions}),We=w.shape,Ge=G({experimental:We.experimental,logging:We.logging,completions:We.completions,prompts:We.prompts,resources:We.resources,tools:We.tools,extensions:We.extensions}),Ke=L({progressToken:n.optional(),[Qn]:W(),[oi]:v.optional(),[wr]:Ue,[wi]:o.optional()}),qe=G({..._.shape,...g.shape,description:W().optional(),inputSchema:L({$schema:W().optional(),type:z(`object`)}),outputSchema:L({$schema:W().optional()}).optional(),annotations:ge.optional(),_meta:F(W(),P()).optional()}),Je=G({type:z(`tool_result`),toolUseId:W(),content:B(me),structuredContent:P().optional(),isError:H().optional(),_meta:F(W(),P()).optional()}),Ye=I([ce,le,ue,de,Je]),Xe=G({role:a,content:I([Ye,B(Ye)]),_meta:F(W(),P()).optional()}),Ze=W(),Qe=L({[xt]:v.optional().catch(void 0)}),$e=Qe.optional();function et(e){return L({_meta:$e,resultType:Ze.default(`complete`),...e})}let tt=et({}),nt=et({nextCursor:r.optional()}),rt=et({content:B(me),structuredContent:P().optional(),isError:H().optional()}),it=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),tools:B(qe),nextCursor:r.optional()}),at=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),prompts:B(oe),nextCursor:r.optional()}),ot=et({description:W().optional(),messages:B(he)}),st=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resources:B(M),nextCursor:r.optional()}),ct=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resourceTemplates:B(N),nextCursor:r.optional()}),lt=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),contents:B(I([j,ee]))}),ut=et({completion:G({values:B(W()).max(100),total:U().int().optional(),hasMore:H().optional()}).loose()}),dt=et({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`])}),ft=et({ttlMs:U().int().min(0).catch(0),cacheScope:V([`public`,`private`]).catch(`private`),supportedVersions:B(W()),capabilities:Ge,instructions:W().optional()}),pt=G({messages:B(Xe),modelPreferences:ye.optional(),systemPrompt:W().optional(),includeContext:V([`none`,`thisServer`,`allServers`]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:B(W()).optional(),metadata:t.optional(),tools:B(qe).optional(),toolChoice:be.optional()}),mt=G({method:z(`sampling/createMessage`),params:pt}),ht=G({method:z(`roots/list`),params:G({_meta:F(W(),P()).optional()}).optional()}),gt=G({...Xe.shape,model:W(),stopReason:W().optional()}),_t=G({roots:B(ze)}),vt=G({action:V([`accept`,`decline`,`cancel`]),content:F(W(),I([W(),U(),H(),B(W())])).optional()}),yt=G({mode:z(`url`),message:W(),url:W().url()}),bt=I([Ne,yt]),St=G({method:z(`elicitation/create`),params:bt}),Ct=I([mt,ht,St]),wt=I([gt,_t,vt]),Tt=F(W(),Ct),Et=F(W(),wt),Dt=et({inputRequests:Tt.optional(),requestState:W().optional()}),Ot={inputResponses:Et.optional(),requestState:W().optional()},kt=G({_meta:Ke,...Ot}),At=L({progressToken:n.optional()});function jt(e,t){return G({method:z(e),params:G({_meta:Ke,...t})})}function Mt(e,t){return G({method:z(e),params:G({_meta:At.optional(),...t}).optional()})}let Nt={name:W(),arguments:F(W(),P()).optional(),...Ot},Pt={cursor:r.optional()},Ft=jt(`tools/call`,Nt),It=jt(`tools/list`,Pt),Lt=jt(`prompts/list`,Pt),Rt=jt(`prompts/get`,{name:W(),arguments:F(W(),W()).optional(),...Ot}),zt=jt(`resources/list`,Pt),Bt=jt(`resources/templates/list`,Pt),Vt=jt(`resources/read`,{uri:W(),...Ot}),Ht={ref:I([Le,Pe]),argument:G({name:W(),value:W()}),context:G({arguments:F(W(),W()).optional()}).optional()},Ut=jt(`completion/complete`,Ht),Wt=jt(`server/discover`,{}),Gt=G({toolsListChanged:H().optional(),promptsListChanged:H().optional(),resourcesListChanged:H().optional(),resourceSubscriptions:B(W()).optional()}),Kt={notifications:Gt},qt=jt(`subscriptions/listen`,Kt),Jt=Qe.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=L({_meta:Jt,resultType:Ze.default(`complete`)}),Xt={"tools/call":Mt(`tools/call`,Nt),"tools/list":Mt(`tools/list`,Pt),"prompts/get":Mt(`prompts/get`,{name:W(),arguments:F(W(),W()).optional()}),"prompts/list":Mt(`prompts/list`,Pt),"resources/list":Mt(`resources/list`,Pt),"resources/templates/list":Mt(`resources/templates/list`,Pt),"resources/read":Mt(`resources/read`,{uri:W()}),"completion/complete":Mt(`completion/complete`,Ht),"server/discover":Mt(`server/discover`,{}),"subscriptions/listen":Mt(`subscriptions/listen`,Kt)};function Zt(e){return L({_meta:$e,...e})}let Qt={"tools/call":Zt({content:B(me),structuredContent:P().optional(),isError:H().optional()}),"tools/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),tools:B(qe),nextCursor:r.optional()}),"prompts/get":Zt({description:W().optional(),messages:B(he)}),"prompts/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),prompts:B(oe),nextCursor:r.optional()}),"resources/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resources:B(M),nextCursor:r.optional()}),"resources/templates/list":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),resourceTemplates:B(N),nextCursor:r.optional()}),"resources/read":Zt({ttlMs:U().int().min(0),cacheScope:V([`public`,`private`]),contents:B(I([j,ee]))}),"completion/complete":Zt({completion:G({values:B(W()).max(100),total:U().int().optional(),hasMore:H().optional()}).loose()}),"server/discover":Zt({ttlMs:U().int().min(0).catch(0),cacheScope:V([`public`,`private`]).catch(`private`),supportedVersions:B(W()),capabilities:Ge,instructions:W().optional()}),"subscriptions/listen":Zt({})},$t=L({"io.modelcontextprotocol/subscriptionId":i.optional()}),en=G({method:z(`notifications/subscriptions/acknowledged`),params:G({_meta:$t.optional(),notifications:Gt})}),tn=G({_meta:$t.optional(),requestId:i,reason:W().optional()}),nn=G({method:z(`notifications/cancelled`),params:tn}),rn={"notifications/cancelled":nn,"notifications/progress":D,"notifications/message":k,"notifications/resources/updated":ie,"notifications/resources/list_changed":ne,"notifications/tools/list_changed":_e,"notifications/prompts/list_changed":se,"notifications/subscriptions/acknowledged":en},an=e=>G({jsonrpc:z(`2.0`),id:I([W(),U().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:v,ClientTasksCapabilitySchema:x,ServerTasksCapabilitySchema:S,ClientCapabilitiesSchema:C,ServerCapabilitiesSchema:w,ProgressSchema:T,ProgressNotificationParamsSchema:E,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:O,LoggingMessageNotificationSchema:k,ResourceContentsSchema:A,TextResourceContentsSchema:j,BlobResourceContentsSchema:ee,AnnotationsSchema:te,ResourceSchema:M,ResourceTemplateSchema:N,ResourceListChangedNotificationSchema:ne,ResourceUpdatedNotificationParamsSchema:re,ResourceUpdatedNotificationSchema:ie,PromptArgumentSchema:ae,PromptSchema:oe,PromptListChangedNotificationSchema:se,TextContentSchema:ce,ImageContentSchema:le,AudioContentSchema:ue,ToolUseContentSchema:de,EmbeddedResourceSchema:fe,ResourceLinkSchema:pe,ContentBlockSchema:me,PromptMessageSchema:he,ToolAnnotationsSchema:ge,ToolListChangedNotificationSchema:_e,ModelHintSchema:ve,ModelPreferencesSchema:ye,ToolChoiceSchema:be,BooleanSchemaSchema:xe,StringSchemaSchema:Se,NumberSchemaSchema:Ce,UntitledSingleSelectEnumSchemaSchema:we,TitledSingleSelectEnumSchemaSchema:Te,LegacyTitledEnumSchemaSchema:Ee,SingleSelectEnumSchemaSchema:De,UntitledMultiSelectEnumSchemaSchema:Oe,TitledMultiSelectEnumSchemaSchema:ke,MultiSelectEnumSchemaSchema:Ae,EnumSchemaSchema:je,PrimitiveSchemaDefinitionSchema:Me,ElicitRequestFormParamsSchema:Ne,ResourceTemplateReferenceSchema:Pe,PromptReferenceSchema:Le,RootSchema:ze,ClientCapabilities2026Schema:Ue,ServerCapabilities2026Schema:Ge,RequestMetaEnvelopeSchema:Ke,ToolSchema:qe,ToolResultContentSchema:Je,SamplingMessageContentBlockSchema:Ye,SamplingMessageSchema:Xe,ResultTypeSchema:Ze,ResultMetaSchema:Qe,ResultSchema:tt,PaginatedResultSchema:nt,CallToolResultSchema:rt,ListToolsResultSchema:it,ListPromptsResultSchema:at,GetPromptResultSchema:ot,ListResourcesResultSchema:st,ListResourceTemplatesResultSchema:ct,ReadResourceResultSchema:lt,CompleteResultSchema:ut,CacheableResultSchema:dt,DiscoverResultSchema:ft,CreateMessageRequestParamsSchema:pt,CreateMessageRequestSchema:mt,ListRootsRequestSchema:ht,CreateMessageResultSchema:gt,ListRootsResultSchema:_t,ElicitResultSchema:vt,ElicitRequestURLParamsSchema:yt,ElicitRequestParamsSchema:bt,ElicitRequestSchema:St,InputRequestSchema:Ct,InputResponseSchema:wt,InputRequestsSchema:Tt,InputResponsesSchema:Et,InputRequiredResultSchema:Dt,InputResponseRequestParamsSchema:kt,CallToolRequestSchema:Ft,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Qt,NotificationMetaSchema:$t,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:rn,JSONRPCResultResponseSchema:an(tt),CallToolResultResponseSchema:an(I([rt,Dt])),ListToolsResultResponseSchema:an(it),ListPromptsResultResponseSchema:an(at),GetPromptResultResponseSchema:an(I([ot,Dt])),ListResourcesResultResponseSchema:an(st),ListResourceTemplatesResultResponseSchema:an(ct),ReadResourceResultResponseSchema:an(I([lt,Dt])),CompleteResultResponseSchema:an(ut),DiscoverResultResponseSchema:an(ft),SubscriptionsListenResultResponseSchema:an(Yt)}}var dp;function fp(){return dp??=up()}var pp=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function mp(e){return pp.includes(e)}var hp=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function gp(e,t){if(t===void 0)return e;let n=e[hp];if(n===void 0)return{...e,[hp]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[hp]:r}}function _p(e){return e[hp]}function vp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function yp(e){return e===`public`||e===`private`}function bp(e,t){if(e.ttlMs!==void 0&&!vp(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!yp(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}var X=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),Z=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Sf(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Sf(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,xf(this,new.target)}static fromError(t,n,r){if(t===X.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sp(e.elicitations,n)}if(t===X.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Cp({supported:e.supported,requested:e.requested},n)}if(t===X.InvalidParams||t===X.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===X.ResourceNotFound||Object.keys(e).length===1))return new xp(e.uri,n)}if(t===X.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new wp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},xp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Sp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Cp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},wp=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Tp=0,Ep=`private`,Dp=[`tools/call`,`prompts/get`,`resources/read`];function Op(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||Dp.includes(e))return t;throw new Z(X.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function kp(e,t){let n=_p(t);if(t.resultType!==`complete`||!mp(e))return n===void 0?t:Pp(t);let r=t,i=vp(r.ttlMs)?r.ttlMs:Mp(n),a=yp(r.cacheScope)?r.cacheScope:Np(n),o={...r,ttlMs:i,cacheScope:a};return delete o[hp],o}function Ap(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[xt]:t}}:!Ap(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[xt]:t}}}function Mp(e){return e!==void 0&&vp(e.ttlMs)?e.ttlMs:Tp}function Np(e){return e!==void 0&&yp(e.cacheScope)?e.cacheScope:Ep}function Pp(e){let t={...e};return delete t[hp],t}var Fp=[`elicitation/create`,`sampling/createMessage`,`roots/list`],Ip;function Lp(){if(Ip)return Ip;let e=fp();return Ip={request:{"elicitation/create":G({method:z(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":G({method:z(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":G({method:z(`roots/list`),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Ip}function Rp(e){return Fp.includes(e)}function zp(e){return Rp(e)?Lp().request[e]:void 0}function Bp(e){return Rp(e)?Lp().response[e]:void 0}var Vp={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Hp={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Up(e){return Object.prototype.hasOwnProperty.call(Vp,e)}function Wp(e){return Object.prototype.hasOwnProperty.call(Hp,e)}function Gp(e){return Object.prototype.hasOwnProperty.call(Vp,e)}function Kp(e){return Up(e)?fp().dispatchRequestSchemas[e]:void 0}function qp(e){return Gp(e)?fp().dispatchResultSchemas[e]:void 0}function Jp(e){return Wp(e)?fp().notificationSchemas2026[e]:void 0}Object.keys(Vp),Object.keys(Hp);function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var Zp={ok:!1,reason:`not-in-era`},Qp=[Qn,wr];function $p(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>Yp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!Yp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(Yp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}var em={era:`2026-07-28`,hasRequestMethod:Up,hasNotificationMethod:Wp,hasInputRequestMethod:e=>zp(e)!==void 0,validateRequest:(e,t)=>Xp(Kp(e),t),validateResult:(e,t)=>Xp(qp(e),t),validateNotification:(e,t)=>Xp(Jp(e),t),validateInputRequest:(e,t)=>Xp(zp(e),t),validateInputResponse:(e,t)=>Xp(Bp(e),t),samplingResultVariant:()=>Zp,outboundEnvelope(e){return{[Qn]:e.protocolVersion,[oi]:e.clientInfo,[wr]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Qp)n in e||t.push({key:n,problem:`missing`});let n=fp().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>If(e),inputRequestSchema:zp,decodeResult(e,t){if(!Yp(t))return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=Yp(n)?n:{},i=t.requestState,a=t._meta===void 0?void 0:fp().ResultMetaSchema.safeParse(t._meta),o=a?.success?a.data:void 0;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i},...o!==void 0&&{_meta:o}}}if(n!==`complete`)return{kind:`invalid`,error:new Y(J.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=nm(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return jp(kp(e,Op(e,$p(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=fp().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},tm;function nm(){if(tm)return tm;let e=fp();return tm={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},tm}var rm=`2026-07-28`;function im(e){return e!==void 0&&Nf(e)?em:lp}function am(e){return e.revision===void 0?e.era===`modern`?em.era:lp.era:im(e.revision).era}function om(e){return lm.some(t=>t.hasRequestMethod(e))}function sm(e){return lm.some(t=>t.hasNotificationMethod(e))}function cm(e){return e===`tasks/get`||e===`tasks/cancel`}var lm=[lp,em];function um(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dm(e){if(!um(e))return;let t=e._meta;return um(t)?t:void 0}function fm(e){let t=dm(e);return t!==void 0&&`io.modelcontextprotocol/protocolVersion`in t}function pm(e){let t=dm(e)?.[Qn];return typeof t==`string`?t:void 0}function mm(e){return im(rm).validateEnvelopeMeta(e)}var hm=df({AnnotationsSchema:()=>Jr,AudioContentSchema:()=>pr,BaseMetadataSchema:()=>In,BaseRequestParamsSchema:()=>Ir,BlobResourceContentsSchema:()=>Qr,BooleanSchemaSchema:()=>Wn,CallToolRequestParamsSchema:()=>Jn,CallToolRequestSchema:()=>tr,CallToolResultSchema:()=>Br,CancelTaskRequestSchema:()=>Or,CancelTaskResultSchema:()=>lr,CancelledNotificationParamsSchema:()=>ar,CancelledNotificationSchema:()=>Mn,ClientCapabilitiesSchema:()=>ui,ClientNotificationSchema:()=>xi,ClientRequestSchema:()=>Bn,ClientResultSchema:()=>_i,ClientTasksCapabilitySchema:()=>an,CompatibilityCallToolResultSchema:()=>$e,CompleteRequestParamsSchema:()=>pi,CompleteRequestSchema:()=>ln,CompleteResultSchema:()=>st,ContentBlockSchema:()=>rt,CreateMessageRequestParamsSchema:()=>Wt,CreateMessageRequestSchema:()=>br,CreateMessageResultSchema:()=>Ke,CreateMessageResultWithToolsSchema:()=>_r,CreateTaskResultSchema:()=>It,CursorSchema:()=>Bt,DiscoverRequestSchema:()=>dt,DiscoverResultSchema:()=>bt,ElicitRequestFormParamsSchema:()=>Mt,ElicitRequestParamsSchema:()=>en,ElicitRequestSchema:()=>Ti,ElicitRequestURLParamsSchema:()=>Xe,ElicitResultSchema:()=>gn,ElicitationCompleteNotificationParamsSchema:()=>_t,ElicitationCompleteNotificationSchema:()=>pn,EmbeddedResourceSchema:()=>bn,EmptyResultSchema:()=>mt,EnumSchemaSchema:()=>Ot,GetPromptRequestParamsSchema:()=>Wr,GetPromptRequestSchema:()=>wt,GetPromptResultSchema:()=>En,GetTaskPayloadRequestSchema:()=>Cn,GetTaskPayloadResultSchema:()=>kn,GetTaskRequestSchema:()=>Zt,GetTaskResultSchema:()=>Ue,IconSchema:()=>er,IconsSchema:()=>ai,ImageContentSchema:()=>Zr,ImplementationSchema:()=>gr,InitializeRequestParamsSchema:()=>zn,InitializeRequestSchema:()=>zr,InitializeResultSchema:()=>ti,InitializedNotificationSchema:()=>qn,JSONArraySchema:()=>Dr,JSONObjectSchema:()=>li,JSONRPCErrorResponseSchema:()=>Zn,JSONRPCMessageSchema:()=>ir,JSONRPCNotificationSchema:()=>Ur,JSONRPCRequestSchema:()=>jr,JSONRPCResponseSchema:()=>fr,JSONRPCResultResponseSchema:()=>cr,JSONValueSchema:()=>Fn,LegacyTitledEnumSchemaSchema:()=>Un,ListChangedOptionsBaseSchema:()=>bi,ListPromptsRequestSchema:()=>cn,ListPromptsResultSchema:()=>nt,ListResourceTemplatesRequestSchema:()=>gi,ListResourceTemplatesResultSchema:()=>fn,ListResourcesRequestSchema:()=>ut,ListResourcesResultSchema:()=>ot,ListRootsRequestSchema:()=>qt,ListRootsResultSchema:()=>Cr,ListTasksRequestSchema:()=>Ye,ListTasksResultSchema:()=>yr,ListToolsRequestSchema:()=>zt,ListToolsResultSchema:()=>Ut,LoggingLevelSchema:()=>Xt,LoggingMessageNotificationParamsSchema:()=>pt,LoggingMessageNotificationSchema:()=>Ct,ModelHintSchema:()=>Ft,ModelPreferencesSchema:()=>rn,MultiSelectEnumSchemaSchema:()=>Oi,NotificationSchema:()=>Qe,NotificationsParamsSchema:()=>yn,NumberSchemaSchema:()=>yt,PaginatedRequestParamsSchema:()=>ri,PaginatedRequestSchema:()=>Nr,PaginatedResultSchema:()=>Yr,PingRequestSchema:()=>mr,PrimitiveSchemaDefinitionSchema:()=>Ln,ProgressNotificationParamsSchema:()=>Lr,ProgressNotificationSchema:()=>$r,ProgressSchema:()=>Gn,ProgressTokenSchema:()=>Tr,PromptArgumentSchema:()=>si,PromptListChangedNotificationSchema:()=>Yn,PromptMessageSchema:()=>nr,PromptReferenceSchema:()=>Vr,PromptSchema:()=>kr,ReadResourceRequestParamsSchema:()=>ur,ReadResourceRequestSchema:()=>or,ReadResourceResultSchema:()=>Nn,RelatedTaskMetadataSchema:()=>di,RequestIdSchema:()=>Si,RequestMetaSchema:()=>Vn,RequestSchema:()=>vi,ResourceContentsSchema:()=>on,ResourceLinkSchema:()=>et,ResourceListChangedNotificationSchema:()=>mi,ResourceRequestParamsSchema:()=>un,ResourceSchema:()=>ct,ResourceTemplateReferenceSchema:()=>it,ResourceTemplateSchema:()=>Gt,ResourceUpdatedNotificationParamsSchema:()=>xr,ResourceUpdatedNotificationSchema:()=>qe,ResultMetaObjectSchema:()=>vr,ResultSchema:()=>Lt,RoleSchema:()=>Vt,RootSchema:()=>Jt,RootsListChangedNotificationSchema:()=>ft,SamplingContentSchema:()=>Ei,SamplingMessageContentBlockSchema:()=>Ze,SamplingMessageSchema:()=>_n,ServerCapabilitiesSchema:()=>vt,ServerNotificationSchema:()=>mn,ServerRequestSchema:()=>xn,ServerResultSchema:()=>ht,ServerTasksCapabilitySchema:()=>kt,SetLevelRequestParamsSchema:()=>Gr,SetLevelRequestSchema:()=>Tt,SingleSelectEnumSchemaSchema:()=>Dn,StringSchemaSchema:()=>wn,SubscribeRequestParamsSchema:()=>An,SubscribeRequestSchema:()=>Qt,SubscriptionFilterSchema:()=>We,SubscriptionsAcknowledgedNotificationParamsSchema:()=>$n,SubscriptionsAcknowledgedNotificationSchema:()=>ii,SubscriptionsListenRequestParamsSchema:()=>Pr,SubscriptionsListenRequestSchema:()=>Xr,SubscriptionsListenResultMetaSchema:()=>hr,SubscriptionsListenResultSchema:()=>Rn,TaskAugmentedRequestParamsSchema:()=>ei,TaskCreationParamsSchema:()=>Kn,TaskMetadataSchema:()=>Er,TaskSchema:()=>ci,TaskStatusNotificationParamsSchema:()=>Xn,TaskStatusNotificationSchema:()=>rr,TaskStatusSchema:()=>Hr,TextContentSchema:()=>Ar,TextResourceContentsSchema:()=>dr,TitledMultiSelectEnumSchemaSchema:()=>sr,TitledSingleSelectEnumSchemaSchema:()=>Pn,ToolAnnotationsSchema:()=>fi,ToolChoiceSchema:()=>Ci,ToolExecutionSchema:()=>Hn,ToolListChangedNotificationSchema:()=>yi,ToolResultContentSchema:()=>sn,ToolSchema:()=>tt,ToolUseContentSchema:()=>hi,UnsubscribeRequestParamsSchema:()=>dn,UnsubscribeRequestSchema:()=>lt,UntitledMultiSelectEnumSchemaSchema:()=>at,UntitledSingleSelectEnumSchemaSchema:()=>Kt}),gm=e=>jr.safeParse(e).success,_m=e=>Ur.safeParse(e).success,vm=e=>cr.safeParse(e).success,ym=e=>Zn.safeParse(e).success,bm=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`,xm=e=>zr.safeParse(e).success;function Sm(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cm(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var wm=`Mcp-Param-`,Tm=`x-mcp-header`,Em=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Dm=new Set([`string`,`integer`,`boolean`,`number`]);function Om(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(Tm in o){if(!a||i.length===0)return`${jm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[Tm];if(typeof e!=`string`||e.length===0)return`${jm(i)}: x-mcp-header MUST be a non-empty string`;if(!Em.test(e))return`${jm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!Dm.has(r))return`${jm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of km){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&Am.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}var km=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],Am=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function jm(e){return e.length===0?`<root>`:e.join(`.`)}var Mm=`=?base64?`,Nm=`?=`,Pm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fm=/^-?\d+(\.\d+)?$/;function Im(e){if(typeof e==`string`)return e;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function Lm(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.codePointAt(e);return new TextDecoder(`utf-8`,{fatal:!0}).decode(n)}function Rm(e){if(!(e.startsWith(Mm)&&e.endsWith(Nm)))return e;let t=e.slice(9,e.length-2);if(Pm.test(t))try{return Lm(t)}catch{return}}function zm(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Bm(e,t,n){for(let r of e){let e=`${wm}${r.headerName}`,i=n.get(e),a=zm(t,r.path);if(a==null)continue;let o=Im(a);if(o===void 0)continue;if(i===null)return Vm(`param-header-missing`,e,`the body carries ${jm(r.path)}=${JSON.stringify(a)} but the ${e} header is absent`);let s=Rm(i);if(s===void 0)return Vm(`param-header-invalid-encoding`,e,`the ${e} header carries an invalid Base64 sentinel value`);if(!((r.type===`integer`||r.type===`number`)&&Fm.test(s)&&typeof a==`number`?Number(s)===a:s===o))return Vm(`param-header-mismatch`,e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${jm(r.path)}=${JSON.stringify(a)}`)}}function Vm(e,t,n){return{kind:`reject`,rung:`param-header-validation`,cell:e,httpStatus:400,code:Hm,message:`Bad Request: the request headers and body disagree: ${n}`,data:{mismatch:{header:t,body:n}},settled:!0}}var Hm=-32020;X.InvalidRequest,X.UnsupportedProtocolVersion,X.InvalidParams,X.MethodNotFound,X.InvalidParams,X.MissingRequiredClientCapability;var Um={[X.ParseError]:400,[X.InvalidRequest]:400,[X.MethodNotFound]:404,[X.UnsupportedProtocolVersion]:400,[X.MissingRequiredClientCapability]:400,[Hm]:400};function Wm(e,t){return t===`in-band`?e===X.MissingRequiredClientCapability?400:200:Um[e]??400}function Gm(e,t,n,r,i){return{kind:`reject`,rung:e,cell:t,httpStatus:n,code:r.code,message:r.message,...r.data!==void 0&&{data:r.data},settled:i}}function Km(e,t,n,r=`era-classification`){return Gm(r,e,400,new Z(Hm,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}}),!0)}var qm={"tools/call":`name`,"prompts/get":`name`,"resources/read":`uri`,"tasks/get":`taskId`,"tasks/update":`taskId`,"tasks/cancel":`taskId`};function Jm(e,t){let n=Object.hasOwn(qm,e)?qm[e]:void 0;if(n===void 0)return;let r=Zm(t)?t[n]:void 0;return{field:n,value:typeof r==`string`?r:void 0}}function Ym(e){let t=0;for(;t<e.length;){let n=e.codePointAt(t);if(n!==9&&n!==32)break;t+=1}let n=e.length;for(;n>t;){let t=e.codePointAt(n-1);if(t!==9&&t!==32)break;--n}return t===0&&n===e.length?e:e.slice(t,n)}function Xm(e,t){if(t.messageKind!==`request`)return;let n=t.message.method;if(e.protocolVersionHeader===void 0){let e=t.classification.revision;return Km(`version-header-missing`,`(missing)`,e===void 0?`the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent`:`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,`standard-header-validation`)}if(e.mcpMethodHeader===void 0)return Km(`method-header-missing`,`(missing)`,`the body names method ${n} but the required Mcp-Method header is absent`,`standard-header-validation`);let r=Jm(n,t.message.params);if(r===void 0)return;let{field:i,value:a}=r;if(e.mcpNameHeader===void 0)return a===void 0?void 0:Km(`name-header-missing`,`(missing)`,`the body carries params.${i}="${a}" but the required Mcp-Name header is absent`,`standard-header-validation`);let o=Ym(e.mcpNameHeader),s=Rm(o);if(s===void 0)return Km(`name-header-invalid-encoding`,o,`the Mcp-Name header carries an invalid Base64 sentinel value`,`standard-header-validation`);if(a!==void 0&&s!==a)return Km(`name-header-mismatch`,o,`the body carries params.${i}="${a}" but the Mcp-Name header names "${s}"`,`standard-header-validation`)}function Zm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qm(e){return e===void 0?{era:`modern`}:{era:Nf(e)?`modern`:`legacy`,revision:e}}function $m(e){if(!fm(e))return!1;let t=pm(e);if(t===void 0||!Nf(t))return!1;let n=dm(e);return n!==void 0&&mm(n).length===0}function eh(e){if(e.length===0)return Gm(`jsonrpc-shape`,`empty-batch`,400,new Z(X.InvalidRequest,`Bad Request: empty JSON-RPC batch`),!0);for(let t of e){if(fm(Zm(t)?t.params:void 0))return Gm(`jsonrpc-shape`,`batch-with-modern-element`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later`),!0);if(!(gm(t)||_m(t)||vm(t)||ym(t)))return Gm(`jsonrpc-shape`,`batch-with-invalid-element`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batch contains an invalid message`),!0)}return{kind:`legacy`,reason:`batch`}}function th(e,t){let n=t.params,r=t.method,i=e.protocolVersionHeader,a=i!==void 0&&Nf(i);if(r===`initialize`&&!$m(n)){if(a)return Km(`initialize-with-modern-header`,i,`an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header`);let e=Zm(n)&&typeof n.protocolVersion==`string`?n.protocolVersion:void 0;return{kind:`legacy`,reason:`initialize`,...e!==void 0&&{requestedVersion:e}}}if(fm(n)){let a=dm(n),o=(a===void 0?[]:mm(a))[0];if(o!==void 0)return Gm(`envelope`,`envelope-invalid`,400,new Z(X.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=pm(n);return i!==void 0&&s!==void 0&&i!==s?Km(`header-body-version-mismatch`,i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`method-header-mismatch`,e.mcpMethodHeader,`the body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`request`,message:t,classification:Qm(s)}}if(a){let e=dm(n),t=mm(e??{}).filter(e=>e.problem===`missing`).map(e=>e.key),r=e===void 0?[`_meta`]:t.length>0?t:[Qn];return Gm(`envelope`,`modern-header-without-claim`,400,new Z(X.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${r.join(`, `)}`,{envelope:{missing:r}}),!0)}return{kind:`legacy`,reason:`no-claim`,...i!==void 0&&{requestedVersion:i}}}function nh(e,t){let n=t.params,r=t.method,i=e.protocolVersionHeader,a=i!==void 0&&Nf(i);if(fm(n)){let a=pm(n);if(a===void 0){let e=dm(n),t=(e===void 0?[]:mm(e)).find(e=>e.key===`io.modelcontextprotocol/protocolVersion`)??{key:`io.modelcontextprotocol/protocolVersion`,problem:`expected a protocol version string`};return Gm(`envelope`,`notification-envelope-invalid`,400,new Z(X.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(i!==void 0&&i!==a)return Km(`notification-header-body-version-mismatch`,i,`the notification envelope names protocol version ${a} but the MCP-Protocol-Version header names ${i}`);let o=Qm(a);return o.era===`modern`&&e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`notification-method-header-mismatch`,e.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`notification`,message:t,classification:o}}return a?e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==r?Km(`notification-method-header-mismatch`,e.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:`modern`,messageKind:`notification`,message:t,classification:{era:`modern`,revision:i}}:{kind:`legacy`,reason:`notification`,...i!==void 0&&{requestedVersion:i}}}function rh(e){if(e={...e,...e.protocolVersionHeader!==void 0&&{protocolVersionHeader:Ym(e.protocolVersionHeader)},...e.mcpMethodHeader!==void 0&&{mcpMethodHeader:Ym(e.mcpMethodHeader)},...e.mcpNameHeader!==void 0&&{mcpNameHeader:Ym(e.mcpNameHeader)}},e.httpMethod.toUpperCase()!==`POST`)return{kind:`legacy`,reason:`http-method`};let t=e.body;return Array.isArray(t)?eh(t):vm(t)||ym(t)?{kind:`legacy`,reason:`response`}:Zm(t)&&gm(t)?th(e,t):Zm(t)&&_m(t)?nh(e,t):Gm(`jsonrpc-shape`,`invalid-json-rpc-body`,400,new Z(X.InvalidRequest,`Bad Request: the request body is not a valid JSON-RPC message`),!0)}function ih(e,t){switch(e.reason){case`http-method`:return Gm(`http-method`,`modern-only-method-not-allowed`,405,new Z(-32e3,`Method not allowed.`),!0);case`batch`:return Gm(`jsonrpc-shape`,`modern-only-batch-not-supported`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC batches are not supported by this endpoint`),!0);case`response`:return Gm(`jsonrpc-shape`,`modern-only-response-post`,400,new Z(X.InvalidRequest,`Bad Request: JSON-RPC responses cannot be posted to this endpoint`),!0);case`notification`:return;case`initialize`:case`no-claim`:{let n=e.requestedVersion;return Gm(`era-classification`,`modern-only-missing-envelope`,400,n===void 0?new Z(X.UnsupportedProtocolVersion,`Unsupported protocol version: the request did not name a protocol version`,{supported:[...t]}):new Cp({supported:[...t],requested:n}),!0)}}}function ah(e,t){return Le(e,t)}function oh(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function sh(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}var ch=!1,lh=`draft-2020-12`;function uh(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:lh});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);ch||(ch=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=Ae(e,{target:lh,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&dh(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function dh(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||dh(e)))}return!1}function fh(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function ph(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>fh(e)).join(`, `)}:{success:!0,data:n.value}}function mh(e){let t=Ae(e,{target:lh,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}var hh=/\\\.\\d\{(\d+)\}/;function gh(e){let t=hh.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>Ie({local:e,offset:t,precision:n}))))}function _h(e,t){let n;switch(e){case`email`:n=[Pe()];break;case`uri`:n=[je()];break;case`date`:n=[Be()];break;case`date-time`:n=gh(t)}return new Set(n.map(e=>mh(e)).filter(e=>e!==void 0))}function vh(e,t,n){return n!==`zod`||_h(e,t).has(t)}function yh(e){let t=uh(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function bh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xh(e){try{return uh(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Z(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}var Sh=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function Ch(e){return Sh.has(e)||e.startsWith(`x-`)}var wh=new Set([`$schema`,...Object.keys(Mt.shape.requestedSchema.shape)]),Th={string:oh([wn,Kt,Pn,Un]),number:oh([yt]),integer:oh([yt]),boolean:oh([Wn]),array:oh([at,sr])},Eh=new Set(wn.shape.format.unwrap().options);function Dh(e,t,n,r){if(!bh(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Th,e.type)?Th[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||Ch(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Eh.has(e.format)?(typeof s!=`string`||!vh(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function Oh(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&bh(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Dh(n,`properties.${e}`,t,r)])):wh.has(i)?n[i]=a:Ch(i)||r.push(i);if(r.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function kh(e,t){if(!bh(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!ah(Ln,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Ah(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Ah(e,t[r],`${n}[${r}]`)):!bh(e)||!bh(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Ah(r,t[e],i):Ch(e)?[]:[i]})}function jh(e){if(!sh(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=Oh(xh(e.requestedSchema),t),r=ah(Mt.shape.requestedSchema,n);if(!r.success)throw new Z(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${kh(n,r.error.message)}`);let i=Ah(n,r.data);if(i.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Mh(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Mh,{elicit(e){try{return{method:`elicitation/create`,params:jh(e)}}catch(e){throw e instanceof Z?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Nh(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Ph(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Fh(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}var Ih=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),Lh={IdJagTokenExchangeResponseSchema:Fr,OAuthClientInformationFullSchema:hn,OAuthClientInformationSchema:Sn,OAuthClientMetadataSchema:gt,OAuthClientRegistrationErrorSchema:jt,OAuthErrorResponseSchema:qr,OAuthMetadataSchema:Dt,OAuthProtectedResourceMetadataSchema:On,OAuthTokenRevocationRequestSchema:Tn,OAuthTokensSchema:jn,OpenIdProviderDiscoveryMetadataSchema:$t,OpenIdProviderMetadataSchema:Ge},Rh={},zh={};function Bh(e,t){let n=e.slice(0,-6);Rh[n]=t,zh[n]=e=>t.safeParse(e).success}for(let e of Ih)Bh(e,hm[e]);for(let[e,t]of Object.entries(Lh))Bh(e,t);Object.freeze(Rh),Object.freeze(zh);function Vh(e){switch(e){case`initialize`:case`notifications/initialized`:return im(void 0);case`server/discover`:return im(rm);default:return}}var Hh=[Qn,oi,wr,wi],Uh=[`inputResponses`,`requestState`];function Wh(e,t){let n=e.params;if(!Qh(n))return{message:e,lifted:{}};let r=n._meta,i=Qh(r)?Hh.filter(e=>e in r):[],a=t===`request`?Uh.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&Qh(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function Gh(e,t){let n=e.validateResult(t,void 0);if(n.ok||n.reason!==`not-in-era`)return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function Kh(e){return()=>e}var qh=Kh(void 0);function Jh(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:Kh(t)}}}var Yh;function Xh(e,t){Yh(e,t)}var Zh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Yh=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??tn,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),vm(e)||ym(e)?this._onresponse(e):gm(e)?this._onrequest(e,t):_m(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new Y(J.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=Wh(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=am(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(sm(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;(i!==void 0||a!==void 0)&&Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=Wh(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=am(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(om(n.method)&&!i.hasRequestMethod(n.method)&&!(cm(n.method)&&this._customSchemaRequestMethods.has(n.method))){o(X.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(X.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(X.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:tg(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?qh:Kh(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),sh(t))return u(e,t,n);let i=Gh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(X.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:X.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),vm(e)?n(e):n(Z.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(sh(t))return cm(e.method)||this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n);this._assertOutboundRequestInEra(r,e.method);let i=Gh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return im(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Vh(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(om(t)&&!e.hasRequestMethod(t))throw new Y(J.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),v=!1,y=e=>{v||(this._progressHandlers.delete(h),m===void 0?t.method!==`initialize`&&this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof Y?e:new Y(J.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(v=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(ng(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;ph(n,o).then(e=>{e.success?d(e.data):f(new Y(J.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>y(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let b=r?.timeout??6e4;this._setupTimeout(h,b,r?.maxTotalTimeout,()=>y(new Y(J.RequestTimeout,`Request timed out`,{timeout:b})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new Y(J.NotConnected,`Not connected`);if(sm(t.method)&&!e.hasNotificationMethod(t.method))throw new Y(J.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&n?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!om(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await ph(t.params,{...r.params});if(!a.success)throw new Z(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);typeof t==`function`?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!sm(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await ph(t.params,{...r.params});if(!i.success)throw new Z(X.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Qh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $h(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Qh(a)&&Qh(i)?{...a,...i}:i}return n}function eg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tg(e){let t={},n=[];if(!eg(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!eg(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function ng(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var rg=pf(q((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))(),1);function ig(e){if(e)try{return rg.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function ag(e){return e===`application/json`||ig(e)===`application/json`}var og=/^[A-Za-z0-9._-]{1,128}$/;function sg(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!og.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function cg(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function lg(e){let t=sg(e);return cg(e,t.warnings),t.isValid}function ug(e){return typeof e==`object`&&!!e&&`_zod`in e}function dg(e){return typeof e==`object`&&!!e&&!(`_zod`in e)&&`_def`in e&&typeof e._def?.typeName==`string`}function fg(e){if(typeof e!=`object`||!e||sh(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(e=>ug(e))}function pg(e){if(e!==void 0){if(fg(e))return G(e);if(typeof e==`object`&&e&&!sh(e)&&Object.values(e).some(e=>dg(e)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!sh(e))throw TypeError(`inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).`);return e}}var mg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{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(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),hg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=mg();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Q=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=mg(),n=hg();var r=mg();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=hg();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
62
62
  `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}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,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${re(e)}`}e.not=j;let ee=ne(e.operators.AND);function te(...e){return e.reduce(ee)}e.and=te;let M=ne(e.operators.OR);function N(...e){return e.reduce(M)}e.or=N;function ne(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${re(n)} ${e} ${re(r)}`}function re(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),$=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=Q(),n=mg();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),gg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),_g=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Q(),n=$(),r=gg();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),vg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=_g(),n=Q(),r=gg(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),yg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),bg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),xg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=yg(),n=bg(),r=_g(),i=Q(),a=$();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
63
63
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
64
64
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
65
65
  || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Sg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=Q(),n=$();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Cg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=Q(),n=$(),r=gg(),i=$();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),wg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Q(),n=gg(),r=Cg(),i=_g();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Tg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Q(),n=$();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Eg=q(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Dg=q(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.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 r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Og=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=$(),n=Eg(),r=Dg(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),kg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=vg(),n=xg(),r=bg(),i=xg(),a=Sg(),o=wg(),s=Tg(),c=Q(),l=gg(),u=Og(),d=$(),f=_g();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return te(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);te(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ee(e),t.return((0,c._)`${l.default.errors} === 0`))}function ee({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function te(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||N(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),M(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):M(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function M(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function N(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ne(e,t),e.opts.allowUnionTypes||re(e,t),ie(e,e.dataTypes))}function ne(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{oe(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),se(e,t)}}function re(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ie(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ae(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ae(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function oe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function se(e,t){let n=[];for(let r of e.dataTypes)oe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,pe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}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:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=pe})),Ag=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),jg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Og();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Mg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Q(),n=Ag(),r=gg(),i=Og(),a=$(),o=kg();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Ng=q(((e,t)=>{t.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}})),Pg=q(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(s!==`[`&&s!==`]`){if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),Fg=q(((e,t)=>{let{isUUID:n}=Pg(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),Ig=q(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Pg(),{SCHEMES:c,getSchemeHandler:l}=Fg();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host){if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Lg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ig();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Rg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Ag(),i=jg(),a=yg(),o=Mg(),s=Q(),c=Og(),l=xg(),u=$(),d=Ng(),f=Lg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={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.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw 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 r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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 t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;ee.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=M(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ee(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=M(t)),e.validateSchema=this.compile(t,!0))}let te={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function M(e){return{anyOf:[e,te]}}})),zg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Bg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=jg(),n=Cg(),r=Q(),i=gg(),a=Mg(),o=$(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),Vg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zg(),n=Bg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Hg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),Ug=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),Wg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Gg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=Wg();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),Kg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=$(),r=Q();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),qg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Jg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=Q(),r=$();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),Yg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),Xg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Eg();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Zg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xg(),n=Q(),r=$(),i=Xg();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),Qg=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=Xg();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),$g=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=Xg();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),e_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Hg(),n=Ug(),r=Gg(),i=Kg(),a=qg(),o=Jg(),s=Yg(),c=Zg(),l=Qg(),u=$g();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),t_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=Q(),n=$(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),n_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=Q(),n=$(),r=Cg(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),r_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=n_();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),i_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=Cg(),i=t_();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),a_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),o_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Q(),n=$(),r=Cg();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
66
66
  missingProperty: ${i},
67
67
  depsCount: ${n},
68
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),s_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),c_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=Q(),r=gg(),i=$();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),l_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kg(),n=Cg(),r=$(),i=c_();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),u_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=Q(),r=$(),i=$();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),d_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),f_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Cg().validateUnion,error:{message:`must match a schema in anyOf`}}})),p_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),m_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),h_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),g_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),__=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=t_(),n=r_(),r=n_(),i=i_(),a=a_(),o=o_(),s=s_(),c=c_(),l=l_(),u=u_(),d=d_(),f=f_(),p=p_(),m=m_(),h=h_(),g=g_();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),v_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),y_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[v_().default]})),b_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),x_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vg(),n=e_(),r=__(),i=y_(),a=b_();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),S_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),C_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=S_(),r=Mg(),i=jg(),a=$();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),w_=q(((e,t)=>{t.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}})),T_=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Rg(),r=x_(),i=C_(),a=w_(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),E_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=Q(),n=gg(),r=Mg(),i=Bg(),a={keyword:`$dynamicAnchor`,schemaType:`string`,code:e=>o(e,e.schema)};function o(e,r){let{gen:i,it:a}=e;a.schemaEnv.root.dynamicAnchors[r]=!0;let o=(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(r)}`,c=a.errSchemaPath===`#`?a.validateName:s(e);i.if((0,t._)`!${o}`,()=>i.assign(o,c))}e.dynamicAnchor=o;function s(e){let{schemaEnv:t,schema:n,self:a}=e.it,{root:o,baseId:s,localRefs:c,meta:l}=t.root,{schemaId:u}=a.opts,d=new r.SchemaEnv({schema:n,schemaId:u,root:o,baseId:s,localRefs:c,meta:l});return r.compileSchema.call(a,d),(0,i.getValidate)(e,d)}e.default=a})),D_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=Q(),n=gg(),r=Bg(),i={keyword:`$dynamicRef`,schemaType:`string`,code:e=>a(e,e.schema)};function a(e,i){let{gen:a,keyword:o,it:s}=e;if(i[0]!==`#`)throw Error(`"${o}" only supports hash fragment reference`);let c=i.slice(1);if(s.allErrors)l();else{let t=a.let(`valid`,!1);l(t),e.ok(t)}function l(e){if(s.schemaEnv.root.dynamicAnchors[c]){let r=a.let(`_v`,(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(c)}`);a.if(r,u(r,e),u(s.validateName,e))}else u(s.validateName,e)()}function u(t,n){return n?()=>a.block(()=>{(0,r.callRef)(e,t),a.let(n,!0)}):()=>(0,r.callRef)(e,t)}}e.dynamicRef=a,e.default=i})),O_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=E_(),n=$();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),k_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=D_();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),A_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=E_(),n=D_(),r=O_(),i=k_();e.default=[t.default,n.default,r.default,i.default]})),j_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=o_();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),M_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=o_();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),N_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:[`maxContains`,`minContains`],type:`array`,schemaType:`number`,code({keyword:e,parentSchema:n,it:r}){n.contains===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}}})),P_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=j_(),n=M_(),r=N_();e.default=[t.default,n.default,r.default]})),F_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=gg();e.default={keyword:`unevaluatedProperties`,type:`object`,schemaType:[`boolean`,`object`],trackErrors:!0,error:{message:`must NOT have unevaluated properties`,params:({params:e})=>(0,t._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){let{gen:i,schema:a,data:o,errsCount:s,it:c}=e;if(!s)throw Error(`ajv implementation error`);let{allErrors:l,props:u}=c;u instanceof t.Name?i.if((0,t._)`${u} !== true`,()=>i.forIn(`key`,o,e=>i.if(f(u,e),()=>d(e)))):u!==!0&&i.forIn(`key`,o,e=>u===void 0?d(e):i.if(p(u,e),()=>d(e))),c.props=!0,e.ok((0,t._)`${s} === ${r.default.errors}`);function d(r){if(a===!1){e.setParams({unevaluatedProperty:r}),e.error(),l||i.break();return}if(!(0,n.alwaysValidSchema)(c,a)){let a=i.name(`valid`);e.subschema({keyword:`unevaluatedProperties`,dataProp:r,dataPropType:n.Type.Str},a),l||i.if((0,t.not)(a),()=>i.break())}}function f(e,n){return(0,t._)`!${e} || !${e}[${n}]`}function p(e,n){let r=[];for(let i in e)e[i]===!0&&r.push((0,t._)`${n} !== ${i}`);return(0,t.and)(...r)}}}})),I_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`unevaluatedItems`,type:`array`,schemaType:[`boolean`,`object`],error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e,s=o.items||0;if(s===!0)return;let c=r.const(`len`,(0,t._)`${a}.length`);if(i===!1)e.setParams({len:s}),e.fail((0,t._)`${c} > ${s}`);else if(typeof i==`object`&&!(0,n.alwaysValidSchema)(o,i)){let n=r.var(`valid`,(0,t._)`${c} <= ${s}`);r.if((0,t.not)(n),()=>l(n,s)),e.ok(n)}o.items=!0;function l(i,a){r.forRange(`i`,a,c,a=>{e.subschema({keyword:`unevaluatedItems`,dataProp:a,dataPropType:n.Type.Num},i),o.allErrors||r.if((0,t.not)(i),()=>r.break())})}}}})),L_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=F_(),n=I_();e.default=[t.default,n.default]})),R_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/schema`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format`},{$ref:`meta/content`}],type:[`object`,`boolean`],properties:{definitions:{$comment:`While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.`,type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},dependencies:{$comment:`"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"`,type:`object`,additionalProperties:{anyOf:[{$recursiveRef:`#`},{$ref:`meta/validation#/$defs/stringArray`}]}}}}})),z_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{additionalItems:{$recursiveRef:`#`},unevaluatedItems:{$recursiveRef:`#`},items:{anyOf:[{$recursiveRef:`#`},{$ref:`#/$defs/schemaArray`}]},contains:{$recursiveRef:`#`},additionalProperties:{$recursiveRef:`#`},unevaluatedProperties:{$recursiveRef:`#`},properties:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$recursiveRef:`#`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$recursiveRef:`#`}},propertyNames:{$recursiveRef:`#`},if:{$recursiveRef:`#`},then:{$recursiveRef:`#`},else:{$recursiveRef:`#`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$recursiveRef:`#`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$recursiveRef:`#`}}}}})),B_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/content`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentMediaType:{type:`string`},contentEncoding:{type:`string`},contentSchema:{$recursiveRef:`#`}}}})),V_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/core`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{type:`string`,format:`uri`},$anchor:{type:`string`,pattern:`^[A-Za-z][-A-Za-z0-9.:_]*$`},$ref:{type:`string`,format:`uri-reference`},$recursiveRef:{type:`string`,format:`uri-reference`},$recursiveAnchor:{type:`boolean`,default:!1},$vocabulary:{type:`object`,propertyNames:{type:`string`,format:`uri`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}}}}})),H_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/format`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:`Format vocabulary meta-schema`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),U_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),W_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),G_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R_(),n=z_(),r=B_(),i=V_(),a=H_(),o=U_(),s=W_(),c=[`/properties`];function l(e){return[t,n,r,i,l(this,a),o,l(this,s)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function l(t,n){return e?t.$dataMetaSchema(n,c):n}}e.default=l})),K_=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2019=void 0;let n=Rg(),r=x_(),i=A_(),a=P_(),o=L_(),s=C_(),c=G_(),l=`https://json-schema.org/draft/2019-09/schema`;var u=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(i.default),r.default.forEach(e=>this.addVocabulary(e)),this.addVocabulary(a.default),this.addVocabulary(o.default),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(c.default.call(this,e),this.refs[`http://json-schema.org/schema`]=l)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}};e.Ajv2019=u,t.exports=e=u,t.exports.Ajv2019=u,Object.defineProperty(e,"__esModule",{value:!0}),e.default=u;var d=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return d.KeywordCxt}});var f=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return f.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return f.CodeGen}});var p=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var m=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return m.default}})})),q_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vg(),n=e_(),r=__(),i=A_(),a=P_(),o=L_(),s=y_(),c=b_();e.default=[i.default,t.default,n.default,(0,r.default)(!0),s.default,c.metadataVocabulary,c.contentVocabulary,a.default,o.default]})),J_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}}})),Y_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}}})),X_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}}})),Z_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}})),Q_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}}})),$_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),ev=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),tv=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),nv=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J_(),n=Y_(),r=X_(),i=Z_(),a=Q_(),o=$_(),s=ev(),c=tv(),l=[`/properties`];function u(e){return[t,n,r,i,a,u(this,o),s,u(this,c)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function u(t,n){return e?t.$dataMetaSchema(n,l):n}}e.default=u})),rv=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let n=Rg(),r=q_(),i=C_(),a=nv(),o=`https://json-schema.org/draft/2020-12/schema`;var s=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(a.default.call(this,e),this.refs[`http://json-schema.org/schema`]=o)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o)?o:void 0)}};e.Ajv2020=s,t.exports=e=s,t.exports.Ajv2020=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s;var c=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var u=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})),iv=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"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:E,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:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\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,m),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},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[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 _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),av=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=T_(),n=Q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),ov=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=iv(),r=av(),i=Q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),sv=T_(),cv=K_(),lv=rv(),uv=pf(ov(),1).default;function dv(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return uv(t),t}var fv=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=dv(lv.Ajv2020)}_engineFor(e){if(this._userAjv)return this.ajv;let t=yf(e,`pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`);return t===`2020-12`?this.ajv:t===`2019-09`?this._ajv2019??=dv(cv.Ajv2019):this._ajvDraft7??=dv(sv.Ajv)}getValidator(e){let t=this._engineFor(e),n=`$id`in e&&typeof e.$id==`string`?t.getSchema(e.$id)??t.compile(e):t.compile(e);return e=>n(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(n.errors)}}};sv.Ajv;var pv=Symbol.for(`mcp.completable`);function mv(e){return!!e&&typeof e==`object`&&pv in e}function hv(e){return e[pv]?.complete}var gv=2**31-1;function _v(e,t){if(!Number.isFinite(e)||e<1)return;let n=setInterval(t,Math.min(e,gv));return n.unref?.(),n}var vv=class{_listeners=new Set;constructor(e){this.onerror=e}publish(e){for(let t of this._listeners)try{t(e)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}subscribe(e){this._listeners.add(e);let t=!0;return()=>{t&&(t=!1,this._listeners.delete(e))}}get listenerCount(){return this._listeners.size}};function yv(e){return{toolsChanged:()=>e.publish({kind:`tools_list_changed`}),promptsChanged:()=>e.publish({kind:`prompts_list_changed`}),resourcesChanged:()=>e.publish({kind:`resources_list_changed`}),resourceUpdated:t=>e.publish({kind:`resource_updated`,uri:t})}}function bv(e,t){switch(t.kind){case`tools_list_changed`:return e.toolsListChanged===!0;case`prompts_list_changed`:return e.promptsListChanged===!0;case`resources_list_changed`:return e.resourcesListChanged===!0;case`resource_updated`:return e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.includes(t.uri)}}function xv(e,t){let n={},r=e=>t===void 0||e===!0;return e.toolsListChanged===!0&&r(t?.tools?.listChanged)&&(n.toolsListChanged=!0),e.promptsListChanged===!0&&r(t?.prompts?.listChanged)&&(n.promptsListChanged=!0),e.resourcesListChanged===!0&&r(t?.resources?.listChanged)&&(n.resourcesListChanged=!0),e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.length>0&&r(t?.resources?.subscribe)&&(n.resourceSubscriptions=[...e.resourceSubscriptions]),n}function Sv(e){switch(e.kind){case`tools_list_changed`:return{method:`notifications/tools/list_changed`};case`prompts_list_changed`:return{method:`notifications/prompts/list_changed`};case`resources_list_changed`:return{method:`notifications/resources/list_changed`};case`resource_updated`:return{method:`notifications/resources/updated`,params:{uri:e.uri}}}}function Cv(e,t,n){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n},id:e},{status:200})}function wv(e,t){return{method:e.method,params:{...e.params,_meta:{...e.params?._meta,[Mt]:t}}}}function Tv(e){let t=im(rm).validateRequest(`subscriptions/listen`,e);return t.ok?t.value.params?.notifications:void 0}function Ev(e){let{bus:t,onerror:n}=e,r=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,a=new Set;function o(e,o,s,c){if(a.size>=r)return n?.(Error(`subscriptions/listen refused: subscription limit reached (${r})`)),Cv(e.id,-32603,`Subscription limit reached`);let l=Tv(e);if(l===void 0)return Cv(e.id,-32602,`Invalid params: 'notifications' is required and must be a valid SubscriptionFilter`);let u=xv(l,s),d=e.id,f=new TextEncoder,p,m=!1,h,g,_,v=e=>{if(!m)try{p.enqueue(f.encode(e))}catch(e){n?.(e instanceof Error?e:Error(String(e)))}},y=(e,t)=>{v(`event: message\ndata: ${JSON.stringify({jsonrpc:`2.0`,method:e,params:t})}\n\n`)},b=e=>{if(!m){e&&v(`event: message\ndata: ${JSON.stringify({jsonrpc:`2.0`,id:d,result:{resultType:`complete`,_meta:{[Mt]:d,[St]:c}}})}\n\n`),m=!0;try{h?.()}catch(e){n?.(e instanceof Error?e:Error(String(e)))}g!==void 0&&clearInterval(g),_?.(),a.delete(b);try{p.close()}catch{}}},x=new ReadableStream({start(e){p=e;let n=wv({method:`notifications/subscriptions/acknowledged`,params:{notifications:u}},d);if(y(n.method,n.params),Object.keys(u).length===0){b(!0);return}h=t.subscribe(e=>{if(m||!bv(u,e))return;let t=wv(Sv(e),d);y(t.method,t.params)}),g=_v(i,()=>v(`: keepalive
68
+ deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),s_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),c_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=Q(),r=gg(),i=$();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),l_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kg(),n=Cg(),r=$(),i=c_();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),u_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cg(),n=Q(),r=$(),i=$();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),d_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),f_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Cg().validateUnion,error:{message:`must match a schema in anyOf`}}})),p_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),m_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),h_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),g_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),__=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=t_(),n=r_(),r=n_(),i=i_(),a=a_(),o=o_(),s=s_(),c=c_(),l=l_(),u=u_(),d=d_(),f=f_(),p=p_(),m=m_(),h=h_(),g=g_();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),v_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),y_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[v_().default]})),b_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),x_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vg(),n=e_(),r=__(),i=y_(),a=b_();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),S_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),C_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=S_(),r=Mg(),i=jg(),a=$();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),w_=q(((e,t)=>{t.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}})),T_=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Rg(),r=x_(),i=C_(),a=w_(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),E_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=Q(),n=gg(),r=Mg(),i=Bg(),a={keyword:`$dynamicAnchor`,schemaType:`string`,code:e=>o(e,e.schema)};function o(e,r){let{gen:i,it:a}=e;a.schemaEnv.root.dynamicAnchors[r]=!0;let o=(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(r)}`,c=a.errSchemaPath===`#`?a.validateName:s(e);i.if((0,t._)`!${o}`,()=>i.assign(o,c))}e.dynamicAnchor=o;function s(e){let{schemaEnv:t,schema:n,self:a}=e.it,{root:o,baseId:s,localRefs:c,meta:l}=t.root,{schemaId:u}=a.opts,d=new r.SchemaEnv({schema:n,schemaId:u,root:o,baseId:s,localRefs:c,meta:l});return r.compileSchema.call(a,d),(0,i.getValidate)(e,d)}e.default=a})),D_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=Q(),n=gg(),r=Bg(),i={keyword:`$dynamicRef`,schemaType:`string`,code:e=>a(e,e.schema)};function a(e,i){let{gen:a,keyword:o,it:s}=e;if(i[0]!==`#`)throw Error(`"${o}" only supports hash fragment reference`);let c=i.slice(1);if(s.allErrors)l();else{let t=a.let(`valid`,!1);l(t),e.ok(t)}function l(e){if(s.schemaEnv.root.dynamicAnchors[c]){let r=a.let(`_v`,(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(c)}`);a.if(r,u(r,e),u(s.validateName,e))}else u(s.validateName,e)()}function u(t,n){return n?()=>a.block(()=>{(0,r.callRef)(e,t),a.let(n,!0)}):()=>(0,r.callRef)(e,t)}}e.dynamicRef=a,e.default=i})),O_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=E_(),n=$();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),k_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=D_();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),A_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=E_(),n=D_(),r=O_(),i=k_();e.default=[t.default,n.default,r.default,i.default]})),j_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=o_();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),M_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=o_();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),N_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$();e.default={keyword:[`maxContains`,`minContains`],type:`array`,schemaType:`number`,code({keyword:e,parentSchema:n,it:r}){n.contains===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}}})),P_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=j_(),n=M_(),r=N_();e.default=[t.default,n.default,r.default]})),F_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$(),r=gg();e.default={keyword:`unevaluatedProperties`,type:`object`,schemaType:[`boolean`,`object`],trackErrors:!0,error:{message:`must NOT have unevaluated properties`,params:({params:e})=>(0,t._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){let{gen:i,schema:a,data:o,errsCount:s,it:c}=e;if(!s)throw Error(`ajv implementation error`);let{allErrors:l,props:u}=c;u instanceof t.Name?i.if((0,t._)`${u} !== true`,()=>i.forIn(`key`,o,e=>i.if(f(u,e),()=>d(e)))):u!==!0&&i.forIn(`key`,o,e=>u===void 0?d(e):i.if(p(u,e),()=>d(e))),c.props=!0,e.ok((0,t._)`${s} === ${r.default.errors}`);function d(r){if(a===!1){e.setParams({unevaluatedProperty:r}),e.error(),l||i.break();return}if(!(0,n.alwaysValidSchema)(c,a)){let a=i.name(`valid`);e.subschema({keyword:`unevaluatedProperties`,dataProp:r,dataPropType:n.Type.Str},a),l||i.if((0,t.not)(a),()=>i.break())}}function f(e,n){return(0,t._)`!${e} || !${e}[${n}]`}function p(e,n){let r=[];for(let i in e)e[i]===!0&&r.push((0,t._)`${n} !== ${i}`);return(0,t.and)(...r)}}}})),I_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q(),n=$();e.default={keyword:`unevaluatedItems`,type:`array`,schemaType:[`boolean`,`object`],error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e,s=o.items||0;if(s===!0)return;let c=r.const(`len`,(0,t._)`${a}.length`);if(i===!1)e.setParams({len:s}),e.fail((0,t._)`${c} > ${s}`);else if(typeof i==`object`&&!(0,n.alwaysValidSchema)(o,i)){let n=r.var(`valid`,(0,t._)`${c} <= ${s}`);r.if((0,t.not)(n),()=>l(n,s)),e.ok(n)}o.items=!0;function l(i,a){r.forRange(`i`,a,c,a=>{e.subschema({keyword:`unevaluatedItems`,dataProp:a,dataPropType:n.Type.Num},i),o.allErrors||r.if((0,t.not)(i),()=>r.break())})}}}})),L_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=F_(),n=I_();e.default=[t.default,n.default]})),R_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/schema`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format`},{$ref:`meta/content`}],type:[`object`,`boolean`],properties:{definitions:{$comment:`While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.`,type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},dependencies:{$comment:`"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"`,type:`object`,additionalProperties:{anyOf:[{$recursiveRef:`#`},{$ref:`meta/validation#/$defs/stringArray`}]}}}}})),z_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{additionalItems:{$recursiveRef:`#`},unevaluatedItems:{$recursiveRef:`#`},items:{anyOf:[{$recursiveRef:`#`},{$ref:`#/$defs/schemaArray`}]},contains:{$recursiveRef:`#`},additionalProperties:{$recursiveRef:`#`},unevaluatedProperties:{$recursiveRef:`#`},properties:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$recursiveRef:`#`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$recursiveRef:`#`}},propertyNames:{$recursiveRef:`#`},if:{$recursiveRef:`#`},then:{$recursiveRef:`#`},else:{$recursiveRef:`#`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$recursiveRef:`#`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$recursiveRef:`#`}}}}})),B_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/content`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentMediaType:{type:`string`},contentEncoding:{type:`string`},contentSchema:{$recursiveRef:`#`}}}})),V_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/core`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{type:`string`,format:`uri`},$anchor:{type:`string`,pattern:`^[A-Za-z][-A-Za-z0-9.:_]*$`},$ref:{type:`string`,format:`uri-reference`},$recursiveRef:{type:`string`,format:`uri-reference`},$recursiveAnchor:{type:`boolean`,default:!1},$vocabulary:{type:`object`,propertyNames:{type:`string`,format:`uri`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}}}}})),H_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/format`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:`Format vocabulary meta-schema`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),U_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),W_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),G_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R_(),n=z_(),r=B_(),i=V_(),a=H_(),o=U_(),s=W_(),c=[`/properties`];function l(e){return[t,n,r,i,l(this,a),o,l(this,s)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function l(t,n){return e?t.$dataMetaSchema(n,c):n}}e.default=l})),K_=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2019=void 0;let n=Rg(),r=x_(),i=A_(),a=P_(),o=L_(),s=C_(),c=G_(),l=`https://json-schema.org/draft/2019-09/schema`;var u=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(i.default),r.default.forEach(e=>this.addVocabulary(e)),this.addVocabulary(a.default),this.addVocabulary(o.default),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(c.default.call(this,e),this.refs[`http://json-schema.org/schema`]=l)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}};e.Ajv2019=u,t.exports=e=u,t.exports.Ajv2019=u,Object.defineProperty(e,"__esModule",{value:!0}),e.default=u;var d=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return d.KeywordCxt}});var f=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return f._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return f.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return f.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return f.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return f.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return f.CodeGen}});var p=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var m=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return m.default}})})),q_=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vg(),n=e_(),r=__(),i=A_(),a=P_(),o=L_(),s=y_(),c=b_();e.default=[i.default,t.default,n.default,(0,r.default)(!0),s.default,c.metadataVocabulary,c.contentVocabulary,a.default,o.default]})),J_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}}})),Y_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}}})),X_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}}})),Z_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}})),Q_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}}})),$_=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),ev=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),tv=q(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),nv=q((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J_(),n=Y_(),r=X_(),i=Z_(),a=Q_(),o=$_(),s=ev(),c=tv(),l=[`/properties`];function u(e){return[t,n,r,i,a,u(this,o),s,u(this,c)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function u(t,n){return e?t.$dataMetaSchema(n,l):n}}e.default=u})),rv=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let n=Rg(),r=q_(),i=C_(),a=nv(),o=`https://json-schema.org/draft/2020-12/schema`;var s=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(a.default.call(this,e),this.refs[`http://json-schema.org/schema`]=o)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o)?o:void 0)}};e.Ajv2020=s,t.exports=e=s,t.exports.Ajv2020=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s;var c=kg();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=Q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var u=Ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=jg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})),iv=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"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:E,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:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\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,m),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},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[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 _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),av=q((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=T_(),n=Q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),ov=q(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=iv(),r=av(),i=Q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),sv=T_(),cv=K_(),lv=rv(),uv=pf(ov(),1).default;function dv(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return uv(t),t}var fv=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=dv(lv.Ajv2020)}_engineFor(e){if(this._userAjv)return this.ajv;let t=yf(e,`pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`);return t===`2020-12`?this.ajv:t===`2019-09`?this._ajv2019??=dv(cv.Ajv2019):this._ajvDraft7??=dv(sv.Ajv)}getValidator(e){let t=this._engineFor(e),n=`$id`in e&&typeof e.$id==`string`?t.getSchema(e.$id)??t.compile(e):t.compile(e);return e=>n(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(n.errors)}}};sv.Ajv;var pv=Symbol.for(`mcp.completable`);function mv(e){return!!e&&typeof e==`object`&&pv in e}function hv(e){return e[pv]?.complete}var gv=2**31-1;function _v(e,t){if(!Number.isFinite(e)||e<1)return;let n=setInterval(t,Math.min(e,gv));return n.unref?.(),n}var vv=class{_listeners=new Set;constructor(e){this.onerror=e}publish(e){for(let t of this._listeners)try{t(e)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}subscribe(e){this._listeners.add(e);let t=!0;return()=>{t&&(t=!1,this._listeners.delete(e))}}get listenerCount(){return this._listeners.size}};function yv(e){return{toolsChanged:()=>e.publish({kind:`tools_list_changed`}),promptsChanged:()=>e.publish({kind:`prompts_list_changed`}),resourcesChanged:()=>e.publish({kind:`resources_list_changed`}),resourceUpdated:t=>e.publish({kind:`resource_updated`,uri:t})}}function bv(e,t){switch(t.kind){case`tools_list_changed`:return e.toolsListChanged===!0;case`prompts_list_changed`:return e.promptsListChanged===!0;case`resources_list_changed`:return e.resourcesListChanged===!0;case`resource_updated`:return e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.includes(t.uri)}}function xv(e,t){let n={},r=e=>t===void 0||e===!0;return e.toolsListChanged===!0&&r(t?.tools?.listChanged)&&(n.toolsListChanged=!0),e.promptsListChanged===!0&&r(t?.prompts?.listChanged)&&(n.promptsListChanged=!0),e.resourcesListChanged===!0&&r(t?.resources?.listChanged)&&(n.resourcesListChanged=!0),e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.length>0&&r(t?.resources?.subscribe)&&(n.resourceSubscriptions=[...e.resourceSubscriptions]),n}function Sv(e){switch(e.kind){case`tools_list_changed`:return{method:`notifications/tools/list_changed`};case`prompts_list_changed`:return{method:`notifications/prompts/list_changed`};case`resources_list_changed`:return{method:`notifications/resources/list_changed`};case`resource_updated`:return{method:`notifications/resources/updated`,params:{uri:e.uri}}}}function Cv(e,t,n){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n},id:e},{status:200})}function wv(e,t){return{method:e.method,params:{...e.params,_meta:{...e.params?._meta,[Nt]:t}}}}function Tv(e){let t=im(rm).validateRequest(`subscriptions/listen`,e);return t.ok?t.value.params?.notifications:void 0}function Ev(e){let{bus:t,onerror:n}=e,r=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,a=new Set;function o(e,o,s,c){if(a.size>=r)return n?.(Error(`subscriptions/listen refused: subscription limit reached (${r})`)),Cv(e.id,-32603,`Subscription limit reached`);let l=Tv(e);if(l===void 0)return Cv(e.id,-32602,`Invalid params: 'notifications' is required and must be a valid SubscriptionFilter`);let u=xv(l,s),d=e.id,f=new TextEncoder,p,m=!1,h,g,_,v=e=>{if(!m)try{p.enqueue(f.encode(e))}catch(e){n?.(e instanceof Error?e:Error(String(e)))}},y=(e,t)=>{v(`event: message\ndata: ${JSON.stringify({jsonrpc:`2.0`,method:e,params:t})}\n\n`)},b=e=>{if(!m){e&&v(`event: message\ndata: ${JSON.stringify({jsonrpc:`2.0`,id:d,result:{resultType:`complete`,_meta:{[Nt]:d,[xt]:c}}})}\n\n`),m=!0;try{h?.()}catch(e){n?.(e instanceof Error?e:Error(String(e)))}g!==void 0&&clearInterval(g),_?.(),a.delete(b);try{p.close()}catch{}}},x=new ReadableStream({start(e){p=e;let n=wv({method:`notifications/subscriptions/acknowledged`,params:{notifications:u}},d);if(y(n.method,n.params),Object.keys(u).length===0){b(!0);return}h=t.subscribe(e=>{if(m||!bv(u,e))return;let t=wv(Sv(e),d);y(t.method,t.params)}),g=_v(i,()=>v(`: keepalive
69
69
 
70
- `)),a.add(b)},cancel(){b(!1)}});if(o!==void 0){if(o.aborted)b(!1);else{let e=()=>b(!1);o.addEventListener(`abort`,e,{once:!0}),_=()=>o.removeEventListener(`abort`,e)}}return new Response(x,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}})}return{serve:o,closeAll(){for(let e of a)e(!0)},get openCount(){return a.size}}}function Dv(e){return e.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g,` `)}function Ov(e,t,n,r){let i=`Bearer error="${Dv(e)}", error_description="${Dv(t)}"`;return n.length>0&&(i+=`, scope="${Dv(n.join(` `))}"`),r&&(i+=`, resource_metadata="${Dv(r)}"`),i}function kv(e,t){let{requiredScopes:n=[],resourceMetadataUrl:r}=t??{};if(!(e instanceof wf)){let e=new wf(Cf.ServerError,`Internal Server Error`);return Response.json(e.toResponseObject(),{status:500})}switch(e.code){case Cf.InvalidToken:{let t=Ov(e.code,e.message,n,r);return Response.json(e.toResponseObject(),{status:401,headers:{"WWW-Authenticate":t}})}case Cf.InsufficientScope:{let t=Ov(e.code,e.message,n,r);return Response.json(e.toResponseObject(),{status:403,headers:{"WWW-Authenticate":t}})}case Cf.ServerError:return Response.json(e.toResponseObject(),{status:500});default:return Response.json(e.toResponseObject(),{status:400})}}function Av(e){let t=new URL(e);return t.pathname=jv(e),t.hash=``,t.href}function jv(e){let t=Mv(e.pathname);return`/.well-known/oauth-protected-resource${t===`/`?``:t}`}function Mv(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}function Nv(e){return typeof e==`object`&&!!e&&`setScopeChallengeResolver`in e&&typeof e.setScopeChallengeResolver==`function`}function Pv(e,t){if(typeof e!=`string`||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e))throw TypeError(`${t} must satisfy the OAuth scope-token grammar`)}function Fv(e){if(typeof e!=`object`||!e||!Array.isArray(e.scopes)||e.scopes.length===0)throw TypeError(`scope challenge must contain at least one scope`);for(let[t,n]of e.scopes.entries())Pv(n,`scope challenge scopes[${t}]`);if(e.errorDescription!==void 0&&typeof e.errorDescription!=`string`)throw TypeError(`scope challenge errorDescription must be a string`);if(e.errorDescription!==void 0&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e.errorDescription))throw TypeError(`scope challenge errorDescription must satisfy the RFC 6750 error-description grammar`);return e}async function Iv(e,t,n){for(let r of e){let e=await n({request:r,...t!==void 0&&{authInfo:t}});if(e!==void 0)return Fv(e)}}function Lv(e){if(e?.resourceMetadataUrl!==void 0)return e.resourceMetadataUrl;if(e?.resource?.protocol===`https:`||e?.resource?.protocol===`http:`)return Av(e.resource)}function Rv(e,t){return kv(new wf(Cf.InsufficientScope,e.errorDescription??`Insufficient scope`),{requiredScopes:[...e.scopes],resourceMetadataUrl:t})}var zv=8,Bv=6e5;function Vv(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??zv,roundTimeoutMs:e?.roundTimeoutMs??Bv,legacyShim:e?.legacyShim??!0}}function Hv(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Z(X.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=kf(r);if(i===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function Uv(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Wv(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Z(X.InternalError,t)}var Gv=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return Wv(e,Nh(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=Hv(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(Af(o,t)!==void 0)return Wv(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Fh(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return Wv(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Ph(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:Kh(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=Jh(p,t))}let m=await t(n,p);if(!bm(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:Uv()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}},Kv=new Set([`tools/call`,`prompts/get`,`resources/read`]),qv,Jv,Yv;function Xv(e,t){qv(e,t)}function Zv(e,t){Jv(e,t)}function Qv(e){return Yv(e)}var $v=class extends Zh{_clientCapabilities;_clientVersion;static{qv=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},Jv=(e,t)=>{let n=t.filter(t=>!e._supportedProtocolVersions.includes(t));n.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...n]),e.setRequestHandler(`server/discover`,()=>e._ondiscover())},Yv=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new Gv({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new fv,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=Vv(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&bp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Ff(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(e){if(this.transport!==void 0)throw new Y(J.AlreadyConnected,`Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.`);await super.connect(e)}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=ah(Yt,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[Ci],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Yt.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new Y(J.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=$h(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=Kv.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(bm(i))throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(bm(o)){if(!r)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:gp(o,n)}}return async(e,n)=>{let r=im(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(bm(a))return a;let o=Rf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Z(s.reason===`not-in-era`?X.InternalError:X.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Nf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Z(X.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=Jh(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Z&&e.code===X.UrlElicitationRequired&&i?new Z(X.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!bm(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=Hv(e,n,r),o=Af(a,t);if(o!==void 0)throw new wp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Z(X.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[wr]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new Y(J.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new Y(J.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new Y(J.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new Y(J.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new Y(J.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new Y(J.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new Y(J.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new Y(J.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new Y(J.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=Pf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ff(this._supportedProtocolVersions),capabilities:ey(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Y(J.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Z(X.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Z(X.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Z(X.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new Y(J.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new Y(J.CapabilityNotSupported,`Client does not support form elicitation.`)}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Z(X.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Z?e:new Z(X.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function ey(e){return{...e}}function ty(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function ny(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var ry=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(t!==void 0&&t.enabled){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return ay;try{let n=uh(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new $v(e,t),this._maxToolInputElements=ny(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return Nv(e)&&e.setScopeChallengeResolver(e=>this.resolveScopeChallenge(e)),await this.server.connect(e)}async close(){await this.server.close()}resolveScopeChallenge=e=>{switch(e.request.method){case`tools/call`:{let t=e.request.params?.name;if(typeof t!=`string`)return;let n=this._registeredTools[t];return n===void 0||!n.enabled?void 0:n.scopeChallenge?.(e)}case`resources/read`:{let t=e.request.params?.uri;if(typeof t!=`string`)return;let n;try{n=new URL(t)}catch{return}let r=this._registeredResources[n.toString()];if(r!==void 0)return r.enabled?r.scopeChallenge?.(e):void 0;for(let t of Object.values(this._registeredResourceTemplates))if(t.resourceTemplate.uriTemplate.match(n.toString()))return t.enabled?t.scopeChallenge?.(e):void 0;return}case`prompts/get`:{let t=e.request.params?.name;if(typeof t!=`string`)return;let n=this._registeredPrompts[t];return n===void 0||!n.enabled?void 0:n.scopeChallenge?.(e)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?oy(e,t.inputSchema):ay,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=uh(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Z(X.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),bm(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Z&&e.code===X.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&ty(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Z(X.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await ph(e.inputSchema,t??{});if(!r.success)throw new Z(X.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||bm(t)||t.isError)return;if(t.structuredContent===void 0)throw new Z(X.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await ph(e.outputSchema,t.structuredContent);if(!r.success)throw new Z(X.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Sm(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Cm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(X.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Z(X.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return uy;let r=py(dy(n.argsSchema)?.[e.params.argument.name]);if(!mv(r))return uy;let i=hv(r);return i?ly(await i(e.params.argument.value,e.params.context)):uy}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return uy;throw new Z(X.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?ly(await r(e.params.argument.value,e.params.context)):uy}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Z(X.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Z(X.InvalidParams,`Resource ${n} disabled`);return gp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r){if(!e.enabled)throw new Z(X.InvalidParams,`Resource template ${e.resourceTemplate.uriTemplate} disabled`);return gp(await e.readCallback(n,r,t),e.cacheHint)}}throw new xp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?yh(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(X.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let{cacheHint:i,scopeChallenge:a,...o}=n,s=o;if(i!==void 0&&bp(i,`resource ${e}`),typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,s,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,s,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i,a){let o={name:e,title:t,metadata:r,readCallback:a,scopeChallenge:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=o)),e.name!==void 0&&(o.name=e.name),e.title!==void 0&&(o.title=e.title),e.metadata!==void 0&&(o.metadata=e.metadata),e.callback!==void 0&&(o.readCallback=e.callback),e.scopeChallenge!==void 0&&(o.scopeChallenge=e.scopeChallenge===null?void 0:e.scopeChallenge),e.enabled!==void 0&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,t,n,r,i,a){let o={resourceTemplate:n,title:t,metadata:r,readCallback:a,scopeChallenge:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=o)),t.title!==void 0&&(o.title=t.title),t.template!==void 0&&(o.resourceTemplate=t.template),t.metadata!==void 0&&(o.metadata=t.metadata),t.callback!==void 0&&(o.readCallback=t.callback),t.scopeChallenge!==void 0&&(o.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t.enabled!==void 0&&(o.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,n,r,i,a,o,s){let c=r,l=i,u={title:t,description:n,argsSchema:r,icons:a,scopeChallenge:o,_meta:s,handler:cy(e,r,i),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description),t.icons!==void 0&&(u.icons=t.icons),t.scopeChallenge!==void 0&&(u.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t._meta!==void 0&&(u._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(u.argsSchema=t.argsSchema,c=t.argsSchema,n=!0),t.callback!==void 0&&(l=t.callback,n=!0),n&&(u.handler=cy(e,c,l)),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,r){let e=dy(r);e&&Object.values(e).some(e=>mv(py(e)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l,u){lg(e);let d=u,f,p={title:t,description:n,inputSchema:r,outputSchema:i,get outputSchemaJson(){return f??=sy(p.outputSchema)},set outputSchemaJson(e){f=e},annotations:a,icons:o,execution:s,scopeChallenge:c,_meta:l,handler:u,executor:iy(r,u),enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&lg(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=p,e=t.name)),t.title!==void 0&&(p.title=t.title),t.description!==void 0&&(p.description=t.description);let n=!1;t.paramsSchema!==void 0&&(p.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(p.handler=t.callback,d=t.callback,n=!0),n&&(p.executor=iy(p.inputSchema,d)),t.outputSchema!==void 0&&(p.outputSchema=t.outputSchema,p.outputSchemaJson=sy(t.outputSchema)),t.annotations!==void 0&&(p.annotations=t.annotations),t.icons!==void 0&&(p.icons=t.icons),t.scopeChallenge!==void 0&&(p.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t._meta!==void 0&&(p._meta=t._meta),t.enabled!==void 0&&(p.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,scopeChallenge:l,_meta:u}=t;return this._createRegisteredTool(e,r,i,pg(a),pg(o),s,c,void 0,l,u,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,scopeChallenge:s,_meta:c}=t,l=this._createRegisteredPrompt(e,r,i,pg(a),n,o,s,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),l}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function iy(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}var ay={type:`object`,properties:{}};function oy(e,t){let n=uh(t,`input`),r=Om(n);return r.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${r.reason}`),n}function sy(e){if(e!==void 0)try{return uh(e,`output`)}catch{return}}function cy(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await ph(t,n??{});if(!a.success)throw new Z(X.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function ly(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}var uy={completion:{values:[],hasMore:!1}};function dy(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function fy(e){return e?.type===`optional`}function py(e){return fy(e)?e.def?.innerType??e:e}var my=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(e){this._classification=e.classification,this._responseMode=e.responseMode??`auto`,this._keepAliveMs=e.keepAliveMs??15e3}async start(){if(this._started)throw Error(`PerRequestHTTPServerTransport is already started`);this._started=!0}async handleMessage(e,t){if(this._used)throw Error(`PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request`);if(!this._started||this.onmessage===void 0)throw Error(`PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message`);if(this._closed)throw Error(`PerRequestHTTPServerTransport is closed`);this._used=!0;let n=t?.request?.signal;if(n?.aborted)throw await this.close(),new Y(J.ConnectionClosed,`The request was aborted before it could be handled`);let r={classification:this._classification,...t?.request!==void 0&&{request:t.request},...t?.authInfo!==void 0&&{authInfo:t.authInfo}};if(gm(e)){this._requestId=e.id;let t,i,a=new Promise((e,n)=>{t=e,i=n});if(this._deferredResponse={promise:a,resolve:t,reject:i,settled:!1},n!==void 0){let e=()=>void this.close();n.addEventListener(`abort`,e,{once:!0}),this._abortCleanup=()=>n.removeEventListener(`abort`,e)}this._dispatchWindowOpen=!0;try{this.onmessage(e,r)}finally{this._dispatchWindowOpen=!1}return this._responseMode===`sse`&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),a}return this.onmessage(e,r),new Response(null,{status:202})}async send(e,t){if(this._closed)return;let n=vm(e)||ym(e),r=n?e.id:t?.relatedRequestId;if(this._requestId===void 0||r===void 0||r!==this._requestId){n&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(e.id)}`));return}if(n){if(this._terminalDelivered)return;this._terminalDelivered=!0;let t=ym(e)?e.error.code:void 0,n=t!==void 0&&(this._dispatchWindowOpen||t===X.MissingRequiredClientCapability)?Um[t]:void 0;if(n!==void 0&&this._sse===void 0){this.settleResponse(Response.json(e,{status:n,headers:{"Content-Type":`application/json`}})),queueMicrotask(()=>void this.close());return}if(this._sse!==void 0||this._responseMode===`sse`){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e),this.finalizeStream();return}this.settleResponse(Response.json(e,{status:200,headers:{"Content-Type":`application/json`}})),queueMicrotask(()=>void this.close());return}this._responseMode!==`json`&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e))}writeCommentFrame(e){if(this._closed||this._sse===void 0||this._sse.closed)return;let t=e.split(`
70
+ `)),a.add(b)},cancel(){b(!1)}});if(o!==void 0){if(o.aborted)b(!1);else{let e=()=>b(!1);o.addEventListener(`abort`,e,{once:!0}),_=()=>o.removeEventListener(`abort`,e)}}return new Response(x,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}})}return{serve:o,closeAll(){for(let e of a)e(!0)},get openCount(){return a.size}}}function Dv(e){return e.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g,` `)}function Ov(e,t,n,r){let i=`Bearer error="${Dv(e)}", error_description="${Dv(t)}"`;return n.length>0&&(i+=`, scope="${Dv(n.join(` `))}"`),r&&(i+=`, resource_metadata="${Dv(r)}"`),i}function kv(e,t){let{requiredScopes:n=[],resourceMetadataUrl:r}=t??{};if(!(e instanceof wf)){let e=new wf(Cf.ServerError,`Internal Server Error`);return Response.json(e.toResponseObject(),{status:500})}switch(e.code){case Cf.InvalidToken:{let t=Ov(e.code,e.message,n,r);return Response.json(e.toResponseObject(),{status:401,headers:{"WWW-Authenticate":t}})}case Cf.InsufficientScope:{let t=Ov(e.code,e.message,n,r);return Response.json(e.toResponseObject(),{status:403,headers:{"WWW-Authenticate":t}})}case Cf.ServerError:return Response.json(e.toResponseObject(),{status:500});default:return Response.json(e.toResponseObject(),{status:400})}}function Av(e){let t=new URL(e);return t.pathname=jv(e),t.hash=``,t.href}function jv(e){let t=Mv(e.pathname);return`/.well-known/oauth-protected-resource${t===`/`?``:t}`}function Mv(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}function Nv(e){return typeof e==`object`&&!!e&&`setScopeChallengeResolver`in e&&typeof e.setScopeChallengeResolver==`function`}function Pv(e,t){if(typeof e!=`string`||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e))throw TypeError(`${t} must satisfy the OAuth scope-token grammar`)}function Fv(e){if(typeof e!=`object`||!e||!Array.isArray(e.scopes)||e.scopes.length===0)throw TypeError(`scope challenge must contain at least one scope`);for(let[t,n]of e.scopes.entries())Pv(n,`scope challenge scopes[${t}]`);if(e.errorDescription!==void 0&&typeof e.errorDescription!=`string`)throw TypeError(`scope challenge errorDescription must be a string`);if(e.errorDescription!==void 0&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e.errorDescription))throw TypeError(`scope challenge errorDescription must satisfy the RFC 6750 error-description grammar`);return e}async function Iv(e,t,n){for(let r of e){let e=await n({request:r,...t!==void 0&&{authInfo:t}});if(e!==void 0)return Fv(e)}}function Lv(e){if(e?.resourceMetadataUrl!==void 0)return e.resourceMetadataUrl;if(e?.resource?.protocol===`https:`||e?.resource?.protocol===`http:`)return Av(e.resource)}function Rv(e,t){return kv(new wf(Cf.InsufficientScope,e.errorDescription??`Insufficient scope`),{requiredScopes:[...e.scopes],resourceMetadataUrl:t})}var zv=8,Bv=6e5;function Vv(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??zv,roundTimeoutMs:e?.roundTimeoutMs??Bv,legacyShim:e?.legacyShim??!0}}function Hv(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Z(X.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=kf(r);if(i===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function Uv(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Wv(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Z(X.InternalError,t)}var Gv=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return Wv(e,Nh(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=Hv(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Z(X.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(Af(o,t)!==void 0)return Wv(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Fh(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return Wv(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Ph(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:Kh(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=Jh(p,t))}let m=await t(n,p);if(!bm(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:Uv()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}},Kv=new Set([`tools/call`,`prompts/get`,`resources/read`]),qv,Jv,Yv;function Xv(e,t){qv(e,t)}function Zv(e,t){Jv(e,t)}function Qv(e){return Yv(e)}var $v=class extends Zh{_clientCapabilities;_clientVersion;static{qv=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},Jv=(e,t)=>{let n=t.filter(t=>!e._supportedProtocolVersions.includes(t));n.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...n]),e.setRequestHandler(`server/discover`,()=>e._ondiscover())},Yv=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new Gv({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new fv,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=Vv(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&bp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Ff(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(e){if(this.transport!==void 0)throw new Y(J.AlreadyConnected,`Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.`);await super.connect(e)}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=ah(Xt,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[wi],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Xt.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new Y(J.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=$h(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=Kv.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(bm(i))throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(bm(o)){if(!r)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:gp(o,n)}}return async(e,n)=>{let r=im(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(bm(a))return a;let o=Rf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Z(s.reason===`not-in-era`?X.InternalError:X.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Nf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Z(X.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=Jh(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Z&&e.code===X.UrlElicitationRequired&&i?new Z(X.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!bm(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Z(X.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=Hv(e,n,r),o=Af(a,t);if(o!==void 0)throw new wp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Z(X.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[wr]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new Y(J.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new Y(J.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new Y(J.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new Y(J.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new Y(J.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new Y(J.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new Y(J.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new Y(J.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new Y(J.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=Pf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ff(this._supportedProtocolVersions),capabilities:ey(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Y(J.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Z(X.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Z(X.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Z(X.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new Y(J.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new Y(J.CapabilityNotSupported,`Client does not support form elicitation.`)}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Z(X.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Z?e:new Z(X.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Y(J.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function ey(e){return{...e}}function ty(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function ny(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var ry=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(t!==void 0&&t.enabled){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return ay;try{let n=uh(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new $v(e,t),this._maxToolInputElements=ny(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return Nv(e)&&e.setScopeChallengeResolver(e=>this.resolveScopeChallenge(e)),await this.server.connect(e)}async close(){await this.server.close()}resolveScopeChallenge=e=>{switch(e.request.method){case`tools/call`:{let t=e.request.params?.name;if(typeof t!=`string`)return;let n=this._registeredTools[t];return n===void 0||!n.enabled?void 0:n.scopeChallenge?.(e)}case`resources/read`:{let t=e.request.params?.uri;if(typeof t!=`string`)return;let n;try{n=new URL(t)}catch{return}let r=this._registeredResources[n.toString()];if(r!==void 0)return r.enabled?r.scopeChallenge?.(e):void 0;for(let t of Object.values(this._registeredResourceTemplates))if(t.resourceTemplate.uriTemplate.match(n.toString()))return t.enabled?t.scopeChallenge?.(e):void 0;return}case`prompts/get`:{let t=e.request.params?.name;if(typeof t!=`string`)return;let n=this._registeredPrompts[t];return n===void 0||!n.enabled?void 0:n.scopeChallenge?.(e)}default:return}};_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?oy(e,t.inputSchema):ay,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=uh(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Z(X.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),bm(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Z&&e.code===X.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&ty(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Z(X.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await ph(e.inputSchema,t??{});if(!r.success)throw new Z(X.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||bm(t)||t.isError)return;if(t.structuredContent===void 0)throw new Z(X.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await ph(e.outputSchema,t.structuredContent);if(!r.success)throw new Z(X.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Sm(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Cm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(X.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Z(X.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return uy;let r=py(dy(n.argsSchema)?.[e.params.argument.name]);if(!mv(r))return uy;let i=hv(r);return i?ly(await i(e.params.argument.value,e.params.context)):uy}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return uy;throw new Z(X.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?ly(await r(e.params.argument.value,e.params.context)):uy}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Z(X.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Z(X.InvalidParams,`Resource ${n} disabled`);return gp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r){if(!e.enabled)throw new Z(X.InvalidParams,`Resource template ${e.resourceTemplate.uriTemplate} disabled`);return gp(await e.readCallback(n,r,t),e.cacheHint)}}throw new xp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?yh(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(X.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(X.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let{cacheHint:i,scopeChallenge:a,...o}=n,s=o;if(i!==void 0&&bp(i,`resource ${e}`),typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,s,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,s,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i,a){let o={name:e,title:t,metadata:r,readCallback:a,scopeChallenge:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=o)),e.name!==void 0&&(o.name=e.name),e.title!==void 0&&(o.title=e.title),e.metadata!==void 0&&(o.metadata=e.metadata),e.callback!==void 0&&(o.readCallback=e.callback),e.scopeChallenge!==void 0&&(o.scopeChallenge=e.scopeChallenge===null?void 0:e.scopeChallenge),e.enabled!==void 0&&(o.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,t,n,r,i,a){let o={resourceTemplate:n,title:t,metadata:r,readCallback:a,scopeChallenge:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=o)),t.title!==void 0&&(o.title=t.title),t.template!==void 0&&(o.resourceTemplate=t.template),t.metadata!==void 0&&(o.metadata=t.metadata),t.callback!==void 0&&(o.readCallback=t.callback),t.scopeChallenge!==void 0&&(o.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t.enabled!==void 0&&(o.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,n,r,i,a,o,s){let c=r,l=i,u={title:t,description:n,argsSchema:r,icons:a,scopeChallenge:o,_meta:s,handler:cy(e,r,i),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description),t.icons!==void 0&&(u.icons=t.icons),t.scopeChallenge!==void 0&&(u.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t._meta!==void 0&&(u._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(u.argsSchema=t.argsSchema,c=t.argsSchema,n=!0),t.callback!==void 0&&(l=t.callback,n=!0),n&&(u.handler=cy(e,c,l)),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,r){let e=dy(r);e&&Object.values(e).some(e=>mv(py(e)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l,u){lg(e);let d=u,f,p={title:t,description:n,inputSchema:r,outputSchema:i,get outputSchemaJson(){return f??=sy(p.outputSchema)},set outputSchemaJson(e){f=e},annotations:a,icons:o,execution:s,scopeChallenge:c,_meta:l,handler:u,executor:iy(r,u),enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&lg(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=p,e=t.name)),t.title!==void 0&&(p.title=t.title),t.description!==void 0&&(p.description=t.description);let n=!1;t.paramsSchema!==void 0&&(p.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(p.handler=t.callback,d=t.callback,n=!0),n&&(p.executor=iy(p.inputSchema,d)),t.outputSchema!==void 0&&(p.outputSchema=t.outputSchema,p.outputSchemaJson=sy(t.outputSchema)),t.annotations!==void 0&&(p.annotations=t.annotations),t.icons!==void 0&&(p.icons=t.icons),t.scopeChallenge!==void 0&&(p.scopeChallenge=t.scopeChallenge===null?void 0:t.scopeChallenge),t._meta!==void 0&&(p._meta=t._meta),t.enabled!==void 0&&(p.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,scopeChallenge:l,_meta:u}=t;return this._createRegisteredTool(e,r,i,pg(a),pg(o),s,c,void 0,l,u,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,scopeChallenge:s,_meta:c}=t,l=this._createRegisteredPrompt(e,r,i,pg(a),n,o,s,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),l}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function iy(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}var ay={type:`object`,properties:{}};function oy(e,t){let n=uh(t,`input`),r=Om(n);return r.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${r.reason}`),n}function sy(e){if(e!==void 0)try{return uh(e,`output`)}catch{return}}function cy(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await ph(t,n??{});if(!a.success)throw new Z(X.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function ly(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}var uy={completion:{values:[],hasMore:!1}};function dy(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function fy(e){return e?.type===`optional`}function py(e){return fy(e)?e.def?.innerType??e:e}var my=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(e){this._classification=e.classification,this._responseMode=e.responseMode??`auto`,this._keepAliveMs=e.keepAliveMs??15e3}async start(){if(this._started)throw Error(`PerRequestHTTPServerTransport is already started`);this._started=!0}async handleMessage(e,t){if(this._used)throw Error(`PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request`);if(!this._started||this.onmessage===void 0)throw Error(`PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message`);if(this._closed)throw Error(`PerRequestHTTPServerTransport is closed`);this._used=!0;let n=t?.request?.signal;if(n?.aborted)throw await this.close(),new Y(J.ConnectionClosed,`The request was aborted before it could be handled`);let r={classification:this._classification,...t?.request!==void 0&&{request:t.request},...t?.authInfo!==void 0&&{authInfo:t.authInfo}};if(gm(e)){this._requestId=e.id;let t,i,a=new Promise((e,n)=>{t=e,i=n});if(this._deferredResponse={promise:a,resolve:t,reject:i,settled:!1},n!==void 0){let e=()=>void this.close();n.addEventListener(`abort`,e,{once:!0}),this._abortCleanup=()=>n.removeEventListener(`abort`,e)}this._dispatchWindowOpen=!0;try{this.onmessage(e,r)}finally{this._dispatchWindowOpen=!1}return this._responseMode===`sse`&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),a}return this.onmessage(e,r),new Response(null,{status:202})}async send(e,t){if(this._closed)return;let n=vm(e)||ym(e),r=n?e.id:t?.relatedRequestId;if(this._requestId===void 0||r===void 0||r!==this._requestId){n&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(e.id)}`));return}if(n){if(this._terminalDelivered)return;this._terminalDelivered=!0;let t=ym(e)?e.error.code:void 0,n=t!==void 0&&(this._dispatchWindowOpen||t===X.MissingRequiredClientCapability)?Um[t]:void 0;if(n!==void 0&&this._sse===void 0){this.settleResponse(Response.json(e,{status:n,headers:{"Content-Type":`application/json`}})),queueMicrotask(()=>void this.close());return}if(this._sse!==void 0||this._responseMode===`sse`){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e),this.finalizeStream();return}this.settleResponse(Response.json(e,{status:200,headers:{"Content-Type":`application/json`}})),queueMicrotask(()=>void this.close());return}this._responseMode!==`json`&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e))}writeCommentFrame(e){if(this._closed||this._sse===void 0||this._sse.closed)return;let t=e.split(`
71
71
  `).map(e=>`: ${e}`).join(`
72
- `);this.writeFrame(`${t}\n\n`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new Y(J.ConnectionClosed,`Connection closed before a response was produced`))),this.onclose?.()}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e,t=new ReadableStream({start:t=>{e=t},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=_v(this._keepAliveMs,()=>this.writeCommentFrame(`keepalive`)),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(e){this.writeFrame(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(e){this.onerror?.(Error(`Failed to write to the response stream: ${e}`))}}};async function hy(e,t,n){let r=new my({classification:n.classification,...n.responseMode!==void 0&&{responseMode:n.responseMode},...n.keepAliveMs!==void 0&&{keepAliveMs:n.keepAliveMs}});return await e.connect(r),r.handleMessage(t,{...n.request!==void 0&&{request:n.request},...n.authInfo!==void 0&&{authInfo:n.authInfo}})}var gy=4194304,_y=100;function vy(e){return`Payload Too Large: Request body must not exceed ${e} bytes`}function yy(e){if(e===void 0)return gy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}async function by(e,t=gy){if(Number(e.headers.get(`content-length`))>t)return{tooLarge:!0};if(e.body===null)return{tooLarge:!1,text:``};let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{for(;;){let{done:e,value:o}=await n.read();if(e)break;if(i+=o.byteLength,i>t)return{tooLarge:!0};a+=r.decode(o,{stream:!0})}}finally{n.releaseLock()}return{tooLarge:!1,text:a+r.decode()}}var xy=class{sessionIdGenerator;_started=!1;_hasHandledRequest=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;_maxRequestBodySize;_scopeChallengeResolver;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??en,this._keepAliveMs=e.keepAliveMs??15e3,this._maxRequestBodySize=yy(e.maxRequestBodySize)}startKeepAlive(e,t){if(this._closed)return;let n=_v(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
72
+ `);this.writeFrame(`${t}\n\n`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new Y(J.ConnectionClosed,`Connection closed before a response was produced`))),this.onclose?.()}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e,t=new ReadableStream({start:t=>{e=t},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=_v(this._keepAliveMs,()=>this.writeCommentFrame(`keepalive`)),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(e){this.writeFrame(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(e){this.onerror?.(Error(`Failed to write to the response stream: ${e}`))}}};async function hy(e,t,n){let r=new my({classification:n.classification,...n.responseMode!==void 0&&{responseMode:n.responseMode},...n.keepAliveMs!==void 0&&{keepAliveMs:n.keepAliveMs}});return await e.connect(r),r.handleMessage(t,{...n.request!==void 0&&{request:n.request},...n.authInfo!==void 0&&{authInfo:n.authInfo}})}var gy=4194304,_y=100;function vy(e){return`Payload Too Large: Request body must not exceed ${e} bytes`}function yy(e){if(e===void 0)return gy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}async function by(e,t=gy){if(Number(e.headers.get(`content-length`))>t)return{tooLarge:!0};if(e.body===null)return{tooLarge:!1,text:``};let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{for(;;){let{done:e,value:o}=await n.read();if(e)break;if(i+=o.byteLength,i>t)return{tooLarge:!0};a+=r.decode(o,{stream:!0})}}finally{n.releaseLock()}return{tooLarge:!1,text:a+r.decode()}}var xy=class{sessionIdGenerator;_started=!1;_hasHandledRequest=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;_maxRequestBodySize;_scopeChallengeResolver;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??tn,this._keepAliveMs=e.keepAliveMs??15e3,this._maxRequestBodySize=yy(e.maxRequestBodySize)}startKeepAlive(e,t){if(this._closed)return;let n=_v(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
73
73
 
74
74
  `))}catch{n!==void 0&&clearInterval(n)}});return n}setScopeChallengeResolver(e){this._scopeChallengeResolver=e}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}async _checkScopeChallenge(e,t){if(!this._scopeChallengeResolver)return;let n=await Iv(e.filter(e=>gm(e)),t,this._scopeChallengeResolver);return n===void 0?void 0:Rv(n,Lv(t))}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(e){return this._supportedProtocolVersions.includes(e)&&e>=`2025-11-25`}async writePrimingEvent(e,t,n,r){if(!this._eventStore||!this.supportsEmptySSEData(r))return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a,o=new ReadableStream({start:e=>{i=e},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};return this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,r),new Response(o,{headers:s})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a,o=!1,s,c=new ReadableStream({start:e=>{i=e},cancel:()=>{o=!0,a!==void 0&&clearInterval(a),s!==void 0&&this._streamMapping.get(s)?.controller===i&&this._streamMapping.delete(s)}}),l=new Set;if(s=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(l.add(e),!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}}),this._closed||o){try{i.close()}catch{}return this.createJsonErrorResponse(404,-32001,`Session not found`)}if(this._streamMapping.get(s)?.cleanup(),this._streamMapping.set(s,{controller:i,encoder:r,replayedEventIds:l,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(s);try{i.close()}catch{}}}),s!==this._standaloneSseStreamId&&![...this._requestToStreamMapping.values()].includes(s)){this._streamMapping.delete(s);try{i.close()}catch{}}return this._streamMapping.get(s)?.controller===i&&(a=this.startKeepAlive(i,r)),new Response(c,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
75
- `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);if(!ag(e.headers.get(`content-type`)))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=e,i;if(t?.parsedBody===void 0)try{let t=await by(e,this._maxRequestBodySize);if(t.tooLarge){let e=vy(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}i=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else i=t.parsedBody;if(Array.isArray(i)&&i.length>_y)return this.onerror?.(Error(`Invalid Request: Batch must not exceed ${_y} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${_y} messages`);let a;try{a=Array.isArray(i)?i.map(e=>ir.parse(e)):[ir.parse(i)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let o=a.some(e=>xm(e));if(o){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(a.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!o){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let s;try{s=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,`Internal server error`)}if(s)return s;if(!a.some(e=>gm(e))){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=a.find(e=>xm(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of a)gm(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r})});let d=new TextEncoder,f,p,m=new ReadableStream({start:e=>{f=e},cancel:()=>{p!==void 0&&clearInterval(p),this._streamMapping.get(c)?.controller===f&&this._streamMapping.delete(c)}}),h={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(h[`mcp-session-id`]=this.sessionId);for(let e of a)gm(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{p!==void 0&&clearInterval(p),this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of a){let n,i;gm(e)&&this._eventStore&&this.supportsEmptySSEData(u)&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:r,closeSSEStream:n,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===f&&(p=this.startKeepAlive(f,d)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((vm(e)||ym(e))&&(n=e.id),n===void 0){if(vm(e)||ym(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&(t===void 0||!n.replayedEventIds?.has(t))&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e),i=this._streamMapping.get(r)),i?.controller&&i?.encoder&&(t===void 0||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(vm(e)||ym(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function Sy(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function Cy(e,t,n,r,i=null){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n,...r!==void 0&&{data:r}},id:i},{status:e})}function wy(e,t=null){return Cy(e.httpStatus,e.code,e.message,e.data,t)}function Ty(e){return e instanceof Error?e:Error(String(e))}function Ey(e=null){return Cy(500,-32603,`Internal server error`,void 0,e)}function Dy(e){if(e.transport!==void 0)throw Error(`The factory returned an instance that is still serving another request. Return a new instance for each request.`)}function Oy(e,t,n,r){return async(i,a)=>{if(i.method.toUpperCase()!==`POST`)return Cy(405,-32e3,`Method not allowed.`);try{let t=await e({era:`legacy`,...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:i}),o=new xy({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n},...r!==void 0&&{maxRequestBodySize:r}});await t.connect(o);let s=()=>{o.close().catch(()=>{}),t.close().catch(()=>{})};i.signal?.addEventListener(`abort`,s,{once:!0});let c=await o.handleRequest(i,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(c.body===null||ig(c.headers.get(`content-type`))!==`text/event-stream`)return s(),c;let l=c.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},f=new ReadableStream({pull:async e=>{try{let{done:t,value:n}=await l.read();if(t){d(),e.close();return}n!==void 0&&e.enqueue(n)}catch(t){d(),e.error(t)}},cancel:e=>(d(),l.cancel(e).catch(()=>{}))});return new Response(f,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{t?.(Ty(e))}catch{}return Ey(Sy(a?.parsedBody))}}}function ky(e){return{protocolVersionHeader:e.headers.get(`mcp-protocol-version`)??void 0,mcpMethodHeader:e.headers.get(`mcp-method`)??void 0,mcpNameHeader:e.headers.get(`mcp-name`)??void 0}}async function Ay(e,t,n=!0,r=gy){let i=e.method.toUpperCase(),a,o=t,s=e,c=!1;if(i===`POST`){if(o===void 0){n&&(s=e.clone());let t;try{let n=await by(e,r);if(n.tooLarge)return{step:`body-too-large`};t=n.text}catch{return{step:`unreadable-body`}}try{a=t.length===0?void 0:JSON.parse(t)}catch{c=!0}!c&&a!==void 0&&(o=a)}else a=o;if(c||a===void 0)return{step:`no-json-body`,forwardRequest:s}}return{step:`classified`,outcome:rh({httpMethod:i,...ky(e),...a!==void 0&&{body:a}}),body:a,parsedBody:o,forwardRequest:s}}function jy(e,t={}){let{legacy:n,onerror:r,responseMode:i}=t,a=yy(t.maxRequestBodySize);if(typeof n==`function`)throw TypeError(`The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.`);let o=new Set,s=!1,c=e=>{try{r?.(e)}catch{}},l=t.bus??new vv(c),u=yv(l),d=Ev({bus:l,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:c});i===`json`&&console.warn(`responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.`);let f=n===`reject`?void 0:Oy(e,c,t.keepAliveMs,a);async function p(n,r,a){let s=n.classification.revision;if(s===void 0||!Mf.includes(s)){let e=new Cp({supported:[...Mf],requested:s??`unknown`});return c(e),Cy(400,e.code,e.message,e.data,Sy(n.message))}let l=Xm({httpMethod:r.method,...ky(r)},n);if(l!==void 0)return c(Error(`Rejected inbound request (${l.cell}): ${l.message}`)),wy(l,Sy(n.message));let u=n.messageKind===`request`?dm(n.message.params):void 0,f=u?.[wr];if(n.messageKind===`request`){let e=Ef(n.message.method);if(e!==void 0){let t=Af(e,f);if(t!==void 0){let e=new wp({requiredCapabilities:t});return c(e),Cy(Wm(e.code,`ladder`),e.code,e.message,e.data,n.message.id)}}}let p=await e({era:`modern`,...a!==void 0&&{authInfo:a},requestInfo:r}),m=p instanceof ry?p.server:p;if(Dy(m),n.messageKind===`request`&&n.message.method===`subscriptions/listen`){let e=m.getCapabilities(),t=Qv(m);return p.close().catch(c),d.serve(n.message,r.signal,e,t)}if(n.messageKind===`request`&&n.message.method===`tools/call`&&p instanceof ry){let e=n.message.params,t=typeof e?.name==`string`?e.name:void 0,i=t===void 0?void 0:p.toolInputSchemaJson(t);if(i!==void 0){let t=Om(i);if(t.valid&&t.declarations.length>0){let i=Bm(t.declarations,e?.arguments,r.headers);if(i!==void 0)return p.close().catch(c),c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),wy(i,n.message.id)}}}if(n.messageKind===`request`&&p instanceof ry)try{let e=await Iv([n.message],a,e=>p.resolveScopeChallenge(e));if(e!==void 0)return p.close().catch(c),Rv(e,Lv(a))}catch(e){return p.close().catch(c),c(Ty(e)),Ey(n.message.id)}Dy(m),Xh(m,s),Zv(m,Mf),u!==void 0&&Xv(m,{clientInfo:u[ai],clientCapabilities:f});let h=m.onclose;o.add(m);let g=()=>{o.delete(m),m.onclose===g&&(m.onclose=h),h?.()};m.onclose=g;try{let e=await hy(p,n.message,{classification:n.classification,request:r,...a!==void 0&&{authInfo:a},...i!==void 0&&{responseMode:i},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});return n.messageKind===`notification`&&queueMicrotask(()=>void m.close().catch(()=>{})),e}catch(e){return e instanceof Y&&e.code===J.ConnectionClosed?new Response(null,{status:499}):(await m.close().catch(()=>{}),o.delete(m),c(Ty(e)),Ey(Sy(n.message)))}}async function m(e,t,n,r){if(f!==void 0)return f(t,{...n!==void 0&&{authInfo:n},...r!==void 0&&{parsedBody:r}});let i=ih(e,Mf);return i===void 0?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),wy(i,Sy(r)))}async function h(e,t){let n=t?.authInfo;if(e.method.toUpperCase()===`POST`&&!ag(e.headers.get(`content-type`)))return c(Error(`Unsupported Media Type: Content-Type must be application/json`)),Cy(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=await Ay(e,t?.parsedBody,!0,a);if(r.step===`unreadable-body`)return Cy(400,-32700,`Parse error: the request body could not be read`);if(r.step===`body-too-large`)return Cy(413,-32e3,vy(a));if(r.step===`no-json-body`)return f===void 0?Cy(400,-32700,`Parse error: the request body is not valid JSON`):f(r.forwardRequest,{...n!==void 0&&{authInfo:n}});let{outcome:i,body:o,parsedBody:s,forwardRequest:l}=r;try{switch(i.kind){case`reject`:return c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),wy(i,Sy(o));case`modern`:return await p(i,e,n);case`legacy`:return await m(i,l,n,s)}}catch(e){return c(Ty(e)),Ey(Sy(o))}}return{fetch:async(e,t)=>{if(s)throw Error(`This MCP handler has been closed`);try{return await h(e,t)}catch(e){return c(Ty(e)),Ey(Sy(t?.parsedBody))}},notify:u,bus:l,close:async()=>{s=!0,d.closeAll();let e=[...o].map(e=>e.close().catch(()=>{}));o.clear(),await Promise.all(e)}}}var My=global.Request,Ny=class extends My{constructor(e,t){typeof e==`object`&&Ly in e&&(e=e[Ly]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Py=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},Fy=Symbol(`wrapBodyStream`),Iy=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Ny(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Fy]){let e;a.body=new ReadableStream({async pull(t){try{e||=Qi.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Qi.toWeb(r)}return new Ny(t,a)},Ly=Symbol(`getRequestCache`),Ry=Symbol(`requestCache`),zy=Symbol(`incomingKey`),By=Symbol(`urlKey`),Vy=Symbol(`headersKey`),Hy=Symbol(`abortControllerKey`),Uy={get method(){return this[zy].method||`GET`},get url(){return this[By]},get headers(){return this[Vy]||=Py(this[zy])},[Symbol(`getAbortController`)](){return this[Ly](),this[Hy]},[Ly](){return this[Hy]||=new AbortController,this[Ry]||=Iy(this.method,this[By],this.headers,this[zy],this[Hy])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Uy,e,{get(){return this[Ly]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Uy,e,{value:function(){return this[Ly]()[e]()}})}),Object.defineProperty(Uy,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Ry]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Uy,Ny.prototype);var Wy=Symbol(`responseCache`),Gy=Symbol(`getResponseCache`),Ky=Symbol(`cache`),qy=global.Response,Jy=class e{#e;#t;[Gy](){return delete this[Ky],this[Wy]||=new qy(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Wy];if(e){this.#t=e,this[Gy]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[Ky]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Ky];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Gy]().headers}get status(){return this[Ky]?.[0]??this[Gy]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Jy.prototype,e,{get(){return this[Gy]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Jy.prototype,e,{value:function(){return this[Gy]()[e]()}})}),Object.defineProperty(Jy.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Wy]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Jy,qy),Object.setPrototypeOf(Jy.prototype,qy.prototype),global.crypto===void 0&&(global.crypto=Zi);var Yy=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name=`RequestBodyTooLargeError`}};function Xy(e){if(e===void 0)return gy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function Zy(e,t){let n=Xy(t?.maxRequestBodySize);return async(r,i,a)=>{typeof a==`function`&&(a=void 0);let o=!1,s=new AbortController;i.on(`close`,()=>{o||s.abort()}),i.destroyed===!0&&s.abort();let c;try{let t=await $y(r,a,{signal:s.signal,maxRequestBodySize:n});c=await e.fetch(t,{...r.auth!==void 0&&{authInfo:r.auth},...a!==void 0&&{parsedBody:a}})}catch(e){if(e instanceof Yy)c=Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:`close`}});else{try{t?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}c=tb(eb(a))}}let l={};for(let[e,t]of c.headers)l[e]=t;if(i.writeHead(c.status,l),c.body===null){o=!0,i.end();return}let u;i.on(`drain`,()=>{u?.(),u=void 0});let d=new Promise(e=>{s.signal.addEventListener(`abort`,()=>e(),{once:!0})});try{for await(let e of c.body){if(s.signal.aborted)break;i.write(e)===!1&&await Promise.race([new Promise(e=>{u=e}),d])}}catch{}o=!0,i.end()}}function Qy(e){return Array.isArray(e)?e[0]:e}async function $y(e,t,n){let r=Xy(n?.maxRequestBodySize),i=(e.method??`GET`).toUpperCase(),a=`http://${Qy(e.headers.host)??Qy(e.headers[`:authority`])??`localhost`}${e.url??`/`}`,o=new Headers;for(let[t,n]of Object.entries(e.headers))if(!(n===void 0||t.startsWith(`:`))){if(Array.isArray(n))for(let e of n)o.append(t,e);else o.set(t,n)}let s;if(i!==`GET`&&i!==`HEAD`){if(t===void 0){if(Number(Qy(e.headers[`content-length`]))>r)throw new Yy(r);let t=new TextDecoder,n=``,i=0;for await(let a of e){if(i+=typeof a==`string`?new TextEncoder().encode(a).byteLength:a.byteLength,i>r)throw new Yy(r);n+=typeof a==`string`?a:t.decode(a,{stream:!0})}n+=t.decode(),n.length>0&&(s=n)}else{let e=JSON.stringify(t);o.delete(`content-encoding`),o.delete(`transfer-encoding`),e===void 0?o.delete(`content-length`):(s=e,o.set(`content-length`,String(new TextEncoder().encode(e).byteLength)))}}return new Request(a,{method:i,headers:o,...n?.signal!==void 0&&{signal:n.signal},...s!==void 0&&{body:s}})}function eb(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function tb(e){return Response.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:e},{status:500})}var nb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=void 0;var t=(u(),o(d)),n=(jc(),o(Ac)),r=(v(),o(w)),i=(ue(),o(ee)),a=`otel.scope.schema_url`;function s(e){return e.replace(/\\/g,`\\\\`).replace(/\n/g,`\\n`)}function c(e=``){return typeof e!=`string`&&(e=JSON.stringify(e)),s(e).replace(/"/g,`\\"`)}var l=/[^a-z0-9_]/gi,f=/_{2,}/g;function p(e){return e.replace(l,`_`).replace(f,`_`)}function m(e,t){return!e.endsWith(`_total`)&&t.dataPointType===n.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function h(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function g(e){switch(e.dataPointType){case n.DataPointType.SUM:return e.isMonotonic?`counter`:`gauge`;case n.DataPointType.GAUGE:return`gauge`;case n.DataPointType.HISTOGRAM:return`histogram`;default:return`untyped`}}function _(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=p(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=p(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${h(n)}${r===void 0?``:` `+String(r)}\n`}var y=`# no registered metrics`;e.PrometheusSerializer=class{_prefix;_appendTimestamp;_additionalAttributes;_withResourceConstantLabels;_withoutScopeInfo;_withoutTargetInfo;constructor(e,t=!1,n,r,i){e&&(this._prefix=e+`_`),this._appendTimestamp=t,this._withResourceConstantLabels=n,this._withoutScopeInfo=!!i,this._withoutTargetInfo=!!r}serialize(e){let t=``;this._additionalAttributes=this._filterResourceConstantLabels(e.resource.attributes,this._withResourceConstantLabels);for(let n of e.scopeMetrics)t+=this._serializeScopeMetrics(n);return t===``&&(t+=y),this._serializeResource(e.resource)+t}_filterResourceConstantLabels(e,t){if(t){let n={};for(let[r,i]of Object.entries(e))r.match(t)&&(n[r]=i);return n}}_serializeScopeMetrics(e){let t=``;for(let n of e.metrics){let r=this._serializeMetricData(n,e.scope);r&&(t+=r+`
75
+ `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);if(!ag(e.headers.get(`content-type`)))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=e,i;if(t?.parsedBody===void 0)try{let t=await by(e,this._maxRequestBodySize);if(t.tooLarge){let e=vy(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}i=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else i=t.parsedBody;if(Array.isArray(i)&&i.length>_y)return this.onerror?.(Error(`Invalid Request: Batch must not exceed ${_y} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${_y} messages`);let a;try{a=Array.isArray(i)?i.map(e=>ir.parse(e)):[ir.parse(i)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let o=a.some(e=>xm(e));if(o){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(a.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!o){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let s;try{s=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,`Internal server error`)}if(s)return s;if(!a.some(e=>gm(e))){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=a.find(e=>xm(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of a)gm(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r})});let d=new TextEncoder,f,p,m=new ReadableStream({start:e=>{f=e},cancel:()=>{p!==void 0&&clearInterval(p),this._streamMapping.get(c)?.controller===f&&this._streamMapping.delete(c)}}),h={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(h[`mcp-session-id`]=this.sessionId);for(let e of a)gm(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{p!==void 0&&clearInterval(p),this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of a){let n,i;gm(e)&&this._eventStore&&this.supportsEmptySSEData(u)&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:r,closeSSEStream:n,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===f&&(p=this.startKeepAlive(f,d)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((vm(e)||ym(e))&&(n=e.id),n===void 0){if(vm(e)||ym(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&(t===void 0||!n.replayedEventIds?.has(t))&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e),i=this._streamMapping.get(r)),i?.controller&&i?.encoder&&(t===void 0||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(vm(e)||ym(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function Sy(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function Cy(e,t,n,r,i=null){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n,...r!==void 0&&{data:r}},id:i},{status:e})}function wy(e,t=null){return Cy(e.httpStatus,e.code,e.message,e.data,t)}function Ty(e){return e instanceof Error?e:Error(String(e))}function Ey(e=null){return Cy(500,-32603,`Internal server error`,void 0,e)}function Dy(e){if(e.transport!==void 0)throw Error(`The factory returned an instance that is still serving another request. Return a new instance for each request.`)}function Oy(e,t,n,r){return async(i,a)=>{if(i.method.toUpperCase()!==`POST`)return Cy(405,-32e3,`Method not allowed.`);try{let t=await e({era:`legacy`,...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:i}),o=new xy({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n},...r!==void 0&&{maxRequestBodySize:r}});await t.connect(o);let s=()=>{o.close().catch(()=>{}),t.close().catch(()=>{})};i.signal?.addEventListener(`abort`,s,{once:!0});let c=await o.handleRequest(i,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(c.body===null||ig(c.headers.get(`content-type`))!==`text/event-stream`)return s(),c;let l=c.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},f=new ReadableStream({pull:async e=>{try{let{done:t,value:n}=await l.read();if(t){d(),e.close();return}n!==void 0&&e.enqueue(n)}catch(t){d(),e.error(t)}},cancel:e=>(d(),l.cancel(e).catch(()=>{}))});return new Response(f,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{t?.(Ty(e))}catch{}return Ey(Sy(a?.parsedBody))}}}function ky(e){return{protocolVersionHeader:e.headers.get(`mcp-protocol-version`)??void 0,mcpMethodHeader:e.headers.get(`mcp-method`)??void 0,mcpNameHeader:e.headers.get(`mcp-name`)??void 0}}async function Ay(e,t,n=!0,r=gy){let i=e.method.toUpperCase(),a,o=t,s=e,c=!1;if(i===`POST`){if(o===void 0){n&&(s=e.clone());let t;try{let n=await by(e,r);if(n.tooLarge)return{step:`body-too-large`};t=n.text}catch{return{step:`unreadable-body`}}try{a=t.length===0?void 0:JSON.parse(t)}catch{c=!0}!c&&a!==void 0&&(o=a)}else a=o;if(c||a===void 0)return{step:`no-json-body`,forwardRequest:s}}return{step:`classified`,outcome:rh({httpMethod:i,...ky(e),...a!==void 0&&{body:a}}),body:a,parsedBody:o,forwardRequest:s}}function jy(e,t={}){let{legacy:n,onerror:r,responseMode:i}=t,a=yy(t.maxRequestBodySize);if(typeof n==`function`)throw TypeError(`The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.`);let o=new Set,s=!1,c=e=>{try{r?.(e)}catch{}},l=t.bus??new vv(c),u=yv(l),d=Ev({bus:l,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:c});i===`json`&&console.warn(`responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.`);let f=n===`reject`?void 0:Oy(e,c,t.keepAliveMs,a);async function p(n,r,a){let s=n.classification.revision;if(s===void 0||!Mf.includes(s)){let e=new Cp({supported:[...Mf],requested:s??`unknown`});return c(e),Cy(400,e.code,e.message,e.data,Sy(n.message))}let l=Xm({httpMethod:r.method,...ky(r)},n);if(l!==void 0)return c(Error(`Rejected inbound request (${l.cell}): ${l.message}`)),wy(l,Sy(n.message));let u=n.messageKind===`request`?dm(n.message.params):void 0,f=u?.[wr];if(n.messageKind===`request`){let e=Ef(n.message.method);if(e!==void 0){let t=Af(e,f);if(t!==void 0){let e=new wp({requiredCapabilities:t});return c(e),Cy(Wm(e.code,`ladder`),e.code,e.message,e.data,n.message.id)}}}let p=await e({era:`modern`,...a!==void 0&&{authInfo:a},requestInfo:r}),m=p instanceof ry?p.server:p;if(Dy(m),n.messageKind===`request`&&n.message.method===`subscriptions/listen`){let e=m.getCapabilities(),t=Qv(m);return p.close().catch(c),d.serve(n.message,r.signal,e,t)}if(n.messageKind===`request`&&n.message.method===`tools/call`&&p instanceof ry){let e=n.message.params,t=typeof e?.name==`string`?e.name:void 0,i=t===void 0?void 0:p.toolInputSchemaJson(t);if(i!==void 0){let t=Om(i);if(t.valid&&t.declarations.length>0){let i=Bm(t.declarations,e?.arguments,r.headers);if(i!==void 0)return p.close().catch(c),c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),wy(i,n.message.id)}}}if(n.messageKind===`request`&&p instanceof ry)try{let e=await Iv([n.message],a,e=>p.resolveScopeChallenge(e));if(e!==void 0)return p.close().catch(c),Rv(e,Lv(a))}catch(e){return p.close().catch(c),c(Ty(e)),Ey(n.message.id)}Dy(m),Xh(m,s),Zv(m,Mf),u!==void 0&&Xv(m,{clientInfo:u[oi],clientCapabilities:f});let h=m.onclose;o.add(m);let g=()=>{o.delete(m),m.onclose===g&&(m.onclose=h),h?.()};m.onclose=g;try{let e=await hy(p,n.message,{classification:n.classification,request:r,...a!==void 0&&{authInfo:a},...i!==void 0&&{responseMode:i},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});return n.messageKind===`notification`&&queueMicrotask(()=>void m.close().catch(()=>{})),e}catch(e){return e instanceof Y&&e.code===J.ConnectionClosed?new Response(null,{status:499}):(await m.close().catch(()=>{}),o.delete(m),c(Ty(e)),Ey(Sy(n.message)))}}async function m(e,t,n,r){if(f!==void 0)return f(t,{...n!==void 0&&{authInfo:n},...r!==void 0&&{parsedBody:r}});let i=ih(e,Mf);return i===void 0?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),wy(i,Sy(r)))}async function h(e,t){let n=t?.authInfo;if(e.method.toUpperCase()===`POST`&&!ag(e.headers.get(`content-type`)))return c(Error(`Unsupported Media Type: Content-Type must be application/json`)),Cy(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=await Ay(e,t?.parsedBody,!0,a);if(r.step===`unreadable-body`)return Cy(400,-32700,`Parse error: the request body could not be read`);if(r.step===`body-too-large`)return Cy(413,-32e3,vy(a));if(r.step===`no-json-body`)return f===void 0?Cy(400,-32700,`Parse error: the request body is not valid JSON`):f(r.forwardRequest,{...n!==void 0&&{authInfo:n}});let{outcome:i,body:o,parsedBody:s,forwardRequest:l}=r;try{switch(i.kind){case`reject`:return c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),wy(i,Sy(o));case`modern`:return await p(i,e,n);case`legacy`:return await m(i,l,n,s)}}catch(e){return c(Ty(e)),Ey(Sy(o))}}return{fetch:async(e,t)=>{if(s)throw Error(`This MCP handler has been closed`);try{return await h(e,t)}catch(e){return c(Ty(e)),Ey(Sy(t?.parsedBody))}},notify:u,bus:l,close:async()=>{s=!0,d.closeAll();let e=[...o].map(e=>e.close().catch(()=>{}));o.clear(),await Promise.all(e)}}}var My=global.Request,Ny=class extends My{constructor(e,t){typeof e==`object`&&Ly in e&&(e=e[Ly]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Py=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},Fy=Symbol(`wrapBodyStream`),Iy=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Ny(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Fy]){let e;a.body=new ReadableStream({async pull(t){try{e||=Qi.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Qi.toWeb(r)}return new Ny(t,a)},Ly=Symbol(`getRequestCache`),Ry=Symbol(`requestCache`),zy=Symbol(`incomingKey`),By=Symbol(`urlKey`),Vy=Symbol(`headersKey`),Hy=Symbol(`abortControllerKey`),Uy={get method(){return this[zy].method||`GET`},get url(){return this[By]},get headers(){return this[Vy]||=Py(this[zy])},[Symbol(`getAbortController`)](){return this[Ly](),this[Hy]},[Ly](){return this[Hy]||=new AbortController,this[Ry]||=Iy(this.method,this[By],this.headers,this[zy],this[Hy])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Uy,e,{get(){return this[Ly]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Uy,e,{value:function(){return this[Ly]()[e]()}})}),Object.defineProperty(Uy,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Ry]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Uy,Ny.prototype);var Wy=Symbol(`responseCache`),Gy=Symbol(`getResponseCache`),Ky=Symbol(`cache`),qy=global.Response,Jy=class e{#e;#t;[Gy](){return delete this[Ky],this[Wy]||=new qy(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Wy];if(e){this.#t=e,this[Gy]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[Ky]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Ky];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Gy]().headers}get status(){return this[Ky]?.[0]??this[Gy]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Jy.prototype,e,{get(){return this[Gy]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Jy.prototype,e,{value:function(){return this[Gy]()[e]()}})}),Object.defineProperty(Jy.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Wy]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Jy,qy),Object.setPrototypeOf(Jy.prototype,qy.prototype),global.crypto===void 0&&(global.crypto=Zi);var Yy=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name=`RequestBodyTooLargeError`}};function Xy(e){if(e===void 0)return gy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function Zy(e,t){let n=Xy(t?.maxRequestBodySize);return async(r,i,a)=>{typeof a==`function`&&(a=void 0);let o=!1,s=new AbortController;i.on(`close`,()=>{o||s.abort()}),i.destroyed===!0&&s.abort();let c;try{let t=await $y(r,a,{signal:s.signal,maxRequestBodySize:n});c=await e.fetch(t,{...r.auth!==void 0&&{authInfo:r.auth},...a!==void 0&&{parsedBody:a}})}catch(e){if(e instanceof Yy)c=Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:`close`}});else{try{t?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}c=tb(eb(a))}}let l={};for(let[e,t]of c.headers)l[e]=t;if(i.writeHead(c.status,l),c.body===null){o=!0,i.end();return}let u;i.on(`drain`,()=>{u?.(),u=void 0});let d=new Promise(e=>{s.signal.addEventListener(`abort`,()=>e(),{once:!0})});try{for await(let e of c.body){if(s.signal.aborted)break;i.write(e)===!1&&await Promise.race([new Promise(e=>{u=e}),d])}}catch{}o=!0,i.end()}}function Qy(e){return Array.isArray(e)?e[0]:e}async function $y(e,t,n){let r=Xy(n?.maxRequestBodySize),i=(e.method??`GET`).toUpperCase(),a=`http://${Qy(e.headers.host)??Qy(e.headers[`:authority`])??`localhost`}${e.url??`/`}`,o=new Headers;for(let[t,n]of Object.entries(e.headers))if(!(n===void 0||t.startsWith(`:`))){if(Array.isArray(n))for(let e of n)o.append(t,e);else o.set(t,n)}let s;if(i!==`GET`&&i!==`HEAD`){if(t===void 0){if(Number(Qy(e.headers[`content-length`]))>r)throw new Yy(r);let t=new TextDecoder,n=``,i=0;for await(let a of e){if(i+=typeof a==`string`?new TextEncoder().encode(a).byteLength:a.byteLength,i>r)throw new Yy(r);n+=typeof a==`string`?a:t.decode(a,{stream:!0})}n+=t.decode(),n.length>0&&(s=n)}else{let e=JSON.stringify(t);o.delete(`content-encoding`),o.delete(`transfer-encoding`),e===void 0?o.delete(`content-length`):(s=e,o.set(`content-length`,String(new TextEncoder().encode(e).byteLength)))}}return new Request(a,{method:i,headers:o,...n?.signal!==void 0&&{signal:n.signal},...s!==void 0&&{body:s}})}function eb(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function tb(e){return Response.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:e},{status:500})}var nb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=void 0;var t=(u(),o(d)),n=(jc(),o(Ac)),r=(v(),o(w)),i=(ue(),o(ee)),a=`otel.scope.schema_url`;function s(e){return e.replace(/\\/g,`\\\\`).replace(/\n/g,`\\n`)}function c(e=``){return typeof e!=`string`&&(e=JSON.stringify(e)),s(e).replace(/"/g,`\\"`)}var l=/[^a-z0-9_]/gi,f=/_{2,}/g;function p(e){return e.replace(l,`_`).replace(f,`_`)}function m(e,t){return!e.endsWith(`_total`)&&t.dataPointType===n.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function h(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function g(e){switch(e.dataPointType){case n.DataPointType.SUM:return e.isMonotonic?`counter`:`gauge`;case n.DataPointType.GAUGE:return`gauge`;case n.DataPointType.HISTOGRAM:return`histogram`;default:return`untyped`}}function _(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=p(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=p(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${h(n)}${r===void 0?``:` `+String(r)}\n`}var y=`# no registered metrics`;e.PrometheusSerializer=class{_prefix;_appendTimestamp;_additionalAttributes;_withResourceConstantLabels;_withoutScopeInfo;_withoutTargetInfo;constructor(e,t=!1,n,r,i){e&&(this._prefix=e+`_`),this._appendTimestamp=t,this._withResourceConstantLabels=n,this._withoutScopeInfo=!!i,this._withoutTargetInfo=!!r}serialize(e){let t=``;this._additionalAttributes=this._filterResourceConstantLabels(e.resource.attributes,this._withResourceConstantLabels);for(let n of e.scopeMetrics)t+=this._serializeScopeMetrics(n);return t===``&&(t+=y),this._serializeResource(e.resource)+t}_filterResourceConstantLabels(e,t){if(t){let n={};for(let[r,i]of Object.entries(e))r.match(t)&&(n[r]=i);return n}}_serializeScopeMetrics(e){let t=``;for(let n of e.metrics){let r=this._serializeMetricData(n,e.scope);r&&(t+=r+`
76
76
  `)}return t}_serializeMetricData(e,r){let o=p(s(e.descriptor.name));if(this._prefix&&(o=`${this._prefix}${o}`),o===``)return t.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in empty name`),``;if(o===`_`)return t.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in an invalid name: "_"`),``;o[0]>=`0`&&o[0]<=`9`&&(o=`_${o}`);let c=e.dataPointType;o=m(o,e);let l=`# HELP ${o} ${s(e.descriptor.description||`description missing`)}`,u=e.descriptor.unit?`\n# UNIT ${o} ${s(e.descriptor.unit)}`:``,d=`# TYPE ${o} ${g(e)}`,f;if(this._withoutScopeInfo)f=this._additionalAttributes;else{let e={[i.ATTR_OTEL_SCOPE_NAME]:r.name};r.schemaUrl&&(e[a]=r.schemaUrl),r.version&&(e[i.ATTR_OTEL_SCOPE_VERSION]=r.version),f=Object.assign(e,this._additionalAttributes)}let h=``;switch(c){case n.DataPointType.SUM:case n.DataPointType.GAUGE:h=e.dataPoints.map(t=>this._serializeSingularDataPoint(o,e,t,f)).join(``);break;case n.DataPointType.HISTOGRAM:h=e.dataPoints.map(t=>this._serializeHistogramDataPoint(o,e,t,f)).join(``);break;default:t.diag.error(`Unrecognizable DataPointType: ${c} for metric "${o}"`)}return`${l}${u}\n${d}\n${h}`.trim()}_serializeSingularDataPoint(e,t,n,i){let a=``,{value:o,attributes:s}=n,c=(0,r.hrTimeToMilliseconds)(n.endTime);return a+=_(e,s,o,this._appendTimestamp?c:void 0,i),a}_serializeHistogramDataPoint(e,t,n,i){let a=``,o=n.attributes,s=n.value,c=(0,r.hrTimeToMilliseconds)(n.endTime);for(let t of[`count`,`sum`]){let n=s[t];n!=null&&(a+=_(e+`_`+t,o,n,this._appendTimestamp?c:void 0,i))}let l=0,u=s.buckets.counts.entries(),d=!1;for(let[t,n]of u){l+=n;let r=s.buckets.boundaries[t];if(r===void 0&&d)break;r===1/0&&(d=!0),a+=_(e+`_bucket`,o,l,this._appendTimestamp?c:void 0,Object.assign({},i,{le:r===void 0||r===1/0?`+Inf`:String(r)}))}return a}_serializeResource(e){if(this._withoutTargetInfo===!0)return``;let t=`target_info`;return`${`# HELP ${t} Target metadata`}\n${`# TYPE ${t} gauge`}\n${_(t,e.attributes,1).trim()}\n`}}})),rb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=void 0,e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=`prometheus_http_text_metric_exporter`})),ib=r((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrometheusExporter=void 0;var n=(u(),o(d)),r=(v(),o(w)),i=(jc(),o(Ac)),a=e(`http`),s=nb(),c=rb(),l=e(`url`);t.PrometheusExporter=class e extends i.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:`/metrics`,prefix:``,appendTimestamp:!1,withResourceConstantLabels:void 0,withoutScopeInfo:!1,withoutTargetInfo:!1};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(t={},r=()=>{}){super({aggregationSelector:e=>({type:i.AggregationType.DEFAULT}),aggregationTemporalitySelector:e=>i.AggregationTemporality.CUMULATIVE,otelComponentType:c.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER,metricProducers:t.metricProducers}),this._host=t.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||e.DEFAULT_OPTIONS.host,this._port=t.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||e.DEFAULT_OPTIONS.port,this._prefix=t.prefix||e.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof t.appendTimestamp==`boolean`?t.appendTimestamp:e.DEFAULT_OPTIONS.appendTimestamp;let o=t.withResourceConstantLabels||e.DEFAULT_OPTIONS.withResourceConstantLabels,l=t.withoutScopeInfo||e.DEFAULT_OPTIONS.withoutScopeInfo,u=t.withoutTargetInfo||e.DEFAULT_OPTIONS.withoutTargetInfo;this._server=(0,a.createServer)(this._requestHandler).unref(),this._serializer=new s.PrometheusSerializer(this._prefix,this._appendTimestamp,o,u,l),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(t.endpoint||e.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,`/$1`),t.preventServerStart===!0?r&&queueMicrotask(r):this.startServer().then(r,e=>{n.diag.error(e),r(e)})}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){return this._server?new Promise(e=>{this._server.close(t=>{t?t.code!==`ERR_SERVER_NOT_RUNNING`&&(0,r.globalErrorHandler)(t):n.diag.debug(`Prometheus exporter was stopped`),e()})}):(n.diag.debug(`Prometheus stopServer() was called but server was never started.`),Promise.resolve())}startServer(){return this._startServerPromise??=new Promise((e,t)=>{this._server.once(`error`,t),this._server.listen({port:this._port,host:this._host},()=>{n.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),e()})}),this._startServerPromise}getMetricsRequestHandler(e,t){this._exportMetrics(t)}_requestHandler=(e,t)=>{let n;try{e.url!=null&&(n=new l.URL(e.url,this._baseUrl).pathname)}catch{t.statusCode=400,t.end(`Bad Request`);return}n===this._endpoint?this._exportMetrics(t):this._notFound(t)};_exportMetrics=e=>{e.statusCode=200,e.setHeader(`content-type`,`text/plain`),this.collect().then(t=>{let{resourceMetrics:r,errors:i}=t;i.length&&n.diag.error(`PrometheusExporter: metrics collection errors`,...i),e.end(this._serializer.serialize(r))},t=>{e.end(`# failed to export metrics: ${t}`)})};_notFound=e=>{e.statusCode=404,e.end()}}})),ab=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=e.PrometheusExporter=void 0;var t=ib();Object.defineProperty(e,"PrometheusExporter",{enumerable:!0,get:function(){return t.PrometheusExporter}});var n=nb();Object.defineProperty(e,"PrometheusSerializer",{enumerable:!0,get:function(){return n.PrometheusSerializer}})})),ob;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`,e[e.LOWMEMORY=2]=`LOWMEMORY`})(ob||={}),v(),jc(),u();var sb=()=>ca.CUMULATIVE,cb=e=>{switch(e){case K.COUNTER:case K.OBSERVABLE_COUNTER:case K.GAUGE:case K.HISTOGRAM:case K.OBSERVABLE_GAUGE:return ca.DELTA;case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:return ca.CUMULATIVE}},lb=e=>{switch(e){case K.COUNTER:case K.HISTOGRAM:return ca.DELTA;case K.GAUGE:case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:case K.OBSERVABLE_COUNTER:case K.OBSERVABLE_GAUGE:return ca.CUMULATIVE}};function ub(){let e=(A(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`)??`cumulative`).toLowerCase();return e===`cumulative`?sb:e===`delta`?cb:e===`lowmemory`?lb:(l.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),sb)}function db(e){return e==null?ub():e===ob.DELTA?cb:e===ob.LOWMEMORY?lb:sb}var fb=Object.freeze({type:jo.DEFAULT});function pb(e){return e?.aggregationPreference??(()=>fb)}var mb=class extends pe{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=pb(t),this._aggregationTemporalitySelector=db(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}},hb=`otlp_http_metric_exporter`,gb=class extends mb{_url;constructor(e){super(me(h(e??{},`METRICS`,`v1/metrics`,{"Content-Type":`application/json`}),Hc,hb,sa,e?.selfObsMeterProvider),e),this._url=e?.url}setSelfObsMeterProvider(e){this.setMetrics(T(hb,sa,this._url,e))}},_b=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PACKAGE_NAME=e.PACKAGE_VERSION=void 0,e.PACKAGE_VERSION=`0.39.0`,e.PACKAGE_NAME=`@opentelemetry/host-metrics`})),vb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseMetrics=void 0;var t=(u(),o(d)),n=_b(),r=n.PACKAGE_NAME;e.BaseMetrics=class{_meter;_name;_metricGroups;constructor(e){t.diag.warn(`@opentelemetry/host-metrics is deprecated. Use @opentelemetry/instrumentation-host-metrics instead.`),this._name=e?.name||r;let i=e?.meterProvider??t.metrics.getMeterProvider();this._meter=i.getMeter(this._name,n.PACKAGE_VERSION),this._metricGroups=e?.metricGroups}}})),yb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SYSTEM_MEMORY_STATE_VALUE_USED=e.SYSTEM_MEMORY_STATE_VALUE_FREE=e.SYSTEM_CPU_STATE_VALUE_USER=e.SYSTEM_CPU_STATE_VALUE_SYSTEM=e.SYSTEM_CPU_STATE_VALUE_NICE=e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=e.SYSTEM_CPU_STATE_VALUE_IDLE=e.PROCESS_CPU_STATE_VALUE_USER=e.PROCESS_CPU_STATE_VALUE_SYSTEM=e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=e.METRIC_SYSTEM_NETWORK_IO=e.METRIC_SYSTEM_NETWORK_ERRORS=e.METRIC_SYSTEM_MEMORY_UTILIZATION=e.METRIC_SYSTEM_MEMORY_USAGE=e.METRIC_SYSTEM_CPU_UTILIZATION=e.METRIC_SYSTEM_CPU_TIME=e.METRIC_PROCESS_MEMORY_USAGE=e.METRIC_PROCESS_CPU_UTILIZATION=e.METRIC_PROCESS_CPU_TIME=e.ATTR_SYSTEM_MEMORY_STATE=e.ATTR_SYSTEM_DEVICE=e.ATTR_SYSTEM_CPU_STATE=e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=e.ATTR_PROCESS_CPU_STATE=e.ATTR_NETWORK_IO_DIRECTION=void 0,e.ATTR_NETWORK_IO_DIRECTION=`network.io.direction`,e.ATTR_PROCESS_CPU_STATE=`process.cpu.state`,e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=`system.cpu.logical_number`,e.ATTR_SYSTEM_CPU_STATE=`system.cpu.state`,e.ATTR_SYSTEM_DEVICE=`system.device`,e.ATTR_SYSTEM_MEMORY_STATE=`system.memory.state`,e.METRIC_PROCESS_CPU_TIME=`process.cpu.time`,e.METRIC_PROCESS_CPU_UTILIZATION=`process.cpu.utilization`,e.METRIC_PROCESS_MEMORY_USAGE=`process.memory.usage`,e.METRIC_SYSTEM_CPU_TIME=`system.cpu.time`,e.METRIC_SYSTEM_CPU_UTILIZATION=`system.cpu.utilization`,e.METRIC_SYSTEM_MEMORY_USAGE=`system.memory.usage`,e.METRIC_SYSTEM_MEMORY_UTILIZATION=`system.memory.utilization`,e.METRIC_SYSTEM_NETWORK_ERRORS=`system.network.errors`,e.METRIC_SYSTEM_NETWORK_IO=`system.network.io`,e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=`receive`,e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=`transmit`,e.PROCESS_CPU_STATE_VALUE_SYSTEM=`system`,e.PROCESS_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_CPU_STATE_VALUE_IDLE=`idle`,e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=`interrupt`,e.SYSTEM_CPU_STATE_VALUE_NICE=`nice`,e.SYSTEM_CPU_STATE_VALUE_SYSTEM=`system`,e.SYSTEM_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_MEMORY_STATE_VALUE_FREE=`free`,e.SYSTEM_MEMORY_STATE_VALUE_USED=`used`})),bb=r((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getProcessMemoryData=t.getMemoryData=t.getProcessCpuUsageData=t.getCpuUsageData=void 0;var n=e(`os`),r=1/1e3,i=1/1e6,a={time:Date.now(),cpus:(0,n.cpus)()};function o(){let e=Date.now(),t=e-a.time,i={time:e,cpus:(0,n.cpus)()},o=i.cpus.map((e,n)=>{let i=a.cpus[n].times,o=e.times,s=o.idle*r,c=o.user*r,l=o.sys*r,u=o.irq*r,d=o.nice*r,f=(o.idle-i.idle)/t,p=(o.user-i.user)/t,m=(o.sys-i.sys)/t,h=(o.irq-i.irq)/t,g=(o.nice-i.nice)/t;return{cpuNumber:String(n),idle:s,user:c,system:l,interrupt:u,nice:d,userP:p,systemP:m,idleP:f,interruptP:h,niceP:g}});return a=i,o}t.getCpuUsageData=o;var s={time:Date.now(),usage:process.cpuUsage()};function c(){let e=Date.now(),t=process.cpuUsage(),n=s.usage,r=(e-s.time)*1e3*a.cpus.length,o=t.user*i,c=t.system*i,l=(t.user-n.user)/r,u=(t.system-n.system)/r;return s={time:e,usage:t},{user:o,system:c,userP:l,systemP:u}}t.getProcessCpuUsageData=c;function l(){let e=(0,n.totalmem)(),t=(0,n.freemem)(),r=e-t,i=t/e;return{used:r,free:t,usedP:r/e,freeP:i}}t.getMemoryData=l;function u(){return process.memoryUsage.rss?process.memoryUsage.rss():process.memoryUsage().rss}t.getProcessMemoryData=u})),xb=r((t=>{var n=e(`os`),r=e(`fs`),i=e(`path`),a=e(`child_process`).spawn,o=e(`child_process`).exec,s=e(`child_process`).execSync;e(`util`);var c=process.platform,l=c===`linux`||c===`android`,u=c===`darwin`,d=c===`win32`,f=c===`freebsd`,p=c===`openbsd`,m=c===`netbsd`,h=0,g=``,_=null,v=null,y=process.env.WINDIR||`C:\\Windows`,b,x=``,S=[],C=!1,w=``,T=`$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; `,E=`--###START###--`,D=`--ERROR--`,O=`--###ENDCMD###--`,k=`--##ID##--`,A={windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})},j={maxBuffer:104857600,encoding:`UTF-8`,stdio:[`pipe`,`pipe`,`ignore`]};function ee(e){let t=parseInt(e,10);return isNaN(t)&&(t=0),t}function te(e){let t=!1,n=``,r=``;for(let i of e)i>=`0`&&i<=`9`||t?(t=!0,n+=i):r+=i;return[r,n]}var M=new String,N=new String().replace,ne=new String().toLowerCase,re=new String().toString,ie=new String().substr,ae=new String().substring,oe=new String().trim,se=new String().startsWith,ce=Math.min;function le(e){return e&&{}.toString.call(e)===`[object Function]`}function ue(e){let t=[],n={};for(let r=0;r<e.length;r++){let i=Object.keys(e[r]);i.sort((e,t)=>e-t);let a=``;for(let t=0;t<i.length;t++)a+=JSON.stringify(i[t]),a+=JSON.stringify(e[r][i[t]]);({}).hasOwnProperty.call(n,a)||(t.push(e[r]),n[a]=!0)}return t}function de(e,t){return e.sort((e,n)=>{let r=``,i=``;return t.forEach(t=>{r+=e[t],i+=n[t]}),r<i?-1:+(r>i)})}function fe(){return h===0&&(h=n.cpus().length),h}function pe(e,t,n,r,i){n||=`:`,t=t.toLowerCase(),r||=!1,i||=!1;let a=``;return e.some(e=>{let o=e.toLowerCase().replace(/\t/g,``);if(r&&(o=o.trim()),o.startsWith(t)&&(!i||o.match(t+n)||o.match(t+` `+n))){let t=r?e.trim().split(n):e.split(n);if(t.length>=2)return t.shift(),a=t.join(n).trim(),!0}return!1}),a}function me(e,t){return t||=16,e.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],t))})}function he(e){let t=``,n=0;return e.split(``).forEach(e=>{e>=`0`&&e<=`9`?n===1&&n++:(n===0&&n++,n===1&&(t+=e))}),t}function ge(e,t){t||=``,e=e.toUpperCase();let n=0,r=0,i=he(e),a=e.split(i);if(a.length>=2){a[2]&&(a[1]+=a[2]);let e=(a[1]||``).toLowerCase(),i=e.indexOf(`pm`)>-1||e.indexOf(`p.m.`)>-1||e.indexOf(`p. m.`)>-1||e.indexOf(`n`)>-1||e.indexOf(`ch`)>-1||e.indexOf(`ös`)>-1||t&&e.indexOf(t)>-1;return n=parseInt(a[0],10),r=parseInt(a[1],10),n=i&&n<12?n+12:n,(`0`+n).substr(-2)+`:`+(`0`+r).substr(-2)}}function _e(e,t){let n={date:``,time:``};t||={};let r=(t.dateFormat||``).toLowerCase(),i=t.pmDesignator||``,a=e.split(` `);if(a[0]){if(a[0].indexOf(`/`)>=0){let t=a[0].split(`/`);t.length===3&&(n.date=t[0].length===4?t[0]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[2]).substr(-2):t[2].length===2?(r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`),`20`+t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2)):(e.toLowerCase().indexOf(`pm`)>-1||e.toLowerCase().indexOf(`p.m.`)>-1||e.toLowerCase().indexOf(`p. m.`)>-1||e.toLowerCase().indexOf(`am`)>-1||e.toLowerCase().indexOf(`a.m.`)>-1||e.toLowerCase().indexOf(`a. m.`)>-1||r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`)>-1)&&r.indexOf(`dd/`)!==0?t[2]+`-`+(`0`+t[0]).substr(-2)+`-`+(`0`+t[1]).substr(-2):t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2))}if(a[0].indexOf(`.`)>=0){let e=a[0].split(`.`);e.length===3&&(n.date=r.indexOf(`.d.`)>-1||r.indexOf(`.dd.`)>-1?e[2]+`-`+(`0`+e[0]).substr(-2)+`-`+(`0`+e[1]).substr(-2):e[2]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[0]).substr(-2))}if(a[0].indexOf(`-`)>=0){let e=a[0].split(`-`);e.length===3&&(n.date=e[0]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[2]).substr(-2))}}return a[1]&&(a.shift(),n.time=ge(a.join(` `),i)),n}function ve(e,t){let n=t>0,r=1,i=0,a=0,o=[];for(let s=0;s<e.length;s++)r<=t?(/\s/.test(e[s])&&!n&&(a=s-1,o.push({from:i,to:a+1,cap:e.substring(i,a+1)}),i=a+2,r++),n=e[s]===` `):(!/\s/.test(e[s])&&n&&(a=s-1,i<a&&o.push({from:i,to:a,cap:e.substring(i,a)}),i=a+1,r++),n=e[s]===` `);a=5e3,o.push({from:i,to:a,cap:e.substring(i,a)});let s=o.length;for(let e=0;e<s;e++)o[e].cap.replace(/\s/g,``).length===0&&e+1<s&&(o[e].to=o[e+1].to,o[e].cap=o[e].cap+o[e+1].cap,o.splice(e+1,1),--s);return o}function ye(e,t,n){for(let r=0;r<e.length;r++)if(e[r][t]===n)return r;return-1}function be(){if(w=`powershell.exe`,d){let e=`${y}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;r.existsSync(e)&&(w=e)}}function xe(){let e=(process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH||``).replace(/["%!^&|<>`$;\r\n]/g,``);return d?`"${e}\\VBoxManage.exe"`:`vboxmanage`}function Se(e){let t=``,n,r=``;if(e.indexOf(E)>=0){n=e.split(E);let r=n[1].split(k);t=r[0],r.length>1&&(e=r.slice(1).join(k))}e.indexOf(O)>=0&&(n=e.split(O),r=n[0]);let i=-1;for(let e=0;e<S.length;e++)S[e].id===t&&(i=e,S[e].callback(r));i>=0&&S.splice(i,1)}function Ce(){b||(b=a(w,[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-Command`,`-`],{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})}),b&&b.pid&&(C=!0,b.stdout.on(`data`,e=>{x+=e.toString(`utf8`);let t=x.indexOf(O);for(;t>=0;){let e=t+16;Se(x.slice(0,e)),x=x.slice(e),t=x.indexOf(O)}}),b.stderr.on(`data`,()=>{Se(x+D)}),b.on(`error`,()=>{Se(x+D)}),b.on(`close`,()=>{b&&b.kill()})))}function we(){try{b&&(b.stdin.write(`exit`+n.EOL),b.stdin.end())}catch{b&&b.kill()}C=!1,b=null}function Te(e){if(C){let t=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function i(e){r(e)}S.push({id:t,cmd:e,callback:i,start:new Date});try{b&&b.pid&&b.stdin.write(T+`echo `+E+t+`--##ID##--; `+n.EOL+e+n.EOL+`echo --###ENDCMD###--`+n.EOL)}catch{r(``)}})})}{let t=``;return new Promise(r=>{process.nextTick(()=>{try{let i=n.release().split(`.`).map(Number),o=i[0]<10?[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,`-`]:[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,T+e],s=a(w,o,{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})});if(s&&!s.pid&&s.on(`error`,()=>{r(t)}),s&&s.pid){if(s.stdout.on(`data`,e=>{t+=e.toString(`utf8`)}),s.stderr.on(`data`,()=>{s.kill(),r(t)}),s.on(`close`,()=>{s.kill(),r(t)}),s.on(`error`,()=>{s.kill(),r(t)}),i[0]<10)try{s.stdin.write(T+e+n.EOL),s.stdin.write(`exit`+n.EOL),s.stdin.end()}catch{s.kill(),r(t)}}else r(t)}catch{r(t)}})})}}function Ee(e,t,n){let r=``;return n||={},new Promise(i=>{process.nextTick(()=>{try{let o=a(e,t,n);o&&!o.pid&&o.on(`error`,()=>{i(r)}),o&&o.pid?(o.stdout.on(`data`,e=>{r+=e.toString()}),o.on(`close`,()=>{o.kill(),i(r)}),o.on(`error`,()=>{o.kill(),i(r)})):i(r)}catch{i(r)}})})}function De(){if(d){if(!g)try{let e=s(`chcp`,A).toString().split(`\r
77
77
  `)[0].split(`:`);g=e.length>1?e[1].replace(`.`,``).trim():``}catch{g=`437`}return g}if(l||u||f||p||m){if(!g)try{let e=s(`echo $LANG`,j).toString().split(`\r
78
78
  `)[0].split(`.`);g=e.length>1?e[1].trim():``,g||=`UTF-8`}catch{g=`UTF-8`}return g}}function Oe(){if(_!==null)return _;if(_=!1,d)try{let e=s(`WHERE smartctl 2>nul`,A).toString().split(`\r
@@ -141,8 +141,8 @@ Profile on interface`)}catch(e){return e.status===1&&e.stdout.includes(`AutoConf
141
141
  `),a=(n&&n[0]?n[0]:``).split(` via `);a&&a[1]&&(a=a[1].split(` `),i=a[0]),e&&e(i),t(i)}})}catch{e&&e(i),t(i)}if(d){let n=`route -n get default`;try{r(n,{maxBuffer:104857600},(a,o)=>{if(!a){let e=o.toString().split(`
142
142
  `).map(e=>e.trim());i=c.getValue(e,`gateway`)}i?(e&&e(i),t(i)):(n=`netstat -rn | awk '/default/ {print $2}'`,r(n,{maxBuffer:104857600},(n,r)=>{i=r.toString().split(`
143
143
  `).map(e=>e.trim()).find(e=>/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)),e&&e(i),t(i)}))})}catch{e&&e(i),t(i)}}if(f)try{r(`netstat -r`,c.execOptsWin,(r,a)=>{a.toString().split(n.EOL).forEach(e=>{if(e=e.replace(/\s+/g,` `).trim(),e.indexOf(`0.0.0.0 0.0.0.0`)>-1&&!/[a-zA-Z]/.test(e)){let t=e.split(` `);t.length>=5&&t[t.length-3].indexOf(`.`)>-1&&(i=t[t.length-3])}}),i?(e&&e(i),t(i)):c.powerShell(`Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' }`).then(n=>{let r=n.toString().split(`\r
144
- `);r.length>1&&!i&&(i=c.getValue(r,`NextHop`),e&&e(i),t(i))})})}catch{e&&e(i),t(i)}})})}t.networkGatewayDefault=ye})),Cb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getNetworkData=void 0;var t=Sb();function n(){return new Promise(e=>{(0,t.networkStats)().then(e).catch(()=>{e([])})})}e.getNetworkData=n})),wb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=void 0;var t=vb(),n=yb(),r=bb(),i=Cb();e.HostMetrics=class extends t.BaseMetrics{_batchUpdateCpuUsages(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._cpuTime,i.user,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.system,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.idle,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.interrupt,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.nice,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.userP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.systemP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.idleP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.interruptP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.niceP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber})}}_batchUpdateProcessCpuUsages(e,t){e.observe(this._processCpuTime,t.user,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuTime,t.system,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM}),e.observe(this._processCpuUtilization,t.userP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuUtilization,t.systemP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM})}_batchUpdateMemUsages(e,t){e.observe(this._memoryUsage,t.used,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUsage,t.free,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE}),e.observe(this._memoryUtilization,t.usedP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUtilization,t.freeP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE})}_batchUpdateProcessMemUsage(e,t){e.observe(this._processMemoryUsage,t)}_batchUpdateNetworkData(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._networkDropped,i.rx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkDropped,i.tx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkErrors,i.rx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkErrors,i.tx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkIo,i.rx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkIo,i.tx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT})}}_createMetrics(){let e=[],t=!this._metricGroups||this._metricGroups.includes(`system.cpu`),a=!this._metricGroups||this._metricGroups.includes(`system.memory`),o=!this._metricGroups||this._metricGroups.includes(`system.network`),s=!this._metricGroups||this._metricGroups.includes(`process.cpu`),c=!this._metricGroups||this._metricGroups.includes(`process.memory`);t&&(this._cpuTime=this._meter.createObservableCounter(n.METRIC_SYSTEM_CPU_TIME,{description:`Cpu time in seconds`,unit:`s`}),e.push(this._cpuTime),this._cpuUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_CPU_UTILIZATION,{description:`Cpu usage time 0-1`}),e.push(this._cpuUtilization)),a&&(this._memoryUsage=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_USAGE,{description:`Memory usage in bytes`}),e.push(this._memoryUsage),this._memoryUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_UTILIZATION,{description:`Memory usage 0-1`}),e.push(this._memoryUtilization)),o&&(this._networkDropped=this._meter.createObservableCounter(`system.network.dropped`,{description:`Network dropped packets`}),e.push(this._networkDropped),this._networkErrors=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_ERRORS,{description:`Network errors counter`}),e.push(this._networkErrors),this._networkIo=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_IO,{description:`Network transmit and received bytes`}),e.push(this._networkIo)),s&&(this._processCpuTime=this._meter.createObservableCounter(n.METRIC_PROCESS_CPU_TIME,{description:`Process Cpu time in seconds`,unit:`s`}),e.push(this._processCpuTime),this._processCpuUtilization=this._meter.createObservableGauge(n.METRIC_PROCESS_CPU_UTILIZATION,{description:`Process Cpu usage time 0-1`}),e.push(this._processCpuUtilization)),c&&(this._processMemoryUsage=this._meter.createObservableGauge(n.METRIC_PROCESS_MEMORY_USAGE,{description:`Process Memory usage in bytes`}),e.push(this._processMemoryUsage)),this._meter.addBatchObservableCallback(async e=>{if(t){let t=(0,r.getCpuUsageData)();this._batchUpdateCpuUsages(e,t)}if(a){let t=(0,r.getMemoryData)();this._batchUpdateMemUsages(e,t)}if(s){let t=(0,r.getProcessCpuUsageData)();this._batchUpdateProcessCpuUsages(e,t)}if(c){let t=(0,r.getProcessMemoryData)();this._batchUpdateProcessMemUsage(e,t)}if(o){let t=await(0,i.getNetworkData)();this._batchUpdateNetworkData(e,t)}},e)}start(){this._createMetrics()}_cpuTime;_cpuUtilization;_memoryUsage;_memoryUtilization;_processCpuTime;_processCpuUtilization;_processMemoryUsage;_networkDropped;_networkErrors;_networkIo}})),Tb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=e.BaseMetrics=void 0;var t=vb();Object.defineProperty(e,"BaseMetrics",{enumerable:!0,get:function(){return t.BaseMetrics}});var n=wb();Object.defineProperty(e,"HostMetrics",{enumerable:!0,get:function(){return n.HostMetrics}})}));u();var Eb=ab(),Db=Tb();m(),jc();var Ob=`aventure-mcp-server`,kb=`http_server_requests_seconds`,Ab=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],jb,Mb,Nb,Pb,Fb;function Ib(e,t){if(Mb!==void 0)return;let n=e?new Eb.PrometheusExporter({preventServerStart:!0}):void 0,r=new Oc({resource:S({...ce(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??Pi().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new Zo({exporter:new gb({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});s.setGlobalMeterProvider(r),Mb=r,jb=n;let i=new Db.HostMetrics({meterProvider:r,name:Ob});i.start(),Fb=i}function Lb(){return Nb===void 0&&(Nb=Mb?.getMeter(Ob)),Nb}function Rb(e,t,n,r,{rpcMethod:i,toolName:a,client:o,outcome:s}){let c=Lb();c!==void 0&&(Pb===void 0&&(Pb=c.createHistogram(kb,{description:`HTTP server request latency in seconds, partitioned by method/route/status/rpc_method/tool/client/outcome.`,unit:`s`,advice:{explicitBucketBoundaries:Ab}})),Pb.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n),rpc_method:i,tool:a,client:o,outcome:s}))}function zb(e,t){let n=Pi().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Ib(n,r);let i=jb;if(!n||t===void 0||i===void 0)return;let a=ia(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!Vb(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function Bb(){let e=Mb;Fb!==void 0&&(Fb=void 0),Mb=void 0,jb=void 0,Nb=void 0,Pb=void 0,e!==void 0&&await e.shutdown()}function Vb(e,t){let n=Mr(e);if(n===void 0)return!1;let r=ia(`sha256`).update(n).digest();return r.length===t.length&&oa(r,t)}var Hb=`#/components/schemas/`,Ub=/"#\/components\/schemas\/([^"]+)"/g,Wb=-32011,Gb=-32012,Kb=-32013,qb=-32015;function Jb(e){let t=Ct().components.schemas[e];if(t===void 0)throw Error(`OpenAPI has no component ${e}`);return t}function Yb(e){let t=ve(e?.content?.[`application/json`]?.schema);return t===void 0?void 0:Jb(t)}function Xb(e){let t=Object.keys(e).length===1?ve(e):void 0,n=t===void 0?e:Jb(t),r={},i=e=>{for(let[,t]of JSON.stringify(e).matchAll(Ub))t===void 0||t in r||(r[t]=Jb(t),i(r[t]))};i(n);let a=Object.keys(r).length===0?n:{...n,$defs:r},o=ji.safeParse(JSON.parse(JSON.stringify(a).replaceAll(`"${Hb}`,`"#/$defs/`)));if(!o.success)throw Error(`Event schema is not JSON: ${o.error}`);return o.data}function Zb(e,t){let n=Object.entries(Ct().paths).find(([,n])=>Yb(n[e]?.requestBody)?.properties?.name?.$ref===t);if(n===void 0)throw Error(`OpenAPI has no ${e} operation for ${t}`);return n[0]}var Qb=new Map(Object.entries(Ct().webhooks??{}).map(([e,t])=>{let n=Yb(t.post.requestBody),r=n?.properties?.name?.$ref,i=n?.properties?.data;if(r===void 0||i===void 0)throw Error(`Webhook ${e} body must carry a name enum $ref and a data schema`);let a=Zb(`put`,r),o=Yb(Ct().paths[a]?.put?.requestBody)?.properties?.arguments;if(o===void 0)throw Error(`Subscribe body for ${e} must carry an arguments schema`);return[e,{descriptor:{name:e,description:t.post.description,delivery:[`webhook`],inputSchema:Xb(o),payloadSchema:Xb(i)},subscribePath:a,unsubscribePath:Zb(`delete`,r)}]})),$b=G({name:W()}).catchall(ji),ex=F(W(),ji);function tx(e){let t=Qb.get(e);if(t===void 0)throw new Z(Wb,`Unknown event ${e}`);return t}async function nx(e,t,n){let{_meta:r,...i}=n,a=await Vt({method:e,path:t,body:i,auth:`auto`});if(a.ok){let e=ex.safeParse(a.data!==null&&typeof a.data==`object`&&`response`in a.data?a.data.response??{}:{});if(e.success)return e.data;throw new Z(X.InternalError,`${t} answered a non-object body`)}let o=rx(a.problem?.code);throw o===void 0?a.problem?.code===`news_subscription_limit`?new Z(Kb,a.summary,{limit:`subscriptions`}):new Z(ix(a.httpStatus),a.summary,a.problem):new Z(qb,`CallbackEndpointError`,{reason:o})}function rx(e){switch(e){case`callback_connection_refused`:return`connection_refused`;case`callback_timeout`:return`timeout`;case`callback_tls_error`:return`tls_error`;case`callback_http_4xx`:return`http_4xx`;case`callback_http_5xx`:return`http_5xx`;case`callback_challenge_failed`:return`challenge_failed`;default:return}}function ix(e){switch(e){case 400:case 422:return X.InvalidParams;case 401:case 403:return Gb;case 404:return Wb;default:return X.InternalError}}function ax(e){if(Qb.size===0)return;let t=[...Qb.values()].map(e=>e.descriptor);e.server.setRequestHandler(`events/list`,{params:G({})},()=>({events:t})),e.server.setRequestHandler(`events/subscribe`,{params:$b},e=>nx(`PUT`,tx(e.name).subscribePath,e)),e.server.setRequestHandler(`events/unsubscribe`,{params:$b},e=>nx(`DELETE`,tx(e.name).unsubscribePath,e))}async function ox(e){try{return await Vt(e)}catch(t){return N({component:`aventure-mcp-server`,event:`tool_request_failed`,fields:{requestId:_e(),method:e.method},error:t}),Ai(le(t))}}function sx(e,t){let n=Ee(e.requestBody??[],t.contentType).data;return[...e.parameter.filter(e=>e.in===`query`).map(e=>({parameter:e,label:`Query parameter`,sent:[e.name,e.legacyName].flatMap(e=>e===void 0?[]:[t.query?.[e]])})),...(n?.parameter??[]).map(e=>({parameter:e,label:`Body field`,sent:lx(t.body,e.name.split(`.`))}))].flatMap(({parameter:{name:e,schemaEnum:t,itemSchemaEnum:n,enumOpen:r},label:i,sent:a})=>{let o=r===!0?[]:t??n??[],s=new Set(o.map(cx)),c=i===`Query parameter`&&n!==void 0,l=a.flatMap(e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?c?e.split(`,`).map(e=>e.trim()):[e]:[]).filter(e=>!s.has(cx(e)));return o.length===0||l.length===0?[]:[` ${i} '${e}' does not accept ${l.map(e=>JSON.stringify(e)).join(`, `)}; send one of ${o.join(`, `)}.`]}).join(``)}var cx=e=>e.toLowerCase().replaceAll(/[^\p{L}\p{N}]/gu,``);function lx(e,t){let[n,...r]=t;if(e===void 0)return[];if(n===void 0)return[e];if(typeof e!=`object`||!e||Array.isArray(e))return[];if(!n.endsWith(`[]`))return lx(e[n],r);let i=e[n.slice(0,-2)];return Array.isArray(i)?i.flatMap(e=>lx(e,r)):[]}var ux=3,dx=200,fx=80;function px(e,t){let{operationId:n}=e;if(n===void 0)return null;let r=t.find(e=>e.operationId===n);if(r!==void 0)return mx(r,e,t);let i=yx(n,t),a=Ki(i.noun),o=xx(e),s=Ui([...a,...o.flatMap(({word:e})=>e)].join(` `),t,zi).map(({item:e,score:t})=>({item:e,score:t+bx(e,a,o.map(({key:e})=>e))})).toSorted((e,t)=>Number(e.item.deprecated===!0)-Number(t.item.deprecated===!0)||Number(i.intent.has(t.item.intent))-Number(i.intent.has(e.item.intent))||Number(i.method.has(t.item.method))-Number(i.method.has(e.item.method))||t.score-e.score).slice(0,ux).map(({item:e})=>Ri(e,!1)),c=s.map(e=>`${e.operationId} (${e.method} ${e.path})`);return Ai(`Operation ${n} is not in the MCP catalog.${c.length===0?``:` Closest operations: ${c.join(`, `)}.`}`,s.map(e=>`Use operationId ${e.operationId} with aventure_${e.intent}: ${e.method} ${e.path}; required inputs: ${e.requiredInput.length===0?`none`:e.requiredInput.join(`, `)}.`))}function mx(e,t,n){let r=t.pathParams??{},i=e.parameter.filter(({in:e,required:t,name:n,legacyName:i})=>e===`path`&&t&&r[n]==null&&(i===void 0||r[i]==null));if(i.length===0)return null;let a=new Set(e.parameter.filter(({in:e})=>e===`query`).flatMap(({name:e,legacyName:t})=>t===void 0?[e]:[e,t])),o=Object.fromEntries(i.flatMap(e=>{let n=[e.name,e.legacyName].find(e=>e!==void 0&&!a.has(e)&&t.query?.[e]!=null),r=n===void 0?void 0:t.query?.[n];return hx(e,r)?[[e.name,r]]:[]})),s=i.map(({name:e})=>e).filter(e=>!(e in o)),c=Object.entries(t.query??{}).filter(([e])=>a.has(e)||!i.some(({name:t,legacyName:n})=>e===t||e===n)),l=JSON.stringify({operationId:e.operationId,pathParams:{...r,...o,...Object.fromEntries(s.map(e=>[e,`<${e}>`]))},...c.length===0?{}:{query:Object.fromEntries(c)}}),u=s.flatMap(t=>gx(e.path,t,n).map(e=>{let n=e.parameter.filter(e=>e.in===`query`&&e.schemaEnum===void 0),r=n.filter(e=>e.required),i=r.length>0?r:n.filter(e=>e.schemaType===`string`&&e.name!==`cursor`).slice(0,1),a=n.filter(e=>e.schemaType===`string`);return` Get ${t} from ${e.operationId} (${e.method} ${e.path}): aventure_${e.intent} ${JSON.stringify({operationId:e.operationId,...i.length===0?{}:{query:Object.fromEntries(i.map(e=>[e.name,`<${e.name}>`]))}})} returns the record whose id goes in pathParams.${t}${a.length===0?``:`; its query takes ${a.map(e=>e.name).join(`, `)}`}.`}));return Ai(`Missing path parameter${i.length===1?``:`s`} ${i.map(({name:e})=>`'${e}'`).join(`, `)} for ${e.operationId}. Path parameters go in pathParams: aventure_${e.intent} ${l}.${u.join(``)}`)}function hx(e,t){return e.schemaType===`integer`?typeof t==`number`&&Number.isInteger(t):e.schemaType===`number`?typeof t==`number`&&Number.isFinite(t):typeof t==`string`&&t.length>0}function gx(e,t,n){let r=`{${t}}`,i=e.slice(0,e.indexOf(r)+r.length),a=n.find(e=>e.method===`GET`&&e.path===i),o=a===void 0?void 0:vx(a);return o===void 0?[]:n.filter(e=>e.method===`GET`&&e.deprecated!==!0&&e.parameter.every(e=>e.in!==`path`)&&vx(e)===o).toSorted((e,t)=>Number(_x(t))-Number(_x(e)))}function _x(e){return e.intent===`lookup`||/lookup/iu.test(e.operationId)}function vx(e){let t=Te(Ct().paths,e.operationId)?.operation.responses??{},n=new Set(Object.entries(t).filter(([e])=>e.startsWith(`2`)).map(([,e])=>e.content?.[`application/json`]?.schema?.$ref));return n.size===1?[...n][0]:void 0}function yx(e,t){let[n=``,...r]=Ji(e).split(` `),i=t.filter(e=>Ji(e.operationId).startsWith(`${n} `));return i.length>0&&r.length>0?{noun:r.join(` `),intent:new Set(i.map(e=>e.intent)),method:new Set(i.map(e=>e.method))}:{noun:e,intent:new Set,method:new Set}}function bx(e,t,n){let r=`${e.operationId} ${e.summary}`,i=new Set(Ki(r)),a=Li(Ji(r)),o=t.reduce((e,t)=>e+(i.has(t)?2:+!!a.has(t)),0),s=new Set([...e.parameter,...(e.requestBody??[]).flatMap(e=>e.parameter)].map(({name:e})=>e)),c=n.filter(e=>s.has(e)).length,l=Li(t.join(` `)),u=Ki(e.operationId).slice(1).filter(e=>!l.has(e)).length;return(o+2*c-u)*fx}function xx(e){let t=e.body,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.entries(t):[];return[...Object.entries(e.pathParams??{}),...Object.entries(e.query??{}),...n].map(([e,t])=>({key:e,word:typeof t==`string`&&t.length<=dx?[e,t]:[e]}))}function Sx({contract:e,input:t,intent:n,contracts:r,catalog:i}){let{operationId:a}=e;if(!n.includes(e.intent))return Ai(`Operation ${a} has intent=${e.intent}; call aventure_${e.intent} ${JSON.stringify({operationId:a,pathParams:t.pathParams,query:t.query,body:t.body})}.`);let o=i.find(e=>e.operationId===a)??e,s=o.parameter.filter(e=>e.in===`query`),c=Object.entries(t.query??{}),l=c.filter(([e])=>!Nt.includes(e)&&!s.some(t=>Cx(t,e))),u=e.parameter.filter(e=>e.in===`query`),d=u.map(({name:e})=>e),f=e.requestBody??[],p=f[0]?.schemaType===`array`,m=new Set((o.requestBody??[]).flatMap(e=>e.parameter.map(({name:e})=>e))),h=p?[]:l.filter(([e])=>m.has(e)),g=new Map(l.flatMap(([e])=>{let t=u.filter(t=>wx(t,e)),n=d.find(t=>cx(t)===cx(e))??(t.length===1?t[0]?.name:void 0);return n===void 0||h.some(([t])=>t===e)?[]:[[e,n]]})),_=l.filter(([e])=>!g.has(e)&&!h.some(([t])=>t===e)),v=t.body===void 0&&f.some(e=>e.required&&e.kind!==`multipart`),y=sx(o,t);if(l.length===0&&!v)return y===``?null:Ai(y.trim());let b=typeof t.body==`object`&&t.body!==null&&!Array.isArray(t.body)?t.body:void 0,x=f[0]?.parameter??[],S=v?x.filter(({name:e,required:t})=>t&&!h.some(([t])=>t===e)).map(({name:e})=>e):[],C=p||t.body!==void 0&&b===void 0?t.body??[]:{...Object.fromEntries(S.map(e=>[e,`<${e}>`])),...b,...Object.fromEntries(h)},w=c.flatMap(([e,t])=>{let n=l.some(([t])=>t===e)?g.get(e):e;return n===void 0?[]:[[n,t]]}),T=JSON.stringify({operationId:a,...t.pathParams===void 0?{}:{pathParams:t.pathParams},...w.length===0?{}:{query:Object.fromEntries(w)},...f.length===0?{}:{body:C}}),E=l.length===0?``:`${a} declares no query parameter ${Dx(l)}; ${d.length===0?`it takes no query`:`its query takes ${d.join(`, `)}`}.${[...g].map(([e,t])=>` Send '${e}' as '${t}'.`).join(``)}${_.length===0?``:` The call below removes ${Dx(_)}: no declared filter matches ${_.length===1?`it`:`them`}.`}`,D=h.length>0?` ${Dx(h)} ${h.length===1?`is a request body field`:`are request body fields`}: send ${h.length===1?`it`:`them`} in body.`:v?` ${a} requires a request body: send it in body${x.length===0?``:`; its fields are ${x.map(({name:e})=>e).join(`, `)}`}.`:``;return Ai(`${E}${D}${y} Call aventure_${e.intent} ${T}.${Ox(e,r)}`.trim())}function Cx(e,t){if(t===e.name||t===e.legacyName)return!0;let n=Number(/^\[(?<index>\d+)\]/u.exec(t.slice(e.name.length))?.groups?.index),r=Ii(e.name,0,``);return t.startsWith(e.name)&&Number.isInteger(n)&&(e.itemProperty??[]).some(i=>t===Ii(e.name,n,i.name.slice(r.length)))}function wx(e,t){let[n=``]=e.description.split(/(?<=\.)\s/u),r=new Set(Ki(`${e.name} ${n}`)),i=Ki(t);return i.length>=Tx&&i.at(-1)===Ki(e.name).at(-1)&&i.every(e=>r.has(e))}var Tx=3,Ex=/\b(?<method>GET|POST|PUT|PATCH|DELETE) (?<path>\/[^\s?),]*[^\s?),.])/u;function Dx(e){return e.map(([e])=>`'${e}'`).join(`, `)}function Ox(e,t){if(e.deprecated!==!0)return``;let n=/^Deprecated: (?<advice>.*?\.)(?=\s|$)/su.exec(e.description)?.groups?.advice;if(n===void 0)return` ${e.operationId} is deprecated.`;let r=Ex.exec(n)?.groups,i=t.find(e=>e.method===r?.method&&e.path===r?.path);return` ${e.operationId} is deprecated: ${n}${i===void 0?``:` Its replacement is ${i.operationId}: call aventure_${i.intent} {"operationId":"${i.operationId}"}.`}`}function kx(e,t){return t?e:e.map(Ax)}function Ax(e){let t=e.parameter.flatMap(Mx),n=jx(e.requestBody);return Px(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function jx(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Mx);return Px(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Mx(e){if(!Nx(e))return[];let t=e.itemProperty?.filter(Nx);return Px(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Nx=e=>e.visibility!==`private`;function Px(e,t){return e===t?!0:e?.length!==t?.length||e===void 0||t===void 0?!1:e.every((e,n)=>e===t[n])}new RegExp(oe.join(`|`),`i`);var Fx;function Ix(e,t){let n=Fx??=Gi([...Yi,...Xi]),r=Wi(e,n),i=Lx(Mi(e,r)),a=t===`json`?JSON.stringify(Lx(Mi(e,{...r,maxBytes:qi}))):Vi(n,i.data,i.summary)??JSON.stringify(i);return{isError:!i.ok,structuredContent:i,content:[{type:`text`,text:a}]}}function Lx(e){let{omitted:t,ids:n,counts:r,references:i,warnings:a,...o}=e;return{...o,...t.length>0?{omitted:t}:{},...n.length>0?{ids:n}:{},...Object.keys(r).length>0?{counts:r}:{},...i.length>0?{references:i}:{},...a.length>0?{warnings:a}:{}}}var Rx=`aventure_help`,zx=`aventure_read`,Bx=`aventure_lookup`,Vx=`aventure_search`,Hx=`aventure_job`,Ux=[Rx,zx,Bx,Vx,Hx],Wx=I([W(),U(),H()]),Gx=F(W(),I([W(),U()])).optional(),Kx=F(W(),I([Wx,B(Wx)])).optional(),qx=F(W(),W()).optional(),Jx=V([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Yx=I([Wx,Ve(),B(Me()),F(W(),Me())]).optional().describe(`JSON request body. For multipart/form-data operations, pass an object keyed by form part name; binary part values are http(s) URLs.`),Xx=G({operationId:W().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Jx.optional().describe(`HTTP method when resolving by method+path.`),path:W().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Gx.describe(`Values for route template parameters.`),query:Kx.describe(`Query parameters.`),headers:qx.describe(`Headers declared by the selected OpenAPI operation.`),contentType:W().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:V([`auto`,`json`]).optional().describe(`Omit for the default: readable text, from the operation's own text/plain rendering when aventure_help lists text/plain in responseContentType, otherwise from its JSON. json returns the JSON result envelope.`)}),Zx=G({q:W().optional().describe(`Plain-English task text, ranked against operationId, path, CLI command, summary, description, and query-parameter enum values. This tool reads no argument named query. Omitting q returns the catalog head unranked.`),root:He(e=>typeof e==`string`?e.trim().toLowerCase()||void 0:e,V([...new Set(Yi.flatMap(e=>[e.resource,...e.projection.cliPath.slice(0,1)]))].sort()).optional()).describe(`Filter by resource or first CLI segment.`),method:Jx.optional().describe(`Filter by HTTP method.`),limit:ze().min(1).max(100).default(20).describe(`Maximum rows to return. Set q to the chosen operationId and limit to 1 for argument types, enum choices, and defaults.`),resolve:H().default(!1).describe(`Resolve q to one operation with the server resolver (requires sign-in): operation advice with an mcpCall skeleton, a clarification between candidate operations, or an abstention. Root, method, and limit do not apply.`)}),Qx=Xx.extend({body:Yx}),$x=(e,t)=>kx(Yi,t?.operationAccess===`ADMIN`||t===void 0&&e===`write`).filter(n=>(t===void 0?e===`write`||n.projection.scope===`read`&&(n.projection.auth===`read`||n.projection.auth===`none`):t.operationAccess!==`READ`||n.projection.scope===`read`||n.projection.visibility!==`private`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function eS(e,t,n,r,i,a){let o=px(e,r)??Lt(e);if(!o.ok)return Ai(o.summary,o.warnings);if(o.data===null)return Ai(`OpenAPI operation resolution returned no data.`);let{method:s,operation:c,path:l,template:u}=o.data,d=c.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===s&&e.path===u);if(f===void 0)return Ai(`Operation `+d+` is not in the MCP catalog.`);let p=Sx({contract:f,input:e,intent:t,contracts:r,catalog:Yi});if(p!==null)return p;let m=Ee(f.requestBody??[],e.contentType);if(!m.ok||m.data===null)return Ai(m.summary,m.warnings);let h=m.data;return f.intent===`delete`&&h===void 0&&e.body!==void 0?Ai(d+` does not accept a request body.`):await ox({method:f.method,path:l,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i,signal:a})}function tS(e,t,n){let r=$x(t,n),i=()=>e.server.getClientVersion();e.registerTool(Rx,{title:`aVenture help`,annotations:{readOnlyHint:!0},description:`Lists the aVenture operations, each with the tool that runs it and the inputs it accepts. Pass q with a plain-English task to rank them. After choosing one, set q to its operationId and limit to 1 to see its full inputs, allowed values, and defaults. Set resolve to have the server pick one operation for q and return the call to make.`,inputSchema:Zx},async(e,n)=>{if(e.resolve)return Ix(await Bi(e,r,Yi,(e,r)=>ox({method:e.method,path:Je(e.operationId,{}),body:r.body,auth:e.projection.auth,requesterScope:t,responseFormat:`json`,clientInfo:i(),signal:n?.mcpReq.signal})));let{summary:a,data:o,counts:s}=Hi(e,r);return Ix(Ni(a,o,{counts:s}))}),e.registerTool(zx,{title:`aVenture read`,annotations:{readOnlyHint:!0},description:`Runs one catalog operation whose intent is read: fetch a record by id or slug, list the records attached to it, or list a collection. Put route values in pathParams and URL query values in query. Example for an aventure.vc profile URL, slug, website, or domain: {"operationId":"getEntityLookup","query":{"url":"https://aventure.vc/investors/firms/<slug>"}}. When a read's newsArticle (or listNews or a web source) reports a newer funding round, investor, role, or detail not yet reflected in the structured fields, report both and ask the user whether to request a record update with aventure_job (enrichEntity or enrichPerson). Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`read`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Bx,{title:`aVenture lookup`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is lookup: identify a record from a name plus clues (such as lookupRecord), resolve a ticker or other identifier, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON body. An exact aventure.vc profile URL, slug, website, or domain is a read, not a lookup: call aventure_read with operationId getEntityLookup (or getPersonLookup) and query {url} or {slug}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`lookup`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Vx,{title:`aVenture search`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is search: search or filter companies, people, news, publications, content, links, or the web, or answer a question. It has no free-text argument of its own: pass search text and filters where the chosen operation declares them, in query or body. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`search`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),r.some(e=>e.intent===`job`)&&e.registerTool(Hx,{title:`aVenture job`,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is job: request a research job that deepens or updates aVenture's data on a company or person (enrichEntity, enrichPerson, createResearchRun, enrichRecords), or a lookup job that identifies the companies and people an article names. When an indexed aVenture news article (newsArticle or listNews) or web source reports a newer or missing detail—such as a funding round, investor, role, or URL—not yet reflected in the structured profile, ask the user if they would like to request an update to the aVenture record; on confirmation, call enrichEntity, enrichPerson, or createResearchRun with body.finding (statement, sourceUrl, verbatim quote from an external page you read for an entity) or body.userPrompt (the observed detail and sourceUrl or newsUrlOriginal). Returns the run or job to poll with aventure_read. A research run costs one research unit only when it saves research, and a record already being researched returns that run instead of starting another. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`job`],t,r,i(),n?.mcpReq.signal),e.responseFormat))}var nS=Pi().version,rS={tools:{},events:{}};function iS(e,t){let n=Ct().info?.description,r=new ry({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:nS,websiteUrl:M,icons:[{src:`${M}/apple-touch-icon.png`,mimeType:`image/png`,sizes:[`180x180`]}]},{capabilities:rS,...n===void 0?{}:{instructions:n}});return tS(r,e,t),ax(r),r}var aS=new Set([...Bn.options,...bi.options].map(e=>e.shape.method.value)),oS=new Set(Ux);function sS(e){let t=typeof e==`object`&&e?Reflect.get(e,`method`):void 0,n=typeof e==`object`&&e?Reflect.get(e,`params`):void 0,r=typeof n==`object`&&n?Reflect.get(n,`name`):void 0;return{rpcMethod:typeof t==`string`&&aS.has(t)?t:`other`,toolName:typeof r==`string`&&oS.has(r)?r:`none`}}var cS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),lS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isHostInSubnet=r,e.isGloballyReachable=i,e.offsetBigInt=a,e.isCorrect=o,e.prefixLengthFromMask=s,e.assertByteArray=c,e.numberToPaddedHex=l,e.stringToPaddedHex=u,e.testBit=d;var t=cS();function n(e){return this.subnetMask<e.subnetMask?!1:r.call(this,e)}function r(e){return this.binaryZeroPad().length===e.binaryZeroPad().length&&this.mask(e.subnetMask)===e.mask()}function i(e){let t=null;for(let n=0;n<e.length;n++){let i=e[n];i.reachable!==null&&r.call(this,i.subnet)&&(t===null||i.subnet.subnetMask>t.subnet.subnetMask)&&(t=i)}return t===null||t.reachable}function a(e,n,r,i){if(typeof n==`number`&&!Number.isSafeInteger(n)||typeof n!=`number`&&typeof n!=`bigint`)throw new t.AddressError(`${i} offset must be an integer`);let a=e+BigInt(n);if(a<BigInt(0)||a>(BigInt(1)<<BigInt(r))-BigInt(1))throw new t.AddressError(`${i} offset leaves the address space`);return a}function o(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function s(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function c(e,n,r,i){if(e.length!==n)throw new t.AddressError(`${r} addresses require exactly ${n} bytes`);for(let n=0;n<e.length;n++)if(!Number.isInteger(e[n])||e[n]<i||e[n]>255)throw new t.AddressError(`All bytes must be integers between ${i} and 255`)}function l(e){return e.toString(16).padStart(2,`0`)}function u(e){return l(parseInt(e,10))}function d(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),uS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/,e.SPECIAL_PURPOSE=[[`0.0.0.0/8`,`This network`,!1],[`0.0.0.0/32`,`This host on this network`,!1],[`10.0.0.0/8`,`Private-Use`,!1],[`100.64.0.0/10`,`Shared Address Space`,!1],[`127.0.0.0/8`,`Loopback`,!1],[`169.254.0.0/16`,`Link Local`,!1],[`172.16.0.0/12`,`Private-Use`,!1],[`192.0.0.0/24`,`IETF Protocol Assignments`,!1],[`192.0.0.0/29`,`IPv4 Service Continuity Prefix`,!1],[`192.0.0.8/32`,`IPv4 dummy address`,!1],[`192.0.0.9/32`,`Port Control Protocol Anycast`,!0],[`192.0.0.10/32`,`Traversal Using Relays around NAT Anycast`,!0],[`192.0.0.170/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.0.171/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.2.0/24`,`Documentation (TEST-NET-1)`,!1],[`192.31.196.0/24`,`AS112-v4`,!0],[`192.52.193.0/24`,`AMT`,!0],[`192.88.99.0/24`,`Deprecated (6to4 Relay Anycast)`,null],[`192.88.99.2/32`,`6a44-relay anycast address`,!1],[`192.168.0.0/16`,`Private-Use`,!1],[`192.175.48.0/24`,`Direct Delegation AS112 Service`,!0],[`198.18.0.0/15`,`Benchmarking`,!1],[`198.51.100.0/24`,`Documentation (TEST-NET-2)`,!1],[`203.0.113.0/24`,`Documentation (TEST-NET-3)`,!1],[`240.0.0.0/4`,`Reserved`,!1],[`255.255.255.255/32`,`Limited Broadcast`,!1]]})),dS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;var i=r(lS()),a=r(uS()),o=cS(),s=i.isCorrect(a.BITS),c=class e{constructor(e){this.addressMinusSuffix=``,this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}let n=a.GROUPS*4-1;if(e.length>n)throw new o.AddressError(`IPv4 addresses are at most ${n} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(t.some(e=>/^0\d/.test(e)))throw new o.AddressError(`IPv4 addresses can't have leading zeroes.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.?$/i,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<BigInt(0)||t>BigInt(4294967295))throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){return i.assertByteArray(e,4,`IPv4`,0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(l)}isPrivate(){return u.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(d)}isLinkLocal(){return this.isHostInSubnet(f)}isUnspecified(){return this.isHostInSubnet(p)}isBroadcast(){return this.isHostInSubnet(m)}isCGNAT(){return this.isHostInSubnet(h)}isDocumentation(){return g.some(e=>this.isHostInSubnet(e))}isBenchmarking(){return this.isHostInSubnet(_)}isReserved(){return this.isHostInSubnet(v)}isGlobal(){return!this.isMulticast()&&i.isGloballyReachable.call(this,y)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;var l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`),g=[new c(`192.0.2.0/24`),new c(`198.51.100.0/24`),new c(`203.0.113.0/24`)],_=new c(`198.18.0.0/15`),v=new c(`240.0.0.0/4`),y=a.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new c(e),reachable:t}))})),fS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"::ffff:0:0/96":`IPv4-mapped`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2001::/32":`Teredo`,"2001:2::/48":`Benchmarking`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"3fff::/20":`Documentation`,"100::/64":`Discard-only`,"fec0::/10":`Site-local unicast (deprecated)`,"::/96":`IPv4-compatible (deprecated)`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i,e.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i,e.SPECIAL_PURPOSE=[[`::1/128`,`Loopback Address`,!1],[`::/128`,`Unspecified Address`,!1],[`::ffff:0:0/96`,`IPv4-mapped Address`,!1],[`64:ff9b::/96`,`IPv4-IPv6 Translat.`,!0],[`64:ff9b:1::/48`,`IPv4-IPv6 Translat.`,!1],[`100::/64`,`Discard-Only Address Block`,!1],[`100:0:0:1::/64`,`Dummy IPv6 Prefix`,!1],[`2001::/23`,`IETF Protocol Assignments`,!1],[`2001::/32`,`TEREDO`,!1],[`2001:1::1/128`,`Port Control Protocol Anycast`,!0],[`2001:1::2/128`,`Traversal Using Relays around NAT Anycast`,!0],[`2001:1::3/128`,`DNS-SD Service Registration Protocol Anycast`,!0],[`2001:2::/48`,`Benchmarking`,!1],[`2001:3::/32`,`AMT`,!0],[`2001:4:112::/48`,`AS112-v6`,!0],[`2001:10::/28`,`Deprecated (previously ORCHID)`,null],[`2001:20::/28`,`ORCHIDv2`,!0],[`2001:30::/28`,`Drone Remote ID Protocol Entity Tags (DETs) Prefix`,!0],[`2001:db8::/32`,`Documentation`,!1],[`2002::/16`,`6to4`,!1],[`2620:4f:8000::/48`,`Direct Delegation AS112 Service`,!0],[`3fff::/20`,`Documentation`,!1],[`5f00::/16`,`Segment Routing (SRv6) SIDs`,!1],[`fc00::/7`,`Unique-Local`,!1],[`fe80::/10`,`Link-Local Unicast`,!1]]})),pS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),mS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;var i=r(fS());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),hS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;var i=r(lS()),a=r(uS()),o=r(fS()),s=r(pS()),c=dS(),l=mS(),u=cS(),d=lS(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``));let a=this.groups*5+5;if(e.length>a)throw new u.AddressError(`IPv6 addresses are at most ${a} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<BigInt(0)||t>(BigInt(1)<<BigInt(o.BITS))-BigInt(1))throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i,a,s=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,``);if(s.indexOf(`[`)!==-1&&s.indexOf(`]:`)!==-1){if(a=`failed to parse address with port`,i=o.RE_URL_WITH_PORT.exec(s),i===null)return{error:a,address:null,port:null};n=i[1],r=i[2]}else{if(a=`failed to parse address from URL`,i=o.RE_URL.exec(s),i===null)return{error:a,address:null,port:null};n=i[1]??i[2]}r?(r=parseInt(r,10),(r<0||r>65535)&&(r=null)):r=null;let c;try{c=new e(n)}catch{return{error:a,address:null,port:null}}return{address:c,port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.?$/i,``);if(!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(n))throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse(),i=r.length*4,a=r.join(``).padEnd(32,`0`),s=[];for(let e=0;e<o.GROUPS;e++)s.push(a.slice(e*4,(e+1)*4));return new e(`${s.join(`:`)}/${i}`)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isHostInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0],r=n.split(`.`);if(r.length===a.GROUPS&&r.every(e=>/^\d{1,3}$/.test(e))&&r.some(e=>/^0\d/.test(e))){let e=r.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),i=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${i}${e}`)}let i=n.match(a.RE_ADDRESS);if(i){this.parsedAddress4=i[0];let n=this.subnetMask>=96?`/${this.subnetMask-96}`:``;this.address4=new c.Address4(`${this.parsedAddress4}${n}`),this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``),t=BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`);if(this.subnetMask>=96){let e=this.subnetMask-96,n=[];for(let e=0;e<8;e+=2)n.push(parseInt(t.slice(e,e+2),16));return new c.Address4(`${n.join(`.`)}/${e}`)}return c.Address4.fromHex(t)}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=[o.slice(0,a),s.slice(0,e),`00000000`,s.slice(e),`0`.repeat(56-(32-e))].join(``)}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isHostInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16).padStart(o.BITS/4,`0`),t=[];for(let n=0,r=e.length;n<r;n+=2)t.push(parseInt(e.substring(n,n+2),16));return t}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return i.assertByteArray(e,16,`IPv6`,-128),this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){i.assertByteArray(t,16,`IPv6`,0);let n=BigInt(`256`),r=BigInt(`0`),a=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=a*BigInt(t[e].toString(10)),a*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.isHostInSubnet(w)}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let t=this.getType();return t===`Multicast`||t.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(k)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(A)?this.to4():null}isTeredo(){return this.isHostInSubnet(x)}is6to4(){return this.isHostInSubnet(S)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()===`Loopback`}isULA(){return this.isHostInSubnet(C)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()||this.isHostInSubnet(j)}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()===`Unspecified`}isDocumentation(){return T.some(e=>this.isHostInSubnet(e))}isBenchmarking(){let e=this.embeddedIPv4();return e?e.isBenchmarking():this.isHostInSubnet(E)}isGlobal(){let e=this.embeddedIPv4();return e?e.isGlobal():this.isHostInSubnet(D)&&i.isGloballyReachable.call(this,O)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;var b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`fe80::/10`),T=[new y(`2001:db8::/32`),new y(`3fff::/20`)],E=new y(`2001:2::/48`),D=new y(`2000::/3`),O=o.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new y(e),reachable:t})),k=new y(`::ffff:0:0/96`),A=new y(`64:ff9b::/96`),j=new y(`64:ff9b:1::/48`)})),gS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=dS();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=hS();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=cS();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(pS())}}))(),_S=n(sl(),1),vS=new gS.Address6(`::/96`);function yS(e,t=56){if(ra(e)){let n=new gS.Address6(e);if(n.isMapped4()||n.is4()&&n.isInSubnet(vS))return n.to4().correctForm();if(t)return new gS.Address6(`${e}/${t}`).networkForm()}return e}var bS=class{constructor(e){this.validations=e,this.previous=new Map,this.current=new Map,this.localKeys=!0}init(e){this.windowMs=e.windowMs,this.validations?.windowMs(this.windowMs),this.interval&&clearInterval(this.interval),this.interval=setInterval(()=>{this.clearExpired()},this.windowMs),this.interval.unref?.()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){let t=this.getClient(e),n=Date.now();return t.resetTime.getTime()<=n&&this.resetClient(t,n),t.totalHits++,t}async decrement(e){let t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){if(this.current.has(e))return this.current.get(e);let t;return this.previous.has(e)?(t=this.previous.get(e),this.previous.delete(e)):(t={totalHits:0,resetTime:new Date},this.resetClient(t)),this.current.set(e,t),t}clearExpired(){this.previous=this.current,this.current=new Map}},xS={warn(...e){console.warn(...e.reverse())},error(...e){console.error(...e.reverse())}},SS=[`draft-6`,`draft-7`,`draft-8`],CS=(e,t)=>{let n;if(t){let e=Math.ceil((t.getTime()-Date.now())/1e3);n=Math.max(0,e)}else n=Math.ceil(e/1e3);return n},wS=e=>{let t=ia(`sha256`);t.update(e);let n=t.digest(`hex`).slice(0,12);return $i.from(n).toString(`base64`)},TS=(e,t)=>{e.headersSent||(e.setHeader(`X-RateLimit-Limit`,t.limit.toString()),e.setHeader(`X-RateLimit-Remaining`,t.remaining.toString()),t.resetTime instanceof Date&&(e.setHeader(`Date`,new Date().toUTCString()),e.setHeader(`X-RateLimit-Reset`,Math.ceil(t.resetTime.getTime()/1e3).toString())))},ES=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=CS(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit-Limit`,t.limit.toString()),e.setHeader(`RateLimit-Remaining`,t.remaining.toString()),typeof i==`number`&&e.setHeader(`RateLimit-Reset`,i.toString())},DS=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=CS(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit`,`limit=${t.limit}, remaining=${t.remaining}, reset=${i}`)},OS=(e,t,n,r,i)=>{if(e.headersSent)return;let a=Math.ceil(n/1e3),o=CS(n,t.resetTime),s=wS(i),c=`r=${t.remaining}; t=${o}`,l=`q=${t.limit}; w=${a}; pk=:${s}:`;e.append(`RateLimit`,`"${r}"; ${c}`),e.append(`RateLimit-Policy`,`"${r}"; ${l}`)},kS=(e,t,n,r)=>{if(e.headersSent)return;let i=r??CS(n,t.resetTime);e.setHeader(`Retry-After`,i.toString())},AS=e=>{let t={};for(let n of Object.keys(e)){let r=n;e[r]!==void 0&&(t[r]=e[r])}return t},jS=class extends Error{constructor(e,t){let n=`https://express-rate-limit.github.io/${e}/`;super(`${t} See ${n} for more information.`),this.name=this.constructor.name,this.code=e,this.help=n}},MS=class extends jS{},NS=new Set,PS=new WeakMap,FS={enabled:{default:!0},disable(){for(let e of Object.keys(this.enabled))this.enabled[e]=!1},ip(e){if(e===void 0)throw new jS(`ERR_ERL_UNDEFINED_IP_ADDRESS`,`An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`);if(!ta(e))throw new jS(`ERR_ERL_INVALID_IP_ADDRESS`,`An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`)},trustProxy(e){if(e.app.get(`trust proxy`)===!0)throw new jS(`ERR_ERL_PERMISSIVE_TRUST_PROXY`,`The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`)},xForwardedForHeader(e){if(e.headers[`x-forwarded-for`]&&e.app.get(`trust proxy`)===!1)throw new jS(`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`,`The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`)},forwardedHeader(e){if(e.headers.forwarded&&e.ip===e.socket?.remoteAddress)throw new jS(`ERR_ERL_FORWARDED_HEADER`,`The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`)},positiveHits(e){if(typeof e!=`number`||e<1||e!==Math.round(e))throw new jS(`ERR_ERL_INVALID_HITS`,`The totalHits value returned from the store must be a positive integer, got ${e}`)},unsharedStore(e){if(NS.has(e)){let t=e?.localKeys?``:` (with a unique prefix)`;throw new jS(`ERR_ERL_STORE_REUSE`,`A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`)}NS.add(e)},singleCount(e,t,n){let r=PS.get(e);r||(r=new Map,PS.set(e,r));let i=t.localKeys?t:t.constructor.name,a=r.get(i);a||(a=[],r.set(i,a));let o=`${t.prefix??``}${n}`;if(a.includes(o))throw new jS(`ERR_ERL_DOUBLE_COUNT`,`The hit count for ${n} was incremented more than once for a single request.`);a.push(o)},limit(e){if(e===0)throw new MS(`WRN_ERL_MAX_ZERO`,`Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7`)},draftPolliHeaders(e){if(e)throw new MS(`WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS`,`The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`)},onLimitReached(e){if(e)throw new MS(`WRN_ERL_DEPRECATED_ON_LIMIT_REACHED`,`The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.`)},headersDraftVersion(e){if(typeof e!=`string`||!SS.includes(e))throw new jS(`ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION`,`standardHeaders: only the following versions of the IETF draft specification are supported: ${SS.join(`, `)}.`)},headersResetTime(e){if(!e)throw new jS(`ERR_ERL_HEADERS_NO_RESET`,`standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`)},knownOptions(e){if(!e)return;let t=Object.keys({windowMs:!0,limit:!0,message:!0,statusCode:!0,legacyHeaders:!0,standardHeaders:!0,identifier:!0,retryAfter:!0,requestPropertyName:!0,skipFailedRequests:!0,skipSuccessfulRequests:!0,keyGenerator:!0,ipv6Subnet:!0,handler:!0,skip:!0,requestWasSuccessful:!0,store:!0,validate:!0,headers:!0,max:!0,passOnStoreError:!0,logger:!0}).concat(`draft_polli_ratelimit_headers`,`delayAfter`,`delayMs`,`maxDelayMs`);for(let n of Object.keys(e))if(!t.includes(n))throw new jS(`ERR_ERL_UNKNOWN_OPTION`,`Unexpected configuration option: ${n}`)},validationsConfig(){let e=Object.keys(this).filter(e=>![`enabled`,`disable`].includes(e));e.push(`default`);for(let t of Object.keys(this.enabled))if(!e.includes(t))throw new jS(`ERR_ERL_UNKNOWN_VALIDATION`,`options.validate.${t} is not recognized. Supported validate options are: ${e.join(`, `)}.`)},creationStack(e){let{stack:t}=Error(`express-rate-limit validation check (set options.validate.creationStack=false to disable)`);if(t?.includes(`Layer.handle [as handle_request]`)||t?.includes(`Layer.handleRequest`))throw e.localKeys?new jS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should be created at app initialization, not when responding to a request.`):new jS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.`)},ipv6Subnet(e){if(e!==!1&&(!Number.isInteger(e)||e<32||e>64))throw new jS(`ERR_ERL_IPV6_SUBNET`,`Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`)},ipv6SubnetOrKeyGenerator(e){if(e.ipv6Subnet!==void 0&&e.keyGenerator)throw new jS(`ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR`,`Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`)},keyGeneratorIpFallback(e){if(!e)return;let t=e.toString();if((t.includes(`req.ip`)||t.includes(`request.ip`))&&!t.includes(`ipKeyGenerator`))throw new jS(`ERR_ERL_KEY_GEN_IPV6`,`Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.`)},windowMs(e){let t=2**31-1;if(typeof e!=`number`||Number.isNaN(e)||e<1||e>t)throw new jS(`ERR_ERL_WINDOW_MS`,`Invalid windowMs value: ${e}${typeof e==`number`?``:` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`)}};function IS(e){if(typeof e!=`object`||typeof e.error!=`function`||typeof e.warn!=`function`)throw TypeError(`Provided logger does not implement the Logger interface`)}var LS=(e,t)=>{IS(t);let n;n=typeof e==`boolean`?{default:e}:{default:!0,...e};let r={enabled:n};for(let[e,i]of Object.entries(FS))typeof i==`function`&&(r[e]=(...a)=>{if(n[e]??n.default){n[e]=!1;try{i.apply(r,a)}catch(e){e instanceof MS?t.warn(e):t.error(e)}}});let i=Symbol.for(`nodejs.util.inspect.custom`);return i&&(r[i]=()=>r.enabled),r},RS=e=>typeof e.incr==`function`&&typeof e.increment!=`function`,zS=e=>{if(!RS(e))return e;let t=e;class n{async increment(e){return new Promise((n,r)=>{t.incr(e,(e,t,i)=>{e&&r(e),n({totalHits:t,resetTime:i})})})}async decrement(e){return t.decrement(e)}async resetKey(e){return t.resetKey(e)}async resetAll(){if(typeof t.resetAll==`function`)return t.resetAll()}}return new n},BS=e=>{let{validations:t,...n}=e;return{...n,validate:t.enabled}},VS=e=>{let t=AS(e),n=e.logger??xS,r=LS(t?.validate??!0,n);r.validationsConfig(),r.knownOptions(e),r.draftPolliHeaders(t.draft_polli_ratelimit_headers),r.onLimitReached(t.onLimitReached),t.ipv6Subnet!==void 0&&typeof t.ipv6Subnet!=`function`&&r.ipv6Subnet(t.ipv6Subnet),r.keyGeneratorIpFallback(t.keyGenerator),r.ipv6SubnetOrKeyGenerator(t);let i=t.standardHeaders??!1;i===!0&&(i=`draft-6`);let a={windowMs:6e4,limit:e.max??5,message:`Too many requests, please try again later.`,statusCode:429,legacyHeaders:e.headers??!0,identifier(e,t){let n=``,{limit:r}=e[a.requestPropertyName],i=a.windowMs/1e3,o=a.windowMs/6e4,s=a.windowMs/36e5,c=a.windowMs/864e5;return n=i<60?`${i}sec`:o<60?`${o}min`:s<24?`${s}hr${s>1?`s`:``}`:`${c}day${c>1?`s`:``}`,`${r}-in-${n}`},requestPropertyName:`rateLimit`,skipFailedRequests:!1,skipSuccessfulRequests:!1,requestWasSuccessful:(e,t)=>t.statusCode<400,skip:(e,t)=>!1,async keyGenerator(e,t){r.ip(e.ip),r.trustProxy(e),r.xForwardedForHeader(e),r.forwardedHeader(e);let n=e.ip,i=56;return ra(n)&&(i=typeof a.ipv6Subnet==`function`?await a.ipv6Subnet(e,t):a.ipv6Subnet,typeof a.ipv6Subnet==`function`&&r.ipv6Subnet(i)),yS(n,i)},ipv6Subnet:56,async handler(e,t,n,r){t.status(a.statusCode);let i=typeof a.message==`function`?await a.message(e,t):a.message;t.writableEnded||t.send(i)},passOnStoreError:!1,...t,standardHeaders:i,store:zS(t.store??new bS(r)),validations:r,logger:n};if(typeof a.store.increment!=`function`||typeof a.store.decrement!=`function`||typeof a.store.resetKey!=`function`||a.store.resetAll!==void 0&&typeof a.store.resetAll!=`function`||a.store.init!==void 0&&typeof a.store.init!=`function`)throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");return a},HS=e=>async(t,n,r)=>{try{await Promise.resolve(e(t,n,r)).catch(r)}catch(e){r(e)}},US=e=>{let t=VS(e??{}),n=BS(t),r=(0,_S.default)(`express-rate-limit`);r(`creating new rate limiter with %o`,t.store.constructor.name);for(let[e,n]of Object.entries(t))r(`set %s to %o`,e,n);if(t.validations.creationStack(t.store),t.validations.unsharedStore(t.store),typeof t.store.init==`function`){r(`executing init for store`);try{let e=t.store.init(n);e instanceof Promise&&e.catch(e=>t.logger.error(e,`express-rate-limit: async error during store initialization.`))}catch(e){t.logger.error(e,`express-rate-limit: error during store initialization.`)}}let i=HS(async(e,i,a)=>{let o=t.skipFailedRequests&&new Promise(e=>i.once(`close`,e)),s=(t.skipFailedRequests||t.skipSuccessfulRequests)&&new Promise(e=>i.once(`finish`,e)),c=t.skipFailedRequests&&new Promise(e=>i.once(`error`,e));if(r(`requested %o`,e.originalUrl),r(`request from ip %o`,e.ip),await t.skip(e,i)){r(`skipping request`),a();return}let l=e,u=await t.keyGenerator(e,i);r(`computed key %o`,u),r(`incrementing count`);let d=0,f;try{let e=await t.store.increment(u);d=e.totalHits,f=e.resetTime}catch(e){if(t.passOnStoreError){t.logger.error(e,`express-rate-limit: error from store, allowing request without rate-limiting.`),a();return}throw e}t.validations.positiveHits(d),t.validations.singleCount(e,t.store,u);let p=await(typeof t.limit==`function`?t.limit(e,i):t.limit);t.validations.limit(p);let m={limit:p,used:d,remaining:Math.max(p-d,0),resetTime:f,key:u};for(let[e,n]of Object.entries(m))r(`set request.%s.%s to be %o`,t.requestPropertyName,e,n);if(Object.defineProperty(m,"current",{configurable:!1,enumerable:!1,value:d}),l[t.requestPropertyName]=m,t.legacyHeaders&&!i.headersSent&&(r(`set legacy headers`),TS(i,m)),t.standardHeaders&&!i.headersSent)switch(t.standardHeaders){case`draft-6`:r(`set ietf draft 6 headers`),ES(i,m,t.windowMs);break;case`draft-7`:r(`set ietf draft 7 headers`),t.validations.headersResetTime(m.resetTime),DS(i,m,t.windowMs);break;case`draft-8`:{let n=await(typeof t.identifier==`function`?t.identifier(e,i):t.identifier);r(`set ietf draft 8 headers`),r(`set name to %o`,n),t.validations.headersResetTime(m.resetTime),OS(i,m,t.windowMs,n,u);break}default:t.validations.headersDraftVersion(t.standardHeaders)}if(t.skipFailedRequests||t.skipSuccessfulRequests){let n=!1,a=async()=>{if(!n){if(f&&Date.now()>=f.getTime())return;r(`decrementing count`),await t.store.decrement(u),n=!0}};t.skipFailedRequests&&(s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n||await a()}),o&&o.then(async()=>{i.writableEnded||await a()}),c&&c.then(async()=>{await a()})),t.skipSuccessfulRequests&&s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n&&await a()})}if(d>p){if(r(`limit exceeded`),t.legacyHeaders||t.standardHeaders){r(`set retry-after header`);let n=await(typeof t.retryAfter==`function`?t.retryAfter(e,i):t.retryAfter);kS(i,m,t.windowMs,n)}t.handler(e,i,a,n);return}a()});return i.resetKey=t.store.resetKey.bind(t.store),i.getKey=typeof t.store.get==`function`?t.store.get.bind(t.store):()=>{throw Error(`The current store does not support the get/getKey method`)},i},WS=Yi.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:De(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,aa()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)})),GS={ttlMs:ti,maxEntries:128,verificationDeadlineMs:1e4,degradedGrantMaxAgeMs:ti+6e5,maxConcurrentVerifications:16,maxOverBudgetVerifications:2},KS=()=>new Sr({status:429,title:`Too Many Requests`,type:`about:blank`,detail:`Too many credential verifications are in progress; retry shortly.`,retryAfterSeconds:1}),qS=e=>e instanceof Sr?yt(e.problem.status,e.problem):mn(e);function JS(e){if(!e.includes(`.`))return 1/0;try{let{exp:t}=tn(e);return t===void 0?1/0:t*1e3}catch(e){if(!(e instanceof Ei))throw e;return 1/0}}var YS=(e,t)=>`${ia(`sha256`).update(e).digest(`hex`)} ${t?.href??``}`;function XS(e=GS){let t=new Map,n={limit:e.maxConcurrentVerifications,inFlight:0},r={limit:e.maxOverBudgetVerifications,inFlight:0},i=(i,a,o)=>{let s=YS(i,a),c=t.get(s);if(c!==void 0&&c.expiresAt>Date.now())return t.delete(s),t.set(s,c),c.verification;let l=c?.grant,u=t=>{let n=l===void 0?1/0:Date.now()-l.grantedAt,r=n<e.degradedGrantMaxAgeMs&&JS(i)>Date.now();if(l===void 0||!r||!qS(t))throw t;return ae({component:`aventure-mcp-server`,event:`authentication_degraded`,fields:{requestId:_e(),grantAgeMs:n},error:t}),l.authorization},d=o?[n,r]:[n];if(d.some(({inFlight:e,limit:t})=>e>=t))return Promise.reject(KS());t.delete(s);for(let e of d)e.inFlight+=1;let f=()=>{for(let e of d)--e.inFlight},p=Jt(i,a,WS,e.verificationDeadlineMs).catch(u),m={verification:p,expiresAt:1/0,grant:l};t.set(s,m);for(let n of t.keys()){if(t.size<=e.maxEntries)break;t.delete(n)}let h=()=>{t.get(s)===m&&t.delete(s)};return p.then(t=>{f(),t===null||t===`forbidden`?h():t===l?.authorization?m.expiresAt=0:(m.grant={authorization:t,grantedAt:Date.now()},m.expiresAt=Math.min(Date.now()+e.ttlMs,JS(i)))},()=>{f(),h()}),p},a=(e,n)=>{let r=Mr(e.header(`authorization`));if(r===void 0)return!1;let i=t.get(YS(r,n))?.expiresAt;return i!==void 0&&Number.isFinite(i)&&i>Date.now()},o=async(e,t,n)=>{let r=e.header(`authorization`),a=Mr(r);if(a===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await i(a,t,n);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:a,authorization:e}}catch(e){if(!(e instanceof Ei))throw e;ae({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:_e()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}},s=new WeakMap,c=(e,t,n=!1)=>{let r=s.get(e);if(r!==void 0&&r.resourceHref===t?.href)return r.decision;let i=o(e,t,n);return s.set(e,{resourceHref:t?.href,decision:i}),i};return Object.assign((e,t)=>c(e,t),{holdsGrant:a,admitsOverBudget:(e,t)=>Mr(e.header(`authorization`))===void 0?Promise.resolve(!1):c(e,t,!0).then(e=>e.ok,()=>!1)})}function ZS(e,t){let n=new WeakMap;return[US({windowMs:6e4,limit:120,skipSuccessfulRequests:!0,skip:async n=>e.holdsGrant(n,await t()),handler:(...[e,,t,r])=>{n.set(e,r),t()}}),async(r,i,a)=>{let o=n.get(r);o===void 0||await e.admitsOverBudget(r,await t())?a():i.status(o.statusCode).send(o.message)},US({windowMs:6e4,limit:120,keyGenerator:QS})]}function QS(e){let t=Mr(e.header(`authorization`));return t===void 0?yS(e.ip??``):ia(`sha256`).update(t).digest(`base64url`)}function $S(e,t){let n=`an API key from https://aventure.vc/settings/api-keys as Authorization: Bearer <key>`,r=t?`Sign in with OAuth through the authorization server in this server's resource metadata; a client that cannot register itself needs the OAuth client ID at https://docs.aventure.vc/mcp. Or send ${n}.`:`Send ${n}. This server advertises no OAuth authorization server.`;return e===`forbidden`?`The supplied credential is valid, but its account may not use this MCP server.`:e===`missing_credential`?r:`The supplied credential was rejected or expired; reconnect this server in the MCP client to sign in again. ${r}`}var eC=1024,tC=eC*eC,nC=1,rC=2,iC=`b`,aC=`kb`,oC=`mb`,sC=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function cC(e){let t=uC(e.limit),n=lC(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||lC(r.path)!==n){a();return}let o=dC(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function lC(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function uC(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=sC.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[nC]);if(Number.isFinite(n))switch(t[rC]??iC){case oC:return Math.floor(n*tC);case aC:return Math.floor(n*eC);case iC:return Math.floor(n)}}function dC(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var fC=256e3,pC=16e3,mC=256,hC=31,gC=127,_C=36e5,vC=`openai/session`,yC=`mcpCallOutcome`;function bC(e,t){let n=`${t??``} ${e??``}`.toLowerCase();return n.includes(`openai-mcp`)||n.includes(`chatgpt`)?`chatgpt`:n.includes(`claude-user`)||n.includes(`claude-ai`)||n.includes(`claude.ai`)?`claude_ai`:n.includes(`claude-code`)||n.includes(`claude code`)?`claude_code`:n.includes(`grok`)?`grok`:n.includes(`codex`)?`codex`:n.includes(`cursor`)?`cursor`:n.includes(`gemini`)||n.includes(`antigravity`)?`gemini`:`other`}function xC(e){let t=typeof e==`object`&&e?Reflect.get(e,`params`):void 0;if(typeof t!=`object`||!t)return{};let n=Reflect.get(t,`_meta`),r=Reflect.get(t,`clientInfo`)??(typeof n==`object`&&n?Reflect.get(n,`io.modelcontextprotocol/clientInfo`):void 0);if(typeof r!=`object`||!r)return{};let i=Reflect.get(r,`name`),a=Reflect.get(r,`version`);return{name:typeof i==`string`?i:void 0,version:typeof a==`string`?a:void 0}}function SC(e,t){let n=t.locals[yC];return{client:bC(e.get(`user-agent`),xC(e.body).name),outcome:CC(n)?n:`none`}}function CC(e){return e===`ok`||e===`tool_error`||e===`protocol_error`||e===`aborted`}function wC(e,t){let n=[],r=0,i=(e,t)=>{if(r>=fC||e==null)return;let i=typeof e==`string`?Buffer.from(e,typeof t==`string`&&Buffer.isEncoding(t)?t:`utf8`):e instanceof Uint8Array?Buffer.from(e):void 0;i!==void 0&&(n.push(i.subarray(0,fC-r)),r+=i.length)},a=e.write.bind(e),o=e.end.bind(e);e.write=((t,n,r)=>(i(t,n),Reflect.apply(a,e,[t,n,r].filter(e=>e!==void 0)))),e.end=((r,a,s)=>(typeof r!=`function`&&i(r,a),t(Buffer.concat(n).toString(`utf8`)),Reflect.apply(o,e,[r,a,s].filter(e=>e!==void 0))))}function TC(e,t){let n=e.trimStart().startsWith(`{`)?[e]:e.split(`
145
- `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());for(let e of n){let n;try{n=JSON.parse(e)}catch(e){return{outcome:`protocol_error`,text:``,summary:`unparseable reply: ${String(e)}`}}let r=ir.safeParse(n);if(!r.success||!(`id`in r.data)||r.data.id!==t)continue;if(`error`in r.data)return{outcome:`protocol_error`,text:``,summary:r.data.error.message};if(!(`result`in r.data))continue;let i=Br.safeParse(r.data.result);if(!i.success)return{outcome:`protocol_error`,text:``,summary:`malformed tool result`};let a=Oi(i.data.structuredContent),o=i.data.content.find(e=>e.type===`text`);return{outcome:i.data.isError===!0?`tool_error`:`ok`,text:o?.type===`text`?o.text:``,httpStatus:a?.httpStatus??a?.problem?.status,problemType:a?.problem?.type,summary:a?.summary}}return{outcome:`protocol_error`,text:``,summary:`no JSON-RPC reply to this call`}}function EC(e,t){return typeof e==`object`&&e?Reflect.get(e,t):void 0}function DC(e){return OC(typeof e==`object`&&e?Object.keys(e).join(`,`):``)}function OC(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n]??``,i=e.charCodeAt(n);t+=i<=hC||i===gC?`�`:r}return t.length>mC?`${t.slice(0,255)}…`:t}function kC(e,t){let n=EC(t,vC);return typeof n==`string`&&n.length>0?`${e}:${OC(n)}`:`${e}:${ia(`sha256`).update(ke()??`anonymous`).digest(`hex`).slice(0,16)}:${Math.floor(Date.now()/_C)}`}var AC=e=>e.length>pC?`${e.slice(0,pC)}…`:e;async function jC(e,t,n){let r=tr.safeParse(e.body),i=typeof e.body==`object`&&e.body!==null?Reflect.get(e.body,`id`):void 0;if(!r.success||typeof i!=`string`&&typeof i!=`number`){await n();return}let a=performance.now(),o=e.get(`user-agent`),s=xC(e.body),c=bC(o,s.name),l=Reflect.get(r.data.params,`_meta`),u=r.data.params.arguments,d=typeof u?.operationId==`string`?OC(u.operationId):void 0,f=s.name===void 0?void 0:OC(s.name),p=s.version===void 0?void 0:OC(s.version),m=o===void 0?void 0:OC(o),h=kC(c,l),g=sS(e.body).toolName,_=EC(l,Rr),v=ye(`mcp ${g}`,{"langfuse.trace.name":`mcp ${g}`,"langfuse.session.id":h,"langfuse.trace.tags":[`mcp`,c,g],"langfuse.observation.type":`tool`,"langfuse.observation.input":AC(JSON.stringify(u??{})),"langfuse.environment":ce()[`deployment.environment.name`]??`unknown`,...process.env.GIT_SHA===void 0?{}:{"langfuse.release":process.env.GIT_SHA},"langfuse.trace.metadata.client":c,"langfuse.trace.metadata.client_name":f??``,"langfuse.trace.metadata.client_version":p??``,"langfuse.trace.metadata.user_agent":m??``,"langfuse.trace.metadata.operation_id":d??``,"langfuse.trace.metadata.meta_keys":DC(l),"aventure.request_id":_e()??``,"mcp.tool.name":g,"mcp.tool.requested_name":OC(r.data.params.name)},typeof _==`string`?_:void 0);wC(t,n=>{let r=t.destroyed||e.socket.destroyed?{outcome:`aborted`,text:``}:TC(n,i);t.locals[yC]=r.outcome;let o=r.outcome===`tool_error`||r.outcome===`protocol_error`,s={requestId:_e(),toolName:g,operationId:d,client:c,clientName:f,clientVersion:p,userAgent:m,metaKeys:DC(l),sessionId:h,outcome:r.outcome,httpStatus:r.httpStatus,problemType:r.problemType,resultChars:r.text.length,durationMs:Math.round(performance.now()-a),traceId:v?.spanContext().traceId};(o?ae:k)({component:`aventure-mcp-server`,event:`tool_call`,fields:s}),v!==void 0&&Ce(v,{"langfuse.observation.output":AC(r.text),"langfuse.observation.level":o?`ERROR`:`DEFAULT`,...r.summary===void 0?{}:{"langfuse.observation.status_message":r.summary},"langfuse.trace.metadata.outcome":r.outcome,"langfuse.trace.metadata.http_status":String(r.httpStatus??``),"langfuse.trace.metadata.problem_type":r.problemType??``,"mcp.tool.outcome":r.outcome},o)}),v===void 0?await n():await Oe(xe(v),n)}var MC=400,NC=400,PC=413,FC=`10mb`,IC=`127.0.0.1`,LC=/^[\w.:/-]{1,128}$/,RC=`0.0.0.0`;async function zC(e){let t=e.jsonBodyLimit??FC,n=XS(),r=e.host??IC,i=r!==RC,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,rf.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=e.get(`x-client-request-id`)??``,i=LC.test(r)?r:aa(),a=performance.now(),o={requestId:i,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},s=HC(e);s||k({component:`aventure-mcp-server`,event:`http_request`,fields:o}),t.on(`finish`,()=>{let n=Math.round(performance.now()-a),r=e.route,i=typeof r==`object`&&r?Reflect.get(r,`path`):null,c={...sS(e.body),...SC(e,t)};Rb(e.method,typeof i==`string`?i:`unmatched`,t.statusCode,n,c),!(s&&t.statusCode<MC)&&(t.statusCode>=MC&&!s?ae:k)({component:`aventure-mcp-server`,event:`http_response`,fields:{...o,...c,status:t.statusCode,durationMs:n}})}),ge(i,()=>n())}),o.use(i?(0,nf.default)({origin:VC}):(0,nf.default)()),o.use(cC({path:e.path,limit:t,reject:e=>UC(e,PC,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(rf.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,nf.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){UC(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),zb(o,e.metricsScrapeSecret),be(),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>e[1].redirect(302,`${M}/favicon.ico`));let s=ZS(n,async()=>(await e.resolveOAuthDiscovery())?.resourceUrl);return o.post(e.path,s,async(t,r)=>{let o=_e(),s=t.header(`origin`);if(i&&!BC(s)){ae({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),UC(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){Yc(e,`authentication_unavailable`),N({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof Sr&&(e.problem.status===429||ki(e.problem.status))?e.problem:void 0;n===void 0?UC(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),WC(r,n));return}if(!c.ok){ae({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${Av(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`);let n=c.reason===`forbidden`;UC(r,n?403:401,n?`Forbidden`:`Unauthorized`,$S(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){UC(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}k({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{Yc(e,`transport_error`),N({component:`aventure-mcp-server`,event:`transport_error`,message:le(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=jy(()=>iS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await Zy(p,{onerror:f})(t,r,t.body);for(let e of d)ki(r.statusCode)?f(e):(r.statusCode<MC?k:ae)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:le(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})},h=()=>jC(t,r,m);c.userBearerToken===void 0?await h():await Se(c.userBearerToken,h)}),o.all(e.path,(...e)=>UC(e[1],405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=GC(e);if(i===void 0){r(e);return}ae({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:_e(),method:t.method,path:t.path,status:i.status}}),UC(n,i.status,i.status===PC?`Payload Too Large`:`Bad Request`,i.status===PC?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Promise.all([Bb(),we()])}})}),i.on(`error`,n)})}function BC(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:na(t)&&t.startsWith(`127.`)}var VC=(e,t)=>t(null,BC(e)),HC=e=>e.method===`GET`&&/^\/(?:robots\.txt|health)\/?$/iu.test(e.path);function UC(e,t,n,r){WC(e,{type:`about:blank`,title:n,status:t,detail:r})}function WC(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function GC(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?PC:e.type===`entity.parse.failed`?NC:e.status===PC||e.status===NC?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}var KC=65535,qC=55e3,JC=Pi(ea(import.meta.url)),{host:YC}=(await new p().name(JC.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(JC.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
144
+ `);r.length>1&&!i&&(i=c.getValue(r,`NextHop`),e&&e(i),t(i))})})}catch{e&&e(i),t(i)}})})}t.networkGatewayDefault=ye})),Cb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getNetworkData=void 0;var t=Sb();function n(){return new Promise(e=>{(0,t.networkStats)().then(e).catch(()=>{e([])})})}e.getNetworkData=n})),wb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=void 0;var t=vb(),n=yb(),r=bb(),i=Cb();e.HostMetrics=class extends t.BaseMetrics{_batchUpdateCpuUsages(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._cpuTime,i.user,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.system,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.idle,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.interrupt,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.nice,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.userP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.systemP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.idleP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.interruptP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.niceP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber})}}_batchUpdateProcessCpuUsages(e,t){e.observe(this._processCpuTime,t.user,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuTime,t.system,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM}),e.observe(this._processCpuUtilization,t.userP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuUtilization,t.systemP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM})}_batchUpdateMemUsages(e,t){e.observe(this._memoryUsage,t.used,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUsage,t.free,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE}),e.observe(this._memoryUtilization,t.usedP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUtilization,t.freeP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE})}_batchUpdateProcessMemUsage(e,t){e.observe(this._processMemoryUsage,t)}_batchUpdateNetworkData(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._networkDropped,i.rx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkDropped,i.tx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkErrors,i.rx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkErrors,i.tx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkIo,i.rx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkIo,i.tx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT})}}_createMetrics(){let e=[],t=!this._metricGroups||this._metricGroups.includes(`system.cpu`),a=!this._metricGroups||this._metricGroups.includes(`system.memory`),o=!this._metricGroups||this._metricGroups.includes(`system.network`),s=!this._metricGroups||this._metricGroups.includes(`process.cpu`),c=!this._metricGroups||this._metricGroups.includes(`process.memory`);t&&(this._cpuTime=this._meter.createObservableCounter(n.METRIC_SYSTEM_CPU_TIME,{description:`Cpu time in seconds`,unit:`s`}),e.push(this._cpuTime),this._cpuUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_CPU_UTILIZATION,{description:`Cpu usage time 0-1`}),e.push(this._cpuUtilization)),a&&(this._memoryUsage=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_USAGE,{description:`Memory usage in bytes`}),e.push(this._memoryUsage),this._memoryUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_UTILIZATION,{description:`Memory usage 0-1`}),e.push(this._memoryUtilization)),o&&(this._networkDropped=this._meter.createObservableCounter(`system.network.dropped`,{description:`Network dropped packets`}),e.push(this._networkDropped),this._networkErrors=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_ERRORS,{description:`Network errors counter`}),e.push(this._networkErrors),this._networkIo=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_IO,{description:`Network transmit and received bytes`}),e.push(this._networkIo)),s&&(this._processCpuTime=this._meter.createObservableCounter(n.METRIC_PROCESS_CPU_TIME,{description:`Process Cpu time in seconds`,unit:`s`}),e.push(this._processCpuTime),this._processCpuUtilization=this._meter.createObservableGauge(n.METRIC_PROCESS_CPU_UTILIZATION,{description:`Process Cpu usage time 0-1`}),e.push(this._processCpuUtilization)),c&&(this._processMemoryUsage=this._meter.createObservableGauge(n.METRIC_PROCESS_MEMORY_USAGE,{description:`Process Memory usage in bytes`}),e.push(this._processMemoryUsage)),this._meter.addBatchObservableCallback(async e=>{if(t){let t=(0,r.getCpuUsageData)();this._batchUpdateCpuUsages(e,t)}if(a){let t=(0,r.getMemoryData)();this._batchUpdateMemUsages(e,t)}if(s){let t=(0,r.getProcessCpuUsageData)();this._batchUpdateProcessCpuUsages(e,t)}if(c){let t=(0,r.getProcessMemoryData)();this._batchUpdateProcessMemUsage(e,t)}if(o){let t=await(0,i.getNetworkData)();this._batchUpdateNetworkData(e,t)}},e)}start(){this._createMetrics()}_cpuTime;_cpuUtilization;_memoryUsage;_memoryUtilization;_processCpuTime;_processCpuUtilization;_processMemoryUsage;_networkDropped;_networkErrors;_networkIo}})),Tb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=e.BaseMetrics=void 0;var t=vb();Object.defineProperty(e,"BaseMetrics",{enumerable:!0,get:function(){return t.BaseMetrics}});var n=wb();Object.defineProperty(e,"HostMetrics",{enumerable:!0,get:function(){return n.HostMetrics}})}));u();var Eb=ab(),Db=Tb();m(),jc();var Ob=`aventure-mcp-server`,kb=`http_server_requests_seconds`,Ab=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],jb,Mb,Nb,Pb,Fb;function Ib(e,t){if(Mb!==void 0)return;let n=e?new Eb.PrometheusExporter({preventServerStart:!0}):void 0,r=new Oc({resource:S({...ce(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??Fi().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new Zo({exporter:new gb({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});s.setGlobalMeterProvider(r),Mb=r,jb=n;let i=new Db.HostMetrics({meterProvider:r,name:Ob});i.start(),Fb=i}function Lb(){return Nb===void 0&&(Nb=Mb?.getMeter(Ob)),Nb}function Rb(e,t,n,r,{rpcMethod:i,toolName:a,client:o,outcome:s}){let c=Lb();c!==void 0&&(Pb===void 0&&(Pb=c.createHistogram(kb,{description:`HTTP server request latency in seconds, partitioned by method/route/status/rpc_method/tool/client/outcome.`,unit:`s`,advice:{explicitBucketBoundaries:Ab}})),Pb.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n),rpc_method:i,tool:a,client:o,outcome:s}))}function zb(e,t){let n=Fi().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Ib(n,r);let i=jb;if(!n||t===void 0||i===void 0)return;let a=ia(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!Vb(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function Bb(){let e=Mb;Fb!==void 0&&(Fb=void 0),Mb=void 0,jb=void 0,Nb=void 0,Pb=void 0,e!==void 0&&await e.shutdown()}function Vb(e,t){let n=Mr(e);if(n===void 0)return!1;let r=ia(`sha256`).update(n).digest();return r.length===t.length&&oa(r,t)}var Hb=`#/components/schemas/`,Ub=/"#\/components\/schemas\/([^"]+)"/g,Wb=-32011,Gb=-32012,Kb=-32013,qb=-32015;function Jb(e){let t=St().components.schemas[e];if(t===void 0)throw Error(`OpenAPI has no component ${e}`);return t}function Yb(e){let t=ve(e?.content?.[`application/json`]?.schema);return t===void 0?void 0:Jb(t)}function Xb(e){let t=Object.keys(e).length===1?ve(e):void 0,n=t===void 0?e:Jb(t),r={},i=e=>{for(let[,t]of JSON.stringify(e).matchAll(Ub))t===void 0||t in r||(r[t]=Jb(t),i(r[t]))};i(n);let a=Object.keys(r).length===0?n:{...n,$defs:r},o=ki.safeParse(JSON.parse(JSON.stringify(a).replaceAll(`"${Hb}`,`"#/$defs/`)));if(!o.success)throw Error(`Event schema is not JSON: ${o.error}`);return o.data}function Zb(e,t){let n=Object.entries(St().paths).find(([,n])=>Yb(n[e]?.requestBody)?.properties?.name?.$ref===t);if(n===void 0)throw Error(`OpenAPI has no ${e} operation for ${t}`);return n[0]}var Qb=new Map(Object.entries(St().webhooks??{}).map(([e,t])=>{let n=Yb(t.post.requestBody),r=n?.properties?.name?.$ref,i=n?.properties?.data;if(r===void 0||i===void 0)throw Error(`Webhook ${e} body must carry a name enum $ref and a data schema`);let a=Zb(`put`,r),o=Yb(St().paths[a]?.put?.requestBody)?.properties?.arguments;if(o===void 0)throw Error(`Subscribe body for ${e} must carry an arguments schema`);return[e,{descriptor:{name:e,description:t.post.description,delivery:[`webhook`],inputSchema:Xb(o),payloadSchema:Xb(i)},subscribePath:a,unsubscribePath:Zb(`delete`,r)}]})),$b=G({name:W()}).catchall(ki),ex=F(W(),ki);function tx(e){let t=Qb.get(e);if(t===void 0)throw new Z(Wb,`Unknown event ${e}`);return t}async function nx(e,t,n){let{_meta:r,...i}=n,a=await Ht({method:e,path:t,body:i,auth:`auto`});if(a.ok){let e=ex.safeParse(a.data!==null&&typeof a.data==`object`&&`response`in a.data?a.data.response??{}:{});if(e.success)return e.data;throw new Z(X.InternalError,`${t} answered a non-object body`)}let o=rx(a.problem?.code);throw o===void 0?a.problem?.code===`news_subscription_limit`?new Z(Kb,a.summary,{limit:`subscriptions`}):new Z(ix(a.httpStatus),a.summary,a.problem):new Z(qb,`CallbackEndpointError`,{reason:o})}function rx(e){switch(e){case`callback_connection_refused`:return`connection_refused`;case`callback_timeout`:return`timeout`;case`callback_tls_error`:return`tls_error`;case`callback_http_4xx`:return`http_4xx`;case`callback_http_5xx`:return`http_5xx`;case`callback_challenge_failed`:return`challenge_failed`;default:return}}function ix(e){switch(e){case 400:case 422:return X.InvalidParams;case 401:case 403:return Gb;case 404:return Wb;default:return X.InternalError}}function ax(e){if(Qb.size===0)return;let t=[...Qb.values()].map(e=>e.descriptor);e.server.setRequestHandler(`events/list`,{params:G({})},()=>({events:t})),e.server.setRequestHandler(`events/subscribe`,{params:$b},e=>nx(`PUT`,tx(e.name).subscribePath,e)),e.server.setRequestHandler(`events/unsubscribe`,{params:$b},e=>nx(`DELETE`,tx(e.name).unsubscribePath,e))}async function ox(e){try{return await Ht(e)}catch(t){return N({component:`aventure-mcp-server`,event:`tool_request_failed`,fields:{requestId:_e(),method:e.method},error:t}),Ai(le(t))}}function sx(e,t){let n=Ee(e.requestBody??[],t.contentType).data;return[...e.parameter.filter(e=>e.in===`query`).map(e=>({parameter:e,label:`Query parameter`,sent:[e.name,e.legacyName].flatMap(e=>e===void 0?[]:[t.query?.[e]])})),...(n?.parameter??[]).map(e=>({parameter:e,label:`Body field`,sent:lx(t.body,e.name.split(`.`))}))].flatMap(({parameter:{name:e,schemaEnum:t,itemSchemaEnum:n,enumOpen:r},label:i,sent:a})=>{let o=r===!0?[]:t??n??[],s=new Set(o.map(cx)),c=i===`Query parameter`&&n!==void 0,l=a.flatMap(e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?c?e.split(`,`).map(e=>e.trim()):[e]:[]).filter(e=>!s.has(cx(e)));return o.length===0||l.length===0?[]:[` ${i} '${e}' does not accept ${l.map(e=>JSON.stringify(e)).join(`, `)}; send one of ${o.join(`, `)}.`]}).join(``)}var cx=e=>e.toLowerCase().replaceAll(/[^\p{L}\p{N}]/gu,``);function lx(e,t){let[n,...r]=t;if(e===void 0)return[];if(n===void 0)return[e];if(typeof e!=`object`||!e||Array.isArray(e))return[];if(!n.endsWith(`[]`))return lx(e[n],r);let i=e[n.slice(0,-2)];return Array.isArray(i)?i.flatMap(e=>lx(e,r)):[]}var ux=3,dx=200,fx=80;function px(e,t){let{operationId:n}=e;if(n===void 0)return null;let r=t.find(e=>e.operationId===n);if(r!==void 0)return mx(r,e,t);let i=yx(n,t),a=Ki(i.noun),o=xx(e),s=Ui([...a,...o.flatMap(({word:e})=>e)].join(` `),t,zi).map(({item:e,score:t})=>({item:e,score:t+bx(e,a,o.map(({key:e})=>e))})).toSorted((e,t)=>Number(e.item.deprecated===!0)-Number(t.item.deprecated===!0)||Number(i.intent.has(t.item.intent))-Number(i.intent.has(e.item.intent))||Number(i.method.has(t.item.method))-Number(i.method.has(e.item.method))||t.score-e.score).slice(0,ux).map(({item:e})=>Ri(e,!1)),c=s.map(e=>`${e.operationId} (${e.method} ${e.path})`);return Ai(`Operation ${n} is not in the MCP catalog.${c.length===0?``:` Closest operations: ${c.join(`, `)}.`}`,s.map(e=>`Use operationId ${e.operationId} with aventure_${e.intent}: ${e.method} ${e.path}; required inputs: ${e.requiredInput.length===0?`none`:e.requiredInput.join(`, `)}.`))}function mx(e,t,n){let r=t.pathParams??{},i=e.parameter.filter(({in:e,required:t,name:n,legacyName:i})=>e===`path`&&t&&r[n]==null&&(i===void 0||r[i]==null));if(i.length===0)return null;let a=new Set(e.parameter.filter(({in:e})=>e===`query`).flatMap(({name:e,legacyName:t})=>t===void 0?[e]:[e,t])),o=Object.fromEntries(i.flatMap(e=>{let n=[e.name,e.legacyName].find(e=>e!==void 0&&!a.has(e)&&t.query?.[e]!=null),r=n===void 0?void 0:t.query?.[n];return hx(e,r)?[[e.name,r]]:[]})),s=i.map(({name:e})=>e).filter(e=>!(e in o)),c=Object.entries(t.query??{}).filter(([e])=>a.has(e)||!i.some(({name:t,legacyName:n})=>e===t||e===n)),l=JSON.stringify({operationId:e.operationId,pathParams:{...r,...o,...Object.fromEntries(s.map(e=>[e,`<${e}>`]))},...c.length===0?{}:{query:Object.fromEntries(c)}}),u=s.flatMap(t=>gx(e.path,t,n).map(e=>{let n=e.parameter.filter(e=>e.in===`query`&&e.schemaEnum===void 0),r=n.filter(e=>e.required),i=r.length>0?r:n.filter(e=>e.schemaType===`string`&&e.name!==`cursor`).slice(0,1),a=n.filter(e=>e.schemaType===`string`);return` Get ${t} from ${e.operationId} (${e.method} ${e.path}): aventure_${e.intent} ${JSON.stringify({operationId:e.operationId,...i.length===0?{}:{query:Object.fromEntries(i.map(e=>[e.name,`<${e.name}>`]))}})} returns the record whose id goes in pathParams.${t}${a.length===0?``:`; its query takes ${a.map(e=>e.name).join(`, `)}`}.`}));return Ai(`Missing path parameter${i.length===1?``:`s`} ${i.map(({name:e})=>`'${e}'`).join(`, `)} for ${e.operationId}. Path parameters go in pathParams: aventure_${e.intent} ${l}.${u.join(``)}`)}function hx(e,t){return e.schemaType===`integer`?typeof t==`number`&&Number.isInteger(t):e.schemaType===`number`?typeof t==`number`&&Number.isFinite(t):typeof t==`string`&&t.length>0}function gx(e,t,n){let r=`{${t}}`,i=e.slice(0,e.indexOf(r)+r.length),a=n.find(e=>e.method===`GET`&&e.path===i),o=a===void 0?void 0:vx(a);return o===void 0?[]:n.filter(e=>e.method===`GET`&&e.deprecated!==!0&&e.parameter.every(e=>e.in!==`path`)&&vx(e)===o).toSorted((e,t)=>Number(_x(t))-Number(_x(e)))}function _x(e){return e.intent===`lookup`||/lookup/iu.test(e.operationId)}function vx(e){let t=Te(St().paths,e.operationId)?.operation.responses??{},n=new Set(Object.entries(t).filter(([e])=>e.startsWith(`2`)).map(([,e])=>e.content?.[`application/json`]?.schema?.$ref));return n.size===1?[...n][0]:void 0}function yx(e,t){let[n=``,...r]=Ji(e).split(` `),i=t.filter(e=>Ji(e.operationId).startsWith(`${n} `));return i.length>0&&r.length>0?{noun:r.join(` `),intent:new Set(i.map(e=>e.intent)),method:new Set(i.map(e=>e.method))}:{noun:e,intent:new Set,method:new Set}}function bx(e,t,n){let r=`${e.operationId} ${e.summary}`,i=new Set(Ki(r)),a=Li(Ji(r)),o=t.reduce((e,t)=>e+(i.has(t)?2:+!!a.has(t)),0),s=new Set([...e.parameter,...(e.requestBody??[]).flatMap(e=>e.parameter)].map(({name:e})=>e)),c=n.filter(e=>s.has(e)).length,l=Li(t.join(` `)),u=Ki(e.operationId).slice(1).filter(e=>!l.has(e)).length;return(o+2*c-u)*fx}function xx(e){let t=e.body,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.entries(t):[];return[...Object.entries(e.pathParams??{}),...Object.entries(e.query??{}),...n].map(([e,t])=>({key:e,word:typeof t==`string`&&t.length<=dx?[e,t]:[e]}))}function Sx({contract:e,input:t,intent:n,contracts:r,catalog:i}){let{operationId:a}=e;if(!n.includes(e.intent))return Ai(`Operation ${a} has intent=${e.intent}; call aventure_${e.intent} ${JSON.stringify({operationId:a,pathParams:t.pathParams,query:t.query,body:t.body})}.`);let o=i.find(e=>e.operationId===a)??e,s=o.parameter.filter(e=>e.in===`query`),c=Object.entries(t.query??{}),l=c.filter(([e])=>!Pt.includes(e)&&!s.some(t=>Cx(t,e))),u=e.parameter.filter(e=>e.in===`query`),d=u.map(({name:e})=>e),f=e.requestBody??[],p=f[0]?.schemaType===`array`,m=new Set((o.requestBody??[]).flatMap(e=>e.parameter.map(({name:e})=>e))),h=p?[]:l.filter(([e])=>m.has(e)),g=new Map(l.flatMap(([e])=>{let t=u.filter(t=>wx(t,e)),n=d.find(t=>cx(t)===cx(e))??(t.length===1?t[0]?.name:void 0);return n===void 0||h.some(([t])=>t===e)?[]:[[e,n]]})),_=l.filter(([e])=>!g.has(e)&&!h.some(([t])=>t===e)),v=t.body===void 0&&f.some(e=>e.required&&e.kind!==`multipart`),y=sx(o,t);if(l.length===0&&!v)return y===``?null:Ai(y.trim());let b=typeof t.body==`object`&&t.body!==null&&!Array.isArray(t.body)?t.body:void 0,x=f[0]?.parameter??[],S=v?x.filter(({name:e,required:t})=>t&&!h.some(([t])=>t===e)).map(({name:e})=>e):[],C=p||t.body!==void 0&&b===void 0?t.body??[]:{...Object.fromEntries(S.map(e=>[e,`<${e}>`])),...b,...Object.fromEntries(h)},w=c.flatMap(([e,t])=>{let n=l.some(([t])=>t===e)?g.get(e):e;return n===void 0?[]:[[n,t]]}),T=JSON.stringify({operationId:a,...t.pathParams===void 0?{}:{pathParams:t.pathParams},...w.length===0?{}:{query:Object.fromEntries(w)},...f.length===0?{}:{body:C}}),E=l.length===0?``:`${a} declares no query parameter ${Dx(l)}; ${d.length===0?`it takes no query`:`its query takes ${d.join(`, `)}`}.${[...g].map(([e,t])=>` Send '${e}' as '${t}'.`).join(``)}${_.length===0?``:` The call below removes ${Dx(_)}: no declared filter matches ${_.length===1?`it`:`them`}.`}`,D=h.length>0?` ${Dx(h)} ${h.length===1?`is a request body field`:`are request body fields`}: send ${h.length===1?`it`:`them`} in body.`:v?` ${a} requires a request body: send it in body${x.length===0?``:`; its fields are ${x.map(({name:e})=>e).join(`, `)}`}.`:``;return Ai(`${E}${D}${y} Call aventure_${e.intent} ${T}.${Ox(e,r)}`.trim())}function Cx(e,t){if(t===e.name||t===e.legacyName)return!0;let n=Number(/^\[(?<index>\d+)\]/u.exec(t.slice(e.name.length))?.groups?.index),r=qi(e.name,0,``);return t.startsWith(e.name)&&Number.isInteger(n)&&(e.itemProperty??[]).some(i=>t===qi(e.name,n,i.name.slice(r.length)))}function wx(e,t){let[n=``]=e.description.split(/(?<=\.)\s/u),r=new Set(Ki(`${e.name} ${n}`)),i=Ki(t);return i.length>=Tx&&i.at(-1)===Ki(e.name).at(-1)&&i.every(e=>r.has(e))}var Tx=3,Ex=/\b(?<method>GET|POST|PUT|PATCH|DELETE) (?<path>\/[^\s?),]*[^\s?),.])/u;function Dx(e){return e.map(([e])=>`'${e}'`).join(`, `)}function Ox(e,t){if(e.deprecated!==!0)return``;let n=/^Deprecated: (?<advice>.*?\.)(?=\s|$)/su.exec(e.description)?.groups?.advice;if(n===void 0)return` ${e.operationId} is deprecated.`;let r=Ex.exec(n)?.groups,i=t.find(e=>e.method===r?.method&&e.path===r?.path);return` ${e.operationId} is deprecated: ${n}${i===void 0?``:` Its replacement is ${i.operationId}: call aventure_${i.intent} {"operationId":"${i.operationId}"}.`}`}function kx(e,t){return t?e:e.map(Ax)}function Ax(e){let t=e.parameter.flatMap(Mx),n=jx(e.requestBody);return Px(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function jx(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Mx);return Px(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Mx(e){if(!Nx(e))return[];let t=e.itemProperty?.filter(Nx);return Px(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Nx=e=>e.visibility!==`private`;function Px(e,t){return e===t?!0:e?.length!==t?.length||e===void 0||t===void 0?!1:e.every((e,n)=>e===t[n])}new RegExp(oe.join(`|`),`i`);var Fx;function Ix(e,t){let n=Fx??=Gi([...Yi,...Xi]),r=Wi(e,n),i=Lx(Mi(e,r)),a=t===`json`?JSON.stringify(Lx(Mi(e,{...r,maxBytes:vn}))):Vi(n,i.data,i.summary)??JSON.stringify(i);return{isError:!i.ok,structuredContent:i,content:[{type:`text`,text:a}]}}function Lx(e){let{omitted:t,ids:n,counts:r,references:i,warnings:a,...o}=e;return{...o,...t.length>0?{omitted:t}:{},...n.length>0?{ids:n}:{},...Object.keys(r).length>0?{counts:r}:{},...i.length>0?{references:i}:{},...a.length>0?{warnings:a}:{}}}var Rx=`aventure_help`,zx=`aventure_read`,Bx=`aventure_lookup`,Vx=`aventure_search`,Hx=`aventure_job`,Ux=[Rx,zx,Bx,Vx,Hx],Wx=I([W(),U(),H()]),Gx=F(W(),I([W(),U()])).optional(),Kx=F(W(),I([Wx,B(Wx)])).optional(),qx=F(W(),W()).optional(),Jx=V([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Yx=I([Wx,Ve(),B(Me()),F(W(),Me())]).optional().describe(`JSON request body. For multipart/form-data operations, pass an object keyed by form part name; binary part values are http(s) URLs.`),Xx=G({operationId:W().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Jx.optional().describe(`HTTP method when resolving by method+path.`),path:W().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Gx.describe(`Values for route template parameters.`),query:Kx.describe(`Query parameters.`),headers:qx.describe(`Headers declared by the selected OpenAPI operation.`),contentType:W().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:V([`auto`,`json`]).optional().describe(`Omit for the default: readable text, from the operation's own text/plain rendering when aventure_help lists text/plain in responseContentType, otherwise from its JSON. json returns the JSON result envelope.`)}),Zx=G({q:W().optional().describe(`Plain-English task text, ranked against operationId, path, CLI command, summary, description, and query-parameter enum values. This tool reads no argument named query. Omitting q returns the catalog head unranked.`),root:He(e=>typeof e==`string`?e.trim().toLowerCase()||void 0:e,V([...new Set(Yi.flatMap(e=>[e.resource,...e.projection.cliPath.slice(0,1)]))].sort()).optional()).describe(`Filter by resource or first CLI segment.`),method:Jx.optional().describe(`Filter by HTTP method.`),limit:ze().min(1).max(100).default(20).describe(`Maximum rows to return. Set q to the chosen operationId and limit to 1 for argument types, enum choices, and defaults.`),resolve:H().default(!1).describe(`Resolve q to one operation with the server resolver (requires sign-in): operation advice with an mcpCall skeleton, a clarification between candidate operations, or an abstention. Root, method, and limit do not apply.`)}),Qx=Xx.extend({body:Yx}),$x=(e,t)=>kx(Yi,t?.operationAccess===`ADMIN`||t===void 0&&e===`write`).filter(n=>(t===void 0?e===`write`||n.projection.scope===`read`&&(n.projection.auth===`read`||n.projection.auth===`none`):t.operationAccess!==`READ`||n.projection.scope===`read`||n.projection.visibility!==`private`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function eS(e,t,n,r,i,a){let o=px(e,r)??Rt(e);if(!o.ok)return Ai(o.summary,o.warnings);if(o.data===null)return Ai(`OpenAPI operation resolution returned no data.`);let{method:s,operation:c,path:l,template:u}=o.data,d=c.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===s&&e.path===u);if(f===void 0)return Ai(`Operation `+d+` is not in the MCP catalog.`);let p=Sx({contract:f,input:e,intent:t,contracts:r,catalog:Yi});if(p!==null)return p;let m=Ee(f.requestBody??[],e.contentType);if(!m.ok||m.data===null)return Ai(m.summary,m.warnings);let h=m.data;return f.intent===`delete`&&h===void 0&&e.body!==void 0?Ai(d+` does not accept a request body.`):await ox({method:f.method,path:l,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i,signal:a})}function tS(e,t,n){let r=$x(t,n),i=()=>e.server.getClientVersion();e.registerTool(Rx,{title:`aVenture help`,annotations:{readOnlyHint:!0},description:`Lists the aVenture operations, each with the tool that runs it and the inputs it accepts. Pass q with a plain-English task to rank them. After choosing one, set q to its operationId and limit to 1 to see its full inputs, allowed values, and defaults. Set resolve to have the server pick one operation for q and return the call to make.`,inputSchema:Zx},async(e,n)=>{if(e.resolve)return Ix(await Bi(e,r,Yi,(e,r)=>ox({method:e.method,path:Je(e.operationId,{}),body:r.body,auth:e.projection.auth,requesterScope:t,responseFormat:`json`,clientInfo:i(),signal:n?.mcpReq.signal})));let{summary:a,data:o,counts:s}=Hi(e,r);return Ix(ji(a,o,{counts:s}))}),e.registerTool(zx,{title:`aVenture read`,annotations:{readOnlyHint:!0},description:`Runs one catalog operation whose intent is read: fetch a record by id or slug, list the records attached to it, or list a collection. Put route values in pathParams and URL query values in query. Example for an aventure.vc profile URL, slug, website, or domain: {"operationId":"getEntityLookup","query":{"url":"https://aventure.vc/investors/firms/<slug>"}}. When a read's newsArticle (or listNews or a web source) reports a newer funding round, investor, role, or detail not yet reflected in the structured fields, report both and ask the user whether to request a record update with aventure_job (enrichEntity or enrichPerson). Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`read`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Bx,{title:`aVenture lookup`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is lookup: identify a record from a name plus clues (such as lookupRecord), resolve a ticker or other identifier, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON body. An exact aventure.vc profile URL, slug, website, or domain is a read, not a lookup: call aventure_read with operationId getEntityLookup (or getPersonLookup) and query {url} or {slug}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`lookup`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Vx,{title:`aVenture search`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is search: search or filter companies, people, news, publications, content, links, or the web, or answer a question. It has no free-text argument of its own: pass search text and filters where the chosen operation declares them, in query or body. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`search`],t,r,i(),n?.mcpReq.signal),e.responseFormat)),r.some(e=>e.intent===`job`)&&e.registerTool(Hx,{title:`aVenture job`,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is job: request a research job that deepens or updates aVenture's data on a company or person (enrichEntity, enrichPerson, createResearchRun, enrichRecords), or a lookup job that identifies the companies and people an article names. When an indexed aVenture news article (newsArticle or listNews) or web source reports a newer or missing detail—such as a funding round, investor, role, or URL—not yet reflected in the structured profile, ask the user if they would like to request an update to the aVenture record; on confirmation, call enrichEntity, enrichPerson, or createResearchRun with body.finding (statement, sourceUrl, verbatim quote from an external page you read for an entity) or body.userPrompt (the observed detail and sourceUrl or newsUrlOriginal). Returns the run or job to poll with aventure_read. A research run costs one research unit only when it saves research, and a record already being researched returns that run instead of starting another. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Ix(await eS(e,[`job`],t,r,i(),n?.mcpReq.signal),e.responseFormat))}var nS=Fi().version,rS={tools:{},events:{}};function iS(e,t){let n=St().info?.description,r=new ry({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:nS,websiteUrl:M,icons:[{src:`${M}/apple-touch-icon.png`,mimeType:`image/png`,sizes:[`180x180`]}]},{capabilities:rS,...n===void 0?{}:{instructions:n}});return tS(r,e,t),ax(r),r}var aS=new Set([...Bn.options,...xi.options].map(e=>e.shape.method.value)),oS=new Set(Ux);function sS(e){let t=typeof e==`object`&&e?Reflect.get(e,`method`):void 0,n=typeof e==`object`&&e?Reflect.get(e,`params`):void 0,r=typeof n==`object`&&n?Reflect.get(n,`name`):void 0;return{rpcMethod:typeof t==`string`&&aS.has(t)?t:`other`,toolName:typeof r==`string`&&oS.has(r)?r:`none`}}var cS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),lS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isHostInSubnet=r,e.isGloballyReachable=i,e.offsetBigInt=a,e.isCorrect=o,e.prefixLengthFromMask=s,e.assertByteArray=c,e.numberToPaddedHex=l,e.stringToPaddedHex=u,e.testBit=d;var t=cS();function n(e){return this.subnetMask<e.subnetMask?!1:r.call(this,e)}function r(e){return this.binaryZeroPad().length===e.binaryZeroPad().length&&this.mask(e.subnetMask)===e.mask()}function i(e){let t=null;for(let n=0;n<e.length;n++){let i=e[n];i.reachable!==null&&r.call(this,i.subnet)&&(t===null||i.subnet.subnetMask>t.subnet.subnetMask)&&(t=i)}return t===null||t.reachable}function a(e,n,r,i){if(typeof n==`number`&&!Number.isSafeInteger(n)||typeof n!=`number`&&typeof n!=`bigint`)throw new t.AddressError(`${i} offset must be an integer`);let a=e+BigInt(n);if(a<BigInt(0)||a>(BigInt(1)<<BigInt(r))-BigInt(1))throw new t.AddressError(`${i} offset leaves the address space`);return a}function o(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function s(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function c(e,n,r,i){if(e.length!==n)throw new t.AddressError(`${r} addresses require exactly ${n} bytes`);for(let n=0;n<e.length;n++)if(!Number.isInteger(e[n])||e[n]<i||e[n]>255)throw new t.AddressError(`All bytes must be integers between ${i} and 255`)}function l(e){return e.toString(16).padStart(2,`0`)}function u(e){return l(parseInt(e,10))}function d(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),uS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/,e.SPECIAL_PURPOSE=[[`0.0.0.0/8`,`This network`,!1],[`0.0.0.0/32`,`This host on this network`,!1],[`10.0.0.0/8`,`Private-Use`,!1],[`100.64.0.0/10`,`Shared Address Space`,!1],[`127.0.0.0/8`,`Loopback`,!1],[`169.254.0.0/16`,`Link Local`,!1],[`172.16.0.0/12`,`Private-Use`,!1],[`192.0.0.0/24`,`IETF Protocol Assignments`,!1],[`192.0.0.0/29`,`IPv4 Service Continuity Prefix`,!1],[`192.0.0.8/32`,`IPv4 dummy address`,!1],[`192.0.0.9/32`,`Port Control Protocol Anycast`,!0],[`192.0.0.10/32`,`Traversal Using Relays around NAT Anycast`,!0],[`192.0.0.170/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.0.171/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.2.0/24`,`Documentation (TEST-NET-1)`,!1],[`192.31.196.0/24`,`AS112-v4`,!0],[`192.52.193.0/24`,`AMT`,!0],[`192.88.99.0/24`,`Deprecated (6to4 Relay Anycast)`,null],[`192.88.99.2/32`,`6a44-relay anycast address`,!1],[`192.168.0.0/16`,`Private-Use`,!1],[`192.175.48.0/24`,`Direct Delegation AS112 Service`,!0],[`198.18.0.0/15`,`Benchmarking`,!1],[`198.51.100.0/24`,`Documentation (TEST-NET-2)`,!1],[`203.0.113.0/24`,`Documentation (TEST-NET-3)`,!1],[`240.0.0.0/4`,`Reserved`,!1],[`255.255.255.255/32`,`Limited Broadcast`,!1]]})),dS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;var i=r(lS()),a=r(uS()),o=cS(),s=i.isCorrect(a.BITS),c=class e{constructor(e){this.addressMinusSuffix=``,this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}let n=a.GROUPS*4-1;if(e.length>n)throw new o.AddressError(`IPv4 addresses are at most ${n} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(t.some(e=>/^0\d/.test(e)))throw new o.AddressError(`IPv4 addresses can't have leading zeroes.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.?$/i,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<BigInt(0)||t>BigInt(4294967295))throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){return i.assertByteArray(e,4,`IPv4`,0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(l)}isPrivate(){return u.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(d)}isLinkLocal(){return this.isHostInSubnet(f)}isUnspecified(){return this.isHostInSubnet(p)}isBroadcast(){return this.isHostInSubnet(m)}isCGNAT(){return this.isHostInSubnet(h)}isDocumentation(){return g.some(e=>this.isHostInSubnet(e))}isBenchmarking(){return this.isHostInSubnet(_)}isReserved(){return this.isHostInSubnet(v)}isGlobal(){return!this.isMulticast()&&i.isGloballyReachable.call(this,y)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;var l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`),g=[new c(`192.0.2.0/24`),new c(`198.51.100.0/24`),new c(`203.0.113.0/24`)],_=new c(`198.18.0.0/15`),v=new c(`240.0.0.0/4`),y=a.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new c(e),reachable:t}))})),fS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"::ffff:0:0/96":`IPv4-mapped`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2001::/32":`Teredo`,"2001:2::/48":`Benchmarking`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"3fff::/20":`Documentation`,"100::/64":`Discard-only`,"fec0::/10":`Site-local unicast (deprecated)`,"::/96":`IPv4-compatible (deprecated)`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i,e.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i,e.SPECIAL_PURPOSE=[[`::1/128`,`Loopback Address`,!1],[`::/128`,`Unspecified Address`,!1],[`::ffff:0:0/96`,`IPv4-mapped Address`,!1],[`64:ff9b::/96`,`IPv4-IPv6 Translat.`,!0],[`64:ff9b:1::/48`,`IPv4-IPv6 Translat.`,!1],[`100::/64`,`Discard-Only Address Block`,!1],[`100:0:0:1::/64`,`Dummy IPv6 Prefix`,!1],[`2001::/23`,`IETF Protocol Assignments`,!1],[`2001::/32`,`TEREDO`,!1],[`2001:1::1/128`,`Port Control Protocol Anycast`,!0],[`2001:1::2/128`,`Traversal Using Relays around NAT Anycast`,!0],[`2001:1::3/128`,`DNS-SD Service Registration Protocol Anycast`,!0],[`2001:2::/48`,`Benchmarking`,!1],[`2001:3::/32`,`AMT`,!0],[`2001:4:112::/48`,`AS112-v6`,!0],[`2001:10::/28`,`Deprecated (previously ORCHID)`,null],[`2001:20::/28`,`ORCHIDv2`,!0],[`2001:30::/28`,`Drone Remote ID Protocol Entity Tags (DETs) Prefix`,!0],[`2001:db8::/32`,`Documentation`,!1],[`2002::/16`,`6to4`,!1],[`2620:4f:8000::/48`,`Direct Delegation AS112 Service`,!0],[`3fff::/20`,`Documentation`,!1],[`5f00::/16`,`Segment Routing (SRv6) SIDs`,!1],[`fc00::/7`,`Unique-Local`,!1],[`fe80::/10`,`Link-Local Unicast`,!1]]})),pS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),mS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;var i=r(fS());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),hS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;var i=r(lS()),a=r(uS()),o=r(fS()),s=r(pS()),c=dS(),l=mS(),u=cS(),d=lS(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``));let a=this.groups*5+5;if(e.length>a)throw new u.AddressError(`IPv6 addresses are at most ${a} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<BigInt(0)||t>(BigInt(1)<<BigInt(o.BITS))-BigInt(1))throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i,a,s=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,``);if(s.indexOf(`[`)!==-1&&s.indexOf(`]:`)!==-1){if(a=`failed to parse address with port`,i=o.RE_URL_WITH_PORT.exec(s),i===null)return{error:a,address:null,port:null};n=i[1],r=i[2]}else{if(a=`failed to parse address from URL`,i=o.RE_URL.exec(s),i===null)return{error:a,address:null,port:null};n=i[1]??i[2]}r?(r=parseInt(r,10),(r<0||r>65535)&&(r=null)):r=null;let c;try{c=new e(n)}catch{return{error:a,address:null,port:null}}return{address:c,port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.?$/i,``);if(!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(n))throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse(),i=r.length*4,a=r.join(``).padEnd(32,`0`),s=[];for(let e=0;e<o.GROUPS;e++)s.push(a.slice(e*4,(e+1)*4));return new e(`${s.join(`:`)}/${i}`)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isHostInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0],r=n.split(`.`);if(r.length===a.GROUPS&&r.every(e=>/^\d{1,3}$/.test(e))&&r.some(e=>/^0\d/.test(e))){let e=r.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),i=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${i}${e}`)}let i=n.match(a.RE_ADDRESS);if(i){this.parsedAddress4=i[0];let n=this.subnetMask>=96?`/${this.subnetMask-96}`:``;this.address4=new c.Address4(`${this.parsedAddress4}${n}`),this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``),t=BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`);if(this.subnetMask>=96){let e=this.subnetMask-96,n=[];for(let e=0;e<8;e+=2)n.push(parseInt(t.slice(e,e+2),16));return new c.Address4(`${n.join(`.`)}/${e}`)}return c.Address4.fromHex(t)}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=[o.slice(0,a),s.slice(0,e),`00000000`,s.slice(e),`0`.repeat(56-(32-e))].join(``)}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isHostInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16).padStart(o.BITS/4,`0`),t=[];for(let n=0,r=e.length;n<r;n+=2)t.push(parseInt(e.substring(n,n+2),16));return t}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return i.assertByteArray(e,16,`IPv6`,-128),this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){i.assertByteArray(t,16,`IPv6`,0);let n=BigInt(`256`),r=BigInt(`0`),a=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=a*BigInt(t[e].toString(10)),a*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.isHostInSubnet(w)}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let t=this.getType();return t===`Multicast`||t.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(k)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(A)?this.to4():null}isTeredo(){return this.isHostInSubnet(x)}is6to4(){return this.isHostInSubnet(S)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()===`Loopback`}isULA(){return this.isHostInSubnet(C)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()||this.isHostInSubnet(j)}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()===`Unspecified`}isDocumentation(){return T.some(e=>this.isHostInSubnet(e))}isBenchmarking(){let e=this.embeddedIPv4();return e?e.isBenchmarking():this.isHostInSubnet(E)}isGlobal(){let e=this.embeddedIPv4();return e?e.isGlobal():this.isHostInSubnet(D)&&i.isGloballyReachable.call(this,O)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;var b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`fe80::/10`),T=[new y(`2001:db8::/32`),new y(`3fff::/20`)],E=new y(`2001:2::/48`),D=new y(`2000::/3`),O=o.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new y(e),reachable:t})),k=new y(`::ffff:0:0/96`),A=new y(`64:ff9b::/96`),j=new y(`64:ff9b:1::/48`)})),gS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=dS();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=hS();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=cS();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(pS())}}))(),_S=n(sl(),1),vS=new gS.Address6(`::/96`);function yS(e,t=56){if(ra(e)){let n=new gS.Address6(e);if(n.isMapped4()||n.is4()&&n.isInSubnet(vS))return n.to4().correctForm();if(t)return new gS.Address6(`${e}/${t}`).networkForm()}return e}var bS=class{constructor(e){this.validations=e,this.previous=new Map,this.current=new Map,this.localKeys=!0}init(e){this.windowMs=e.windowMs,this.validations?.windowMs(this.windowMs),this.interval&&clearInterval(this.interval),this.interval=setInterval(()=>{this.clearExpired()},this.windowMs),this.interval.unref?.()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){let t=this.getClient(e),n=Date.now();return t.resetTime.getTime()<=n&&this.resetClient(t,n),t.totalHits++,t}async decrement(e){let t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){if(this.current.has(e))return this.current.get(e);let t;return this.previous.has(e)?(t=this.previous.get(e),this.previous.delete(e)):(t={totalHits:0,resetTime:new Date},this.resetClient(t)),this.current.set(e,t),t}clearExpired(){this.previous=this.current,this.current=new Map}},xS={warn(...e){console.warn(...e.reverse())},error(...e){console.error(...e.reverse())}},SS=[`draft-6`,`draft-7`,`draft-8`],CS=(e,t)=>{let n;if(t){let e=Math.ceil((t.getTime()-Date.now())/1e3);n=Math.max(0,e)}else n=Math.ceil(e/1e3);return n},wS=e=>{let t=ia(`sha256`);t.update(e);let n=t.digest(`hex`).slice(0,12);return $i.from(n).toString(`base64`)},TS=(e,t)=>{e.headersSent||(e.setHeader(`X-RateLimit-Limit`,t.limit.toString()),e.setHeader(`X-RateLimit-Remaining`,t.remaining.toString()),t.resetTime instanceof Date&&(e.setHeader(`Date`,new Date().toUTCString()),e.setHeader(`X-RateLimit-Reset`,Math.ceil(t.resetTime.getTime()/1e3).toString())))},ES=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=CS(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit-Limit`,t.limit.toString()),e.setHeader(`RateLimit-Remaining`,t.remaining.toString()),typeof i==`number`&&e.setHeader(`RateLimit-Reset`,i.toString())},DS=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=CS(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit`,`limit=${t.limit}, remaining=${t.remaining}, reset=${i}`)},OS=(e,t,n,r,i)=>{if(e.headersSent)return;let a=Math.ceil(n/1e3),o=CS(n,t.resetTime),s=wS(i),c=`r=${t.remaining}; t=${o}`,l=`q=${t.limit}; w=${a}; pk=:${s}:`;e.append(`RateLimit`,`"${r}"; ${c}`),e.append(`RateLimit-Policy`,`"${r}"; ${l}`)},kS=(e,t,n,r)=>{if(e.headersSent)return;let i=r??CS(n,t.resetTime);e.setHeader(`Retry-After`,i.toString())},AS=e=>{let t={};for(let n of Object.keys(e)){let r=n;e[r]!==void 0&&(t[r]=e[r])}return t},jS=class extends Error{constructor(e,t){let n=`https://express-rate-limit.github.io/${e}/`;super(`${t} See ${n} for more information.`),this.name=this.constructor.name,this.code=e,this.help=n}},MS=class extends jS{},NS=new Set,PS=new WeakMap,FS={enabled:{default:!0},disable(){for(let e of Object.keys(this.enabled))this.enabled[e]=!1},ip(e){if(e===void 0)throw new jS(`ERR_ERL_UNDEFINED_IP_ADDRESS`,`An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`);if(!ta(e))throw new jS(`ERR_ERL_INVALID_IP_ADDRESS`,`An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`)},trustProxy(e){if(e.app.get(`trust proxy`)===!0)throw new jS(`ERR_ERL_PERMISSIVE_TRUST_PROXY`,`The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`)},xForwardedForHeader(e){if(e.headers[`x-forwarded-for`]&&e.app.get(`trust proxy`)===!1)throw new jS(`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`,`The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`)},forwardedHeader(e){if(e.headers.forwarded&&e.ip===e.socket?.remoteAddress)throw new jS(`ERR_ERL_FORWARDED_HEADER`,`The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`)},positiveHits(e){if(typeof e!=`number`||e<1||e!==Math.round(e))throw new jS(`ERR_ERL_INVALID_HITS`,`The totalHits value returned from the store must be a positive integer, got ${e}`)},unsharedStore(e){if(NS.has(e)){let t=e?.localKeys?``:` (with a unique prefix)`;throw new jS(`ERR_ERL_STORE_REUSE`,`A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`)}NS.add(e)},singleCount(e,t,n){let r=PS.get(e);r||(r=new Map,PS.set(e,r));let i=t.localKeys?t:t.constructor.name,a=r.get(i);a||(a=[],r.set(i,a));let o=`${t.prefix??``}${n}`;if(a.includes(o))throw new jS(`ERR_ERL_DOUBLE_COUNT`,`The hit count for ${n} was incremented more than once for a single request.`);a.push(o)},limit(e){if(e===0)throw new MS(`WRN_ERL_MAX_ZERO`,`Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7`)},draftPolliHeaders(e){if(e)throw new MS(`WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS`,`The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`)},onLimitReached(e){if(e)throw new MS(`WRN_ERL_DEPRECATED_ON_LIMIT_REACHED`,`The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.`)},headersDraftVersion(e){if(typeof e!=`string`||!SS.includes(e))throw new jS(`ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION`,`standardHeaders: only the following versions of the IETF draft specification are supported: ${SS.join(`, `)}.`)},headersResetTime(e){if(!e)throw new jS(`ERR_ERL_HEADERS_NO_RESET`,`standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`)},knownOptions(e){if(!e)return;let t=Object.keys({windowMs:!0,limit:!0,message:!0,statusCode:!0,legacyHeaders:!0,standardHeaders:!0,identifier:!0,retryAfter:!0,requestPropertyName:!0,skipFailedRequests:!0,skipSuccessfulRequests:!0,keyGenerator:!0,ipv6Subnet:!0,handler:!0,skip:!0,requestWasSuccessful:!0,store:!0,validate:!0,headers:!0,max:!0,passOnStoreError:!0,logger:!0}).concat(`draft_polli_ratelimit_headers`,`delayAfter`,`delayMs`,`maxDelayMs`);for(let n of Object.keys(e))if(!t.includes(n))throw new jS(`ERR_ERL_UNKNOWN_OPTION`,`Unexpected configuration option: ${n}`)},validationsConfig(){let e=Object.keys(this).filter(e=>![`enabled`,`disable`].includes(e));e.push(`default`);for(let t of Object.keys(this.enabled))if(!e.includes(t))throw new jS(`ERR_ERL_UNKNOWN_VALIDATION`,`options.validate.${t} is not recognized. Supported validate options are: ${e.join(`, `)}.`)},creationStack(e){let{stack:t}=Error(`express-rate-limit validation check (set options.validate.creationStack=false to disable)`);if(t?.includes(`Layer.handle [as handle_request]`)||t?.includes(`Layer.handleRequest`))throw e.localKeys?new jS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should be created at app initialization, not when responding to a request.`):new jS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.`)},ipv6Subnet(e){if(e!==!1&&(!Number.isInteger(e)||e<32||e>64))throw new jS(`ERR_ERL_IPV6_SUBNET`,`Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`)},ipv6SubnetOrKeyGenerator(e){if(e.ipv6Subnet!==void 0&&e.keyGenerator)throw new jS(`ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR`,`Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`)},keyGeneratorIpFallback(e){if(!e)return;let t=e.toString();if((t.includes(`req.ip`)||t.includes(`request.ip`))&&!t.includes(`ipKeyGenerator`))throw new jS(`ERR_ERL_KEY_GEN_IPV6`,`Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.`)},windowMs(e){let t=2**31-1;if(typeof e!=`number`||Number.isNaN(e)||e<1||e>t)throw new jS(`ERR_ERL_WINDOW_MS`,`Invalid windowMs value: ${e}${typeof e==`number`?``:` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`)}};function IS(e){if(typeof e!=`object`||typeof e.error!=`function`||typeof e.warn!=`function`)throw TypeError(`Provided logger does not implement the Logger interface`)}var LS=(e,t)=>{IS(t);let n;n=typeof e==`boolean`?{default:e}:{default:!0,...e};let r={enabled:n};for(let[e,i]of Object.entries(FS))typeof i==`function`&&(r[e]=(...a)=>{if(n[e]??n.default){n[e]=!1;try{i.apply(r,a)}catch(e){e instanceof MS?t.warn(e):t.error(e)}}});let i=Symbol.for(`nodejs.util.inspect.custom`);return i&&(r[i]=()=>r.enabled),r},RS=e=>typeof e.incr==`function`&&typeof e.increment!=`function`,zS=e=>{if(!RS(e))return e;let t=e;class n{async increment(e){return new Promise((n,r)=>{t.incr(e,(e,t,i)=>{e&&r(e),n({totalHits:t,resetTime:i})})})}async decrement(e){return t.decrement(e)}async resetKey(e){return t.resetKey(e)}async resetAll(){if(typeof t.resetAll==`function`)return t.resetAll()}}return new n},BS=e=>{let{validations:t,...n}=e;return{...n,validate:t.enabled}},VS=e=>{let t=AS(e),n=e.logger??xS,r=LS(t?.validate??!0,n);r.validationsConfig(),r.knownOptions(e),r.draftPolliHeaders(t.draft_polli_ratelimit_headers),r.onLimitReached(t.onLimitReached),t.ipv6Subnet!==void 0&&typeof t.ipv6Subnet!=`function`&&r.ipv6Subnet(t.ipv6Subnet),r.keyGeneratorIpFallback(t.keyGenerator),r.ipv6SubnetOrKeyGenerator(t);let i=t.standardHeaders??!1;i===!0&&(i=`draft-6`);let a={windowMs:6e4,limit:e.max??5,message:`Too many requests, please try again later.`,statusCode:429,legacyHeaders:e.headers??!0,identifier(e,t){let n=``,{limit:r}=e[a.requestPropertyName],i=a.windowMs/1e3,o=a.windowMs/6e4,s=a.windowMs/36e5,c=a.windowMs/864e5;return n=i<60?`${i}sec`:o<60?`${o}min`:s<24?`${s}hr${s>1?`s`:``}`:`${c}day${c>1?`s`:``}`,`${r}-in-${n}`},requestPropertyName:`rateLimit`,skipFailedRequests:!1,skipSuccessfulRequests:!1,requestWasSuccessful:(e,t)=>t.statusCode<400,skip:(e,t)=>!1,async keyGenerator(e,t){r.ip(e.ip),r.trustProxy(e),r.xForwardedForHeader(e),r.forwardedHeader(e);let n=e.ip,i=56;return ra(n)&&(i=typeof a.ipv6Subnet==`function`?await a.ipv6Subnet(e,t):a.ipv6Subnet,typeof a.ipv6Subnet==`function`&&r.ipv6Subnet(i)),yS(n,i)},ipv6Subnet:56,async handler(e,t,n,r){t.status(a.statusCode);let i=typeof a.message==`function`?await a.message(e,t):a.message;t.writableEnded||t.send(i)},passOnStoreError:!1,...t,standardHeaders:i,store:zS(t.store??new bS(r)),validations:r,logger:n};if(typeof a.store.increment!=`function`||typeof a.store.decrement!=`function`||typeof a.store.resetKey!=`function`||a.store.resetAll!==void 0&&typeof a.store.resetAll!=`function`||a.store.init!==void 0&&typeof a.store.init!=`function`)throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");return a},HS=e=>async(t,n,r)=>{try{await Promise.resolve(e(t,n,r)).catch(r)}catch(e){r(e)}},US=e=>{let t=VS(e??{}),n=BS(t),r=(0,_S.default)(`express-rate-limit`);r(`creating new rate limiter with %o`,t.store.constructor.name);for(let[e,n]of Object.entries(t))r(`set %s to %o`,e,n);if(t.validations.creationStack(t.store),t.validations.unsharedStore(t.store),typeof t.store.init==`function`){r(`executing init for store`);try{let e=t.store.init(n);e instanceof Promise&&e.catch(e=>t.logger.error(e,`express-rate-limit: async error during store initialization.`))}catch(e){t.logger.error(e,`express-rate-limit: error during store initialization.`)}}let i=HS(async(e,i,a)=>{let o=t.skipFailedRequests&&new Promise(e=>i.once(`close`,e)),s=(t.skipFailedRequests||t.skipSuccessfulRequests)&&new Promise(e=>i.once(`finish`,e)),c=t.skipFailedRequests&&new Promise(e=>i.once(`error`,e));if(r(`requested %o`,e.originalUrl),r(`request from ip %o`,e.ip),await t.skip(e,i)){r(`skipping request`),a();return}let l=e,u=await t.keyGenerator(e,i);r(`computed key %o`,u),r(`incrementing count`);let d=0,f;try{let e=await t.store.increment(u);d=e.totalHits,f=e.resetTime}catch(e){if(t.passOnStoreError){t.logger.error(e,`express-rate-limit: error from store, allowing request without rate-limiting.`),a();return}throw e}t.validations.positiveHits(d),t.validations.singleCount(e,t.store,u);let p=await(typeof t.limit==`function`?t.limit(e,i):t.limit);t.validations.limit(p);let m={limit:p,used:d,remaining:Math.max(p-d,0),resetTime:f,key:u};for(let[e,n]of Object.entries(m))r(`set request.%s.%s to be %o`,t.requestPropertyName,e,n);if(Object.defineProperty(m,"current",{configurable:!1,enumerable:!1,value:d}),l[t.requestPropertyName]=m,t.legacyHeaders&&!i.headersSent&&(r(`set legacy headers`),TS(i,m)),t.standardHeaders&&!i.headersSent)switch(t.standardHeaders){case`draft-6`:r(`set ietf draft 6 headers`),ES(i,m,t.windowMs);break;case`draft-7`:r(`set ietf draft 7 headers`),t.validations.headersResetTime(m.resetTime),DS(i,m,t.windowMs);break;case`draft-8`:{let n=await(typeof t.identifier==`function`?t.identifier(e,i):t.identifier);r(`set ietf draft 8 headers`),r(`set name to %o`,n),t.validations.headersResetTime(m.resetTime),OS(i,m,t.windowMs,n,u);break}default:t.validations.headersDraftVersion(t.standardHeaders)}if(t.skipFailedRequests||t.skipSuccessfulRequests){let n=!1,a=async()=>{if(!n){if(f&&Date.now()>=f.getTime())return;r(`decrementing count`),await t.store.decrement(u),n=!0}};t.skipFailedRequests&&(s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n||await a()}),o&&o.then(async()=>{i.writableEnded||await a()}),c&&c.then(async()=>{await a()})),t.skipSuccessfulRequests&&s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n&&await a()})}if(d>p){if(r(`limit exceeded`),t.legacyHeaders||t.standardHeaders){r(`set retry-after header`);let n=await(typeof t.retryAfter==`function`?t.retryAfter(e,i):t.retryAfter);kS(i,m,t.windowMs,n)}t.handler(e,i,a,n);return}a()});return i.resetKey=t.store.resetKey.bind(t.store),i.getKey=typeof t.store.get==`function`?t.store.get.bind(t.store):()=>{throw Error(`The current store does not support the get/getKey method`)},i},WS=Yi.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:De(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,aa()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)})),GS={ttlMs:ni,maxEntries:128,verificationDeadlineMs:1e4,degradedGrantMaxAgeMs:ni+6e5,maxConcurrentVerifications:16,maxOverBudgetVerifications:2},KS=()=>new Sr({status:429,title:`Too Many Requests`,type:`about:blank`,detail:`Too many credential verifications are in progress; retry shortly.`,retryAfterSeconds:1}),qS=e=>e instanceof Sr?Kr(e.problem.status,e.problem):Et(e);function JS(e){if(!e.includes(`.`))return 1/0;try{let{exp:t}=nn(e);return t===void 0?1/0:t*1e3}catch(e){if(!(e instanceof Di))throw e;return 1/0}}var YS=(e,t)=>`${ia(`sha256`).update(e).digest(`hex`)} ${t?.href??``}`;function XS(e=GS){let t=new Map,n={limit:e.maxConcurrentVerifications,inFlight:0},r={limit:e.maxOverBudgetVerifications,inFlight:0},i=(i,a,o)=>{let s=YS(i,a),c=t.get(s);if(c!==void 0&&c.expiresAt>Date.now())return t.delete(s),t.set(s,c),c.verification;let l=c?.grant,u=t=>{let n=l===void 0?1/0:Date.now()-l.grantedAt,r=n<e.degradedGrantMaxAgeMs&&JS(i)>Date.now();if(l===void 0||!r||!qS(t))throw t;return ae({component:`aventure-mcp-server`,event:`authentication_degraded`,fields:{requestId:_e(),grantAgeMs:n},error:t}),l.authorization},d=o?[n,r]:[n];if(d.some(({inFlight:e,limit:t})=>e>=t))return Promise.reject(KS());t.delete(s);for(let e of d)e.inFlight+=1;let f=()=>{for(let e of d)--e.inFlight},p=Yt(i,a,WS,e.verificationDeadlineMs).catch(u),m={verification:p,expiresAt:1/0,grant:l};t.set(s,m);for(let n of t.keys()){if(t.size<=e.maxEntries)break;t.delete(n)}let h=()=>{t.get(s)===m&&t.delete(s)};return p.then(t=>{f(),t===null||t===`forbidden`?h():t===l?.authorization?m.expiresAt=0:(m.grant={authorization:t,grantedAt:Date.now()},m.expiresAt=Math.min(Date.now()+e.ttlMs,JS(i)))},()=>{f(),h()}),p},a=(e,n)=>{let r=Mr(e.header(`authorization`));if(r===void 0)return!1;let i=t.get(YS(r,n))?.expiresAt;return i!==void 0&&Number.isFinite(i)&&i>Date.now()},o=async(e,t,n)=>{let r=e.header(`authorization`),a=Mr(r);if(a===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await i(a,t,n);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:a,authorization:e}}catch(e){if(!(e instanceof Di))throw e;ae({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:_e()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}},s=new WeakMap,c=(e,t,n=!1)=>{let r=s.get(e);if(r!==void 0&&r.resourceHref===t?.href)return r.decision;let i=o(e,t,n);return s.set(e,{resourceHref:t?.href,decision:i}),i};return Object.assign((e,t)=>c(e,t),{holdsGrant:a,admitsOverBudget:(e,t)=>Mr(e.header(`authorization`))===void 0?Promise.resolve(!1):c(e,t,!0).then(e=>e.ok,()=>!1)})}function ZS(e,t){let n=new WeakMap;return[US({windowMs:6e4,limit:120,skipSuccessfulRequests:!0,skip:async n=>e.holdsGrant(n,await t()),handler:(...[e,,t,r])=>{n.set(e,r),t()}}),async(r,i,a)=>{let o=n.get(r);o===void 0||await e.admitsOverBudget(r,await t())?a():i.status(o.statusCode).send(o.message)},US({windowMs:6e4,limit:120,keyGenerator:QS})]}function QS(e){let t=Mr(e.header(`authorization`));return t===void 0?yS(e.ip??``):ia(`sha256`).update(t).digest(`base64url`)}function $S(e,t){let n=`an API key from https://aventure.vc/settings/api-keys as Authorization: Bearer <key>`,r=t?`Sign in with OAuth through the authorization server in this server's resource metadata; a client that cannot register itself needs the OAuth client ID at https://docs.aventure.vc/mcp. Or send ${n}.`:`Send ${n}. This server advertises no OAuth authorization server.`;return e===`forbidden`?`The supplied credential is valid, but its account may not use this MCP server.`:e===`missing_credential`?r:`The supplied credential was rejected or expired; reconnect this server in the MCP client to sign in again. ${r}`}var eC=1024,tC=eC*eC,nC=1,rC=2,iC=`b`,aC=`kb`,oC=`mb`,sC=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function cC(e){let t=uC(e.limit),n=lC(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||lC(r.path)!==n){a();return}let o=dC(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function lC(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function uC(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=sC.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[nC]);if(Number.isFinite(n))switch(t[rC]??iC){case oC:return Math.floor(n*tC);case aC:return Math.floor(n*eC);case iC:return Math.floor(n)}}function dC(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var fC=256e3,pC=16e3,mC=256,hC=31,gC=127,_C=36e5,vC=`openai/session`,yC=`mcpCallOutcome`;function bC(e,t){let n=`${t??``} ${e??``}`.toLowerCase();return n.includes(`openai-mcp`)||n.includes(`chatgpt`)?`chatgpt`:n.includes(`claude-user`)||n.includes(`claude-ai`)||n.includes(`claude.ai`)?`claude_ai`:n.includes(`claude-code`)||n.includes(`claude code`)?`claude_code`:n.includes(`grok`)?`grok`:n.includes(`codex`)?`codex`:n.includes(`cursor`)?`cursor`:n.includes(`gemini`)||n.includes(`antigravity`)?`gemini`:`other`}function xC(e){let t=typeof e==`object`&&e?Reflect.get(e,`params`):void 0;if(typeof t!=`object`||!t)return{};let n=Reflect.get(t,`_meta`),r=Reflect.get(t,`clientInfo`)??(typeof n==`object`&&n?Reflect.get(n,`io.modelcontextprotocol/clientInfo`):void 0);if(typeof r!=`object`||!r)return{};let i=Reflect.get(r,`name`),a=Reflect.get(r,`version`);return{name:typeof i==`string`?i:void 0,version:typeof a==`string`?a:void 0}}function SC(e,t){let n=t.locals[yC];return{client:bC(e.get(`user-agent`),xC(e.body).name),outcome:CC(n)?n:`none`}}function CC(e){return e===`ok`||e===`tool_error`||e===`protocol_error`||e===`aborted`}function wC(e,t){let n=[],r=0,i=(e,t)=>{if(r>=fC||e==null)return;let i=typeof e==`string`?Buffer.from(e,typeof t==`string`&&Buffer.isEncoding(t)?t:`utf8`):e instanceof Uint8Array?Buffer.from(e):void 0;i!==void 0&&(n.push(i.subarray(0,fC-r)),r+=i.length)},a=e.write.bind(e),o=e.end.bind(e);e.write=((t,n,r)=>(i(t,n),Reflect.apply(a,e,[t,n,r].filter(e=>e!==void 0)))),e.end=((r,a,s)=>(typeof r!=`function`&&i(r,a),t(Buffer.concat(n).toString(`utf8`)),Reflect.apply(o,e,[r,a,s].filter(e=>e!==void 0))))}function TC(e,t){let n=e.trimStart().startsWith(`{`)?[e]:e.split(`
145
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());for(let e of n){let n;try{n=JSON.parse(e)}catch(e){return{outcome:`protocol_error`,text:``,summary:`unparseable reply: ${String(e)}`}}let r=ir.safeParse(n);if(!r.success||!(`id`in r.data)||r.data.id!==t)continue;if(`error`in r.data)return{outcome:`protocol_error`,text:``,summary:r.data.error.message};if(!(`result`in r.data))continue;let i=Br.safeParse(r.data.result);if(!i.success)return{outcome:`protocol_error`,text:``,summary:`malformed tool result`};let a=Ni(i.data.structuredContent),o=i.data.content.find(e=>e.type===`text`);return{outcome:i.data.isError===!0?`tool_error`:`ok`,text:o?.type===`text`?o.text:``,httpStatus:a?.httpStatus??a?.problem?.status,problemType:a?.problem?.type,summary:a?.summary}}return{outcome:`protocol_error`,text:``,summary:`no JSON-RPC reply to this call`}}function EC(e,t){return typeof e==`object`&&e?Reflect.get(e,t):void 0}function DC(e){return OC(typeof e==`object`&&e?Object.keys(e).join(`,`):``)}function OC(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n]??``,i=e.charCodeAt(n);t+=i<=hC||i===gC?`�`:r}return t.length>mC?`${t.slice(0,255)}…`:t}function kC(e,t){let n=EC(t,vC);return typeof n==`string`&&n.length>0?`${e}:${OC(n)}`:`${e}:${ia(`sha256`).update(ke()??`anonymous`).digest(`hex`).slice(0,16)}:${Math.floor(Date.now()/_C)}`}var AC=e=>e.length>pC?`${e.slice(0,pC)}…`:e;async function jC(e,t,n){let r=tr.safeParse(e.body),i=typeof e.body==`object`&&e.body!==null?Reflect.get(e.body,`id`):void 0;if(!r.success||typeof i!=`string`&&typeof i!=`number`){await n();return}let a=performance.now(),o=e.get(`user-agent`),s=xC(e.body),c=bC(o,s.name),l=Reflect.get(r.data.params,`_meta`),u=r.data.params.arguments,d=typeof u?.operationId==`string`?OC(u.operationId):void 0,f=s.name===void 0?void 0:OC(s.name),p=s.version===void 0?void 0:OC(s.version),m=o===void 0?void 0:OC(o),h=kC(c,l),g=sS(e.body).toolName,_=EC(l,Rr),v=ye(`mcp ${g}`,{"langfuse.trace.name":`mcp ${g}`,"langfuse.session.id":h,"langfuse.trace.tags":[`mcp`,c,g],"langfuse.observation.type":`tool`,"langfuse.observation.input":AC(JSON.stringify(u??{})),"langfuse.environment":ce()[`deployment.environment.name`]??`unknown`,...process.env.GIT_SHA===void 0?{}:{"langfuse.release":process.env.GIT_SHA},"langfuse.trace.metadata.client":c,"langfuse.trace.metadata.client_name":f??``,"langfuse.trace.metadata.client_version":p??``,"langfuse.trace.metadata.user_agent":m??``,"langfuse.trace.metadata.operation_id":d??``,"langfuse.trace.metadata.meta_keys":DC(l),"aventure.request_id":_e()??``,"mcp.tool.name":g,"mcp.tool.requested_name":OC(r.data.params.name)},typeof _==`string`?_:void 0);wC(t,n=>{let r=t.destroyed||e.socket.destroyed?{outcome:`aborted`,text:``}:TC(n,i);t.locals[yC]=r.outcome;let o=r.outcome===`tool_error`||r.outcome===`protocol_error`,s={requestId:_e(),toolName:g,operationId:d,client:c,clientName:f,clientVersion:p,userAgent:m,metaKeys:DC(l),sessionId:h,outcome:r.outcome,httpStatus:r.httpStatus,problemType:r.problemType,resultChars:r.text.length,durationMs:Math.round(performance.now()-a),traceId:v?.spanContext().traceId};(o?ae:k)({component:`aventure-mcp-server`,event:`tool_call`,fields:s}),v!==void 0&&Ce(v,{"langfuse.observation.output":AC(r.text),"langfuse.observation.level":o?`ERROR`:`DEFAULT`,...r.summary===void 0?{}:{"langfuse.observation.status_message":r.summary},"langfuse.trace.metadata.outcome":r.outcome,"langfuse.trace.metadata.http_status":String(r.httpStatus??``),"langfuse.trace.metadata.problem_type":r.problemType??``,"mcp.tool.outcome":r.outcome},o)}),v===void 0?await n():await Oe(xe(v),n)}var MC=400,NC=400,PC=413,FC=`10mb`,IC=`127.0.0.1`,LC=/^[\w.:/-]{1,128}$/,RC=`0.0.0.0`;async function zC(e){let t=e.jsonBodyLimit??FC,n=XS(),r=e.host??IC,i=r!==RC,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,rf.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=e.get(`x-client-request-id`)??``,i=LC.test(r)?r:aa(),a=performance.now(),o={requestId:i,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},s=HC(e);s||k({component:`aventure-mcp-server`,event:`http_request`,fields:o}),t.on(`finish`,()=>{let n=Math.round(performance.now()-a),r=e.route,i=typeof r==`object`&&r?Reflect.get(r,`path`):null,c={...sS(e.body),...SC(e,t)};Rb(e.method,typeof i==`string`?i:`unmatched`,t.statusCode,n,c),!(s&&t.statusCode<MC)&&(t.statusCode>=MC&&!s?ae:k)({component:`aventure-mcp-server`,event:`http_response`,fields:{...o,...c,status:t.statusCode,durationMs:n}})}),ge(i,()=>n())}),o.use(i?(0,nf.default)({origin:VC}):(0,nf.default)()),o.use(cC({path:e.path,limit:t,reject:e=>UC(e,PC,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(rf.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,nf.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){UC(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),zb(o,e.metricsScrapeSecret),be(),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>e[1].redirect(302,`${M}/favicon.ico`));let s=ZS(n,async()=>(await e.resolveOAuthDiscovery())?.resourceUrl);return o.post(e.path,s,async(t,r)=>{let o=_e(),s=t.header(`origin`);if(i&&!BC(s)){ae({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),UC(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){Yc(e,`authentication_unavailable`),N({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof Sr&&(e.problem.status===429||Pi(e.problem.status))?e.problem:void 0;n===void 0?UC(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),WC(r,n));return}if(!c.ok){ae({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${Av(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`);let n=c.reason===`forbidden`;UC(r,n?403:401,n?`Forbidden`:`Unauthorized`,$S(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){UC(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}k({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{Yc(e,`transport_error`),N({component:`aventure-mcp-server`,event:`transport_error`,message:le(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=jy(()=>iS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await Zy(p,{onerror:f})(t,r,t.body);for(let e of d)Pi(r.statusCode)?f(e):(r.statusCode<MC?k:ae)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:le(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})},h=()=>jC(t,r,m);c.userBearerToken===void 0?await h():await Se(c.userBearerToken,h)}),o.all(e.path,(...e)=>UC(e[1],405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=GC(e);if(i===void 0){r(e);return}ae({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:_e(),method:t.method,path:t.path,status:i.status}}),UC(n,i.status,i.status===PC?`Payload Too Large`:`Bad Request`,i.status===PC?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Promise.all([Bb(),we()])}})}),i.on(`error`,n)})}function BC(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:na(t)&&t.startsWith(`127.`)}var VC=(e,t)=>t(null,BC(e)),HC=e=>e.method===`GET`&&/^\/(?:robots\.txt|health)\/?$/iu.test(e.path);function UC(e,t,n,r){WC(e,{type:`about:blank`,title:n,status:t,detail:r})}function WC(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function GC(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?PC:e.type===`entity.parse.failed`?NC:e.status===PC||e.status===NC?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}var KC=65535,qC=55e3,JC=Fi(ea(import.meta.url)),{host:YC}=(await new p().name(JC.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(JC.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
146
146
  Connect an MCP client to the server's /mcp URL and send
147
147
  Authorization: Bearer <credential> using an OAuth access token or API key from
148
148
  aventure.vc. The hosted