@easbot/gateway 0.2.39 → 0.2.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/chunk-3SBZTZXS.cjs +7 -0
- package/dist/chunks/chunk-OBFSXYWV.mjs +30 -0
- package/dist/chunks/chunk-RFOEJ3A2.cjs +30 -0
- package/dist/chunks/chunk-RGPJTZUB.mjs +7 -0
- package/dist/chunks/log-FQII2FT4.mjs +1 -0
- package/dist/chunks/log-VLMXTUPA.cjs +1 -0
- package/dist/chunks/server-3QASQ56E.cjs +1 -0
- package/dist/chunks/server-54GY5XXD.mjs +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +210 -23
- package/dist/index.d.ts +210 -23
- package/dist/index.mjs +2 -2
- package/package.json +5 -5
- package/dist/chunks/chunk-7OFQ65NG.mjs +0 -7
- package/dist/chunks/chunk-AUPHFE34.cjs +0 -7
- package/dist/chunks/chunk-GY3SWWW3.cjs +0 -1
- package/dist/chunks/chunk-H425RRAV.mjs +0 -18
- package/dist/chunks/chunk-HAMGVOQD.mjs +0 -1
- package/dist/chunks/chunk-O6R6U45A.cjs +0 -18
- package/dist/chunks/global-FIBJJFBN.cjs +0 -1
- package/dist/chunks/global-Z3HUTR5L.mjs +0 -2
- package/dist/chunks/log-JFEBRH2W.cjs +0 -1
- package/dist/chunks/log-MIT4H7S5.mjs +0 -1
- package/dist/chunks/server-4GO5DAEQ.cjs +0 -1
- package/dist/chunks/server-QOFBCSK5.mjs +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import Zi,{win32,posix}from'path';import ch,{realpath,readlink,readdir,lstat}from'fs/promises';import*as Ln from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import mo from'zod';import {fileURLToPath}from'url';import {EventEmitter}from'events';import Nr from'stream';import {StringDecoder}from'string_decoder';import {formatLogTime}from'@easbot/utils';var fh=Object.defineProperty;var Cs=e=>{throw TypeError(e)};var dh=(e,t,i)=>t in e?fh(e,t,{enumerable:true,configurable:true,writable:true,value:i}):e[t]=i;var p=(e,t,i)=>dh(e,typeof t!="symbol"?t+"":t,i),Yi=(e,t,i)=>t.has(e)||Cs("Cannot "+i);var r=(e,t,i)=>(Yi(e,t,"read from private field"),i?i.call(e):t.get(e)),m=(e,t,i)=>t.has(e)?Cs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),c=(e,t,i,s)=>(Yi(e,t,"write to private field"),t.set(e,i),i),g=(e,t,i)=>(Yi(e,t,"access private method"),i);var ki=(e,t,i,s)=>({set _(h){c(e,t,h);},get _(){return r(e,t,s)}});var br=(e,t,i)=>{let s=e instanceof RegExp?Os(e,i):e,h=t instanceof RegExp?Os(t,i):t,n=s!==null&&h!=null&&wh(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},Os=(e,t)=>{let i=t.match(e);return i?i[0]:null},wh=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},Sr="\0SLASH"+Math.random()+"\0",vr="\0OPEN"+Math.random()+"\0",Ss="\0CLOSE"+Math.random()+"\0",Er="\0COMMA"+Math.random()+"\0",xr="\0PERIOD"+Math.random()+"\0",yh=new RegExp(Sr,"g"),bh=new RegExp(vr,"g"),Sh=new RegExp(Ss,"g"),vh=new RegExp(Er,"g"),Eh=new RegExp(xr,"g"),xh=/\\\\/g,kh=/\\{/g,Rh=/\\}/g,Ch=/\\,/g,Oh=/\\./g,Ah=1e5;function Xi(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Fh(e){return e.replace(xh,Sr).replace(kh,vr).replace(Rh,Ss).replace(Ch,Er).replace(Oh,xr)}function Th(e){return e.replace(yh,"\\").replace(bh,"{").replace(Sh,"}").replace(vh,",").replace(Eh,".")}function kr(e){if(!e)return [""];let t=[],i=br("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=kr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Lh(e,t={}){if(!e)return [];let{max:i=Ah}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),qe(Fh(e),i,true).map(Th)}function Mh(e){return "{"+e+"}"}function Wh(e){return /^-?0\d/.test(e)}function Ph(e,t){return e<=t}function Dh(e,t){return e>=t}function qe(e,t,i){let s=[],h=br("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?qe(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+Ss+h.post,qe(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=kr(h.body),f.length===1&&f[0]!==void 0&&(f=qe(f[0],t,false).map(Mh),f.length===1))return o.map(v=>h.pre+f[0]+v);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let v=Xi(f[0]),S=Xi(f[1]),y=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Xi(f[2])):1,E=Ph;S<v&&(x*=-1,E=Dh);let O=f.some(Wh);w=[];for(let A=v;E(A,S);A+=x){let T;if(l)T=String.fromCharCode(A),T==="\\"&&(T="");else if(T=String(A),O){let L=y-T.length;if(L>0){let mt=new Array(L+1).join("0");A<0?T="-"+mt+T.slice(1):T=mt+T;}}w.push(T);}}else {w=[];for(let v=0;v<f.length;v++)w.push.apply(w,qe(f[v],t,false));}for(let v=0;v<w.length;v++)for(let S=0;S<o.length&&s.length<t;S++){let y=n+w[v]+o[S];(!i||u||y)&&s.push(y);}}return s}var Bi=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},jh={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},Be=e=>e.replace(/[[\]\\-]/g,"\\$&"),Nh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),As=e=>e.join(""),zh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let S=e.charAt(n);if((S==="!"||S==="^")&&n===i+1){u=true,n++;continue}if(S==="]"&&o&&!l){d=n+1;break}if(o=true,S==="\\"&&!l){l=true,n++;continue}if(S==="["&&!l){for(let[y,[x,E,O]]of Object.entries(jh))if(e.startsWith(y,n)){if(f)return ["$.",false,e.length-i,true];n+=y.length,O?h.push(x):s.push(x),a=a||E;continue t}}if(l=false,f){S>f?s.push(Be(f)+"-"+Be(S)):S===f&&s.push(Be(S)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push(Be(S+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=S,n+=2;continue}s.push(Be(S)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let S=s[0].length===2?s[0].slice(-1):s[0];return [Nh(S),false,d-i,false]}let w="["+(u?"^":"")+As(s)+"]",v="["+(u?"":"^")+As(h)+"]";return [s.length&&h.length?"("+w+"|"+v+")":s.length?w:v,a,d-i,true]},Oe=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),_h=new Set(["!","?","+","*","@"]),Fs=e=>_h.has(e),$h="(?!(?:^|/)\\.\\.?(?:$|/))",Ri="(?!\\.)",Bh=new Set(["[","."]),Uh=new Set(["..","."]),Gh=new Set("().*{}+?[]^$\\!"),Ih=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vs="[^/]",Ts=vs+"*?",Ls=vs+"+?",B,Z,Bt,W,_,te,pe,ee,Dt,fe,ti,Ee,Cr,oe,Y,Wi,ns,Or,Rr=(Y=class{constructor(t,i,s={}){m(this,Ee);p(this,"type");m(this,B);m(this,Z);m(this,Bt,false);m(this,W,[]);m(this,_);m(this,te);m(this,pe);m(this,ee,false);m(this,Dt);m(this,fe);m(this,ti,false);this.type=t,t&&c(this,Z,true),c(this,_,i),c(this,B,r(this,_)?r(r(this,_),B):this),c(this,Dt,r(this,B)===this?s:r(r(this,B),Dt)),c(this,pe,r(this,B)===this?[]:r(r(this,B),pe)),t==="!"&&!r(r(this,B),ee)&&r(this,pe).push(this),c(this,te,r(this,_)?r(r(this,_),W).length:0);}get hasMagic(){if(r(this,Z)!==void 0)return r(this,Z);for(let t of r(this,W))if(typeof t!="string"&&(t.type||t.hasMagic))return c(this,Z,true);return r(this,Z)}toString(){return r(this,fe)!==void 0?r(this,fe):this.type?c(this,fe,this.type+"("+r(this,W).map(t=>String(t)).join("|")+")"):c(this,fe,r(this,W).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof Y&&r(i,_)===this))throw new Error("invalid part: "+i);r(this,W).push(i);}}toJSON(){let t=this.type===null?r(this,W).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...r(this,W).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===r(this,B)||r(r(this,B),ee)&&r(this,_)?.type==="!")&&t.push({}),t}isStart(){if(r(this,B)===this)return true;if(!r(this,_)?.isStart())return false;if(r(this,te)===0)return true;let t=r(this,_);for(let i=0;i<r(this,te);i++){let s=r(t,W)[i];if(!(s instanceof Y&&s.type==="!"))return false}return true}isEnd(){if(r(this,B)===this||r(this,_)?.type==="!")return true;if(!r(this,_)?.isEnd())return false;if(!this.type)return r(this,_)?.isEnd();let t=r(this,_)?r(r(this,_),W).length:0;return r(this,te)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new Y(this.type,t);for(let s of r(this,W))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new Y(null,void 0,i);return g(h=Y,oe,Wi).call(h,t,s,0,i),s}toMMPattern(){if(this!==r(this,B))return r(this,B).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||r(this,Z)||r(this,Dt).nocase&&!r(this,Dt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(r(this,Dt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return r(this,Dt)}toRegExpSource(t){let i=t??!!r(this,Dt).dot;if(r(this,B)===this&&g(this,Ee,Cr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!r(this,W).some(w=>typeof w!="string"),u=r(this,W).map(w=>{var E;let[v,S,y,x]=typeof w=="string"?g(E=Y,oe,Or).call(E,w,r(this,Z),l):w.toRegExpSource(t);return c(this,Z,r(this,Z)||y),c(this,Bt,r(this,Bt)||x),v}).join(""),d="";if(this.isStart()&&typeof r(this,W)[0]=="string"&&!(r(this,W).length===1&&Uh.has(r(this,W)[0]))){let w=Bh,v=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),S=!i&&!t&&w.has(u.charAt(0));d=v?$h:S?Ri:"";}let f="";return this.isEnd()&&r(r(this,B),ee)&&r(this,_)?.type==="!"&&(f="(?:$|\\/)"),[d+u+f,Oe(u),c(this,Z,!!r(this,Z)),r(this,Bt)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=g(this,Ee,ns).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return c(this,W,[l]),this.type=null,c(this,Z,void 0),[l,Oe(this.toString()),false,false]}let o=!s||t||i||!Ri?"":g(this,Ee,ns).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&r(this,ti))a=(this.isStart()&&!i?Ri:"")+Ls;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?Ri:"")+Ts+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Oe(n),c(this,Z,!!r(this,Z)),r(this,Bt)]}},B=new WeakMap,Z=new WeakMap,Bt=new WeakMap,W=new WeakMap,_=new WeakMap,te=new WeakMap,pe=new WeakMap,ee=new WeakMap,Dt=new WeakMap,fe=new WeakMap,ti=new WeakMap,Ee=new WeakSet,Cr=function(){if(this!==r(this,B))throw new Error("should only call on root");if(r(this,ee))return this;this.toString(),c(this,ee,true);let t;for(;t=r(this,pe).pop();){if(t.type!=="!")continue;let i=t,s=r(i,_);for(;s;){for(let h=r(i,te)+1;!s.type&&h<r(s,W).length;h++)for(let n of r(t,W)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(r(s,W)[h]);}i=s,s=r(i,_);}}return this},oe=new WeakSet,Wi=function(t,i,s,h){var v,S;let n=false,o=false,a=-1,l=false;if(i.type===null){let y=s,x="";for(;y<t.length;){let E=t.charAt(y++);if(n||E==="\\"){n=!n,x+=E;continue}if(o){y===a+1?(E==="^"||E==="!")&&(l=true):E==="]"&&!(y===a+2&&l)&&(o=false),x+=E;continue}else if(E==="["){o=true,a=y,l=false,x+=E;continue}if(!h.noext&&Fs(E)&&t.charAt(y)==="("){i.push(x),x="";let O=new Y(E,i);y=g(v=Y,oe,Wi).call(v,t,O,y,h),i.push(O);continue}x+=E;}return i.push(x),y}let u=s+1,d=new Y(null,i),f=[],w="";for(;u<t.length;){let y=t.charAt(u++);if(n||y==="\\"){n=!n,w+=y;continue}if(o){u===a+1?(y==="^"||y==="!")&&(l=true):y==="]"&&!(u===a+2&&l)&&(o=false),w+=y;continue}else if(y==="["){o=true,a=u,l=false,w+=y;continue}if(Fs(y)&&t.charAt(u)==="("){d.push(w),w="";let x=new Y(y,d);d.push(x),u=g(S=Y,oe,Wi).call(S,t,x,u,h);continue}if(y==="|"){d.push(w),w="",f.push(d),d=new Y(null,i);continue}if(y===")")return w===""&&r(i,W).length===0&&c(i,ti,true),d.push(w),w="",i.push(...f,d),u;w+=y;}return i.type=null,c(i,Z,void 0),c(i,W,[t.substring(s-1)]),u},ns=function(t){return r(this,W).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return c(this,Bt,r(this,Bt)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},Or=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(Gh.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?Ls:Ts,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,v]=zh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||v;continue}}if(u==="?"){n+=vs,i=true;continue}n+=Ih(u);}return [n,Oe(t),!!i,o]},m(Y,oe),Y),Ar=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),nt=(e,t,i={})=>(Bi(t),!i.nocomment&&t.charAt(0)==="#"?false:new ae(t,i).match(e)),Hh=/^\*+([^+@!?\*\[\(]*)$/,Jh=e=>t=>!t.startsWith(".")&&t.endsWith(e),qh=e=>t=>t.endsWith(e),Zh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Vh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Kh=/^\*+\.\*+$/,Yh=e=>!e.startsWith(".")&&e.includes("."),Xh=e=>e!=="."&&e!==".."&&e.includes("."),Qh=/^\.\*+$/,tn=e=>e!=="."&&e!==".."&&e.startsWith("."),en=/^\*+$/,sn=e=>e.length!==0&&!e.startsWith("."),rn=e=>e.length!==0&&e!=="."&&e!=="..",hn=/^\?+([^+@!?\*\[\(]*)?$/,nn=([e,t=""])=>{let i=Fr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},on=([e,t=""])=>{let i=Tr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},an=([e,t=""])=>{let i=Tr([e]);return t?s=>i(s)&&s.endsWith(t):i},ln=([e,t=""])=>{let i=Fr([e]);return t?s=>i(s)&&s.endsWith(t):i},Fr=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Tr=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Lr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ms={win32:{sep:"\\"},posix:{sep:"/"}},cn=Lr==="win32"?Ms.win32.sep:Ms.posix.sep;nt.sep=cn;var ht=Symbol("globstar **");nt.GLOBSTAR=ht;var un="[^/]",pn=un+"*?",fn="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",dn="(?:(?!(?:\\/|^)\\.).)*?",gn=(e,t={})=>i=>nt(i,e,t);nt.filter=gn;var wt=(e,t={})=>Object.assign({},e,t),mn=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return nt;let t=nt;return Object.assign((i,s,h={})=>t(i,s,wt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,wt(e,s));}static defaults(i){return t.defaults(wt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,wt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,wt(e,s))}},unescape:(i,s={})=>t.unescape(i,wt(e,s)),escape:(i,s={})=>t.escape(i,wt(e,s)),filter:(i,s={})=>t.filter(i,wt(e,s)),defaults:i=>t.defaults(wt(e,i)),makeRe:(i,s={})=>t.makeRe(i,wt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,wt(e,s)),match:(i,s,h={})=>t.match(i,s,wt(e,h)),sep:t.sep,GLOBSTAR:ht})};nt.defaults=mn;var Mr=(e,t={})=>(Bi(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Lh(e,{max:t.braceExpandMax}));nt.braceExpand=Mr;var wn=(e,t={})=>new ae(e,t).makeRe();nt.makeRe=wn;var yn=(e,t,i={})=>{let s=new ae(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};nt.match=yn;var Ws=/[?*]|[+@!]\(.*?\)|\[|\]/,bn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ae=class{constructor(e,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");Bi(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Lr,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ws.test(h[2]))&&!Ws.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let S=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!S&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),E=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),O=y?3:S?0:void 0,A=E?3:x?0:void 0;if(typeof O=="number"&&typeof A=="number"){let[T,L]=[e[O],t[A]];T.toLowerCase()===L.toLowerCase()&&(t[A]=T,A>O?t=t.slice(A):O>A&&(e=e.slice(O)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===ht){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var v=e[f];if(this.debug(`
|
|
2
|
+
globstar while`,e,f,t,w,v),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,v),true;if(v==="."||v===".."||!s.dot&&v.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
|
|
3
|
+
>>> no match, partial?`,e,f,t,w),f===a))}let S;if(typeof u=="string"?(S=d===u,this.debug("string match",u,d,S)):(S=u.test(d),this.debug("pattern match",u,d,S)),!S)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Mr(this.pattern,this.options)}parse(e){Bi(e);let t=this.options;if(e==="**")return ht;if(e==="")return "";let i,s=null;(i=e.match(en))?s=t.dot?rn:sn:(i=e.match(Hh))?s=(t.nocase?t.dot?Vh:Zh:t.dot?qh:Jh)(i[1]):(i=e.match(hn))?s=(t.nocase?t.dot?on:nn:t.dot?an:ln)(i):(i=e.match(Kh))?s=t.dot?Xh:Yh:(i=e.match(Qh))&&(s=tn);let h=Rr.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?pn:t.dot?fn:dn,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?bn(d):d===ht?ht:d._src});l.forEach((d,f)=>{let w=l[f+1],v=l[f-1];d!==ht||v===ht||(v===void 0?w!==void 0&&w!==ht?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=v+"(?:\\/|\\/"+i+")?":w!==ht&&(l[f-1]=v+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=ht));});let u=l.filter(d=>d!==ht);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return nt.defaults(e).Minimatch}};nt.AST=Rr;nt.Minimatch=ae;nt.escape=Ar;nt.unescape=Oe;var vn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Wr=new Set,os=typeof process=="object"&&process?process:{},Pr=(e,t,i,s)=>{typeof os.emitWarning=="function"?os.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Ui=globalThis.AbortController,Ps=globalThis.AbortSignal;if(typeof Ui>"u"){Ps=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Ui=class{constructor(){p(this,"signal",new Ps);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e=os.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Pr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var En=e=>!Wr.has(e),Kt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Dr=e=>Kt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Pi:null:null,Pi=class extends Array{constructor(e){super(e),this.fill(0);}},zt,Ae,xn=(zt=class{constructor(t,i){p(this,"heap");p(this,"length");if(!r(zt,Ae))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=Dr(t);if(!i)return [];c(zt,Ae,true);let s=new zt(t,i);return c(zt,Ae,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Ae=new WeakMap,m(zt,Ae,false),zt),Vs,Ks,bt,ut,kt,de,Rt,Fe,Te,Ct,U,Ot,$,P,C,it,pt,tt,V,At,K,Ft,Tt,ft,dt,Lt,ie,st,Le,b,as,ge,Ut,ei,gt,jr,me,Me,ii,Yt,Xt,ls,Di,ji,M,cs,Ze,Qt,us,We,Hi=(We=class{constructor(t){m(this,b);m(this,bt);m(this,ut);m(this,kt);m(this,de);m(this,Rt);m(this,Fe);m(this,Te);m(this,Ct);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");m(this,U);m(this,Ot);m(this,$);m(this,P);m(this,C);m(this,it);m(this,pt);m(this,tt);m(this,V);m(this,At);m(this,K);m(this,Ft);m(this,Tt);m(this,ft);m(this,dt);m(this,Lt);m(this,ie);m(this,st);m(this,Le);m(this,ge,()=>{});m(this,Ut,()=>{});m(this,ei,()=>{});m(this,gt,()=>false);m(this,me,t=>{});m(this,Me,(t,i,s)=>{});m(this,ii,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Vs,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:u,onInsert:d,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:v,maxSize:S=0,maxEntrySize:y=0,sizeCalculation:x,fetchMethod:E,memoMethod:O,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:mt,ignoreFetchAbort:F,perf:D}=t;if(D!==void 0&&typeof D?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(c(this,Ct,D??vn),i!==0&&!Kt(i))throw new TypeError("max option must be a nonnegative integer");let N=i?Dr(i):Array;if(!N)throw new Error("invalid max value: "+i);if(c(this,bt,i),c(this,ut,S),this.maxEntrySize=y||r(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!r(this,ut)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(O!==void 0&&typeof O!="function")throw new TypeError("memoMethod must be a function if defined");if(c(this,Te,O),E!==void 0&&typeof E!="function")throw new TypeError("fetchMethod must be a function if specified");if(c(this,Fe,E),c(this,ie,!!E),c(this,$,new Map),c(this,P,new Array(i).fill(void 0)),c(this,C,new Array(i).fill(void 0)),c(this,it,new N(i)),c(this,pt,new N(i)),c(this,tt,0),c(this,V,0),c(this,At,xn.create(i)),c(this,U,0),c(this,Ot,0),typeof u=="function"&&c(this,kt,u),typeof d=="function"&&c(this,de,d),typeof f=="function"?(c(this,Rt,f),c(this,K,[])):(c(this,Rt,void 0),c(this,K,void 0)),c(this,Lt,!!r(this,kt)),c(this,Le,!!r(this,de)),c(this,st,!!r(this,Rt)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!mt,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(r(this,ut)!==0&&!Kt(r(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Kt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");g(this,b,jr).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Kt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Kt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");g(this,b,as).call(this);}if(r(this,bt)===0&&this.ttl===0&&r(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!r(this,bt)&&!r(this,ut)){let X="LRU_CACHE_UNBOUNDED";En(X)&&(Wr.add(X),Pr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",X,We));}}get perf(){return r(this,Ct)}static unsafeExposeInternals(t){return {starts:r(t,Tt),ttls:r(t,ft),autopurgeTimers:r(t,dt),sizes:r(t,Ft),keyMap:r(t,$),keyList:r(t,P),valList:r(t,C),next:r(t,it),prev:r(t,pt),get head(){return r(t,tt)},get tail(){return r(t,V)},free:r(t,At),isBackgroundFetch:i=>{var s;return g(s=t,b,M).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return g(o=t,b,ji).call(o,i,s,h,n)},moveToTail:i=>{var s;return g(s=t,b,Ze).call(s,i)},indexes:i=>{var s;return g(s=t,b,Yt).call(s,i)},rindexes:i=>{var s;return g(s=t,b,Xt).call(s,i)},isStale:i=>{var s;return r(s=t,gt).call(s,i)}}}get max(){return r(this,bt)}get maxSize(){return r(this,ut)}get calculatedSize(){return r(this,Ot)}get size(){return r(this,U)}get fetchMethod(){return r(this,Fe)}get memoMethod(){return r(this,Te)}get dispose(){return r(this,kt)}get onInsert(){return r(this,de)}get disposeAfter(){return r(this,Rt)}getRemainingTTL(t){return r(this,$).has(t)?1/0:0}*entries(){for(let t of g(this,b,Yt).call(this))r(this,C)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield [r(this,P)[t],r(this,C)[t]]);}*rentries(){for(let t of g(this,b,Xt).call(this))r(this,C)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield [r(this,P)[t],r(this,C)[t]]);}*keys(){for(let t of g(this,b,Yt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield i);}}*rkeys(){for(let t of g(this,b,Xt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield i);}}*values(){for(let t of g(this,b,Yt).call(this))r(this,C)[t]!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield r(this,C)[t]);}*rvalues(){for(let t of g(this,b,Xt).call(this))r(this,C)[t]!==void 0&&!g(this,b,M).call(this,r(this,C)[t])&&(yield r(this,C)[t]);}[(Ks=Symbol.iterator,Vs=Symbol.toStringTag,Ks)](){return this.entries()}find(t,i={}){for(let s of g(this,b,Yt).call(this)){let h=r(this,C)[s],n=g(this,b,M).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,r(this,P)[s],this))return this.get(r(this,P)[s],i)}}forEach(t,i=this){for(let s of g(this,b,Yt).call(this)){let h=r(this,C)[s],n=g(this,b,M).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}rforEach(t,i=this){for(let s of g(this,b,Xt).call(this)){let h=r(this,C)[s],n=g(this,b,M).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}purgeStale(){let t=false;for(let i of g(this,b,Xt).call(this,{allowStale:true}))r(this,gt).call(this,i)&&(g(this,b,Qt).call(this,r(this,P)[i],"expire"),t=true);return t}info(t){let i=r(this,$).get(t);if(i===void 0)return;let s=r(this,C)[i],h=g(this,b,M).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(r(this,ft)&&r(this,Tt)){let o=r(this,ft)[i],a=r(this,Tt)[i];if(o&&a){let l=o-(r(this,Ct).now()-a);n.ttl=l,n.start=Date.now();}}return r(this,Ft)&&(n.size=r(this,Ft)[i]),n}dump(){let t=[];for(let i of g(this,b,Yt).call(this,{allowStale:true})){let s=r(this,P)[i],h=r(this,C)[i],n=g(this,b,M).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(r(this,ft)&&r(this,Tt)){o.ttl=r(this,ft)[i];let a=r(this,Ct).now()-r(this,Tt)[i];o.start=Math.floor(Date.now()-a);}r(this,Ft)&&(o.size=r(this,Ft)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=r(this,Ct).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,v,S,y;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d=r(this,ii).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),g(this,b,Qt).call(this,t,"set"),this;let f=r(this,U)===0?void 0:r(this,$).get(t);if(f===void 0)f=r(this,U)===0?r(this,V):r(this,At).length!==0?r(this,At).pop():r(this,U)===r(this,bt)?g(this,b,Di).call(this,false):r(this,U),r(this,P)[f]=t,r(this,C)[f]=i,r(this,$).set(t,f),r(this,it)[r(this,V)]=f,r(this,pt)[f]=r(this,V),c(this,V,f),ki(this,U)._++,r(this,Me).call(this,f,d,l),l&&(l.set="add"),u=false,r(this,Le)&&((w=r(this,de))==null||w.call(this,i,t,"add"));else {g(this,b,Ze).call(this,f);let x=r(this,C)[f];if(i!==x){if(r(this,ie)&&g(this,b,M).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:E}=x;E!==void 0&&!o&&(r(this,Lt)&&((v=r(this,kt))==null||v.call(this,E,t,"set")),r(this,st)&&r(this,K)?.push([E,t,"set"]));}else o||(r(this,Lt)&&((S=r(this,kt))==null||S.call(this,x,t,"set")),r(this,st)&&r(this,K)?.push([x,t,"set"]));if(r(this,me).call(this,f),r(this,Me).call(this,f,d,l),r(this,C)[f]=i,l){l.set="replace";let E=x&&g(this,b,M).call(this,x)?x.__staleWhileFetching:x;E!==void 0&&(l.oldValue=E);}}else l&&(l.set="update");r(this,Le)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!r(this,ft)&&g(this,b,as).call(this),r(this,ft)&&(u||r(this,ei).call(this,f,h,n),l&&r(this,Ut).call(this,l,f)),!o&&r(this,st)&&r(this,K)){let x=r(this,K),E;for(;E=x?.shift();)(y=r(this,Rt))==null||y.call(this,...E);}return this}pop(){var t;try{for(;r(this,U);){let i=r(this,C)[r(this,tt)];if(g(this,b,Di).call(this,!0),g(this,b,M).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(r(this,st)&&r(this,K)){let i=r(this,K),s;for(;s=i?.shift();)(t=r(this,Rt))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=r(this,$).get(t);if(n!==void 0){let o=r(this,C)[n];if(g(this,b,M).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(r(this,gt).call(this,n))h&&(h.has="stale",r(this,Ut).call(this,h,n));else return s&&r(this,ge).call(this,n),h&&(h.has="hit",r(this,Ut).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=r(this,$).get(t);if(h===void 0||!s&&r(this,gt).call(this,h))return;let n=r(this,C)[h];return g(this,b,M).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:v=this.ignoreFetchAbort,allowStaleOnFetchAbort:S=this.allowStaleOnFetchAbort,context:y,forceRefresh:x=false,status:E,signal:O}=i;if(!r(this,ie))return E&&(E.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:E});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:S,ignoreFetchAbort:v,status:E,signal:O},T=r(this,$).get(t);if(T===void 0){E&&(E.fetch="miss");let L=g(this,b,ji).call(this,t,T,A,y);return L.__returned=L}else {let L=r(this,C)[T];if(g(this,b,M).call(this,L)){let N=s&&L.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=true)),N?L.__staleWhileFetching:L.__returned=L}let mt=r(this,gt).call(this,T);if(!x&&!mt)return E&&(E.fetch="hit"),g(this,b,Ze).call(this,T),h&&r(this,ge).call(this,T),E&&r(this,Ut).call(this,E,T),L;let F=g(this,b,ji).call(this,t,T,A,y),D=F.__staleWhileFetching!==void 0&&s;return E&&(E.fetch=mt?"stale":"refresh",D&&mt&&(E.returnedStale=true)),D?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=r(this,Te);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=r(this,$).get(t);if(a!==void 0){let l=r(this,C)[a],u=g(this,b,M).call(this,l);return o&&r(this,Ut).call(this,o,a),r(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||g(this,b,Qt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(g(this,b,Ze).call(this,a),h&&r(this,ge).call(this,a),l))}else o&&(o.get="miss");}delete(t){return g(this,b,Qt).call(this,t,"delete")}clear(){return g(this,b,us).call(this,"delete")}},bt=new WeakMap,ut=new WeakMap,kt=new WeakMap,de=new WeakMap,Rt=new WeakMap,Fe=new WeakMap,Te=new WeakMap,Ct=new WeakMap,U=new WeakMap,Ot=new WeakMap,$=new WeakMap,P=new WeakMap,C=new WeakMap,it=new WeakMap,pt=new WeakMap,tt=new WeakMap,V=new WeakMap,At=new WeakMap,K=new WeakMap,Ft=new WeakMap,Tt=new WeakMap,ft=new WeakMap,dt=new WeakMap,Lt=new WeakMap,ie=new WeakMap,st=new WeakMap,Le=new WeakMap,b=new WeakSet,as=function(){let t=new Pi(r(this,bt)),i=new Pi(r(this,bt));c(this,ft,t),c(this,Tt,i);let s=this.ttlAutopurge?new Array(r(this,bt)):void 0;c(this,dt,s),c(this,ei,(o,a,l=r(this,Ct).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{r(this,gt).call(this,o)&&g(this,b,Qt).call(this,r(this,P)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),c(this,ge,o=>{i[o]=t[o]!==0?r(this,Ct).now():0;}),c(this,Ut,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=r(this,Ct).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=r(this,$).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},c(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},ge=new WeakMap,Ut=new WeakMap,ei=new WeakMap,gt=new WeakMap,jr=function(){let t=new Pi(r(this,bt));c(this,Ot,0),c(this,Ft,t),c(this,me,i=>{c(this,Ot,r(this,Ot)-t[i]),t[i]=0;}),c(this,ii,(i,s,h,n)=>{if(g(this,b,M).call(this,s))return 0;if(!Kt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Kt(h))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return h}),c(this,Me,(i,s,h)=>{if(t[i]=s,r(this,ut)){let n=r(this,ut)-t[i];for(;r(this,Ot)>n;)g(this,b,Di).call(this,true);}c(this,Ot,r(this,Ot)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=r(this,Ot));});},me=new WeakMap,Me=new WeakMap,ii=new WeakMap,Yt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,V);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,tt)));)i=r(this,pt)[i];},Xt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,tt);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,V)));)i=r(this,it)[i];},ls=function(t){return t!==void 0&&r(this,$).get(r(this,P)[t])===t},Di=function(t){var n;let i=r(this,tt),s=r(this,P)[i],h=r(this,C)[i];return r(this,ie)&&g(this,b,M).call(this,h)?h.__abortController.abort(new Error("evicted")):(r(this,Lt)||r(this,st))&&(r(this,Lt)&&((n=r(this,kt))==null||n.call(this,h,s,"evict")),r(this,st)&&r(this,K)?.push([h,s,"evict"])),r(this,me).call(this,i),r(this,dt)?.[i]&&(clearTimeout(r(this,dt)[i]),r(this,dt)[i]=void 0),t&&(r(this,P)[i]=void 0,r(this,C)[i]=void 0,r(this,At).push(i)),r(this,U)===1?(c(this,tt,c(this,V,0)),r(this,At).length=0):c(this,tt,r(this,it)[i]),r(this,$).delete(s),ki(this,U)._--,i},ji=function(t,i,s,h){let n=i===void 0?void 0:r(this,C)[i];if(g(this,b,M).call(this,n))return n;let o=new Ui,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(y,x=false)=>{let{aborted:E}=o.signal,O=s.ignoreFetchAbort&&y!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&y!==void 0);if(s.status&&(E&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,O&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),E&&!O&&!x)return f(o.signal.reason,A);let T=v,L=r(this,C)[i];return (L===v||O&&x&&L===void 0)&&(y===void 0?T.__staleWhileFetching!==void 0?r(this,C)[i]=T.__staleWhileFetching:g(this,b,Qt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,y,l.options))),y},d=y=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=y),f(y,false)),f=(y,x)=>{let{aborted:E}=o.signal,O=E&&s.allowStaleOnFetchAbort,A=O||s.allowStaleOnFetchRejection,T=A||s.noDeleteOnFetchRejection,L=v;if(r(this,C)[i]===v&&(!T||!x&&L.__staleWhileFetching===void 0?g(this,b,Qt).call(this,t,"fetch"):O||(r(this,C)[i]=L.__staleWhileFetching)),A)return s.status&&L.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),L.__staleWhileFetching;if(L.__returned===L)throw y},w=(y,x)=>{var O;let E=(O=r(this,Fe))==null?void 0:O.call(this,t,n,l);E&&E instanceof Promise&&E.then(A=>y(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(y(void 0),s.allowStaleOnFetchAbort&&(y=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let v=new Promise(w).then(u,d),S=Object.assign(v,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,S,{...l.options,status:void 0}),i=r(this,$).get(t)):r(this,C)[i]=S,S},M=function(t){if(!r(this,ie))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Ui},cs=function(t,i){r(this,pt)[i]=t,r(this,it)[t]=i;},Ze=function(t){t!==r(this,V)&&(t===r(this,tt)?c(this,tt,r(this,it)[t]):g(this,b,cs).call(this,r(this,pt)[t],r(this,it)[t]),g(this,b,cs).call(this,r(this,V),t),c(this,V,t));},Qt=function(t,i){var h,n;let s=false;if(r(this,U)!==0){let o=r(this,$).get(t);if(o!==void 0)if(r(this,dt)?.[o]&&(clearTimeout(r(this,dt)?.[o]),r(this,dt)[o]=void 0),s=true,r(this,U)===1)g(this,b,us).call(this,i);else {r(this,me).call(this,o);let a=r(this,C)[o];if(g(this,b,M).call(this,a)?a.__abortController.abort(new Error("deleted")):(r(this,Lt)||r(this,st))&&(r(this,Lt)&&((h=r(this,kt))==null||h.call(this,a,t,i)),r(this,st)&&r(this,K)?.push([a,t,i])),r(this,$).delete(t),r(this,P)[o]=void 0,r(this,C)[o]=void 0,o===r(this,V))c(this,V,r(this,pt)[o]);else if(o===r(this,tt))c(this,tt,r(this,it)[o]);else {let l=r(this,pt)[o];r(this,it)[l]=r(this,it)[o];let u=r(this,it)[o];r(this,pt)[u]=r(this,pt)[o];}ki(this,U)._--,r(this,At).push(o);}}if(r(this,st)&&r(this,K)?.length){let o=r(this,K),a;for(;a=o?.shift();)(n=r(this,Rt))==null||n.call(this,...a);}return s},us=function(t){var i,s;for(let h of g(this,b,Xt).call(this,{allowStale:true})){let n=r(this,C)[h];if(g(this,b,M).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=r(this,P)[h];r(this,Lt)&&((i=r(this,kt))==null||i.call(this,n,o,t)),r(this,st)&&r(this,K)?.push([n,o,t]);}}if(r(this,$).clear(),r(this,C).fill(void 0),r(this,P).fill(void 0),r(this,ft)&&r(this,Tt)){r(this,ft).fill(0),r(this,Tt).fill(0);for(let h of r(this,dt)??[])h!==void 0&&clearTimeout(h);r(this,dt)?.fill(void 0);}if(r(this,Ft)&&r(this,Ft).fill(0),c(this,tt,0),c(this,V,0),r(this,At).length=0,c(this,Ot,0),c(this,U,0),r(this,st)&&r(this,K)){let h=r(this,K),n;for(;n=h?.shift();)(s=r(this,Rt))==null||s.call(this,...n);}},We),Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},Nn=e=>!!e&&typeof e=="object"&&(e instanceof Gi||e instanceof Nr||zn(e)||_n(e)),zn=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.pipe=="function"&&e.pipe!==Nr.Writable.prototype.pipe,_n=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",_t=Symbol("EOF"),$t=Symbol("maybeEmitEnd"),Vt=Symbol("emittedEnd"),Ci=Symbol("emittingEnd"),Ue=Symbol("emittedError"),Oi=Symbol("closed"),js=Symbol("read"),Ai=Symbol("flush"),Ns=Symbol("flushChunk"),Et=Symbol("encoding"),Re=Symbol("decoder"),H=Symbol("flowing"),Ge=Symbol("paused"),Ce=Symbol("resume"),J=Symbol("buffer"),et=Symbol("pipes"),q=Symbol("bufferLength"),Qi=Symbol("bufferPush"),Fi=Symbol("bufferShift"),Q=Symbol("objectMode"),z=Symbol("destroyed"),ts=Symbol("error"),es=Symbol("emitData"),zs=Symbol("emitEnd"),is=Symbol("emitEnd2"),Wt=Symbol("async"),ss=Symbol("abort"),Ti=Symbol("aborted"),Ie=Symbol("signal"),le=Symbol("dataListeners"),ct=Symbol("discarded"),He=e=>Promise.resolve().then(e),$n=e=>e(),Bn=e=>e==="end"||e==="finish"||e==="prefinish",Un=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Gn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),zr=class{constructor(e,t,i){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Ce](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},In=class extends zr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},Hn=e=>!!e.objectMode,Jn=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Ys,Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,fr,dr,gr,Gi=class extends EventEmitter{constructor(...t){let i=t[0]||{};super();p(this,gr,false);p(this,dr,false);p(this,fr,[]);p(this,pr,[]);p(this,ur);p(this,cr);p(this,lr);p(this,ar);p(this,or,false);p(this,nr,false);p(this,hr,false);p(this,rr,false);p(this,sr,null);p(this,ir,0);p(this,er,false);p(this,tr);p(this,Qs,false);p(this,Xs,0);p(this,Ys,false);p(this,"writable",true);p(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Hn(i)?(this[Q]=true,this[Et]=null):Jn(i)?(this[Et]=i.encoding,this[Q]=false):(this[Q]=false,this[Et]=null),this[Wt]=!!i.async,this[Re]=this[Et]?new StringDecoder(this[Et]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[J]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:s}=i;s&&(this[Ie]=s,s.aborted?this[ss]():s.addEventListener("abort",()=>this[ss]()));}get bufferLength(){return this[q]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Q]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Wt]}set async(t){this[Wt]=this[Wt]||!!t;}[(gr=H,dr=Ge,fr=et,pr=J,ur=Q,cr=Et,lr=Wt,ar=Re,or=_t,nr=Vt,hr=Ci,rr=Oi,sr=Ue,ir=q,er=z,tr=Ie,Qs=Ti,Xs=le,Ys=ct,ss)](){this[Ti]=true,this.emit("abort",this[Ie]?.reason),this.destroy(this[Ie]?.reason);}get aborted(){return this[Ti]}set aborted(t){}write(t,i,s){if(this[Ti])return false;if(this[_t])throw new Error("write after end");if(this[z])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let h=this[Wt]?He:$n;if(!this[Q]&&!Buffer.isBuffer(t)){if(Gn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Un(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Q]?(this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):t.length?(typeof t=="string"&&!(i===this[Et]&&!this[Re]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[Et]&&(t=this[Re].write(t)),this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):(this[q]!==0&&this.emit("readable"),s&&h(s),this[H])}read(t){if(this[z])return null;if(this[ct]=false,this[q]===0||t===0||t&&t>this[q])return this[$t](),null;this[Q]&&(t=null),this[J].length>1&&!this[Q]&&(this[J]=[this[Et]?this[J].join(""):Buffer.concat(this[J],this[q])]);let i=this[js](t||null,this[J][0]);return this[$t](),i}[js](t,i){if(this[Q])this[Fi]();else {let s=i;t===s.length||t===null?this[Fi]():typeof s=="string"?(this[J][0]=s.slice(t),i=s.slice(0,t),this[q]-=t):(this[J][0]=s.subarray(t),i=s.subarray(0,t),this[q]-=t);}return this.emit("data",i),!this[J].length&&!this[_t]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[_t]=true,this.writable=false,(this[H]||!this[Ge])&&this[$t](),this}[Ce](){this[z]||(!this[le]&&!this[et].length&&(this[ct]=true),this[Ge]=false,this[H]=true,this.emit("resume"),this[J].length?this[Ai]():this[_t]?this[$t]():this.emit("drain"));}resume(){return this[Ce]()}pause(){this[H]=false,this[Ge]=true,this[ct]=false;}get destroyed(){return this[z]}get flowing(){return this[H]}get paused(){return this[Ge]}[Qi](t){this[Q]?this[q]+=1:this[q]+=t.length,this[J].push(t);}[Fi](){return this[Q]?this[q]-=1:this[q]-=this[J][0].length,this[J].shift()}[Ai](t=false){do;while(this[Ns](this[Fi]())&&this[J].length);!t&&!this[J].length&&!this[_t]&&this.emit("drain");}[Ns](t){return this.emit("data",t),this[H]}pipe(t,i){if(this[z])return t;this[ct]=false;let s=this[Vt];return i=i||{},t===Ds.stdout||t===Ds.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[et].push(i.proxyErrors?new In(this,t,i):new zr(this,t,i)),this[Wt]?He(()=>this[Ce]()):this[Ce]()),t}unpipe(t){let i=this[et].find(s=>s.dest===t);i&&(this[et].length===1?(this[H]&&this[le]===0&&(this[H]=false),this[et]=[]):this[et].splice(this[et].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[le]++,!this[et].length&&!this[H]&&this[Ce]();else if(t==="readable"&&this[q]!==0)super.emit("readable");else if(Bn(t)&&this[Vt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ue]){let h=i;this[Wt]?He(()=>h.call(this,this[Ue])):h.call(this,this[Ue]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[le]=this.listeners("data").length,this[le]===0&&!this[ct]&&!this[et].length&&(this[H]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[le]=0,!this[ct]&&!this[et].length&&(this[H]=false)),i}get emittedEnd(){return this[Vt]}[$t](){!this[Ci]&&!this[Vt]&&!this[z]&&this[J].length===0&&this[_t]&&(this[Ci]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Oi]&&this.emit("close"),this[Ci]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return false;if(t==="data")return !this[Q]&&!s?false:this[Wt]?(He(()=>this[es](s)),true):this[es](s);if(t==="end")return this[zs]();if(t==="close"){if(this[Oi]=true,!this[Vt]&&!this[z])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Ue]=s,super.emit(ts,s);let n=!this[Ie]||this.listeners("error").length?super.emit("error",s):false;return this[$t](),n}else if(t==="resume"){let n=super.emit("resume");return this[$t](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[$t](),h}[es](t){for(let s of this[et])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[$t](),i}[zs](){return this[Vt]?false:(this[Vt]=true,this.readable=false,this[Wt]?(He(()=>this[is]()),true):this[is]())}[is](){if(this[Re]){let i=this[Re].end();if(i){for(let s of this[et])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[et])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Q]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[Q]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[Q])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(z,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[_t])return i();let h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(z,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(z,u),this.pause(),h({value:d,done:!!this[_t]});},l=()=>{this.off("error",o),this.off("data",a),this.off(z,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(z,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(ts,i),this.off(z,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(ts,i),this.once(z,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=true,this[ct]=true,this[J].length=0,this[q]=0;let i=this;return typeof i.close=="function"&&!this[Oi]&&i.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return Nn}},qn=realpathSync.native,Ve={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:qn,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},_r=e=>!e||e===Ve||e===Ln?Ve:{...Ve,...e,promises:{...Ve.promises,...e.promises||{}}},$r=/^\\\\\?\\([a-z]:)\\?$/i,Zn=e=>e.replace(/\//g,"\\").replace($r,"$1\\"),Vn=/[\\\/]/,St=0,Br=1,Ur=2,Pt=4,Gr=6,Ir=8,ce=10,Hr=12,yt=15,Je=~yt,rs=16,_s=32,Ke=64,xt=128,Li=256,Ni=512,$s=Ke|xt|Ni,Kn=1023,hs=e=>e.isFile()?Ir:e.isDirectory()?Pt:e.isSymbolicLink()?ce:e.isCharacterDevice()?Ur:e.isBlockDevice()?Gr:e.isSocket()?Hr:e.isFIFO()?Br:St,Bs=new Hi({max:2**12}),Ye=e=>{let t=Bs.get(e);if(t)return t;let i=e.normalize("NFKD");return Bs.set(e,i),i},Us=new Hi({max:2**12}),Mi=e=>{let t=Us.get(e);if(t)return t;let i=Ye(e.toLowerCase());return Us.set(e,i),i},Gs=class extends Hi{constructor(){super({max:256});}},Yn=class extends Hi{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Jr=Symbol("PathScurry setAsCwd"),rt,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,Si,se,we,jt,Gt,It,Ht,R,ye,Jt,Nt,k,fs,zi,Xe,ds,gs,Qe,_i,ms,ws,$i,qr,Zr,Vr,ys,Pe,De,Kr,be,mr,at=(mr=class{constructor(e,t=St,i,s,h,n,o){m(this,k);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);m(this,rt);m(this,si);m(this,ri);m(this,hi);m(this,ni);m(this,oi);m(this,ai);m(this,li);m(this,ci);m(this,ui);m(this,pi);m(this,fi);m(this,di);m(this,gi);m(this,mi);m(this,wi);m(this,yi);m(this,bi);m(this,Si);m(this,se);m(this,we);m(this,jt);m(this,Gt);m(this,It);m(this,Ht);m(this,R);m(this,ye);m(this,Jt);m(this,Nt);m(this,Pe,[]);m(this,De,false);m(this,be);this.name=e,c(this,se,h?Mi(e):Ye(e)),c(this,R,t&Kn),this.nocase=h,this.roots=s,this.root=i||this,c(this,ye,n),c(this,jt,o.fullpath),c(this,It,o.relative),c(this,Ht,o.relativePosix),this.parent=o.parent,this.parent?c(this,rt,r(this.parent,rt)):c(this,rt,_r(o.fs));}get dev(){return r(this,si)}get mode(){return r(this,ri)}get nlink(){return r(this,hi)}get uid(){return r(this,ni)}get gid(){return r(this,oi)}get rdev(){return r(this,ai)}get blksize(){return r(this,li)}get ino(){return r(this,ci)}get size(){return r(this,ui)}get blocks(){return r(this,pi)}get atimeMs(){return r(this,fi)}get mtimeMs(){return r(this,di)}get ctimeMs(){return r(this,gi)}get birthtimeMs(){return r(this,mi)}get atime(){return r(this,wi)}get mtime(){return r(this,yi)}get ctime(){return r(this,bi)}get birthtime(){return r(this,Si)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return r(this,we)!==void 0?r(this,we):this.parent?c(this,we,this.parent.depth()+1):c(this,we,0)}childrenCache(){return r(this,ye)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i=e.substring(t.length).split(this.splitSep);return t?g(s=this.getRoot(t),k,fs).call(s,i):g(this,k,fs).call(this,i)}children(){let e=r(this,ye).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return r(this,ye).set(this,t),c(this,R,r(this,R)&~rs),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Mi(e):Ye(e);for(let a of i)if(r(a,se)===s)return a;let h=this.parent?this.sep:"",n=r(this,jt)?r(this,jt)+h+e:void 0,o=this.newChild(e,St,{...t,parent:this,fullpath:n});return this.canReaddir()||c(o,R,r(o,R)|xt),i.push(o),o}relative(){if(this.isCWD)return "";if(r(this,It)!==void 0)return r(this,It);let e=this.name,t=this.parent;if(!t)return c(this,It,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(r(this,Ht)!==void 0)return r(this,Ht);let e=this.name,t=this.parent;if(!t)return c(this,Ht,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(r(this,jt)!==void 0)return r(this,jt);let e=this.name,t=this.parent;if(!t)return c(this,jt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return c(this,jt,i)}fullpathPosix(){if(r(this,Gt)!==void 0)return r(this,Gt);if(this.sep==="/")return c(this,Gt,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?c(this,Gt,`//?/${s}`):c(this,Gt,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return c(this,Gt,i)}isUnknown(){return (r(this,R)&yt)===St}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (r(this,R)&yt)===Ir}isDirectory(){return (r(this,R)&yt)===Pt}isCharacterDevice(){return (r(this,R)&yt)===Ur}isBlockDevice(){return (r(this,R)&yt)===Gr}isFIFO(){return (r(this,R)&yt)===Br}isSocket(){return (r(this,R)&yt)===Hr}isSymbolicLink(){return (r(this,R)&ce)===ce}lstatCached(){return r(this,R)&_s?this:void 0}readlinkCached(){return r(this,Jt)}realpathCached(){return r(this,Nt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(r(this,Jt))return true;if(!this.parent)return false;let e=r(this,R)&yt;return !(e!==St&&e!==ce||r(this,R)&Li||r(this,R)&xt)}calledReaddir(){return !!(r(this,R)&rs)}isENOENT(){return !!(r(this,R)&xt)}isNamed(e){return this.nocase?r(this,se)===Mi(e):r(this,se)===Ye(e)}async readlink(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await r(this,rt).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}readlinkSync(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=r(this,rt).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}async lstat(){if((r(this,R)&xt)===0)try{return g(this,k,ys).call(this,await r(this,rt).promises.lstat(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}lstatSync(){if((r(this,R)&xt)===0)try{return g(this,k,ys).call(this,r(this,rt).lstatSync(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e(null,h):queueMicrotask(()=>e(null,h));return}if(r(this,Pe).push(e),r(this,De))return;c(this,De,true);let s=this.fullpath();r(this,rt).readdir(s,{withFileTypes:true},(h,n)=>{if(h)g(this,k,_i).call(this,h.code),i.provisional=0;else {for(let o of n)g(this,k,$i).call(this,o,i);g(this,k,zi).call(this,i);}g(this,k,Kr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(r(this,be))await r(this,be);else {let i=()=>{};c(this,be,new Promise(s=>i=s));try{for(let s of await r(this,rt).promises.readdir(t,{withFileTypes:!0}))g(this,k,$i).call(this,s,e);g(this,k,zi).call(this,e);}catch(s){g(this,k,_i).call(this,s.code),e.provisional=0;}c(this,be,void 0),i();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i of r(this,rt).readdirSync(t,{withFileTypes:!0}))g(this,k,$i).call(this,i,e);g(this,k,zi).call(this,e);}catch(i){g(this,k,_i).call(this,i.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(r(this,R)&$s)return false;let e=yt&r(this,R);return e===St||e===Pt||e===ce}shouldWalk(e,t){return (r(this,R)&Pt)===Pt&&!(r(this,R)&$s)&&!e.has(this)&&(!t||t(this))}async realpath(){if(r(this,Nt))return r(this,Nt);if(!((Ni|Li|xt)&r(this,R)))try{let e=await r(this,rt).promises.realpath(this.fullpath());return c(this,Nt,this.resolve(e))}catch{g(this,k,gs).call(this);}}realpathSync(){if(r(this,Nt))return r(this,Nt);if(!((Ni|Li|xt)&r(this,R)))try{let e=r(this,rt).realpathSync(this.fullpath());return c(this,Nt,this.resolve(e))}catch{g(this,k,gs).call(this);}}[Jr](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),c(s,It,i.join(this.sep)),c(s,Ht,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)c(s,It,void 0),c(s,Ht,void 0),s=s.parent;}},rt=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,Si=new WeakMap,se=new WeakMap,we=new WeakMap,jt=new WeakMap,Gt=new WeakMap,It=new WeakMap,Ht=new WeakMap,R=new WeakMap,ye=new WeakMap,Jt=new WeakMap,Nt=new WeakMap,k=new WeakSet,fs=function(e){let t=this;for(let i of e)t=t.child(i);return t},zi=function(e){var t;c(this,R,r(this,R)|rs);for(let i=e.provisional;i<e.length;i++){let s=e[i];s&&g(t=s,k,Xe).call(t);}},Xe=function(){r(this,R)&xt||(c(this,R,(r(this,R)|xt)&Je),g(this,k,ds).call(this));},ds=function(){var t;let e=this.children();e.provisional=0;for(let i of e)g(t=i,k,Xe).call(t);},gs=function(){c(this,R,r(this,R)|Ni),g(this,k,Qe).call(this);},Qe=function(){if(r(this,R)&Ke)return;let e=r(this,R);(e&yt)===Pt&&(e&=Je),c(this,R,e|Ke),g(this,k,ds).call(this);},_i=function(e=""){e==="ENOTDIR"||e==="EPERM"?g(this,k,Qe).call(this):e==="ENOENT"?g(this,k,Xe).call(this):this.children().provisional=0;},ms=function(e=""){var t;e==="ENOTDIR"?g(t=this.parent,k,Qe).call(t):e==="ENOENT"&&g(this,k,Xe).call(this);},ws=function(e=""){var i;let t=r(this,R);t|=Li,e==="ENOENT"&&(t|=xt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Je),c(this,R,t),e==="ENOTDIR"&&this.parent&&g(i=this.parent,k,Qe).call(i);},$i=function(e,t){return g(this,k,Zr).call(this,e,t)||g(this,k,qr).call(this,e,t)},qr=function(e,t){let i=hs(e),s=this.newChild(e.name,i,{parent:this}),h=r(s,R)&yt;return h!==Pt&&h!==ce&&h!==St&&c(s,R,r(s,R)|Ke),t.unshift(s),t.provisional++,s},Zr=function(e,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Mi(e.name):Ye(e.name))===r(s,se))return g(this,k,Vr).call(this,e,s,i,t)}},Vr=function(e,t,i,s){let h=t.name;return c(t,R,r(t,R)&Je|hs(e)),h!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},ys=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d,ino:f,mode:w,mtime:v,mtimeMs:S,nlink:y,rdev:x,size:E,uid:O}=e;c(this,wi,t),c(this,fi,i),c(this,Si,s),c(this,mi,h),c(this,li,n),c(this,pi,o),c(this,bi,a),c(this,gi,l),c(this,si,u),c(this,oi,d),c(this,ci,f),c(this,ri,w),c(this,yi,v),c(this,di,S),c(this,hi,y),c(this,ai,x),c(this,ui,E),c(this,ni,O);let A=hs(e);c(this,R,r(this,R)&Je|A|_s),A!==St&&A!==Pt&&A!==ce&&c(this,R,r(this,R)|Ke);},Pe=new WeakMap,De=new WeakMap,Kr=function(e){c(this,De,false);let t=r(this,Pe).slice();r(this,Pe).length=0,t.forEach(i=>i(null,e));},be=new WeakMap,mr),Yr=class Xr extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"sep","\\");p(this,"splitSep",Vn);}newChild(i,s=St,h={}){return new Xr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return win32.parse(i).root}getRoot(i){if(i=Zn(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new xs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace($r,"$1\\"),i===s}},Qr=class th extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"splitSep","/");p(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=St,h={}){return new th(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},je,Ne,vi,Ei,wr,eh=(wr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ve}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");m(this,je);m(this,Ne);m(this,vi);p(this,"nocase");m(this,Ei);c(this,Ei,_r(n)),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),c(this,je,new Gs),c(this,Ne,new Gs),c(this,vi,new Yn(h));let a=o.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(r(this,Ei)),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,d=t.sep,f=this.rootPath,w=false;for(let v of a){let S=u--;l=l.child(v,{relative:new Array(S).fill("..").join(d),relativePosix:new Array(S).fill("..").join("/"),fullpath:f+=(w?"":d)+v}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return r(this,vi)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return r(this,je).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,Ne).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return r(this,Ne).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,v)=>{if(w)return f(w);let S=v.length;if(!S)return f();let y=()=>{--S===0&&f();};for(let x of v)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(E=>E?.isUnknown()?E.lstat():E).then(E=>E?.shouldWalk(a,n)?l(E,y):y()):x.shouldWalk(a,n)?l(x,y):y();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Gi({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=(y,x,E=false)=>{if(y)return o.emit("error",y);if(s&&!E){let O=[];for(let A of x)A.isSymbolicLink()&&O.push(A.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(O.length){Promise.all(O).then(()=>v(null,x,true));return}}for(let O of x)O&&(!h||h(O))&&(o.write(i?O:O.fullpath())||(f=true));u--;for(let O of x){let A=O.realpathCached()||O;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):S||d();},S=true;w.readdirCB(v,true),S=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Gi({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=w.readdirSync();for(let S of v)(!h||h(S))&&(o.write(i?S:S.fullpath())||(f=true));u--;for(let S of v){let y=S;if(S.isSymbolicLink()){if(!(s&&(y=S.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(a,n)&&l.push(y);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Jr](t);}},je=new WeakMap,Ne=new WeakMap,vi=new WeakMap,Ei=new WeakMap,wr),xs=class extends eh{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,win32,"\\",{...i,nocase:s});p(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return win32.parse(t).root.toUpperCase()}newRoot(t){return new Yr(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},ks=class extends eh{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,posix,"/",{...i,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Qr(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},ih=class extends ks{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Yr:Qr;var Xn=process.platform==="win32"?xs:process.platform==="darwin"?ih:ks,Qn=e=>e.length>=1,to=e=>e.length>=1,eo=Symbol.for("nodejs.util.inspect.custom"),G,lt,I,Se,Mt,xi,re,he,ne,ze,_e,sh=(_e=class{constructor(t,i,s,h){m(this,G);m(this,lt);m(this,I);p(this,"length");m(this,Se);m(this,Mt);m(this,xi);m(this,re);m(this,he);m(this,ne);m(this,ze,true);if(!Qn(t))throw new TypeError("empty pattern list");if(!to(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(c(this,G,t),c(this,lt,i),c(this,I,s),c(this,Se,h),r(this,I)===0){if(this.isUNC()){let[n,o,a,l,...u]=r(this,G),[d,f,w,v,...S]=r(this,lt);u[0]===""&&(u.shift(),S.shift());let y=[n,o,a,l,""].join("/"),x=[d,f,w,v,""].join("/");c(this,G,[y,...u]),c(this,lt,[x,...S]),this.length=r(this,G).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=r(this,G),[a,...l]=r(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d=a+"/";c(this,G,[u,...o]),c(this,lt,[d,...l]),this.length=r(this,G).length;}}}[eo](){return "Pattern <"+r(this,lt).slice(r(this,I)).join("/")+">"}pattern(){return r(this,G)[r(this,I)]}isString(){return typeof r(this,G)[r(this,I)]=="string"}isGlobstar(){return r(this,G)[r(this,I)]===ht}isRegExp(){return r(this,G)[r(this,I)]instanceof RegExp}globString(){return c(this,xi,r(this,xi)||(r(this,I)===0?this.isAbsolute()?r(this,lt)[0]+r(this,lt).slice(1).join("/"):r(this,lt).join("/"):r(this,lt).slice(r(this,I)).join("/")))}hasMore(){return this.length>r(this,I)+1}rest(){return r(this,Mt)!==void 0?r(this,Mt):this.hasMore()?(c(this,Mt,new _e(r(this,G),r(this,lt),r(this,I)+1,r(this,Se))),c(r(this,Mt),ne,r(this,ne)),c(r(this,Mt),he,r(this,he)),c(r(this,Mt),re,r(this,re)),r(this,Mt)):c(this,Mt,null)}isUNC(){let t=r(this,G);return r(this,he)!==void 0?r(this,he):c(this,he,r(this,Se)==="win32"&&r(this,I)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=r(this,G);return r(this,re)!==void 0?r(this,re):c(this,re,r(this,Se)==="win32"&&r(this,I)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=r(this,G);return r(this,ne)!==void 0?r(this,ne):c(this,ne,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=r(this,G)[0];return typeof t=="string"&&this.isAbsolute()&&r(this,I)===0?t:""}checkFollowGlobstar(){return !(r(this,I)===0||!this.isGlobstar()||!r(this,ze))}markFollowGlobstar(){return r(this,I)===0||!this.isGlobstar()||!r(this,ze)?false:(c(this,ze,false),true)}},G=new WeakMap,lt=new WeakMap,I=new WeakMap,Se=new WeakMap,Mt=new WeakMap,xi=new WeakMap,re=new WeakMap,he=new WeakMap,ne=new WeakMap,ze=new WeakMap,_e),io=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Is=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=io}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new ae(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new sh(s,h,0,this.platform),o=new ae(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},so=class rh{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new rh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},ro=class{constructor(){p(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ho=class{constructor(){p(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Hs=class hh{constructor(t,i){p(this,"hasWalkedCache");p(this,"matches",new ro);p(this,"subwalks",new ho);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new so;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===ht){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let v=h.parent||h;w?this.hasWalkedCache.hasWalked(v,w)||this.subwalks.add(v,w):this.matches.add(v,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new hh(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===ht?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},no=(e,t)=>typeof e=="string"?new Is([e],t):Array.isArray(e)?new Is(e,t):e,$e,qt,ve,vt,ue,bs,yr,nh=(yr=class{constructor(e,t,i){m(this,vt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);m(this,$e,[]);m(this,qt);m(this,ve);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,c(this,ve,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(c(this,qt,no(i.ignore??[],i)),!this.includeChildMatches&&typeof r(this,qt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{r(this,$e).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=r(this,$e).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?r(this,$e).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!g(this,vt,ue).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(g(this,vt,ue).call(this,e))return;if(!this.includeChildMatches&&r(this,qt)?.add){let h=`${e.relativePosix()}/**`;r(this,qt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?r(this,ve):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i){let h=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+r(this,ve))?"."+r(this,ve):"";this.matchEmit(h?n+h+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new Hs(this.opts),i);}walkCB2(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Hs(this.opts),i);}walkCB2Sync(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},$e=new WeakMap,qt=new WeakMap,ve=new WeakMap,vt=new WeakSet,ue=function(e){return this.seen.has(e)||!!r(this,qt)?.ignored?.(e)},bs=function(e){return !!r(this,qt)?.childrenIgnored?.(e)},yr),Js=class extends nh{constructor(t,i,s){super(t,i,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},qs=class extends nh{constructor(t,i,s){super(t,i,s);p(this,"results");this.results=new Gi({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},oo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",xe=class{constructor(e,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||oo,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=t.platform==="win32"?xs:t.platform==="darwin"?ih:t.platform?ks:Xn;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},h=this.pattern.map(a=>new ae(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new sh(a,u,0,this.platform)});}async walk(){return [...await new Js(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new Js(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},ao=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new ae(i,t).hasMagic())return true;return false};function Ji(e,t={}){return new xe(e,t).streamSync()}function oh(e,t={}){return new xe(e,t).stream()}function ah(e,t={}){return new xe(e,t).walkSync()}async function Zs(e,t={}){return new xe(e,t).walk()}function qi(e,t={}){return new xe(e,t).iterateSync()}function lh(e,t={}){return new xe(e,t).iterate()}var lo=Ji,co=Object.assign(oh,{sync:Ji}),uo=qi,po=Object.assign(lh,{sync:qi}),fo=Object.assign(ah,{stream:Ji,iterate:qi}),Ii=Object.assign(Zs,{glob:Zs,globSync:ah,sync:fo,globStream:oh,stream:co,globStreamSync:Ji,streamSync:lo,globIterate:lh,iterate:po,globIterateSync:qi,iterateSync:uo,Glob:xe,hasMagic:ao,escape:Ar,unescape:Oe});Ii.glob=Ii;var uh;(mt=>{mt.Level=mo.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(F){return t[F]>=t[i]}function h(){return i}mt.getLevel=h;let n=new Map;mt.Default=L({service:"default"});let a="";function l(){return a}mt.file=l;let u,d,f=false,w=false,v=F=>{try{w&&process.stderr.write(F);}catch{}},S=false,y=false;async function x(F){if(f)return;F.level&&(i=F.level),F.print&&(w=F.print??false);let D=F.logDir||Zi.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");if(F.print){f=true;return}F.logFile?a=Zi.join(D,F.logFile??"gateway.log"):a=Zi.join(D,"gateway.log");try{await ch.mkdir(D,{recursive:!0}),u=await ch.open(a,"a"),d=createWriteStream("",{fd:u.fd,autoClose:!1}),v=N=>{if(!(S||y||!d||d.destroyed))try{if(!d.writable)return;d.write(N,X=>{if(X&&!S){let j=X;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(X){let j=X;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch(N){process.stderr.write(`[LOG ERROR] Failed to init log file: ${N}
|
|
4
|
+
`),v=X=>{try{process.stderr.write(X);}catch{}},f=true;}}mt.init=x;async function E(){f&&(d&&!d.destroyed&&(await new Promise((F,D)=>{d.end(N=>{N?D(N):F();});}).catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${F}
|
|
5
|
+
`);}),d=void 0),u&&(await u.close().catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${F}
|
|
6
|
+
`);}),u=void 0),v=F=>{try{process.stderr.write(F);}catch{}},f=false);}mt.close=E;function A(F,D=0){let N=F.message;return F.cause instanceof Error&&D<10?N+" Caused by: "+A(F.cause,D+1):N}let T=Date.now();function L(F){F=F||{};let D=F.service;if(D&&typeof D=="string"){let j=n.get(D);if(j)return j}function N(j,ot){let Vi=Object.entries({...F,...ot}).filter(([Rs,Zt])=>Zt!=null).map(([Rs,Zt])=>{let Ki=`${Rs}=`;return Zt instanceof Error?Ki+A(Zt):typeof Zt=="object"?Ki+JSON.stringify(Zt):Ki+Zt}).join(" "),ke=new Date,ph=ke.getTime()-T;return T=ke.getTime(),[formatLogTime(ke),"+"+ph+"ms",Vi,j].filter(Boolean).join(" ")+`
|
|
7
|
+
`}let X={debug(j,ot){s("DEBUG")&&v("DEBUG "+N(j,ot));},info(j,ot){s("INFO")&&v("INFO "+N(j,ot));},error(j,ot){s("ERROR")&&v("ERROR "+N(j,ot));},warn(j,ot){s("WARN")&&v("WARN "+N(j,ot));},tag(j,ot){return F&&(F[j]=ot),X},clone(){return mt.create({...F})},time(j,ot){let Vi=Date.now();X.info(j,{status:"started",...ot});function ke(){X.info(j,{status:"completed",duration:Date.now()-Vi,...ot});}return {stop:ke,[Symbol.dispose](){ke();}}}};return D&&typeof D=="string"&&n.set(D,X),X}mt.create=L;})(uh||(uh={}));export{p as a,uh as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as Log}from'./chunk-RGPJTZUB.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk3SBZTZXS_cjs=require('./chunk-3SBZTZXS.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunk3SBZTZXS_cjs.b}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkRFOEJ3A2_cjs=require('./chunk-RFOEJ3A2.cjs');require('./chunk-3SBZTZXS.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.fa}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ta}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ga}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{fa as ChannelPluginLoader,ta as GatewayServer,ga as GatewayWebSocketServer}from'./chunk-OBFSXYWV.mjs';import'./chunk-RGPJTZUB.mjs';
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkO6R6U45A_cjs=require('./chunks/chunk-O6R6U45A.cjs'),chunkAUPHFE34_cjs=require('./chunks/chunk-AUPHFE34.cjs'),chunkGY3SWWW3_cjs=require('./chunks/chunk-GY3SWWW3.cjs'),utils=require('@easbot/utils');var a=chunkAUPHFE34_cjs.a.create({service:"gateway"}),m=class c extends Error{constructor(t,n,s){super(t);chunkGY3SWWW3_cjs.a(this,"type");chunkGY3SWWW3_cjs.a(this,"stage");chunkGY3SWWW3_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,c);}};function k(c){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=c.code;return e.includes(t??"")}function Ze(){process.on("unhandledRejection",c=>{let e=c instanceof Error?c:new Error(String(c));k(e)||a.error("unhandled promise rejection",{error:e.message,stack:e.stack});}),process.on("uncaughtException",c=>{k(c)||(a.error("uncaught exception",{error:c.message,stack:c.stack}),process.exit(1));});}exports.Gateway=void 0;(rt=>{let c={initialized:false,initPromise:null,directory:".easbot",config:null},e,t={server:null,config:null,initialized:false,status:"stopped"};async function n(u={}){if(c.initialized)return;if(c.initPromise)return c.initPromise;let d={directory:u.directory??".easbot",printLogs:u.printLogs??false,logLevel:u.logLevel??"INFO"};return c.directory=d.directory,c.initPromise=(async()=>{let{Global:C}=await import('./chunks/global-FIBJJFBN.cjs');try{await C.init();}catch(l){throw new m("Failed to initialize global directories","global",l instanceof Error?l:void 0)}try{await chunkAUPHFE34_cjs.a.init({logDir:C.Path.log,print:d.printLogs,level:d.logLevel});}catch(l){throw new m("Failed to initialize log infrastructure","log",l instanceof Error?l:void 0)}try{Ze();}catch(l){throw new m("Failed to install unhandled exception handlers","server",l instanceof Error?l:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),a.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{c.config=await chunkO6R6U45A_cjs.v(d.directory);}catch(l){throw new m("Failed to load gateway configuration","config",l instanceof Error?l:void 0)}c.initialized=true,a.info("gateway runtime initialized",{directory:d.directory,logLevel:d.logLevel});})(),c.initPromise}rt.init=n;function s(){return c.initialized}rt.isInitialized=s;function r(){return e||(e=async()=>{if(!c.initialized)throw new m("Gateway not initialized. Call init() first.","server");let u=chunkO6R6U45A_cjs.Q(),d=await chunkO6R6U45A_cjs.v(u.directory);return d.server?.enabled?(t={server:null,config:d,initialized:true,status:"stopped"},a.info("gateway initialized",{port:d.server?.port,hostname:d.server?.hostname}),t):(a.debug("gateway server disabled or not configured"),{server:null,config:d,initialized:true,status:"stopped"})}),e}function i(){return r()()}rt.state=i;async function o(){return (await i()).server}rt.get=o;async function p(){return (await i()).config?.server?.enabled??false}rt.isEnabled=p;async function x(){return (await i()).config}rt.config=x;function tt(){return t.status}rt.getStatus=tt;async function _(u){a.debug("Gateway.start: called"),c.initialized||(a.debug("Gateway.start: calling init()"),await n(),a.debug("Gateway.start: init() completed")),a.debug("Gateway.start: calling state()");let d=await i();if(a.debug("Gateway.start: state() completed",{status:d.status}),!(d.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){a.info("gateway server is already running");return}if(t.status==="starting"){a.info("gateway server is starting");return}t.status="starting",a.debug("Gateway.start: status set to starting");try{let l={...d.config?.server,...u};a.debug("gateway start: creating server with config",{port:l.port,hostname:l.hostname,path:l.path,https:l.https?.enabled}),a.debug("Gateway.start: calling createGatewayServer");let w=await F(l);a.debug("Gateway.start: createGatewayServer completed"),a.debug("gateway start: server created, updating state"),t.server=w,t.status="running",t.error=void 0,a.info("gateway server started",{port:l.port,hostname:l.hostname});}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),a.error("failed to start gateway server",{error:t.error}),l}}rt.start=_;async function O(){if(t.status==="stopped"){a.info("gateway server is already stopped");return}if(t.status==="stopping"){a.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,await chunkAUPHFE34_cjs.a.close(),a.info("gateway server stopped");}catch(u){throw t.status="error",t.error=u instanceof Error?u.message:String(u),a.error("failed to stop gateway server",{error:t.error}),u}}rt.stop=O;async function nt(u){a.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await O(),await _(u);}rt.restart=nt;async function st(){let u=chunkO6R6U45A_cjs.Q(),d=await chunkO6R6U45A_cjs.v(u.directory);return t.config=d,c.config=d,a.info("gateway config reloaded"),d}rt.reloadConfig=st;async function F(u,d){a.debug("createGatewayServer: starting");let{GatewayServer:C}=await import('./chunks/server-4GO5DAEQ.cjs');a.debug("createGatewayServer: GatewayServer imported");let l=new C(u);a.debug("createGatewayServer: server instance created"),a.debug("createGatewayServer: created server instance, calling start()");let w=d?.startupTimeout??3e4;if(await(async()=>{let b=new Promise((A,D)=>{setTimeout(()=>{D(new Error(`Gateway server startup timeout after ${w}ms`));},w);});try{a.debug("createGatewayServer: calling server.start()"),await Promise.race([l.start(),b]),a.debug("createGatewayServer: server.start() completed");}catch(A){a.error("gateway server start failed, attempting cleanup",{error:A instanceof Error?A.message:String(A)});try{await l.stop();}catch{}throw A}})(),d?.onStarted)try{await d.onStarted(l);}catch(b){a.warn("server started but onStarted callback failed",{error:b instanceof Error?b.message:String(b)});}return a.info("gateway server created and started",{port:u.port,hostname:u.hostname}),l}rt.createGatewayServer=F;})(exports.Gateway||(exports.Gateway={}));var f=chunkAUPHFE34_cjs.a.create({service:"gateway:agent-registry"}),P=class{constructor(e={}){chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"agents",new Map);chunkGY3SWWW3_cjs.a(this,"heartbeatTimer",null);chunkGY3SWWW3_cjs.a(this,"roundRobinIndex",0);this.config={...chunkO6R6U45A_cjs.Z,...e};}async register(e){if(this.agents.has(e.id))throw new Error(`Agent with ID "${e.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let t=Date.now(),n={...e,status:"healthy",lastHeartbeat:t,registeredAt:t,connectionCount:0};this.agents.set(e.id,n),f.info("Agent registered",{agentId:e.id,name:e.name,capabilities:e.capabilities,address:e.address,totalAgents:this.agents.size});}async deregister(e){let t=this.agents.get(e);if(!t){f.warn("Attempted to deregister unknown agent",{agentId:e});return}this.agents.delete(e),f.info("Agent deregistered",{agentId:e,name:t.name,totalAgents:this.agents.size});}async heartbeat(e,t){let n=this.agents.get(e);if(!n)throw f.warn("Heartbeat received from unknown agent",{agentId:e}),new Error(`Agent "${e}" is not registered`);n.lastHeartbeat=Date.now(),n.status="healthy",t&&(n.metadata={...n.metadata,...t}),f.debug("Agent heartbeat received",{agentId:e,lastHeartbeat:n.lastHeartbeat});}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(e=>e.status==="healthy")}selectAgent(e){let{strategy:t,capabilities:n,healthyOnly:s=true}=e,r=s?this.getHealthyAgents():this.getAllAgents();if(n&&n.length>0&&(r=r.filter(o=>n.every(p=>o.capabilities.includes(p)))),r.length===0){f.warn("No agents available for selection",{strategy:t,capabilities:n,healthyOnly:s,totalAgents:this.agents.size});return}let i;switch(t){case "random":i=this.selectRandom(r);break;case "round-robin":i=this.selectRoundRobin(r);break;case "least-connections":i=this.selectLeastConnections(r);break;default:i=this.selectRandom(r);}return f.debug("Agent selected",{agentId:i.id,strategy:t,connectionCount:i.connectionCount}),i}incrementConnection(e){let t=this.agents.get(e);t&&(t.connectionCount++,f.debug("Agent connection incremented",{agentId:e,connectionCount:t.connectionCount}));}decrementConnection(e){let t=this.agents.get(e);t&&t.connectionCount>0&&(t.connectionCount--,f.debug("Agent connection decremented",{agentId:e,connectionCount:t.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let e=Date.now(),{heartbeatTimeout:t,autoDeregisterTimeout:n}=this.config,s=[],r=0;for(let[i,o]of this.agents.entries()){let p=e-o.lastHeartbeat;if(p>n){s.push(i);continue}p>t&&o.status==="healthy"&&(o.status="unhealthy",r++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:i,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:t}));}for(let i of s){let o=this.agents.get(i);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:i,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:n}),this.agents.delete(i));}(r>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:r,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}selectRoundRobin(e){this.roundRobinIndex=this.roundRobinIndex%e.length;let t=e[this.roundRobinIndex];return this.roundRobinIndex++,t}selectLeastConnections(e){return e.reduce((t,n)=>n.connectionCount<t.connectionCount?n:t)}getStats(){let e=this.getAllAgents();return {totalAgents:e.length,healthyAgents:e.filter(t=>t.status==="healthy").length,unhealthyAgents:e.filter(t=>t.status==="unhealthy").length,offlineAgents:e.filter(t=>t.status==="offline").length,totalConnections:e.reduce((t,n)=>t+n.connectionCount,0)}}setAgentStatus(e,t){let n=this.agents.get(e);n&&(n.status=t);}setLastHeartbeat(e,t){let n=this.agents.get(e);n&&(n.lastHeartbeat=t);}};var h=chunkAUPHFE34_cjs.a.create({service:"gateway:agent-sync-manager"}),T=class{constructor(e){chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"registry");chunkGY3SWWW3_cjs.a(this,"localNodeId");chunkGY3SWWW3_cjs.a(this,"localNodeName");chunkGY3SWWW3_cjs.a(this,"remoteNodes",new Map);chunkGY3SWWW3_cjs.a(this,"remoteAgents",new Map);chunkGY3SWWW3_cjs.a(this,"syncTimer",null);chunkGY3SWWW3_cjs.a(this,"running",false);this.registry=e.registry,this.localNodeId=e.localNodeId,this.localNodeName=e.localNodeName,this.config={...chunkO6R6U45A_cjs._,...e.config};}async start(){if(this.running){h.warn("Agent sync manager is already running");return}h.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let e of this.config.remoteNodes)this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,h.info("Agent sync manager started");}async stop(){if(!this.running){h.warn("Agent sync manager is not running");return}h.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,h.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[e]of this.remoteNodes.entries())try{await this.pullFromNode(e);}catch(t){h.error("Failed to pull from node",{nodeId:e,error:t.message});}}async pullFromNode(e){let t=this.remoteNodes.get(e);if(!t)throw new Error(`Unknown remote node: ${e}`);t.status="syncing";let n=this.config.remoteNodes.find(s=>s.id===e);if(!n)throw new Error(`Remote node not found in config: ${e}`);h.debug("Pulling agent list from node",{nodeId:e,address:n.address});try{let s=`http://${n.address}:${n.port}/sync/agents`,r=await utils.Fetch.get(s,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let i=r.data.agents||[];for(let o of i)o.sourceGatewayId=e,this.remoteAgents.set(o.id,o);return t.lastSyncAt=Date.now(),t.status="synced",t.info.lastSyncAt=t.lastSyncAt,t.info.status="online",delete t.error,h.info("Pulled agent list from node",{nodeId:e,agentCount:i.length,lastSyncAt:t.lastSyncAt}),i}catch(s){throw t.status="error",t.error=s.message,t.info.status="offline",h.error("Failed to pull from node",{nodeId:e,error:s.message}),s}}async pushEvent(e){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let t=[];for(let[n]of this.remoteNodes.entries())t.push(this.pushToNode(n,e));await Promise.allSettled(t);}async pushToNode(e,t){let n=this.config.remoteNodes.find(s=>s.id===e);if(!n){h.warn("Unknown remote node for push",{nodeId:e});return}try{let s=`http://${n.address}:${n.port}/sync/events`,r=await utils.Fetch.post(s,t,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);h.debug("Pushed event to node",{nodeId:e,eventType:t.type});}catch(s){h.error("Failed to push to node",{nodeId:e,eventType:t.type,error:s.message});}}async handleSyncMessage(e){switch(h.debug("Received sync message",{type:e.type,sourceNodeId:e.sourceNodeId}),e.type){case "agent_list_request":await this.handleAgentListRequest(e);break;case "agent_list_response":await this.handleAgentListResponse(e);break;case "agent_register":await this.handleAgentRegister(e);break;case "agent_deregister":await this.handleAgentDeregister(e);break;case "agent_heartbeat":await this.handleAgentHeartbeat(e);break;case "agent_status_change":await this.handleAgentStatusChange(e);break;default:h.warn("Unknown sync message type",{type:e.type});}}async handleAgentListRequest(e){let t=this.getLocalAgentsForSync(),n={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:e.requestId,agents:t,fullList:true,syncAt:Date.now()};await this.pushToNode(e.sourceNodeId,n);}async handleAgentListResponse(e){for(let t of e.agents)this.remoteAgents.set(t.id,t);h.info("Received agent list response",{sourceNodeId:e.sourceNodeId,agentCount:e.agents.length});}async handleAgentRegister(e){let{agent:t}=e,n=this.remoteAgents.get(t.id);if(n){let s=this.resolveConflict(n,t);this.remoteAgents.set(t.id,s);}else this.remoteAgents.set(t.id,t);h.info("Remote agent registered",{agentId:t.id,name:t.name,sourceNodeId:e.sourceNodeId});}async handleAgentDeregister(e){let{agentId:t}=e;this.remoteAgents.delete(t),h.info("Remote agent deregistered",{agentId:t,sourceNodeId:e.sourceNodeId});}async handleAgentHeartbeat(e){let{agentId:t,heartbeatAt:n,status:s}=e,r=this.remoteAgents.get(t);r&&(r.updatedAt=n,r.status=s),h.debug("Remote agent heartbeat received",{agentId:t,status:s,sourceNodeId:e.sourceNodeId});}async handleAgentStatusChange(e){let{agentId:t,newStatus:n,changedAt:s}=e,r=this.remoteAgents.get(t);r&&(r.status=n,r.updatedAt=s),h.info("Remote agent status changed",{agentId:t,newStatus:n,sourceNodeId:e.sourceNodeId});}resolveConflict(e,t){switch(this.config.conflictResolution){case "latest":return t.updatedAt>e.updatedAt?t:e;case "local":return e;case "remote":return t;default:return t.updatedAt>e.updatedAt?t:e}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>({id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}))}getMergedAgentList(){let e=new Map;for(let t of this.getLocalAgentsForSync())e.set(t.id,t);for(let[t,n]of this.remoteAgents.entries())e.has(t)||e.set(t,n);return Array.from(e.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let e=this.registry.getAllAgents(),t=0,n=0;for(let r of this.remoteNodes.values())r.info.status==="online"?t++:n++;let s=null;for(let r of this.remoteNodes.values())r.lastSyncAt>(s||0)&&(s=r.lastSyncAt);return {localAgentCount:e.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:e.length+this.remoteAgents.size,onlineNodeCount:t,offlineNodeCount:n,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(e){this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),h.info("Remote node added",{nodeId:e.id,address:e.address});}removeRemoteNode(e){this.remoteNodes.delete(e);for(let[t,n]of this.remoteAgents.entries())n.sourceGatewayId===e&&this.remoteAgents.delete(t);h.info("Remote node removed",{nodeId:e});}};var M=class{constructor(e){chunkGY3SWWW3_cjs.a(this,"log");chunkGY3SWWW3_cjs.a(this,"config");chunkGY3SWWW3_cjs.a(this,"ws",null);chunkGY3SWWW3_cjs.a(this,"state","disconnected");chunkGY3SWWW3_cjs.a(this,"subscriptions",new Map);chunkGY3SWWW3_cjs.a(this,"messageCallbacks",new Set);chunkGY3SWWW3_cjs.a(this,"agentListCallbacks",new Set);chunkGY3SWWW3_cjs.a(this,"cachedAgentList",[]);chunkGY3SWWW3_cjs.a(this,"localAgentList",[]);chunkGY3SWWW3_cjs.a(this,"reconnectAttempts",0);chunkGY3SWWW3_cjs.a(this,"reconnectTimer",null);chunkGY3SWWW3_cjs.a(this,"heartbeatTimer",null);chunkGY3SWWW3_cjs.a(this,"agentListRequestId",null);chunkGY3SWWW3_cjs.a(this,"agentListRequestResolve",null);this.config={url:e.url,type:e.type,id:e.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:e.reconnect?.enabled??true,maxAttempts:e.reconnect?.maxAttempts??5,delay:e.reconnect?.delay??3e3},heartbeat:{enabled:e.heartbeat?.enabled??true,interval:e.heartbeat?.interval??3e4}},this.log=chunkAUPHFE34_cjs.a.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((e,t)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),e();},this.ws.onmessage=n=>{this.handleMessage(n.data);},this.ws.onclose=n=>{this.handleClose(n.code,n.reason);},this.ws.onerror=n=>{this.log.error("WebSocket error",{error:String(n)}),this.state==="connecting"&&t(new Error("Connection failed"));};}catch(n){this.state="disconnected",t(n);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(e,t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:e,backendSessionId:t,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:e,backendSessionId:t});}async unsubscribe(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:e,clientId:this.config.id}),this.subscriptions.delete(e),this.log.info("unsubscribed from session",{sessionId:e});}async send(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:e});}onMessage(e){this.messageCallbacks.add(e);}offMessage(e){this.messageCallbacks.delete(e);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(e){this.localAgentList=e,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((e,t)=>{let n=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=n,this.agentListRequestResolve=e,this.sendData({type:"agent_list_request",requestId:n}),setTimeout(()=>{this.agentListRequestId===n&&(this.agentListRequestId=null,this.agentListRequestResolve=null,t(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(e={}){let{localAgents:t,preferLocal:n=true,filterOffline:s=true}=e,r=t||this.localAgentList,i=this.cachedAgentList,o=this.mergeAgentLists(r,i,n);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(e){this.agentListCallbacks.add(e);}offAgentListChange(e){this.agentListCallbacks.delete(e);}mergeAgentLists(e,t,n){let s=new Map,r=n?t:e,i=n?e:t;for(let o of r)s.set(o.id,o);for(let o of i)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let e=this.getConnectableAgents({filterOffline:false});for(let t of this.agentListCallbacks)try{t(e);}catch(n){this.log.error("agent list callback error",{error:String(n)});}}handleAgentListResponse(e,t){t&&this.agentListRequestId===t&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(e),this.agentListRequestResolve=null),this.cachedAgentList=e,this.updateMergedAgentList(),this.log.debug("received agent list",{count:e.length});}sendData(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(e));}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case "message":this.handleGatewayMessage(t.message);break;case "subscribed":this.subscriptions.set(t.sessionId,t.subscription);break;case "unsubscribed":this.subscriptions.delete(t.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(t.agents||[],t.requestId);break;case "agent_update":this.handleAgentUpdate(t.agent,t.action);break;default:this.log.debug("unknown message type",{type:t.type});}}catch(t){this.log.error("failed to parse message",{error:String(t)});}}handleAgentUpdate(e,t){switch(t){case "add":case "update":{let n=this.cachedAgentList.findIndex(s=>s.id===e.id);n>=0?this.cachedAgentList[n]=e:this.cachedAgentList.push(e);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(n=>n.id!==e.id);break}this.updateMergedAgentList();}handleGatewayMessage(e){for(let t of this.messageCallbacks)try{t(e);}catch(n){this.log.error("message callback error",{error:String(n)});}}handleClose(e,t){this.log.info("connection closed",{code:e,reason:t}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let e=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:e}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(t){this.log.error("reconnect failed",{error:String(t)});}},e);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let e of this.subscriptions.keys())try{await this.subscribe(e);}catch(t){this.log.error("failed to resubscribe",{sessionId:e,error:String(t)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(e,t={}){let n=`${this.getHttpUrl()}${e}`,s=t.method||"GET",{signal:r,...i}=t,o=await utils.Fetch.request(n,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!o.ok){let p=o.data,x=typeof p=="object"?JSON.stringify(p):String(p||"Unknown error");throw new Error(`HTTP ${o.status}: ${x}`)}return o.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(e,t={}){let n=new URLSearchParams({platform:e,limit:String(t.limit??100),offset:String(t.offset??0)});return this.httpRequest(`/contacts?${n}`)}async getContact(e){return this.httpRequest(`/contacts/${encodeURIComponent(e)}`)}async getSession(e){return this.httpRequest(`/sessions/${encodeURIComponent(e)}`)}async createSession(e){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(e??{})})}async getOrCreateSession(e){if(e.sessionId)try{return await this.getSession(e.sessionId),{sessionId:e.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:e.sessionId});}if(e.platform||e.channel||e.userId){let n=e.chatId??e.userId;try{let i=await this.listSessions({platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n});if(i.sessions.length>0){let o=i.sessions[0];if(o)return this.log.info("found existing session",{sessionId:o.id,channel:e.channel,userId:e.userId,chatId:n}),{sessionId:o.id,created:!1}}}catch(i){this.log.warn("failed to search sessions",{error:String(i)});}let s={channel:{platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n}},r=await this.createSession(s);return this.log.info("session created",{sessionId:r.id,params:s}),{sessionId:r.id,created:true}}let t=await this.createSession({channel:{platform:"api",channelId:"default"}});return this.log.info("session created (default)",{sessionId:t.id}),{sessionId:t.id,created:true}}async listSessions(e={}){let t=new URLSearchParams;return t.set("limit",String(e.limit??100)),t.set("offset",String(e.offset??0)),e.platform&&t.set("platform",e.platform),e.channelId&&t.set("channelId",e.channelId),e.userId&&t.set("userId",e.userId),e.chatId&&t.set("chatId",e.chatId),this.httpRequest(`/sessions?${t}`)}async sendMessage(e,t){return this.httpRequest(`/session/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t)})}};async function Ut(c){let{Log:e}=await import('./chunks/log-JFEBRH2W.cjs'),t=false;await e.init({logDir:c.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:c.print??false,dev:c.dev??t,level:c.level??("INFO")});}
|
|
2
|
-
Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return
|
|
1
|
+
'use strict';var chunkRFOEJ3A2_cjs=require('./chunks/chunk-RFOEJ3A2.cjs'),chunk3SBZTZXS_cjs=require('./chunks/chunk-3SBZTZXS.cjs'),utils=require('@easbot/utils');var a=chunk3SBZTZXS_cjs.b.create({service:"gateway"}),S=class c extends Error{constructor(t,n,s){super(t);chunk3SBZTZXS_cjs.a(this,"type");chunk3SBZTZXS_cjs.a(this,"stage");chunk3SBZTZXS_cjs.a(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,c);}};function H(c){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=c.code;return e.includes(t??"")}function et(){process.on("unhandledRejection",c=>{let e=c instanceof Error?c:new Error(String(c));H(e)||a.error("unhandled promise rejection",{error:e.message,stack:e.stack});}),process.on("uncaughtException",c=>{H(c)||(a.error("uncaught exception",{error:c.message,stack:c.stack}),process.exit(1));});}exports.Gateway=void 0;(at=>{let c={initialized:false,initPromise:null,directory:".easbot",config:null},e,t={server:null,config:null,initialized:false,status:"stopped"};async function n(u={}){if(c.initialized)return;if(c.initPromise)return c.initPromise;let d={directory:u.directory??".easbot",printLogs:u.printLogs??false,logLevel:u.logLevel??"INFO"};return c.directory=d.directory,c.initPromise=(async()=>{let v=chunkRFOEJ3A2_cjs.Q();try{await chunk3SBZTZXS_cjs.b.init({logDir:v.Path.log,print:d.printLogs,level:d.logLevel});}catch(l){throw new S("Failed to initialize log infrastructure","log",l instanceof Error?l:void 0)}try{et();}catch(l){throw new S("Failed to install unhandled exception handlers","server",l instanceof Error?l:void 0)}utils.Fetch.hasProxyConfigured()&&(utils.Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),a.info("global proxy enabled",{proxyUrl:utils.Fetch.getProxyUrl()}));try{c.config=await chunkRFOEJ3A2_cjs.v(d.directory);}catch(l){throw new S("Failed to load gateway configuration","config",l instanceof Error?l:void 0)}c.initialized=true,a.info("gateway runtime initialized",{directory:d.directory,logLevel:d.logLevel});})(),c.initPromise}at.init=n;function s(){return c.initialized}at.isInitialized=s;function r(){return e||(e=async()=>{if(!c.initialized)throw new S("Gateway not initialized. Call init() first.","server");let u=chunkRFOEJ3A2_cjs.R(),d=await chunkRFOEJ3A2_cjs.v(u.directory);return d.server?.enabled?(t={server:null,config:d,initialized:true,status:"stopped"},a.info("gateway initialized",{port:d.server?.port,hostname:d.server?.hostname}),t):(a.debug("gateway server disabled or not configured"),{server:null,config:d,initialized:true,status:"stopped"})}),e}function i(){return r()()}at.state=i;async function o(){return (await i()).server}at.get=o;async function p(){return (await i()).config?.server?.enabled??false}at.isEnabled=p;async function x(){return (await i()).config}at.config=x;function nt(){return t.status}at.getStatus=nt;async function O(u){a.debug("Gateway.start: called"),c.initialized||(a.debug("Gateway.start: calling init()"),await n(),a.debug("Gateway.start: init() completed")),a.debug("Gateway.start: calling state()");let d=await i();if(a.debug("Gateway.start: state() completed",{status:d.status}),!(d.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){a.info("gateway server is already running");return}if(t.status==="starting"){a.info("gateway server is starting");return}t.status="starting",a.debug("Gateway.start: status set to starting");try{let l={...d.config?.server,...u};a.debug("gateway start: creating server with config",{port:l.port,hostname:l.hostname,path:l.path,https:l.https?.enabled}),a.debug("Gateway.start: calling createGatewayServer");let w=await D(l);a.debug("Gateway.start: createGatewayServer completed"),a.debug("gateway start: server created, updating state"),t.server=w,t.status="running",t.error=void 0,a.info("gateway server started",{port:l.port,hostname:l.hostname});}catch(l){throw t.status="error",t.error=l instanceof Error?l.message:String(l),a.error("failed to start gateway server",{error:t.error}),l}}at.start=O;async function F(){if(t.status==="stopped"){a.info("gateway server is already stopped");return}if(t.status==="stopping"){a.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,await chunk3SBZTZXS_cjs.b.close(),a.info("gateway server stopped");}catch(u){throw t.status="error",t.error=u instanceof Error?u.message:String(u),a.error("failed to stop gateway server",{error:t.error}),u}}at.stop=F;async function st(u){a.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await F(),await O(u);}at.restart=st;async function rt(){let u=chunkRFOEJ3A2_cjs.R(),d=await chunkRFOEJ3A2_cjs.v(u.directory);return t.config=d,c.config=d,a.info("gateway config reloaded"),d}at.reloadConfig=rt;async function D(u,d){a.debug("createGatewayServer: starting");let{GatewayServer:v}=await import('./chunks/server-3QASQ56E.cjs');a.debug("createGatewayServer: GatewayServer imported");let l=new v(u);a.debug("createGatewayServer: server instance created"),a.debug("createGatewayServer: created server instance, calling start()");let w=d?.startupTimeout??3e4;if(await(async()=>{let C=new Promise((b,q)=>{setTimeout(()=>{q(new Error(`Gateway server startup timeout after ${w}ms`));},w);});try{a.debug("createGatewayServer: calling server.start()"),await Promise.race([l.start(),C]),a.debug("createGatewayServer: server.start() completed");}catch(b){a.error("gateway server start failed, attempting cleanup",{error:b instanceof Error?b.message:String(b)});try{await l.stop();}catch{}throw b}})(),d?.onStarted)try{await d.onStarted(l);}catch(C){a.warn("server started but onStarted callback failed",{error:C instanceof Error?C.message:String(C)});}return a.info("gateway server created and started",{port:u.port,hostname:u.hostname}),l}at.createGatewayServer=D;})(exports.Gateway||(exports.Gateway={}));var f=chunk3SBZTZXS_cjs.b.create({service:"gateway:agent-registry"}),P=class{constructor(e={}){chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"agents",new Map);chunk3SBZTZXS_cjs.a(this,"heartbeatTimer",null);chunk3SBZTZXS_cjs.a(this,"roundRobinIndex",0);this.config={...chunkRFOEJ3A2_cjs._,...e};}async register(e){if(this.agents.has(e.id))throw new Error(`Agent with ID "${e.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let t=Date.now(),n={...e,status:"healthy",lastHeartbeat:t,registeredAt:t,connectionCount:0};this.agents.set(e.id,n),f.info("Agent registered",{agentId:e.id,name:e.name,capabilities:e.capabilities,address:e.address,totalAgents:this.agents.size});}async deregister(e){let t=this.agents.get(e);if(!t){f.warn("Attempted to deregister unknown agent",{agentId:e});return}this.agents.delete(e),f.info("Agent deregistered",{agentId:e,name:t.name,totalAgents:this.agents.size});}async heartbeat(e,t){let n=this.agents.get(e);if(!n)throw f.warn("Heartbeat received from unknown agent",{agentId:e}),new Error(`Agent "${e}" is not registered`);n.lastHeartbeat=Date.now(),n.status="healthy",t&&(n.metadata={...n.metadata,...t}),f.debug("Agent heartbeat received",{agentId:e,lastHeartbeat:n.lastHeartbeat});}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(e=>e.status==="healthy")}selectAgent(e){let{strategy:t,capabilities:n,healthyOnly:s=true}=e,r=s?this.getHealthyAgents():this.getAllAgents();if(n&&n.length>0&&(r=r.filter(o=>n.every(p=>o.capabilities.includes(p)))),r.length===0){f.warn("No agents available for selection",{strategy:t,capabilities:n,healthyOnly:s,totalAgents:this.agents.size});return}let i;switch(t){case "random":i=this.selectRandom(r);break;case "round-robin":i=this.selectRoundRobin(r);break;case "least-connections":i=this.selectLeastConnections(r);break;default:i=this.selectRandom(r);}return f.debug("Agent selected",{agentId:i.id,strategy:t,connectionCount:i.connectionCount}),i}incrementConnection(e){let t=this.agents.get(e);t&&(t.connectionCount++,f.debug("Agent connection incremented",{agentId:e,connectionCount:t.connectionCount}));}decrementConnection(e){let t=this.agents.get(e);t&&t.connectionCount>0&&(t.connectionCount--,f.debug("Agent connection decremented",{agentId:e,connectionCount:t.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let e=Date.now(),{heartbeatTimeout:t,autoDeregisterTimeout:n}=this.config,s=[],r=0;for(let[i,o]of this.agents.entries()){let p=e-o.lastHeartbeat;if(p>n){s.push(i);continue}p>t&&o.status==="healthy"&&(o.status="unhealthy",r++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:i,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:t}));}for(let i of s){let o=this.agents.get(i);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:i,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:n}),this.agents.delete(i));}(r>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:r,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}selectRoundRobin(e){this.roundRobinIndex=this.roundRobinIndex%e.length;let t=e[this.roundRobinIndex];return this.roundRobinIndex++,t}selectLeastConnections(e){return e.reduce((t,n)=>n.connectionCount<t.connectionCount?n:t)}getStats(){let e=this.getAllAgents();return {totalAgents:e.length,healthyAgents:e.filter(t=>t.status==="healthy").length,unhealthyAgents:e.filter(t=>t.status==="unhealthy").length,offlineAgents:e.filter(t=>t.status==="offline").length,totalConnections:e.reduce((t,n)=>t+n.connectionCount,0)}}setAgentStatus(e,t){let n=this.agents.get(e);n&&(n.status=t);}setLastHeartbeat(e,t){let n=this.agents.get(e);n&&(n.lastHeartbeat=t);}};var h=chunk3SBZTZXS_cjs.b.create({service:"gateway:agent-sync-manager"}),T=class{constructor(e){chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"registry");chunk3SBZTZXS_cjs.a(this,"localNodeId");chunk3SBZTZXS_cjs.a(this,"localNodeName");chunk3SBZTZXS_cjs.a(this,"remoteNodes",new Map);chunk3SBZTZXS_cjs.a(this,"remoteAgents",new Map);chunk3SBZTZXS_cjs.a(this,"syncTimer",null);chunk3SBZTZXS_cjs.a(this,"running",false);this.registry=e.registry,this.localNodeId=e.localNodeId,this.localNodeName=e.localNodeName,this.config={...chunkRFOEJ3A2_cjs.$,...e.config};}async start(){if(this.running){h.warn("Agent sync manager is already running");return}h.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let e of this.config.remoteNodes)this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,h.info("Agent sync manager started");}async stop(){if(!this.running){h.warn("Agent sync manager is not running");return}h.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,h.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[e]of this.remoteNodes.entries())try{await this.pullFromNode(e);}catch(t){h.error("Failed to pull from node",{nodeId:e,error:t.message});}}async pullFromNode(e){let t=this.remoteNodes.get(e);if(!t)throw new Error(`Unknown remote node: ${e}`);t.status="syncing";let n=this.config.remoteNodes.find(s=>s.id===e);if(!n)throw new Error(`Remote node not found in config: ${e}`);h.debug("Pulling agent list from node",{nodeId:e,address:n.address});try{let s=`http://${n.address}:${n.port}/sync/agents`,r=await utils.Fetch.get(s,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let i=r.data.agents||[];for(let o of i)o.sourceGatewayId=e,this.remoteAgents.set(o.id,o);return t.lastSyncAt=Date.now(),t.status="synced",t.info.lastSyncAt=t.lastSyncAt,t.info.status="online",delete t.error,h.info("Pulled agent list from node",{nodeId:e,agentCount:i.length,lastSyncAt:t.lastSyncAt}),i}catch(s){throw t.status="error",t.error=s.message,t.info.status="offline",h.error("Failed to pull from node",{nodeId:e,error:s.message}),s}}async pushEvent(e){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let t=[];for(let[n]of this.remoteNodes.entries())t.push(this.pushToNode(n,e));await Promise.allSettled(t);}async pushToNode(e,t){let n=this.config.remoteNodes.find(s=>s.id===e);if(!n){h.warn("Unknown remote node for push",{nodeId:e});return}try{let s=`http://${n.address}:${n.port}/sync/events`,r=await utils.Fetch.post(s,t,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);h.debug("Pushed event to node",{nodeId:e,eventType:t.type});}catch(s){h.error("Failed to push to node",{nodeId:e,eventType:t.type,error:s.message});}}async handleSyncMessage(e){switch(h.debug("Received sync message",{type:e.type,sourceNodeId:e.sourceNodeId}),e.type){case "agent_list_request":await this.handleAgentListRequest(e);break;case "agent_list_response":await this.handleAgentListResponse(e);break;case "agent_register":await this.handleAgentRegister(e);break;case "agent_deregister":await this.handleAgentDeregister(e);break;case "agent_heartbeat":await this.handleAgentHeartbeat(e);break;case "agent_status_change":await this.handleAgentStatusChange(e);break;default:h.warn("Unknown sync message type",{type:e.type});}}async handleAgentListRequest(e){let t=this.getLocalAgentsForSync(),n={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:e.requestId,agents:t,fullList:true,syncAt:Date.now()};await this.pushToNode(e.sourceNodeId,n);}async handleAgentListResponse(e){for(let t of e.agents)this.remoteAgents.set(t.id,t);h.info("Received agent list response",{sourceNodeId:e.sourceNodeId,agentCount:e.agents.length});}async handleAgentRegister(e){let{agent:t}=e,n=this.remoteAgents.get(t.id);if(n){let s=this.resolveConflict(n,t);this.remoteAgents.set(t.id,s);}else this.remoteAgents.set(t.id,t);h.info("Remote agent registered",{agentId:t.id,name:t.name,sourceNodeId:e.sourceNodeId});}async handleAgentDeregister(e){let{agentId:t}=e;this.remoteAgents.delete(t),h.info("Remote agent deregistered",{agentId:t,sourceNodeId:e.sourceNodeId});}async handleAgentHeartbeat(e){let{agentId:t,heartbeatAt:n,status:s}=e,r=this.remoteAgents.get(t);r&&(r.updatedAt=n,r.status=s),h.debug("Remote agent heartbeat received",{agentId:t,status:s,sourceNodeId:e.sourceNodeId});}async handleAgentStatusChange(e){let{agentId:t,newStatus:n,changedAt:s}=e,r=this.remoteAgents.get(t);r&&(r.status=n,r.updatedAt=s),h.info("Remote agent status changed",{agentId:t,newStatus:n,sourceNodeId:e.sourceNodeId});}resolveConflict(e,t){switch(this.config.conflictResolution){case "latest":return t.updatedAt>e.updatedAt?t:e;case "local":return e;case "remote":return t;default:return t.updatedAt>e.updatedAt?t:e}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>({id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}))}getMergedAgentList(){let e=new Map;for(let t of this.getLocalAgentsForSync())e.set(t.id,t);for(let[t,n]of this.remoteAgents.entries())e.has(t)||e.set(t,n);return Array.from(e.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let e=this.registry.getAllAgents(),t=0,n=0;for(let r of this.remoteNodes.values())r.info.status==="online"?t++:n++;let s=null;for(let r of this.remoteNodes.values())r.lastSyncAt>(s||0)&&(s=r.lastSyncAt);return {localAgentCount:e.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:e.length+this.remoteAgents.size,onlineNodeCount:t,offlineNodeCount:n,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(e){this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),h.info("Remote node added",{nodeId:e.id,address:e.address});}removeRemoteNode(e){this.remoteNodes.delete(e);for(let[t,n]of this.remoteAgents.entries())n.sourceGatewayId===e&&this.remoteAgents.delete(t);h.info("Remote node removed",{nodeId:e});}};var M=class{constructor(e){chunk3SBZTZXS_cjs.a(this,"log");chunk3SBZTZXS_cjs.a(this,"config");chunk3SBZTZXS_cjs.a(this,"ws",null);chunk3SBZTZXS_cjs.a(this,"state","disconnected");chunk3SBZTZXS_cjs.a(this,"subscriptions",new Map);chunk3SBZTZXS_cjs.a(this,"messageCallbacks",new Set);chunk3SBZTZXS_cjs.a(this,"agentListCallbacks",new Set);chunk3SBZTZXS_cjs.a(this,"cachedAgentList",[]);chunk3SBZTZXS_cjs.a(this,"localAgentList",[]);chunk3SBZTZXS_cjs.a(this,"reconnectAttempts",0);chunk3SBZTZXS_cjs.a(this,"reconnectTimer",null);chunk3SBZTZXS_cjs.a(this,"heartbeatTimer",null);chunk3SBZTZXS_cjs.a(this,"agentListRequestId",null);chunk3SBZTZXS_cjs.a(this,"agentListRequestResolve",null);this.config={url:e.url,type:e.type,id:e.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:e.reconnect?.enabled??true,maxAttempts:e.reconnect?.maxAttempts??5,delay:e.reconnect?.delay??3e3},heartbeat:{enabled:e.heartbeat?.enabled??true,interval:e.heartbeat?.interval??3e4}},this.log=chunk3SBZTZXS_cjs.b.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((e,t)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),e();},this.ws.onmessage=n=>{this.handleMessage(n.data);},this.ws.onclose=n=>{this.handleClose(n.code,n.reason);},this.ws.onerror=n=>{this.log.error("WebSocket error",{error:String(n)}),this.state==="connecting"&&t(new Error("Connection failed"));};}catch(n){this.state="disconnected",t(n);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(e,t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:e,backendSessionId:t,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:e,backendSessionId:t});}async unsubscribe(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:e,clientId:this.config.id}),this.subscriptions.delete(e),this.log.info("unsubscribed from session",{sessionId:e});}async send(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:e});}onMessage(e){this.messageCallbacks.add(e);}offMessage(e){this.messageCallbacks.delete(e);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(e){this.localAgentList=e,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((e,t)=>{let n=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=n,this.agentListRequestResolve=e,this.sendData({type:"agent_list_request",requestId:n}),setTimeout(()=>{this.agentListRequestId===n&&(this.agentListRequestId=null,this.agentListRequestResolve=null,t(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(e={}){let{localAgents:t,preferLocal:n=true,filterOffline:s=true}=e,r=t||this.localAgentList,i=this.cachedAgentList,o=this.mergeAgentLists(r,i,n);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(e){this.agentListCallbacks.add(e);}offAgentListChange(e){this.agentListCallbacks.delete(e);}mergeAgentLists(e,t,n){let s=new Map,r=n?t:e,i=n?e:t;for(let o of r)s.set(o.id,o);for(let o of i)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let e=this.getConnectableAgents({filterOffline:false});for(let t of this.agentListCallbacks)try{t(e);}catch(n){this.log.error("agent list callback error",{error:String(n)});}}handleAgentListResponse(e,t){t&&this.agentListRequestId===t&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(e),this.agentListRequestResolve=null),this.cachedAgentList=e,this.updateMergedAgentList(),this.log.debug("received agent list",{count:e.length});}sendData(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(e));}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case "message":this.handleGatewayMessage(t.message);break;case "subscribed":this.subscriptions.set(t.sessionId,t.subscription);break;case "unsubscribed":this.subscriptions.delete(t.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(t.agents||[],t.requestId);break;case "agent_update":this.handleAgentUpdate(t.agent,t.action);break;default:this.log.debug("unknown message type",{type:t.type});}}catch(t){this.log.error("failed to parse message",{error:String(t)});}}handleAgentUpdate(e,t){switch(t){case "add":case "update":{let n=this.cachedAgentList.findIndex(s=>s.id===e.id);n>=0?this.cachedAgentList[n]=e:this.cachedAgentList.push(e);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(n=>n.id!==e.id);break}this.updateMergedAgentList();}handleGatewayMessage(e){for(let t of this.messageCallbacks)try{t(e);}catch(n){this.log.error("message callback error",{error:String(n)});}}handleClose(e,t){this.log.info("connection closed",{code:e,reason:t}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let e=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:e}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(t){this.log.error("reconnect failed",{error:String(t)});}},e);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let e of this.subscriptions.keys())try{await this.subscribe(e);}catch(t){this.log.error("failed to resubscribe",{sessionId:e,error:String(t)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(e,t={}){let n=`${this.getHttpUrl()}${e}`,s=t.method||"GET",{signal:r,...i}=t,o=await utils.Fetch.request(n,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!o.ok){let p=o.data,x=typeof p=="object"?JSON.stringify(p):String(p||"Unknown error");throw new Error(`HTTP ${o.status}: ${x}`)}return o.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(e,t={}){let n=new URLSearchParams({platform:e,limit:String(t.limit??100),offset:String(t.offset??0)});return this.httpRequest(`/contacts?${n}`)}async getContact(e){return this.httpRequest(`/contacts/${encodeURIComponent(e)}`)}async getSession(e){return this.httpRequest(`/sessions/${encodeURIComponent(e)}`)}async createSession(e){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(e??{})})}async getOrCreateSession(e){if(e.sessionId)try{return await this.getSession(e.sessionId),{sessionId:e.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:e.sessionId});}if(e.platform||e.channel||e.userId){let n=e.chatId??e.userId;try{let i=await this.listSessions({platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n});if(i.sessions.length>0){let o=i.sessions[0];if(o)return this.log.info("found existing session",{sessionId:o.id,channel:e.channel,userId:e.userId,chatId:n}),{sessionId:o.id,created:!1}}}catch(i){this.log.warn("failed to search sessions",{error:String(i)});}let s={channel:{platform:e.platform,channelId:e.channel,userId:e.userId,chatId:n}},r=await this.createSession(s);return this.log.info("session created",{sessionId:r.id,params:s}),{sessionId:r.id,created:true}}let t=await this.createSession({channel:{platform:"api",channelId:"default"}});return this.log.info("session created (default)",{sessionId:t.id}),{sessionId:t.id,created:true}}async listSessions(e={}){let t=new URLSearchParams;return t.set("limit",String(e.limit??100)),t.set("offset",String(e.offset??0)),e.platform&&t.set("platform",e.platform),e.channelId&&t.set("channelId",e.channelId),e.userId&&t.set("userId",e.userId),e.chatId&&t.set("chatId",e.chatId),this.httpRequest(`/sessions?${t}`)}async sendMessage(e,t){return this.httpRequest(`/session/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t)})}};async function Bt(c){let{Log:e}=await import('./chunks/log-VLMXTUPA.cjs'),t=false;await e.init({logDir:c.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:c.print??false,dev:c.dev??t,level:c.level??("INFO")});}
|
|
2
|
+
Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.p}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.k}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.j}});Object.defineProperty(exports,"BaseChannelPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ha}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.h}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.fa}});Object.defineProperty(exports,"ChannelPluginRegistry",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ra}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.o}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.m}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs._}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.aa}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.$}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.Z}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.Y}});Object.defineProperty(exports,"DiscordPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ja}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.c}});Object.defineProperty(exports,"FeishuPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.la}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.l}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.s}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ta}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.r}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ea}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.i}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.n}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ba}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ca}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.g}});Object.defineProperty(exports,"NostrPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.pa}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.q}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.da}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.f}});Object.defineProperty(exports,"SignalPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.oa}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.b}});Object.defineProperty(exports,"SlackPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ka}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.a}});Object.defineProperty(exports,"TelegramPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ia}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.d}});Object.defineProperty(exports,"WeChatPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.ma}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.e}});Object.defineProperty(exports,"WebChatPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.na}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.y}});Object.defineProperty(exports,"convertToGatewayMessage",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.U}});Object.defineProperty(exports,"createChannelPlugin",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.qa}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.W}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.S}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.T}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.V}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.X}});Object.defineProperty(exports,"getAgentAdapter",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.N}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.F}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.I}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.B}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.E}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.J}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.w}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.z}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.C}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.K}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.H}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.L}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.D}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.A}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.G}});Object.defineProperty(exports,"getSupportedPlatforms",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.sa}});Object.defineProperty(exports,"hasAgentAdapter",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.O}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.x}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.v}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.u}});Object.defineProperty(exports,"requireAgentAdapter",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.P}});Object.defineProperty(exports,"setAgentAdapter",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.M}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkRFOEJ3A2_cjs.t}});exports.AgentRegistry=P;exports.AgentSyncManager=T;exports.GatewayClient=M;exports.initLog=Bt;
|