@easbot/codebase 0.1.13 → 0.1.15

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/index.cjs CHANGED
@@ -1,7 +1,4 @@
1
- 'use strict';var Kt=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),In=require('fs'),Gi=require('fs/promises'),Xo=require('zod'),url=require('url'),events=require('events'),an=require('stream'),string_decoder=require('string_decoder'),Vo=require('better-sqlite3'),utils=require('@easbot/utils'),crypto=require('crypto'),ah=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Kt__default=/*#__PURE__*/_interopDefault(Kt);var In__namespace=/*#__PURE__*/_interopNamespace(In);var Gi__default=/*#__PURE__*/_interopDefault(Gi);var Xo__default=/*#__PURE__*/_interopDefault(Xo);var an__default=/*#__PURE__*/_interopDefault(an);var Vo__default=/*#__PURE__*/_interopDefault(Vo);var ah__default=/*#__PURE__*/_interopDefault(ah);var Hn=Object.defineProperty;var Xi=s=>{throw TypeError(s)};var Xn=(s,e,t)=>e in s?Hn(s,e,{enumerable:true,configurable:true,writable:true,value:t}):s[e]=t;var u=(s,e,t)=>Xn(s,typeof e!="symbol"?e+"":e,t),fi=(s,e,t)=>e.has(s)||Xi("Cannot "+t);var n=(s,e,t)=>(fi(s,e,"read from private field"),t?t.call(s):e.get(s)),E=(s,e,t)=>e.has(s)?Xi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),g=(s,e,t,i)=>(fi(s,e,"write to private field"),e.set(s,t),t),m=(s,e,t)=>(fi(s,e,"access private method"),t);var Ws=(s,e,t,i)=>({set _(r){g(s,e,r);},get _(){return n(s,e,i)}});var Qn=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,oe=Qn();var Qi={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var It=class s extends Error{constructor(t,i,r){super(t);u(this,"name","ParserError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},dt=class s extends Error{constructor(t,i,r){super(t);u(this,"name","DatabaseError");u(this,"operation");u(this,"cause");this.operation=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},zs=class s extends Error{constructor(t,i,r){super(t);u(this,"name","FileSystemError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},js=class s extends Error{constructor(t,i){super(t);u(this,"name","SchemaError");u(this,"missing");this.missing=i,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},Jt=class s extends Error{constructor(t,i){super(t);u(this,"name","ConfigError");u(this,"field");this.field=i,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},$s=class s extends Error{constructor(t,i,r){super(t);u(this,"name","IndexError");u(this,"filePath");u(this,"cause");this.filePath=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},Zt=class s extends Error{constructor(t,i,r){super(t);u(this,"name","QueryError");u(this,"params");u(this,"cause");this.params=i,this.cause=r,Object.setPrototypeOf(this,s.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",i=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${i}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Bs=class s extends Error{constructor(t,i){super(`Unsupported language: ${t}`);u(this,"name","UnsupportedLanguageError");u(this,"extension");u(this,"filePath");this.extension=t,this.filePath=i,Object.setPrototypeOf(this,s.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var $r=(s,e,t)=>{let i=s instanceof RegExp?Vi(s,t):s,r=e instanceof RegExp?Vi(e,t):e,a=i!==null&&r!=null&&Vn(i,r,t);return a&&{start:a[0],end:a[1],pre:t.slice(0,a[0]),body:t.slice(a[0]+i.length,a[1]),post:t.slice(a[1]+r.length)}},Vi=(s,e)=>{let t=e.match(s);return t?t[0]:null},Vn=(s,e,t)=>{let i,r,a,o,h,l=t.indexOf(s),c=t.indexOf(e,l+1),p=l;if(l>=0&&c>0){if(s===e)return [l,c];for(i=[],a=t.length;p>=0&&!h;){if(p===l)i.push(p),l=t.indexOf(s,p+1);else if(i.length===1){let d=i.pop();d!==void 0&&(h=[d,c]);}else r=i.pop(),r!==void 0&&r<a&&(a=r,o=c),c=t.indexOf(e,p+1);p=l<c&&l>=0?l:c;}i.length&&o!==void 0&&(h=[a,o]);}return h},Br="\0SLASH"+Math.random()+"\0",Ur="\0OPEN"+Math.random()+"\0",Wi="\0CLOSE"+Math.random()+"\0",Gr="\0COMMA"+Math.random()+"\0",qr="\0PERIOD"+Math.random()+"\0",Yn=new RegExp(Br,"g"),Kn=new RegExp(Ur,"g"),Jn=new RegExp(Wi,"g"),Zn=new RegExp(Gr,"g"),ea=new RegExp(qr,"g"),ta=/\\\\/g,sa=/\\{/g,ia=/\\}/g,ra=/\\,/g,na=/\\./g,aa=1e5;function mi(s){return isNaN(s)?s.charCodeAt(0):parseInt(s,10)}function oa(s){return s.replace(ta,Br).replace(sa,Ur).replace(ia,Wi).replace(ra,Gr).replace(na,qr)}function ha(s){return s.replace(Yn,"\\").replace(Kn,"{").replace(Jn,"}").replace(Zn,",").replace(ea,".")}function Hr(s){if(!s)return [""];let e=[],t=$r("{","}",s);if(!t)return s.split(",");let{pre:i,body:r,post:a}=t,o=i.split(",");o[o.length-1]+="{"+r+"}";let h=Hr(a);return a.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),e.push.apply(e,o),e}function la(s,e={}){if(!s)return [];let{max:t=aa}=e;return s.slice(0,2)==="{}"&&(s="\\{\\}"+s.slice(2)),as(oa(s),t,true).map(ha)}function ca(s){return "{"+s+"}"}function da(s){return /^-?0\d/.test(s)}function ua(s,e){return s<=e}function pa(s,e){return s>=e}function as(s,e,t){let i=[],r=$r("{","}",s);if(!r)return [s];let a=r.pre,o=r.post.length?as(r.post,e,false):[""];if(/\$$/.test(r.pre))for(let h=0;h<o.length&&h<e;h++){let l=a+"{"+r.body+"}"+o[h];i.push(l);}else {let h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=h||l,p=r.body.indexOf(",")>=0;if(!c&&!p)return r.post.match(/,(?!,).*\}/)?(s=r.pre+"{"+r.body+Wi+r.post,as(s,e,true)):[s];let d;if(c)d=r.body.split(/\.\./);else if(d=Hr(r.body),d.length===1&&d[0]!==void 0&&(d=as(d[0],e,false).map(ca),d.length===1))return o.map(S=>r.pre+d[0]+S);let f;if(c&&d[0]!==void 0&&d[1]!==void 0){let S=mi(d[0]),w=mi(d[1]),x=Math.max(d[0].length,d[1].length),b=d.length===3&&d[2]!==void 0?Math.abs(mi(d[2])):1,y=ua;w<S&&(b*=-1,y=pa);let _=d.some(da);f=[];for(let N=S;y(N,w);N+=b){let P;if(l)P=String.fromCharCode(N),P==="\\"&&(P="");else if(P=String(N),_){let T=x-P.length;if(T>0){let O=new Array(T+1).join("0");N<0?P="-"+O+P.slice(1):P=O+P;}}f.push(P);}}else {f=[];for(let S=0;S<d.length;S++)f.push.apply(f,as(d[S],e,false));}for(let S=0;S<f.length;S++)for(let w=0;w<o.length&&i.length<e;w++){let x=a+f[S]+o[w];(!t||c||x)&&i.push(x);}}return i}var ni=s=>{if(typeof s!="string")throw new TypeError("invalid pattern");if(s.length>65536)throw new TypeError("pattern is too long")},ga={"[: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]},es=s=>s.replace(/[[\]\\-]/g,"\\$&"),fa=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Yi=s=>s.join(""),ma=(s,e)=>{let t=e;if(s.charAt(t)!=="[")throw new Error("not in a brace expression");let i=[],r=[],a=t+1,o=false,h=false,l=false,c=false,p=t,d="";e:for(;a<s.length;){let w=s.charAt(a);if((w==="!"||w==="^")&&a===t+1){c=true,a++;continue}if(w==="]"&&o&&!l){p=a+1;break}if(o=true,w==="\\"&&!l){l=true,a++;continue}if(w==="["&&!l){for(let[x,[b,y,_]]of Object.entries(ga))if(s.startsWith(x,a)){if(d)return ["$.",false,s.length-t,true];a+=x.length,_?r.push(b):i.push(b),h=h||y;continue e}}if(l=false,d){w>d?i.push(es(d)+"-"+es(w)):w===d&&i.push(es(w)),d="",a++;continue}if(s.startsWith("-]",a+1)){i.push(es(w+"-")),a+=2;continue}if(s.startsWith("-",a+1)){d=w,a+=2;continue}i.push(es(w)),a++;}if(p<a)return ["",false,0,false];if(!i.length&&!r.length)return ["$.",false,s.length-t,true];if(r.length===0&&i.length===1&&/^\\?.$/.test(i[0])&&!c){let w=i[0].length===2?i[0].slice(-1):i[0];return [fa(w),false,p-t,false]}let f="["+(c?"^":"")+Yi(i)+"]",S="["+(c?"":"^")+Yi(r)+"]";return [i.length&&r.length?"("+f+"|"+S+")":i.length?f:S,h,p-t,true]},kt=(s,{windowsPathsNoEscape:e=false,magicalBraces:t=true}={})=>t?e?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?s.replace(/\[([^\/\\{}])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),ya=new Set(["!","?","+","*","@"]),Ki=s=>ya.has(s),ba="(?!(?:^|/)\\.\\.?(?:$|/))",Us="(?!\\.)",wa=new Set(["[","."]),Ea=new Set(["..","."]),Sa=new Set("().*{}+?[]^$\\!"),xa=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zi="[^/]",Ji=zi+"*?",Zi=zi+"+?",j,Q,$e,I,W,tt,ft,st,Me,mt,ps,Nt,Qr,ht,K,Ks,_i,Vr,Xr=(K=class{constructor(e,t,i={}){E(this,Nt);u(this,"type");E(this,j);E(this,Q);E(this,$e,false);E(this,I,[]);E(this,W);E(this,tt);E(this,ft);E(this,st,false);E(this,Me);E(this,mt);E(this,ps,false);this.type=e,e&&g(this,Q,true),g(this,W,t),g(this,j,n(this,W)?n(n(this,W),j):this),g(this,Me,n(this,j)===this?i:n(n(this,j),Me)),g(this,ft,n(this,j)===this?[]:n(n(this,j),ft)),e==="!"&&!n(n(this,j),st)&&n(this,ft).push(this),g(this,tt,n(this,W)?n(n(this,W),I).length:0);}get hasMagic(){if(n(this,Q)!==void 0)return n(this,Q);for(let e of n(this,I))if(typeof e!="string"&&(e.type||e.hasMagic))return g(this,Q,true);return n(this,Q)}toString(){return n(this,mt)!==void 0?n(this,mt):this.type?g(this,mt,this.type+"("+n(this,I).map(e=>String(e)).join("|")+")"):g(this,mt,n(this,I).map(e=>String(e)).join(""))}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof K&&n(t,W)===this))throw new Error("invalid part: "+t);n(this,I).push(t);}}toJSON(){let e=this.type===null?n(this,I).slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...n(this,I).map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===n(this,j)||n(n(this,j),st)&&n(this,W)?.type==="!")&&e.push({}),e}isStart(){if(n(this,j)===this)return true;if(!n(this,W)?.isStart())return false;if(n(this,tt)===0)return true;let e=n(this,W);for(let t=0;t<n(this,tt);t++){let i=n(e,I)[t];if(!(i instanceof K&&i.type==="!"))return false}return true}isEnd(){if(n(this,j)===this||n(this,W)?.type==="!")return true;if(!n(this,W)?.isEnd())return false;if(!this.type)return n(this,W)?.isEnd();let e=n(this,W)?n(n(this,W),I).length:0;return n(this,tt)===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new K(this.type,e);for(let i of n(this,I))t.copyIn(i);return t}static fromGlob(e,t={}){var r;let i=new K(null,void 0,t);return m(r=K,ht,Ks).call(r,e,i,0,t),i}toMMPattern(){if(this!==n(this,j))return n(this,j).toMMPattern();let e=this.toString(),[t,i,r,a]=this.toRegExpSource();if(!(r||n(this,Q)||n(this,Me).nocase&&!n(this,Me).nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return i;let o=(n(this,Me).nocase?"i":"")+(a?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return n(this,Me)}toRegExpSource(e){let t=e??!!n(this,Me).dot;if(n(this,j)===this&&m(this,Nt,Qr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!n(this,I).some(f=>typeof f!="string"),c=n(this,I).map(f=>{var y;let[S,w,x,b]=typeof f=="string"?m(y=K,ht,Vr).call(y,f,n(this,Q),l):f.toRegExpSource(e);return g(this,Q,n(this,Q)||x),g(this,$e,n(this,$e)||b),S}).join(""),p="";if(this.isStart()&&typeof n(this,I)[0]=="string"&&!(n(this,I).length===1&&Ea.has(n(this,I)[0]))){let f=wa,S=t&&f.has(c.charAt(0))||c.startsWith("\\.")&&f.has(c.charAt(2))||c.startsWith("\\.\\.")&&f.has(c.charAt(4)),w=!t&&!e&&f.has(c.charAt(0));p=S?ba:w?Us:"";}let d="";return this.isEnd()&&n(n(this,j),st)&&n(this,W)?.type==="!"&&(d="(?:$|\\/)"),[p+c+d,kt(c),g(this,Q,!!n(this,Q)),n(this,$e)]}let i=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",a=m(this,Nt,_i).call(this,t);if(this.isStart()&&this.isEnd()&&!a&&this.type!=="!"){let l=this.toString();return g(this,I,[l]),this.type=null,g(this,Q,void 0),[l,kt(this.toString()),false,false]}let o=!i||e||t||!Us?"":m(this,Nt,_i).call(this,true);o===a&&(o=""),o&&(a=`(?:${a})(?:${o})*?`);let h="";if(this.type==="!"&&n(this,ps))h=(this.isStart()&&!t?Us:"")+Zi;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Us:"")+Ji+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=r+a+l;}return [h,kt(a),g(this,Q,!!n(this,Q)),n(this,$e)]}},j=new WeakMap,Q=new WeakMap,$e=new WeakMap,I=new WeakMap,W=new WeakMap,tt=new WeakMap,ft=new WeakMap,st=new WeakMap,Me=new WeakMap,mt=new WeakMap,ps=new WeakMap,Nt=new WeakSet,Qr=function(){if(this!==n(this,j))throw new Error("should only call on root");if(n(this,st))return this;this.toString(),g(this,st,true);let e;for(;e=n(this,ft).pop();){if(e.type!=="!")continue;let t=e,i=n(t,W);for(;i;){for(let r=n(t,tt)+1;!i.type&&r<n(i,I).length;r++)for(let a of n(e,I)){if(typeof a=="string")throw new Error("string part in extglob AST??");a.copyIn(n(i,I)[r]);}t=i,i=n(t,W);}}return this},ht=new WeakSet,Ks=function(e,t,i,r){var S,w;let a=false,o=false,h=-1,l=false;if(t.type===null){let x=i,b="";for(;x<e.length;){let y=e.charAt(x++);if(a||y==="\\"){a=!a,b+=y;continue}if(o){x===h+1?(y==="^"||y==="!")&&(l=true):y==="]"&&!(x===h+2&&l)&&(o=false),b+=y;continue}else if(y==="["){o=true,h=x,l=false,b+=y;continue}if(!r.noext&&Ki(y)&&e.charAt(x)==="("){t.push(b),b="";let _=new K(y,t);x=m(S=K,ht,Ks).call(S,e,_,x,r),t.push(_);continue}b+=y;}return t.push(b),x}let c=i+1,p=new K(null,t),d=[],f="";for(;c<e.length;){let x=e.charAt(c++);if(a||x==="\\"){a=!a,f+=x;continue}if(o){c===h+1?(x==="^"||x==="!")&&(l=true):x==="]"&&!(c===h+2&&l)&&(o=false),f+=x;continue}else if(x==="["){o=true,h=c,l=false,f+=x;continue}if(Ki(x)&&e.charAt(c)==="("){p.push(f),f="";let b=new K(x,p);p.push(b),c=m(w=K,ht,Ks).call(w,e,b,c,r);continue}if(x==="|"){p.push(f),f="",d.push(p),p=new K(null,t);continue}if(x===")")return f===""&&n(t,I).length===0&&g(t,ps,true),p.push(f),f="",t.push(...d,p),c;f+=x;}return t.type=null,g(t,Q,void 0),g(t,I,[e.substring(i-1)]),c},_i=function(e){return n(this,I).map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[i,r,a,o]=t.toRegExpSource(e);return g(this,$e,n(this,$e)||o),i}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")},Vr=function(e,t,i=false){let r=false,a="",o=false,h=false;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(r){r=false,a+=(Sa.has(c)?"\\":"")+c;continue}if(c==="*"){if(h)continue;h=true,a+=i&&/^[*]+$/.test(e)?Zi:Ji,t=true;continue}else h=false;if(c==="\\"){l===e.length-1?a+="\\\\":r=true;continue}if(c==="["){let[p,d,f,S]=ma(e,l);if(f){a+=p,o=o||d,l+=f-1,t=t||S;continue}}if(c==="?"){a+=zi,t=true;continue}a+=xa(c);}return [a,kt(e),!!t,o]},E(K,ht),K),Yr=(s,{windowsPathsNoEscape:e=false,magicalBraces:t=false}={})=>t?e?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):e?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&"),ae=(s,e,t={})=>(ni(e),!t.nocomment&&e.charAt(0)==="#"?false:new lt(e,t).match(s)),va=/^\*+([^+@!?\*\[\(]*)$/,_a=s=>e=>!e.startsWith(".")&&e.endsWith(s),Na=s=>e=>e.endsWith(s),Ta=s=>(s=s.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(s)),Ca=s=>(s=s.toLowerCase(),e=>e.toLowerCase().endsWith(s)),Ra=/^\*+\.\*+$/,Fa=s=>!s.startsWith(".")&&s.includes("."),Pa=s=>s!=="."&&s!==".."&&s.includes("."),Oa=/^\.\*+$/,La=s=>s!=="."&&s!==".."&&s.startsWith("."),Ia=/^\*+$/,Aa=s=>s.length!==0&&!s.startsWith("."),Ma=s=>s.length!==0&&s!=="."&&s!=="..",ka=/^\?+([^+@!?\*\[\(]*)?$/,Da=([s,e=""])=>{let t=Kr([s]);return e?(e=e.toLowerCase(),i=>t(i)&&i.toLowerCase().endsWith(e)):t},Wa=([s,e=""])=>{let t=Jr([s]);return e?(e=e.toLowerCase(),i=>t(i)&&i.toLowerCase().endsWith(e)):t},za=([s,e=""])=>{let t=Jr([s]);return e?i=>t(i)&&i.endsWith(e):t},ja=([s,e=""])=>{let t=Kr([s]);return e?i=>t(i)&&i.endsWith(e):t},Kr=([s])=>{let e=s.length;return t=>t.length===e&&!t.startsWith(".")},Jr=([s])=>{let e=s.length;return t=>t.length===e&&t!=="."&&t!==".."},Zr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",er={win32:{sep:"\\"},posix:{sep:"/"}},$a=Zr==="win32"?er.win32.sep:er.posix.sep;ae.sep=$a;var ne=Symbol("globstar **");ae.GLOBSTAR=ne;var Ba="[^/]",Ua=Ba+"*?",Ga="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",qa="(?:(?!(?:\\/|^)\\.).)*?",Ha=(s,e={})=>t=>ae(t,s,e);ae.filter=Ha;var me=(s,e={})=>Object.assign({},s,e),Xa=s=>{if(!s||typeof s!="object"||!Object.keys(s).length)return ae;let e=ae;return Object.assign((t,i,r={})=>e(t,i,me(s,r)),{Minimatch:class extends e.Minimatch{constructor(t,i={}){super(t,me(s,i));}static defaults(t){return e.defaults(me(s,t)).Minimatch}},AST:class extends e.AST{constructor(t,i,r={}){super(t,i,me(s,r));}static fromGlob(t,i={}){return e.AST.fromGlob(t,me(s,i))}},unescape:(t,i={})=>e.unescape(t,me(s,i)),escape:(t,i={})=>e.escape(t,me(s,i)),filter:(t,i={})=>e.filter(t,me(s,i)),defaults:t=>e.defaults(me(s,t)),makeRe:(t,i={})=>e.makeRe(t,me(s,i)),braceExpand:(t,i={})=>e.braceExpand(t,me(s,i)),match:(t,i,r={})=>e.match(t,i,me(s,r)),sep:e.sep,GLOBSTAR:ne})};ae.defaults=Xa;var en=(s,e={})=>(ni(s),e.nobrace||!/\{(?:(?!\{).)*\}/.test(s)?[s]:la(s,{max:e.braceExpandMax}));ae.braceExpand=en;var Qa=(s,e={})=>new lt(s,e).makeRe();ae.makeRe=Qa;var Va=(s,e,t={})=>{let i=new lt(e,t);return s=s.filter(r=>i.match(r)),i.options.nonull&&!s.length&&s.push(e),s};ae.match=Va;var tr=/[?*]|[+@!]\(.*?\)|\[|\]/,Ya=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),lt=class{constructor(s,e={}){u(this,"options");u(this,"set");u(this,"pattern");u(this,"windowsPathsNoEscape");u(this,"nonegate");u(this,"negate");u(this,"comment");u(this,"empty");u(this,"preserveMultipleSlashes");u(this,"partial");u(this,"globSet");u(this,"globParts");u(this,"nocase");u(this,"isWindows");u(this,"platform");u(this,"windowsNoMagicRoot");u(this,"regexp");ni(s),e=e||{},this.options=e,this.pattern=s,this.platform=e.platform||Zr,this.isWindows=this.platform==="win32";let t="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[t]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!e.nonegate,this.comment=false,this.empty=false,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.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 s of this.set)for(let e of s)if(typeof e!="string")return true;return false}debug(...s){}make(){let s=this.pattern,e=this.options;if(!e.nocomment&&s.charAt(0)==="#"){this.comment=true;return}if(!s){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let t=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(t),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,a,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let h=r[0]===""&&r[1]===""&&(r[2]==="?"||!tr.test(r[2]))&&!tr.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(h)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(l)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(h=>this.parse(h))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let a=this.set[r];a[0]===""&&a[1]===""&&this.globParts[r][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?");}this.debug(this.pattern,this.set);}preprocess(s){if(this.options.noglobstar)for(let t=0;t<s.length;t++)for(let i=0;i<s[t].length;i++)s[t][i]==="**"&&(s[t][i]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(s=this.firstPhasePreProcess(s),s=this.secondPhasePreProcess(s)):e>=1?s=this.levelOneOptimize(s):s=this.adjascentGlobstarOptimize(s),s}adjascentGlobstarOptimize(s){return s.map(e=>{let t=-1;for(;(t=e.indexOf("**",t+1))!==-1;){let i=t;for(;e[i+1]==="**";)i++;i!==t&&e.splice(t,i-t);}return e})}levelOneOptimize(s){return s.map(e=>(e=e.reduce((t,i)=>{let r=t[t.length-1];return i==="**"&&r==="**"?t:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(t.pop(),t):(t.push(i),t)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(s){Array.isArray(s)||(s=this.slashSplit(s));let e=false;do{if(e=false,!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let r=s[i];i===1&&r===""&&s[0]===""||(r==="."||r==="")&&(e=true,s.splice(i,1),i--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(e=true,s.pop());}let t=0;for(;(t=s.indexOf("..",t+1))!==-1;){let i=s[t-1];i&&i!=="."&&i!==".."&&i!=="**"&&(e=true,s.splice(t-1,2),t-=2);}}while(e);return s.length===0?[""]:s}firstPhasePreProcess(s){let e=false;do{e=false;for(let t of s){let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let a=i;for(;t[a+1]==="**";)a++;a>i&&t.splice(i+1,a-i);let o=t[i+1],h=t[i+2],l=t[i+3];if(o!==".."||!h||h==="."||h===".."||!l||l==="."||l==="..")continue;e=true,t.splice(i,1);let c=t.slice(0);c[i]="**",s.push(c),i--;}if(!this.preserveMultipleSlashes){for(let a=1;a<t.length-1;a++){let o=t[a];a===1&&o===""&&t[0]===""||(o==="."||o==="")&&(e=true,t.splice(a,1),a--);}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=true,t.pop());}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let a=t[r-1];if(a&&a!=="."&&a!==".."&&a!=="**"){e=true;let o=r===1&&t[r+1]==="**"?["."]:[];t.splice(r-1,2,...o),t.length===0&&t.push(""),r-=2;}}}}while(e);return s}secondPhasePreProcess(s){for(let e=0;e<s.length-1;e++)for(let t=e+1;t<s.length;t++){let i=this.partsMatch(s[e],s[t],!this.preserveMultipleSlashes);if(i){s[e]=[],s[t]=i;break}}return s.filter(e=>e.length)}partsMatch(s,e,t=false){let i=0,r=0,a=[],o="";for(;i<s.length&&r<e.length;)if(s[i]===e[r])a.push(o==="b"?e[r]:s[i]),i++,r++;else if(t&&s[i]==="**"&&e[r]===s[i+1])a.push(s[i]),i++;else if(t&&e[r]==="**"&&s[i]===e[r+1])a.push(e[r]),r++;else if(s[i]==="*"&&e[r]&&(this.options.dot||!e[r].startsWith("."))&&e[r]!=="**"){if(o==="b")return false;o="a",a.push(s[i]),i++,r++;}else if(e[r]==="*"&&s[i]&&(this.options.dot||!s[i].startsWith("."))&&s[i]!=="**"){if(o==="a")return false;o="b",a.push(e[r]),i++,r++;}else return false;return s.length===e.length&&a}parseNegate(){if(this.nonegate)return;let s=this.pattern,e=false,t=0;for(let i=0;i<s.length&&s.charAt(i)==="!";i++)e=!e,t++;t&&(this.pattern=s.slice(t)),this.negate=e;}matchOne(s,e,t=false){let i=this.options;if(this.isWindows){let w=typeof s[0]=="string"&&/^[a-z]:$/i.test(s[0]),x=!w&&s[0]===""&&s[1]===""&&s[2]==="?"&&/^[a-z]:$/i.test(s[3]),b=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!b&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),_=x?3:w?0:void 0,N=y?3:b?0:void 0;if(typeof _=="number"&&typeof N=="number"){let[P,T]=[s[_],e[N]];P.toLowerCase()===T.toLowerCase()&&(e[N]=P,N>_?e=e.slice(N):_>N&&(s=s.slice(_)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(s=this.levelTwoFileOptimize(s)),this.debug("matchOne",this,{file:s,pattern:e}),this.debug("matchOne",s.length,e.length);for(var a=0,o=0,h=s.length,l=e.length;a<h&&o<l;a++,o++){this.debug("matchOne loop");var c=e[o],p=s[a];if(this.debug(e,c,p),c===false)return false;if(c===ne){this.debug("GLOBSTAR",[e,c,p]);var d=a,f=o+1;if(f===l){for(this.debug("** at the end");a<h;a++)if(s[a]==="."||s[a]===".."||!i.dot&&s[a].charAt(0)===".")return false;return true}for(;d<h;){var S=s[d];if(this.debug(`
2
- globstar while`,s,d,e,f,S),this.matchOne(s.slice(d),e.slice(f),t))return this.debug("globstar found match!",d,h,S),true;if(S==="."||S===".."||!i.dot&&S.charAt(0)==="."){this.debug("dot detected!",s,d,e,f);break}this.debug("globstar swallow a segment, and continue"),d++;}return !!(t&&(this.debug(`
3
- >>> no match, partial?`,s,d,e,f),d===h))}let w;if(typeof c=="string"?(w=p===c,this.debug("string match",c,p,w)):(w=c.test(p),this.debug("pattern match",c,p,w)),!w)return false}if(a===h&&o===l)return true;if(a===h)return t;if(o===l)return a===h-1&&s[a]==="";throw new Error("wtf?")}braceExpand(){return en(this.pattern,this.options)}parse(s){ni(s);let e=this.options;if(s==="**")return ne;if(s==="")return "";let t,i=null;(t=s.match(Ia))?i=e.dot?Ma:Aa:(t=s.match(va))?i=(e.nocase?e.dot?Ca:Ta:e.dot?Na:_a)(t[1]):(t=s.match(ka))?i=(e.nocase?e.dot?Wa:Da:e.dot?za:ja)(t):(t=s.match(Ra))?i=e.dot?Pa:Fa:(t=s.match(Oa))&&(i=La);let r=Xr.fromGlob(s,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let s=this.set;if(!s.length)return this.regexp=false,this.regexp;let e=this.options,t=e.noglobstar?Ua:e.dot?Ga:qa,i=new Set(e.nocase?["i"]:[]),r=s.map(h=>{let l=h.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))i.add(d);return typeof p=="string"?Ya(p):p===ne?ne:p._src});l.forEach((p,d)=>{let f=l[d+1],S=l[d-1];p!==ne||S===ne||(S===void 0?f!==void 0&&f!==ne?l[d+1]="(?:\\/|"+t+"\\/)?"+f:l[d]=t:f===void 0?l[d-1]=S+"(?:\\/|\\/"+t+")?":f!==ne&&(l[d-1]=S+"(?:\\/|\\/"+t+"\\/)"+f,l[d+1]=ne));});let c=l.filter(p=>p!==ne);if(this.partial&&c.length>=1){let p=[];for(let d=1;d<=c.length;d++)p.push(c.slice(0,d).join("/"));return "(?:"+p.join("|")+")"}return c.join("/")}).join("|"),[a,o]=s.length>1?["(?:",")"]:["",""];r="^"+a+r+o+"$",this.partial&&(r="^(?:\\/|"+a+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(s){return this.preserveMultipleSlashes?s.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(s)?["",...s.split(/\/+/)]:s.split(/\/+/)}match(s,e=this.partial){if(this.debug("match",s,this.pattern),this.comment)return false;if(this.empty)return s==="";if(s==="/"&&e)return true;let t=this.options;this.isWindows&&(s=s.split("\\").join("/"));let i=this.slashSplit(s);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let a=i[i.length-1];if(!a)for(let o=i.length-2;!a&&o>=0;o--)a=i[o];for(let o=0;o<r.length;o++){let h=r[o],l=i;if(t.matchBase&&h.length===1&&(l=[a]),this.matchOne(l,h,e))return t.flipNegate?true:!this.negate}return t.flipNegate?false:this.negate}static defaults(s){return ae.defaults(s).Minimatch}};ae.AST=Xr;ae.Minimatch=lt;ae.escape=Yr;ae.unescape=kt;var Ja=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,tn=new Set,Ni=typeof process=="object"&&process?process:{},sn=(s,e,t,i)=>{typeof Ni.emitWarning=="function"?Ni.emitWarning(s,e,t,i):console.error(`[${t}] ${e}: ${s}`);},ai=globalThis.AbortController,sr=globalThis.AbortSignal;if(typeof ai>"u"){sr=class{constructor(){u(this,"onabort");u(this,"_onabort",[]);u(this,"reason");u(this,"aborted",false);}addEventListener(t,i){this._onabort.push(i);}},ai=class{constructor(){u(this,"signal",new sr);e();}abort(t){if(!this.signal.aborted){this.signal.reason=t,this.signal.aborted=true;for(let i of this.signal._onabort)i(t);this.signal.onabort?.(t);}}};let s=Ni.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{s&&(s=false,sn("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",e));};}var Za=s=>!tn.has(s),Ke=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),rn=s=>Ke(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?Js:null:null,Js=class extends Array{constructor(s){super(s),this.fill(0);}},We,Dt,eo=(We=class{constructor(e,t){u(this,"heap");u(this,"length");if(!n(We,Dt))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0;}static create(e){let t=rn(e);if(!t)return [];g(We,Dt,true);let i=new We(e,t);return g(We,Dt,false),i}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}},Dt=new WeakMap,E(We,Dt,false),We),yr,br,be,de,_e,yt,Ne,Wt,zt,Te,$,Ce,z,A,F,se,ue,ee,V,Re,Y,Fe,Pe,pe,ge,Oe,it,ie,jt,v,Ti,bt,Be,gs,fe,nn,wt,$t,fs,Je,Ze,Ci,Zs,ei,L,Ri,os,et,Fi,Bt,li=(Bt=class{constructor(e){E(this,v);E(this,be);E(this,de);E(this,_e);E(this,yt);E(this,Ne);E(this,Wt);E(this,zt);E(this,Te);u(this,"ttl");u(this,"ttlResolution");u(this,"ttlAutopurge");u(this,"updateAgeOnGet");u(this,"updateAgeOnHas");u(this,"allowStale");u(this,"noDisposeOnSet");u(this,"noUpdateTTL");u(this,"maxEntrySize");u(this,"sizeCalculation");u(this,"noDeleteOnFetchRejection");u(this,"noDeleteOnStaleGet");u(this,"allowStaleOnFetchAbort");u(this,"allowStaleOnFetchRejection");u(this,"ignoreFetchAbort");E(this,$);E(this,Ce);E(this,z);E(this,A);E(this,F);E(this,se);E(this,ue);E(this,ee);E(this,V);E(this,Re);E(this,Y);E(this,Fe);E(this,Pe);E(this,pe);E(this,ge);E(this,Oe);E(this,it);E(this,ie);E(this,jt);E(this,bt,()=>{});E(this,Be,()=>{});E(this,gs,()=>{});E(this,fe,()=>false);E(this,wt,e=>{});E(this,$t,(e,t,i)=>{});E(this,fs,(e,t,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});u(this,yr,"LRUCache");let{max:t=0,ttl:i,ttlResolution:r=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:l,dispose:c,onInsert:p,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:S,maxSize:w=0,maxEntrySize:x=0,sizeCalculation:b,fetchMethod:y,memoMethod:_,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:O,ignoreFetchAbort:k,perf:J}=e;if(J!==void 0&&typeof J?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(g(this,Te,J??Ja),t!==0&&!Ke(t))throw new TypeError("max option must be a nonnegative integer");let M=t?rn(t):Array;if(!M)throw new Error("invalid max value: "+t);if(g(this,be,t),g(this,de,w),this.maxEntrySize=x||n(this,de),this.sizeCalculation=b,this.sizeCalculation){if(!n(this,de)&&!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(_!==void 0&&typeof _!="function")throw new TypeError("memoMethod must be a function if defined");if(g(this,zt,_),y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(g(this,Wt,y),g(this,it,!!y),g(this,z,new Map),g(this,A,new Array(t).fill(void 0)),g(this,F,new Array(t).fill(void 0)),g(this,se,new M(t)),g(this,ue,new M(t)),g(this,ee,0),g(this,V,0),g(this,Re,eo.create(t)),g(this,$,0),g(this,Ce,0),typeof c=="function"&&g(this,_e,c),typeof p=="function"&&g(this,yt,p),typeof d=="function"?(g(this,Ne,d),g(this,Y,[])):(g(this,Ne,void 0),g(this,Y,void 0)),g(this,Oe,!!n(this,_e)),g(this,jt,!!n(this,yt)),g(this,ie,!!n(this,Ne)),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(n(this,de)!==0&&!Ke(n(this,de)))throw new TypeError("maxSize must be a positive integer if specified");if(!Ke(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");m(this,v,nn).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=Ke(r)||r===0?r:1,this.ttlAutopurge=!!a,this.ttl=i||0,this.ttl){if(!Ke(this.ttl))throw new TypeError("ttl must be a positive integer if specified");m(this,v,Ti).call(this);}if(n(this,be)===0&&this.ttl===0&&n(this,de)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,be)&&!n(this,de)){let G="LRU_CACHE_UNBOUNDED";Za(G)&&(tn.add(G),sn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",G,Bt));}}get perf(){return n(this,Te)}static unsafeExposeInternals(e){return {starts:n(e,Pe),ttls:n(e,pe),autopurgeTimers:n(e,ge),sizes:n(e,Fe),keyMap:n(e,z),keyList:n(e,A),valList:n(e,F),next:n(e,se),prev:n(e,ue),get head(){return n(e,ee)},get tail(){return n(e,V)},free:n(e,Re),isBackgroundFetch:t=>{var i;return m(i=e,v,L).call(i,t)},backgroundFetch:(t,i,r,a)=>{var o;return m(o=e,v,ei).call(o,t,i,r,a)},moveToTail:t=>{var i;return m(i=e,v,os).call(i,t)},indexes:t=>{var i;return m(i=e,v,Je).call(i,t)},rindexes:t=>{var i;return m(i=e,v,Ze).call(i,t)},isStale:t=>{var i;return n(i=e,fe).call(i,t)}}}get max(){return n(this,be)}get maxSize(){return n(this,de)}get calculatedSize(){return n(this,Ce)}get size(){return n(this,$)}get fetchMethod(){return n(this,Wt)}get memoMethod(){return n(this,zt)}get dispose(){return n(this,_e)}get onInsert(){return n(this,yt)}get disposeAfter(){return n(this,Ne)}getRemainingTTL(e){return n(this,z).has(e)?1/0:0}*entries(){for(let e of m(this,v,Je).call(this))n(this,F)[e]!==void 0&&n(this,A)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield [n(this,A)[e],n(this,F)[e]]);}*rentries(){for(let e of m(this,v,Ze).call(this))n(this,F)[e]!==void 0&&n(this,A)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield [n(this,A)[e],n(this,F)[e]]);}*keys(){for(let e of m(this,v,Je).call(this)){let t=n(this,A)[e];t!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield t);}}*rkeys(){for(let e of m(this,v,Ze).call(this)){let t=n(this,A)[e];t!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield t);}}*values(){for(let e of m(this,v,Je).call(this))n(this,F)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield n(this,F)[e]);}*rvalues(){for(let e of m(this,v,Ze).call(this))n(this,F)[e]!==void 0&&!m(this,v,L).call(this,n(this,F)[e])&&(yield n(this,F)[e]);}[(br=Symbol.iterator,yr=Symbol.toStringTag,br)](){return this.entries()}find(e,t={}){for(let i of m(this,v,Je).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;if(a!==void 0&&e(a,n(this,A)[i],this))return this.get(n(this,A)[i],t)}}forEach(e,t=this){for(let i of m(this,v,Je).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;a!==void 0&&e.call(t,a,n(this,A)[i],this);}}rforEach(e,t=this){for(let i of m(this,v,Ze).call(this)){let r=n(this,F)[i],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;a!==void 0&&e.call(t,a,n(this,A)[i],this);}}purgeStale(){let e=false;for(let t of m(this,v,Ze).call(this,{allowStale:true}))n(this,fe).call(this,t)&&(m(this,v,et).call(this,n(this,A)[t],"expire"),e=true);return e}info(e){let t=n(this,z).get(e);if(t===void 0)return;let i=n(this,F)[t],r=m(this,v,L).call(this,i)?i.__staleWhileFetching:i;if(r===void 0)return;let a={value:r};if(n(this,pe)&&n(this,Pe)){let o=n(this,pe)[t],h=n(this,Pe)[t];if(o&&h){let l=o-(n(this,Te).now()-h);a.ttl=l,a.start=Date.now();}}return n(this,Fe)&&(a.size=n(this,Fe)[t]),a}dump(){let e=[];for(let t of m(this,v,Je).call(this,{allowStale:true})){let i=n(this,A)[t],r=n(this,F)[t],a=m(this,v,L).call(this,r)?r.__staleWhileFetching:r;if(a===void 0||i===void 0)continue;let o={value:a};if(n(this,pe)&&n(this,Pe)){o.ttl=n(this,pe)[t];let h=n(this,Te).now()-n(this,Pe)[t];o.start=Math.floor(Date.now()-h);}n(this,Fe)&&(o.size=n(this,Fe)[t]),e.unshift([i,o]);}return e}load(e){this.clear();for(let[t,i]of e){if(i.start){let r=Date.now()-i.start;i.start=n(this,Te).now()-r;}this.set(t,i.value,i);}}set(e,t,i={}){var f,S,w,x;if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:l}=i,{noUpdateTTL:c=this.noUpdateTTL}=i,p=n(this,fs).call(this,e,t,i.size||0,h);if(this.maxEntrySize&&p>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),m(this,v,et).call(this,e,"set"),this;let d=n(this,$)===0?void 0:n(this,z).get(e);if(d===void 0)d=n(this,$)===0?n(this,V):n(this,Re).length!==0?n(this,Re).pop():n(this,$)===n(this,be)?m(this,v,Zs).call(this,false):n(this,$),n(this,A)[d]=e,n(this,F)[d]=t,n(this,z).set(e,d),n(this,se)[n(this,V)]=d,n(this,ue)[d]=n(this,V),g(this,V,d),Ws(this,$)._++,n(this,$t).call(this,d,p,l),l&&(l.set="add"),c=false,n(this,jt)&&((f=n(this,yt))==null||f.call(this,t,e,"add"));else {m(this,v,os).call(this,d);let b=n(this,F)[d];if(t!==b){if(n(this,it)&&m(this,v,L).call(this,b)){b.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:y}=b;y!==void 0&&!o&&(n(this,Oe)&&((S=n(this,_e))==null||S.call(this,y,e,"set")),n(this,ie)&&n(this,Y)?.push([y,e,"set"]));}else o||(n(this,Oe)&&((w=n(this,_e))==null||w.call(this,b,e,"set")),n(this,ie)&&n(this,Y)?.push([b,e,"set"]));if(n(this,wt).call(this,d),n(this,$t).call(this,d,p,l),n(this,F)[d]=t,l){l.set="replace";let y=b&&m(this,v,L).call(this,b)?b.__staleWhileFetching:b;y!==void 0&&(l.oldValue=y);}}else l&&(l.set="update");n(this,jt)&&this.onInsert?.(t,e,t===b?"update":"replace");}if(r!==0&&!n(this,pe)&&m(this,v,Ti).call(this),n(this,pe)&&(c||n(this,gs).call(this,d,r,a),l&&n(this,Be).call(this,l,d)),!o&&n(this,ie)&&n(this,Y)){let b=n(this,Y),y;for(;y=b?.shift();)(x=n(this,Ne))==null||x.call(this,...y);}return this}pop(){var e;try{for(;n(this,$);){let t=n(this,F)[n(this,ee)];if(m(this,v,Zs).call(this,!0),m(this,v,L).call(this,t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(n(this,ie)&&n(this,Y)){let t=n(this,Y),i;for(;i=t?.shift();)(e=n(this,Ne))==null||e.call(this,...i);}}}has(e,t={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=t,a=n(this,z).get(e);if(a!==void 0){let o=n(this,F)[a];if(m(this,v,L).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(n(this,fe).call(this,a))r&&(r.has="stale",n(this,Be).call(this,r,a));else return i&&n(this,bt).call(this,a),r&&(r.has="hit",n(this,Be).call(this,r,a)),true}else r&&(r.has="miss");return false}peek(e,t={}){let{allowStale:i=this.allowStale}=t,r=n(this,z).get(e);if(r===void 0||!i&&n(this,fe).call(this,r))return;let a=n(this,F)[r];return m(this,v,L).call(this,a)?a.__staleWhileFetching:a}async fetch(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:w=this.allowStaleOnFetchAbort,context:x,forceRefresh:b=false,status:y,signal:_}=t;if(!n(this,it))return y&&(y.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:a,status:y});let N={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:h,size:l,sizeCalculation:c,noUpdateTTL:p,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:w,ignoreFetchAbort:S,status:y,signal:_},P=n(this,z).get(e);if(P===void 0){y&&(y.fetch="miss");let T=m(this,v,ei).call(this,e,P,N,x);return T.__returned=T}else {let T=n(this,F)[P];if(m(this,v,L).call(this,T)){let M=i&&T.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",M&&(y.returnedStale=true)),M?T.__staleWhileFetching:T.__returned=T}let O=n(this,fe).call(this,P);if(!b&&!O)return y&&(y.fetch="hit"),m(this,v,os).call(this,P),r&&n(this,bt).call(this,P),y&&n(this,Be).call(this,y,P),T;let k=m(this,v,ei).call(this,e,P,N,x),J=k.__staleWhileFetching!==void 0&&i;return y&&(y.fetch=O?"stale":"refresh",J&&O&&(y.returnedStale=true)),J?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,t={}){let i=await this.fetch(e,t);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,t={}){let i=n(this,zt);if(!i)throw new Error("no memoMethod provided to constructor");let{context:r,forceRefresh:a,...o}=t,h=this.get(e,o);if(!a&&h!==void 0)return h;let l=i(e,h,{options:o,context:r});return this.set(e,l,o),l}get(e,t={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=t,h=n(this,z).get(e);if(h!==void 0){let l=n(this,F)[h],c=m(this,v,L).call(this,l);return o&&n(this,Be).call(this,o,h),n(this,fe).call(this,h)?(o&&(o.get="stale"),c?(o&&i&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),i?l.__staleWhileFetching:void 0):(a||m(this,v,et).call(this,e,"expire"),o&&i&&(o.returnedStale=true),i?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(m(this,v,os).call(this,h),r&&n(this,bt).call(this,h),l))}else o&&(o.get="miss");}delete(e){return m(this,v,et).call(this,e,"delete")}clear(){return m(this,v,Fi).call(this,"delete")}},be=new WeakMap,de=new WeakMap,_e=new WeakMap,yt=new WeakMap,Ne=new WeakMap,Wt=new WeakMap,zt=new WeakMap,Te=new WeakMap,$=new WeakMap,Ce=new WeakMap,z=new WeakMap,A=new WeakMap,F=new WeakMap,se=new WeakMap,ue=new WeakMap,ee=new WeakMap,V=new WeakMap,Re=new WeakMap,Y=new WeakMap,Fe=new WeakMap,Pe=new WeakMap,pe=new WeakMap,ge=new WeakMap,Oe=new WeakMap,it=new WeakMap,ie=new WeakMap,jt=new WeakMap,v=new WeakSet,Ti=function(){let e=new Js(n(this,be)),t=new Js(n(this,be));g(this,pe,e),g(this,Pe,t);let i=this.ttlAutopurge?new Array(n(this,be)):void 0;g(this,ge,i),g(this,gs,(o,h,l=n(this,Te).now())=>{if(t[o]=h!==0?l:0,e[o]=h,i?.[o]&&(clearTimeout(i[o]),i[o]=void 0),h!==0&&i){let c=setTimeout(()=>{n(this,fe).call(this,o)&&m(this,v,et).call(this,n(this,A)[o],"expire");},h+1);c.unref&&c.unref(),i[o]=c;}}),g(this,bt,o=>{t[o]=e[o]!==0?n(this,Te).now():0;}),g(this,Be,(o,h)=>{if(e[h]){let l=e[h],c=t[h];if(!l||!c)return;o.ttl=l,o.start=c,o.now=r||a();let p=o.now-c;o.remainingTTL=l-p;}});let r=0,a=()=>{let o=n(this,Te).now();if(this.ttlResolution>0){r=o;let h=setTimeout(()=>r=0,this.ttlResolution);h.unref&&h.unref();}return o};this.getRemainingTTL=o=>{let h=n(this,z).get(o);if(h===void 0)return 0;let l=e[h],c=t[h];if(!l||!c)return 1/0;let p=(r||a())-c;return l-p},g(this,fe,o=>{let h=t[o],l=e[o];return !!l&&!!h&&(r||a())-h>l});},bt=new WeakMap,Be=new WeakMap,gs=new WeakMap,fe=new WeakMap,nn=function(){let e=new Js(n(this,be));g(this,Ce,0),g(this,Fe,e),g(this,wt,t=>{g(this,Ce,n(this,Ce)-e[t]),e[t]=0;}),g(this,fs,(t,i,r,a)=>{if(m(this,v,L).call(this,i))return 0;if(!Ke(r))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(r=a(i,t),!Ke(r))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 r}),g(this,$t,(t,i,r)=>{if(e[t]=i,n(this,de)){let a=n(this,de)-e[t];for(;n(this,Ce)>a;)m(this,v,Zs).call(this,true);}g(this,Ce,n(this,Ce)+e[t]),r&&(r.entrySize=i,r.totalCalculatedSize=n(this,Ce));});},wt=new WeakMap,$t=new WeakMap,fs=new WeakMap,Je=function*({allowStale:e=this.allowStale}={}){if(n(this,$))for(let t=n(this,V);!(!m(this,v,Ci).call(this,t)||((e||!n(this,fe).call(this,t))&&(yield t),t===n(this,ee)));)t=n(this,ue)[t];},Ze=function*({allowStale:e=this.allowStale}={}){if(n(this,$))for(let t=n(this,ee);!(!m(this,v,Ci).call(this,t)||((e||!n(this,fe).call(this,t))&&(yield t),t===n(this,V)));)t=n(this,se)[t];},Ci=function(e){return e!==void 0&&n(this,z).get(n(this,A)[e])===e},Zs=function(e){var a;let t=n(this,ee),i=n(this,A)[t],r=n(this,F)[t];return n(this,it)&&m(this,v,L).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Oe)||n(this,ie))&&(n(this,Oe)&&((a=n(this,_e))==null||a.call(this,r,i,"evict")),n(this,ie)&&n(this,Y)?.push([r,i,"evict"])),n(this,wt).call(this,t),n(this,ge)?.[t]&&(clearTimeout(n(this,ge)[t]),n(this,ge)[t]=void 0),e&&(n(this,A)[t]=void 0,n(this,F)[t]=void 0,n(this,Re).push(t)),n(this,$)===1?(g(this,ee,g(this,V,0)),n(this,Re).length=0):g(this,ee,n(this,se)[t]),n(this,z).delete(i),Ws(this,$)._--,t},ei=function(e,t,i,r){let a=t===void 0?void 0:n(this,F)[t];if(m(this,v,L).call(this,a))return a;let o=new ai,{signal:h}=i;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let l={signal:o.signal,options:i,context:r},c=(x,b=false)=>{let{aborted:y}=o.signal,_=i.ignoreFetchAbort&&x!==void 0,N=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&x!==void 0);if(i.status&&(y&&!b?(i.status.fetchAborted=true,i.status.fetchError=o.signal.reason,_&&(i.status.fetchAbortIgnored=true)):i.status.fetchResolved=true),y&&!_&&!b)return d(o.signal.reason,N);let P=S,T=n(this,F)[t];return (T===S||_&&b&&T===void 0)&&(x===void 0?P.__staleWhileFetching!==void 0?n(this,F)[t]=P.__staleWhileFetching:m(this,v,et).call(this,e,"fetch"):(i.status&&(i.status.fetchUpdated=true),this.set(e,x,l.options))),x},p=x=>(i.status&&(i.status.fetchRejected=true,i.status.fetchError=x),d(x,false)),d=(x,b)=>{let{aborted:y}=o.signal,_=y&&i.allowStaleOnFetchAbort,N=_||i.allowStaleOnFetchRejection,P=N||i.noDeleteOnFetchRejection,T=S;if(n(this,F)[t]===S&&(!P||!b&&T.__staleWhileFetching===void 0?m(this,v,et).call(this,e,"fetch"):_||(n(this,F)[t]=T.__staleWhileFetching)),N)return i.status&&T.__staleWhileFetching!==void 0&&(i.status.returnedStale=true),T.__staleWhileFetching;if(T.__returned===T)throw x},f=(x,b)=>{var _;let y=(_=n(this,Wt))==null?void 0:_.call(this,e,a,l);y&&y instanceof Promise&&y.then(N=>x(N===void 0?void 0:N),b),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(void 0),i.allowStaleOnFetchAbort&&(x=N=>c(N,true)));});};i.status&&(i.status.fetchDispatched=true);let S=new Promise(f).then(c,p),w=Object.assign(S,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return t===void 0?(this.set(e,w,{...l.options,status:void 0}),t=n(this,z).get(e)):n(this,F)[t]=w,w},L=function(e){if(!n(this,it))return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof ai},Ri=function(e,t){n(this,ue)[t]=e,n(this,se)[e]=t;},os=function(e){e!==n(this,V)&&(e===n(this,ee)?g(this,ee,n(this,se)[e]):m(this,v,Ri).call(this,n(this,ue)[e],n(this,se)[e]),m(this,v,Ri).call(this,n(this,V),e),g(this,V,e));},et=function(e,t){var r,a;let i=false;if(n(this,$)!==0){let o=n(this,z).get(e);if(o!==void 0)if(n(this,ge)?.[o]&&(clearTimeout(n(this,ge)?.[o]),n(this,ge)[o]=void 0),i=true,n(this,$)===1)m(this,v,Fi).call(this,t);else {n(this,wt).call(this,o);let h=n(this,F)[o];if(m(this,v,L).call(this,h)?h.__abortController.abort(new Error("deleted")):(n(this,Oe)||n(this,ie))&&(n(this,Oe)&&((r=n(this,_e))==null||r.call(this,h,e,t)),n(this,ie)&&n(this,Y)?.push([h,e,t])),n(this,z).delete(e),n(this,A)[o]=void 0,n(this,F)[o]=void 0,o===n(this,V))g(this,V,n(this,ue)[o]);else if(o===n(this,ee))g(this,ee,n(this,se)[o]);else {let l=n(this,ue)[o];n(this,se)[l]=n(this,se)[o];let c=n(this,se)[o];n(this,ue)[c]=n(this,ue)[o];}Ws(this,$)._--,n(this,Re).push(o);}}if(n(this,ie)&&n(this,Y)?.length){let o=n(this,Y),h;for(;h=o?.shift();)(a=n(this,Ne))==null||a.call(this,...h);}return i},Fi=function(e){var t,i;for(let r of m(this,v,Ze).call(this,{allowStale:true})){let a=n(this,F)[r];if(m(this,v,L).call(this,a))a.__abortController.abort(new Error("deleted"));else {let o=n(this,A)[r];n(this,Oe)&&((t=n(this,_e))==null||t.call(this,a,o,e)),n(this,ie)&&n(this,Y)?.push([a,o,e]);}}if(n(this,z).clear(),n(this,F).fill(void 0),n(this,A).fill(void 0),n(this,pe)&&n(this,Pe)){n(this,pe).fill(0),n(this,Pe).fill(0);for(let r of n(this,ge)??[])r!==void 0&&clearTimeout(r);n(this,ge)?.fill(void 0);}if(n(this,Fe)&&n(this,Fe).fill(0),g(this,ee,0),g(this,V,0),n(this,Re).length=0,g(this,Ce,0),g(this,$,0),n(this,ie)&&n(this,Y)){let r=n(this,Y),a;for(;a=r?.shift();)(i=n(this,Ne))==null||i.call(this,...a);}},Bt),ir=typeof process=="object"&&process?process:{stdout:null,stderr:null},fo=s=>!!s&&typeof s=="object"&&(s instanceof oi||s instanceof an__default.default||mo(s)||yo(s)),mo=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.pipe=="function"&&s.pipe!==an__default.default.Writable.prototype.pipe,yo=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.write=="function"&&typeof s.end=="function",ze=Symbol("EOF"),je=Symbol("maybeEmitEnd"),Ye=Symbol("emittedEnd"),Gs=Symbol("emittingEnd"),ts=Symbol("emittedError"),qs=Symbol("closed"),rr=Symbol("read"),Hs=Symbol("flush"),nr=Symbol("flushChunk"),xe=Symbol("encoding"),At=Symbol("decoder"),q=Symbol("flowing"),ss=Symbol("paused"),Mt=Symbol("resume"),H=Symbol("buffer"),te=Symbol("pipes"),X=Symbol("bufferLength"),yi=Symbol("bufferPush"),Xs=Symbol("bufferShift"),Z=Symbol("objectMode"),D=Symbol("destroyed"),bi=Symbol("error"),wi=Symbol("emitData"),ar=Symbol("emitEnd"),Ei=Symbol("emitEnd2"),Ie=Symbol("async"),Si=Symbol("abort"),Qs=Symbol("aborted"),is=Symbol("signal"),ut=Symbol("dataListeners"),ce=Symbol("discarded"),rs=s=>Promise.resolve().then(s),bo=s=>s(),wo=s=>s==="end"||s==="finish"||s==="prefinish",Eo=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,So=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),on=class{constructor(s,e,t){u(this,"src");u(this,"dest");u(this,"opts");u(this,"ondrain");this.src=s,this.dest=e,this.opts=t,this.ondrain=()=>s[Mt](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(s){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},xo=class extends on{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(s,e,t){super(s,e,t),this.proxyErrors=i=>this.dest.emit("error",i),s.on("error",this.proxyErrors);}},vo=s=>!!s.objectMode,_o=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",wr,Er,Sr,xr,vr,_r,Nr,Tr,Cr,Rr,Fr,Pr,Or,Lr,Ir,Ar,Mr,kr,Dr,oi=class extends events.EventEmitter{constructor(...e){let t=e[0]||{};super();u(this,Dr,false);u(this,kr,false);u(this,Mr,[]);u(this,Ar,[]);u(this,Ir);u(this,Lr);u(this,Or);u(this,Pr);u(this,Fr,false);u(this,Rr,false);u(this,Cr,false);u(this,Tr,false);u(this,Nr,null);u(this,_r,0);u(this,vr,false);u(this,xr);u(this,Sr,false);u(this,Er,0);u(this,wr,false);u(this,"writable",true);u(this,"readable",true);if(t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");vo(t)?(this[Z]=true,this[xe]=null):_o(t)?(this[xe]=t.encoding,this[Z]=false):(this[Z]=false,this[xe]=null),this[Ie]=!!t.async,this[At]=this[xe]?new string_decoder.StringDecoder(this[xe]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[H]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[te]});let{signal:i}=t;i&&(this[is]=i,i.aborted?this[Si]():i.addEventListener("abort",()=>this[Si]()));}get bufferLength(){return this[X]}get encoding(){return this[xe]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Z]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ie]}set async(e){this[Ie]=this[Ie]||!!e;}[(Dr=q,kr=ss,Mr=te,Ar=H,Ir=Z,Lr=xe,Or=Ie,Pr=At,Fr=ze,Rr=Ye,Cr=Gs,Tr=qs,Nr=ts,_r=X,vr=D,xr=is,Sr=Qs,Er=ut,wr=ce,Si)](){this[Qs]=true,this.emit("abort",this[is]?.reason),this.destroy(this[is]?.reason);}get aborted(){return this[Qs]}set aborted(e){}write(e,t,i){if(this[Qs])return false;if(this[ze])throw new Error("write after end");if(this[D])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8");let r=this[Ie]?rs:bo;if(!this[Z]&&!Buffer.isBuffer(e)){if(So(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Eo(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Z]?(this[q]&&this[X]!==0&&this[Hs](true),this[q]?this.emit("data",e):this[yi](e),this[X]!==0&&this.emit("readable"),i&&r(i),this[q]):e.length?(typeof e=="string"&&!(t===this[xe]&&!this[At]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[xe]&&(e=this[At].write(e)),this[q]&&this[X]!==0&&this[Hs](true),this[q]?this.emit("data",e):this[yi](e),this[X]!==0&&this.emit("readable"),i&&r(i),this[q]):(this[X]!==0&&this.emit("readable"),i&&r(i),this[q])}read(e){if(this[D])return null;if(this[ce]=false,this[X]===0||e===0||e&&e>this[X])return this[je](),null;this[Z]&&(e=null),this[H].length>1&&!this[Z]&&(this[H]=[this[xe]?this[H].join(""):Buffer.concat(this[H],this[X])]);let t=this[rr](e||null,this[H][0]);return this[je](),t}[rr](e,t){if(this[Z])this[Xs]();else {let i=t;e===i.length||e===null?this[Xs]():typeof i=="string"?(this[H][0]=i.slice(e),t=i.slice(0,e),this[X]-=e):(this[H][0]=i.subarray(e),t=i.subarray(0,e),this[X]-=e);}return this.emit("data",t),!this[H].length&&!this[ze]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t="utf8"),e!==void 0&&this.write(e,t),i&&this.once("end",i),this[ze]=true,this.writable=false,(this[q]||!this[ss])&&this[je](),this}[Mt](){this[D]||(!this[ut]&&!this[te].length&&(this[ce]=true),this[ss]=false,this[q]=true,this.emit("resume"),this[H].length?this[Hs]():this[ze]?this[je]():this.emit("drain"));}resume(){return this[Mt]()}pause(){this[q]=false,this[ss]=true,this[ce]=false;}get destroyed(){return this[D]}get flowing(){return this[q]}get paused(){return this[ss]}[yi](e){this[Z]?this[X]+=1:this[X]+=e.length,this[H].push(e);}[Xs](){return this[Z]?this[X]-=1:this[X]-=this[H][0].length,this[H].shift()}[Hs](e=false){do;while(this[nr](this[Xs]())&&this[H].length);!e&&!this[H].length&&!this[ze]&&this.emit("drain");}[nr](e){return this.emit("data",e),this[q]}pipe(e,t){if(this[D])return e;this[ce]=false;let i=this[Ye];return t=t||{},e===ir.stdout||e===ir.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,i?t.end&&e.end():(this[te].push(t.proxyErrors?new xo(this,e,t):new on(this,e,t)),this[Ie]?rs(()=>this[Mt]()):this[Mt]()),e}unpipe(e){let t=this[te].find(i=>i.dest===e);t&&(this[te].length===1?(this[q]&&this[ut]===0&&(this[q]=false),this[te]=[]):this[te].splice(this[te].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let i=super.on(e,t);if(e==="data")this[ce]=false,this[ut]++,!this[te].length&&!this[q]&&this[Mt]();else if(e==="readable"&&this[X]!==0)super.emit("readable");else if(wo(e)&&this[Ye])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[ts]){let r=t;this[Ie]?rs(()=>r.call(this,this[ts])):r.call(this,this[ts]);}return i}removeListener(e,t){return this.off(e,t)}off(e,t){let i=super.off(e,t);return e==="data"&&(this[ut]=this.listeners("data").length,this[ut]===0&&!this[ce]&&!this[te].length&&(this[q]=false)),i}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[ut]=0,!this[ce]&&!this[te].length&&(this[q]=false)),t}get emittedEnd(){return this[Ye]}[je](){!this[Gs]&&!this[Ye]&&!this[D]&&this[H].length===0&&this[ze]&&(this[Gs]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[qs]&&this.emit("close"),this[Gs]=false);}emit(e,...t){let i=t[0];if(e!=="error"&&e!=="close"&&e!==D&&this[D])return false;if(e==="data")return !this[Z]&&!i?false:this[Ie]?(rs(()=>this[wi](i)),true):this[wi](i);if(e==="end")return this[ar]();if(e==="close"){if(this[qs]=true,!this[Ye]&&!this[D])return false;let a=super.emit("close");return this.removeAllListeners("close"),a}else if(e==="error"){this[ts]=i,super.emit(bi,i);let a=!this[is]||this.listeners("error").length?super.emit("error",i):false;return this[je](),a}else if(e==="resume"){let a=super.emit("resume");return this[je](),a}else if(e==="finish"||e==="prefinish"){let a=super.emit(e);return this.removeAllListeners(e),a}let r=super.emit(e,...t);return this[je](),r}[wi](e){for(let i of this[te])i.dest.write(e)===false&&this.pause();let t=this[ce]?false:super.emit("data",e);return this[je](),t}[ar](){return this[Ye]?false:(this[Ye]=true,this.readable=false,this[Ie]?(rs(()=>this[Ei]()),true):this[Ei]())}[Ei](){if(this[At]){let t=this[At].end();if(t){for(let i of this[te])i.dest.write(t);this[ce]||super.emit("data",t);}}for(let t of this[te])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Z]||(e.dataLength=0);let t=this.promise();return this.on("data",i=>{e.push(i),this[Z]||(e.dataLength+=i.length);}),await t,e}async concat(){if(this[Z])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[xe]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(D,()=>t(new Error("stream destroyed"))),this.on("error",i=>t(i)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[ce]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let i=this.read();if(i!==null)return Promise.resolve({done:false,value:i});if(this[ze])return t();let r,a,o=p=>{this.off("data",h),this.off("end",l),this.off(D,c),t(),a(p);},h=p=>{this.off("error",o),this.off("end",l),this.off(D,c),this.pause(),r({value:p,done:!!this[ze]});},l=()=>{this.off("error",o),this.off("data",h),this.off(D,c),t(),r({done:true,value:void 0});},c=()=>o(new Error("stream destroyed"));return new Promise((p,d)=>{a=d,r=p,this.once(D,c),this.once("error",o),this.once("end",l),this.once("data",h);})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ce]=false;let e=false,t=()=>(this.pause(),this.off(bi,t),this.off(D,t),this.off("end",t),e=true,{done:true,value:void 0}),i=()=>{if(e)return t();let r=this.read();return r===null?t():{done:false,value:r}};return this.once("end",t),this.once(bi,t),this.once(D,t),{next:i,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[D])return e?this.emit("error",e):this.emit(D),this;this[D]=true,this[ce]=true,this[H].length=0,this[X]=0;let t=this;return typeof t.close=="function"&&!this[qs]&&t.close(),e?this.emit("error",e):this.emit(D),this}static get isStream(){return fo}},No=In.realpathSync.native,hs={lstatSync:In.lstatSync,readdir:In.readdir,readdirSync:In.readdirSync,readlinkSync:In.readlinkSync,realpathSync:No,promises:{lstat:Gi.lstat,readdir:Gi.readdir,readlink:Gi.readlink,realpath:Gi.realpath}},hn=s=>!s||s===hs||s===In__namespace?hs:{...hs,...s,promises:{...hs.promises,...s.promises||{}}},ln=/^\\\\\?\\([a-z]:)\\?$/i,To=s=>s.replace(/\//g,"\\").replace(ln,"$1\\"),Co=/[\\\/]/,we=0,cn=1,dn=2,Ae=4,un=6,pn=8,pt=10,gn=12,ye=15,ns=~ye,xi=16,or=32,ls=64,ve=128,Vs=256,ti=512,hr=ls|ve|ti,Ro=1023,vi=s=>s.isFile()?pn:s.isDirectory()?Ae:s.isSymbolicLink()?pt:s.isCharacterDevice()?dn:s.isBlockDevice()?un:s.isSocket()?gn:s.isFIFO()?cn:we,lr=new li({max:2**12}),cs=s=>{let e=lr.get(s);if(e)return e;let t=s.normalize("NFKD");return lr.set(s,t),t},cr=new li({max:2**12}),Ys=s=>{let e=cr.get(s);if(e)return e;let t=cs(s.toLowerCase());return cr.set(s,t),t},dr=class extends li{constructor(){super({max:256});}},Fo=class extends li{constructor(s=16*1024){super({maxSize:s,sizeCalculation:e=>e.length+1});}},fn=Symbol("PathScurry setAsCwd"),re,ms,ys,bs,ws,Es,Ss,xs,vs,_s,Ns,Ts,Cs,Rs,Fs,Ps,Os,Ls,Is,rt,Et,ke,Ue,Ge,qe,R,St,He,De,C,Oi,si,ds,Li,Ii,us,ii,Ai,Mi,ri,mn,yn,bn,ki,Ut,Gt,wn,xt,Wr,he=(Wr=class{constructor(s,e=we,t,i,r,a,o){E(this,C);u(this,"name");u(this,"root");u(this,"roots");u(this,"parent");u(this,"nocase");u(this,"isCWD",false);E(this,re);E(this,ms);E(this,ys);E(this,bs);E(this,ws);E(this,Es);E(this,Ss);E(this,xs);E(this,vs);E(this,_s);E(this,Ns);E(this,Ts);E(this,Cs);E(this,Rs);E(this,Fs);E(this,Ps);E(this,Os);E(this,Ls);E(this,Is);E(this,rt);E(this,Et);E(this,ke);E(this,Ue);E(this,Ge);E(this,qe);E(this,R);E(this,St);E(this,He);E(this,De);E(this,Ut,[]);E(this,Gt,false);E(this,xt);this.name=s,g(this,rt,r?Ys(s):cs(s)),g(this,R,e&Ro),this.nocase=r,this.roots=i,this.root=t||this,g(this,St,a),g(this,ke,o.fullpath),g(this,Ge,o.relative),g(this,qe,o.relativePosix),this.parent=o.parent,this.parent?g(this,re,n(this.parent,re)):g(this,re,hn(o.fs));}get dev(){return n(this,ms)}get mode(){return n(this,ys)}get nlink(){return n(this,bs)}get uid(){return n(this,ws)}get gid(){return n(this,Es)}get rdev(){return n(this,Ss)}get blksize(){return n(this,xs)}get ino(){return n(this,vs)}get size(){return n(this,_s)}get blocks(){return n(this,Ns)}get atimeMs(){return n(this,Ts)}get mtimeMs(){return n(this,Cs)}get ctimeMs(){return n(this,Rs)}get birthtimeMs(){return n(this,Fs)}get atime(){return n(this,Ps)}get mtime(){return n(this,Os)}get ctime(){return n(this,Ls)}get birthtime(){return n(this,Is)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,Et)!==void 0?n(this,Et):this.parent?g(this,Et,this.parent.depth()+1):g(this,Et,0)}childrenCache(){return n(this,St)}resolve(s){var i;if(!s)return this;let e=this.getRootString(s),t=s.substring(e.length).split(this.splitSep);return e?m(i=this.getRoot(e),C,Oi).call(i,t):m(this,C,Oi).call(this,t)}children(){let s=n(this,St).get(this);if(s)return s;let e=Object.assign([],{provisional:0});return n(this,St).set(this,e),g(this,R,n(this,R)&~xi),e}child(s,e){if(s===""||s===".")return this;if(s==="..")return this.parent||this;let t=this.children(),i=this.nocase?Ys(s):cs(s);for(let h of t)if(n(h,rt)===i)return h;let r=this.parent?this.sep:"",a=n(this,ke)?n(this,ke)+r+s:void 0,o=this.newChild(s,we,{...e,parent:this,fullpath:a});return this.canReaddir()||g(o,R,n(o,R)|ve),t.push(o),o}relative(){if(this.isCWD)return "";if(n(this,Ge)!==void 0)return n(this,Ge);let s=this.name,e=this.parent;if(!e)return g(this,Ge,this.name);let t=e.relative();return t+(!t||!e.parent?"":this.sep)+s}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(n(this,qe)!==void 0)return n(this,qe);let s=this.name,e=this.parent;if(!e)return g(this,qe,this.fullpathPosix());let t=e.relativePosix();return t+(!t||!e.parent?"":"/")+s}fullpath(){if(n(this,ke)!==void 0)return n(this,ke);let s=this.name,e=this.parent;if(!e)return g(this,ke,this.name);let t=e.fullpath()+(e.parent?this.sep:"")+s;return g(this,ke,t)}fullpathPosix(){if(n(this,Ue)!==void 0)return n(this,Ue);if(this.sep==="/")return g(this,Ue,this.fullpath());if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(i)?g(this,Ue,`//?/${i}`):g(this,Ue,i)}let s=this.parent,e=s.fullpathPosix(),t=e+(!e||!s.parent?"":"/")+this.name;return g(this,Ue,t)}isUnknown(){return (n(this,R)&ye)===we}isType(s){return this[`is${s}`]()}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 (n(this,R)&ye)===pn}isDirectory(){return (n(this,R)&ye)===Ae}isCharacterDevice(){return (n(this,R)&ye)===dn}isBlockDevice(){return (n(this,R)&ye)===un}isFIFO(){return (n(this,R)&ye)===cn}isSocket(){return (n(this,R)&ye)===gn}isSymbolicLink(){return (n(this,R)&pt)===pt}lstatCached(){return n(this,R)&or?this:void 0}readlinkCached(){return n(this,He)}realpathCached(){return n(this,De)}readdirCached(){let s=this.children();return s.slice(0,s.provisional)}canReadlink(){if(n(this,He))return true;if(!this.parent)return false;let s=n(this,R)&ye;return !(s!==we&&s!==pt||n(this,R)&Vs||n(this,R)&ve)}calledReaddir(){return !!(n(this,R)&xi)}isENOENT(){return !!(n(this,R)&ve)}isNamed(s){return this.nocase?n(this,rt)===Ys(s):n(this,rt)===cs(s)}async readlink(){let s=n(this,He);if(s)return s;if(this.canReadlink()&&this.parent)try{let e=await n(this,re).promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return g(this,He,t)}catch(e){m(this,C,Mi).call(this,e.code);return}}readlinkSync(){let s=n(this,He);if(s)return s;if(this.canReadlink()&&this.parent)try{let e=n(this,re).readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return g(this,He,t)}catch(e){m(this,C,Mi).call(this,e.code);return}}async lstat(){if((n(this,R)&ve)===0)try{return m(this,C,ki).call(this,await n(this,re).promises.lstat(this.fullpath())),this}catch(s){m(this,C,Ai).call(this,s.code);}}lstatSync(){if((n(this,R)&ve)===0)try{return m(this,C,ki).call(this,n(this,re).lstatSync(this.fullpath())),this}catch(s){m(this,C,Ai).call(this,s.code);}}readdirCB(s,e=false){if(!this.canReaddir()){e?s(null,[]):queueMicrotask(()=>s(null,[]));return}let t=this.children();if(this.calledReaddir()){let r=t.slice(0,t.provisional);e?s(null,r):queueMicrotask(()=>s(null,r));return}if(n(this,Ut).push(s),n(this,Gt))return;g(this,Gt,true);let i=this.fullpath();n(this,re).readdir(i,{withFileTypes:true},(r,a)=>{if(r)m(this,C,ii).call(this,r.code),t.provisional=0;else {for(let o of a)m(this,C,ri).call(this,o,t);m(this,C,si).call(this,t);}m(this,C,wn).call(this,t.slice(0,t.provisional));});}async readdir(){if(!this.canReaddir())return [];let s=this.children();if(this.calledReaddir())return s.slice(0,s.provisional);let e=this.fullpath();if(n(this,xt))await n(this,xt);else {let t=()=>{};g(this,xt,new Promise(i=>t=i));try{for(let i of await n(this,re).promises.readdir(e,{withFileTypes:!0}))m(this,C,ri).call(this,i,s);m(this,C,si).call(this,s);}catch(i){m(this,C,ii).call(this,i.code),s.provisional=0;}g(this,xt,void 0),t();}return s.slice(0,s.provisional)}readdirSync(){if(!this.canReaddir())return [];let s=this.children();if(this.calledReaddir())return s.slice(0,s.provisional);let e=this.fullpath();try{for(let t of n(this,re).readdirSync(e,{withFileTypes:!0}))m(this,C,ri).call(this,t,s);m(this,C,si).call(this,s);}catch(t){m(this,C,ii).call(this,t.code),s.provisional=0;}return s.slice(0,s.provisional)}canReaddir(){if(n(this,R)&hr)return false;let s=ye&n(this,R);return s===we||s===Ae||s===pt}shouldWalk(s,e){return (n(this,R)&Ae)===Ae&&!(n(this,R)&hr)&&!s.has(this)&&(!e||e(this))}async realpath(){if(n(this,De))return n(this,De);if(!((ti|Vs|ve)&n(this,R)))try{let s=await n(this,re).promises.realpath(this.fullpath());return g(this,De,this.resolve(s))}catch{m(this,C,Ii).call(this);}}realpathSync(){if(n(this,De))return n(this,De);if(!((ti|Vs|ve)&n(this,R)))try{let s=n(this,re).realpathSync(this.fullpath());return g(this,De,this.resolve(s))}catch{m(this,C,Ii).call(this);}}[fn](s){if(s===this)return;s.isCWD=false,this.isCWD=true;let e=new Set([]),t=[],i=this;for(;i&&i.parent;)e.add(i),g(i,Ge,t.join(this.sep)),g(i,qe,t.join("/")),i=i.parent,t.push("..");for(i=s;i&&i.parent&&!e.has(i);)g(i,Ge,void 0),g(i,qe,void 0),i=i.parent;}},re=new WeakMap,ms=new WeakMap,ys=new WeakMap,bs=new WeakMap,ws=new WeakMap,Es=new WeakMap,Ss=new WeakMap,xs=new WeakMap,vs=new WeakMap,_s=new WeakMap,Ns=new WeakMap,Ts=new WeakMap,Cs=new WeakMap,Rs=new WeakMap,Fs=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Ls=new WeakMap,Is=new WeakMap,rt=new WeakMap,Et=new WeakMap,ke=new WeakMap,Ue=new WeakMap,Ge=new WeakMap,qe=new WeakMap,R=new WeakMap,St=new WeakMap,He=new WeakMap,De=new WeakMap,C=new WeakSet,Oi=function(s){let e=this;for(let t of s)e=e.child(t);return e},si=function(s){var e;g(this,R,n(this,R)|xi);for(let t=s.provisional;t<s.length;t++){let i=s[t];i&&m(e=i,C,ds).call(e);}},ds=function(){n(this,R)&ve||(g(this,R,(n(this,R)|ve)&ns),m(this,C,Li).call(this));},Li=function(){var e;let s=this.children();s.provisional=0;for(let t of s)m(e=t,C,ds).call(e);},Ii=function(){g(this,R,n(this,R)|ti),m(this,C,us).call(this);},us=function(){if(n(this,R)&ls)return;let s=n(this,R);(s&ye)===Ae&&(s&=ns),g(this,R,s|ls),m(this,C,Li).call(this);},ii=function(s=""){s==="ENOTDIR"||s==="EPERM"?m(this,C,us).call(this):s==="ENOENT"?m(this,C,ds).call(this):this.children().provisional=0;},Ai=function(s=""){var e;s==="ENOTDIR"?m(e=this.parent,C,us).call(e):s==="ENOENT"&&m(this,C,ds).call(this);},Mi=function(s=""){var t;let e=n(this,R);e|=Vs,s==="ENOENT"&&(e|=ve),(s==="EINVAL"||s==="UNKNOWN")&&(e&=ns),g(this,R,e),s==="ENOTDIR"&&this.parent&&m(t=this.parent,C,us).call(t);},ri=function(s,e){return m(this,C,yn).call(this,s,e)||m(this,C,mn).call(this,s,e)},mn=function(s,e){let t=vi(s),i=this.newChild(s.name,t,{parent:this}),r=n(i,R)&ye;return r!==Ae&&r!==pt&&r!==we&&g(i,R,n(i,R)|ls),e.unshift(i),e.provisional++,i},yn=function(s,e){for(let t=e.provisional;t<e.length;t++){let i=e[t];if((this.nocase?Ys(s.name):cs(s.name))===n(i,rt))return m(this,C,bn).call(this,s,i,t,e)}},bn=function(s,e,t,i){let r=e.name;return g(e,R,n(e,R)&ns|vi(s)),r!==s.name&&(e.name=s.name),t!==i.provisional&&(t===i.length-1?i.pop():i.splice(t,1),i.unshift(e)),i.provisional++,e},ki=function(s){let{atime:e,atimeMs:t,birthtime:i,birthtimeMs:r,blksize:a,blocks:o,ctime:h,ctimeMs:l,dev:c,gid:p,ino:d,mode:f,mtime:S,mtimeMs:w,nlink:x,rdev:b,size:y,uid:_}=s;g(this,Ps,e),g(this,Ts,t),g(this,Is,i),g(this,Fs,r),g(this,xs,a),g(this,Ns,o),g(this,Ls,h),g(this,Rs,l),g(this,ms,c),g(this,Es,p),g(this,vs,d),g(this,ys,f),g(this,Os,S),g(this,Cs,w),g(this,bs,x),g(this,Ss,b),g(this,_s,y),g(this,ws,_);let N=vi(s);g(this,R,n(this,R)&ns|N|or),N!==we&&N!==Ae&&N!==pt&&g(this,R,n(this,R)|ls);},Ut=new WeakMap,Gt=new WeakMap,wn=function(s){g(this,Gt,false);let e=n(this,Ut).slice();n(this,Ut).length=0,e.forEach(t=>t(null,s));},xt=new WeakMap,Wr),En=class Sn extends he{constructor(t,i=we,r,a,o,h,l){super(t,i,r,a,o,h,l);u(this,"sep","\\");u(this,"splitSep",Co);}newChild(t,i=we,r={}){return new Sn(t,i,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(t){return Kt.win32.parse(t).root}getRoot(t){if(t=To(t.toUpperCase()),t===this.root.name)return this.root;for(let[i,r]of Object.entries(this.roots))if(this.sameRoot(t,i))return this.roots[t]=r;return this.roots[t]=new $i(t,this).root}sameRoot(t,i=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(ln,"$1\\"),t===i}},xn=class vn extends he{constructor(t,i=we,r,a,o,h,l){super(t,i,r,a,o,h,l);u(this,"splitSep","/");u(this,"sep","/");}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,i=we,r={}){return new vn(t,i,this.root,this.roots,this.nocase,this.childrenCache(),r)}},qt,Ht,As,Ms,zr,_n=(zr=class{constructor(s=process.cwd(),e,t,{nocase:i,childrenCacheSize:r=16*1024,fs:a=hs}={}){u(this,"root");u(this,"rootPath");u(this,"roots");u(this,"cwd");E(this,qt);E(this,Ht);E(this,As);u(this,"nocase");E(this,Ms);g(this,Ms,hn(a)),(s instanceof URL||s.startsWith("file://"))&&(s=url.fileURLToPath(s));let o=e.resolve(s);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),g(this,qt,new dr),g(this,Ht,new dr),g(this,As,new Fo(r));let h=o.substring(this.rootPath.length).split(t);if(h.length===1&&!h[0]&&h.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(n(this,Ms)),this.roots[this.rootPath]=this.root;let l=this.root,c=h.length-1,p=e.sep,d=this.rootPath,f=false;for(let S of h){let w=c--;l=l.child(S,{relative:new Array(w).fill("..").join(p),relativePosix:new Array(w).fill("..").join("/"),fullpath:d+=(f?"":p)+S}),f=true;}this.cwd=l;}depth(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.depth()}childrenCache(){return n(this,As)}resolve(...s){let e="";for(let r=s.length-1;r>=0;r--){let a=s[r];if(!(!a||a===".")&&(e=e?`${a}/${e}`:a,this.isAbsolute(a)))break}let t=n(this,qt).get(e);if(t!==void 0)return t;let i=this.cwd.resolve(e).fullpath();return n(this,qt).set(e,i),i}resolvePosix(...s){let e="";for(let r=s.length-1;r>=0;r--){let a=s[r];if(!(!a||a===".")&&(e=e?`${a}/${e}`:a,this.isAbsolute(a)))break}let t=n(this,Ht).get(e);if(t!==void 0)return t;let i=this.cwd.resolve(e).fullpathPosix();return n(this,Ht).set(e,i),i}relative(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.relative()}relativePosix(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.relativePosix()}basename(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.name}dirname(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),(s.parent||s).fullpath()}async readdir(s=this.cwd,e={withFileTypes:true}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t}=e;if(s.canReaddir()){let i=await s.readdir();return t?i:i.map(r=>r.name)}else return []}readdirSync(s=this.cwd,e={withFileTypes:true}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true}=e;return s.canReaddir()?t?s.readdirSync():s.readdirSync().map(i=>i.name):[]}async lstat(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.lstat()}lstatSync(s=this.cwd){return typeof s=="string"&&(s=this.cwd.resolve(s)),s.lstatSync()}async readlink(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=await s.readlink();return e?t:t?.fullpath()}readlinkSync(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=s.readlinkSync();return e?t:t?.fullpath()}async realpath(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=await s.realpath();return e?t:t?.fullpath()}realpathSync(s=this.cwd,{withFileTypes:e}={withFileTypes:false}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s.withFileTypes,s=this.cwd);let t=s.realpathSync();return e?t:t?.fullpath()}async walk(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=[];(!r||r(s))&&o.push(t?s:s.fullpath());let h=new Set,l=(p,d)=>{h.add(p),p.readdirCB((f,S)=>{if(f)return d(f);let w=S.length;if(!w)return d();let x=()=>{--w===0&&d();};for(let b of S)(!r||r(b))&&o.push(t?b:b.fullpath()),i&&b.isSymbolicLink()?b.realpath().then(y=>y?.isUnknown()?y.lstat():y).then(y=>y?.shouldWalk(h,a)?l(y,x):x()):b.shouldWalk(h,a)?l(b,x):x();},true);},c=s;return new Promise((p,d)=>{l(c,f=>{if(f)return d(f);p(o);});})}walkSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=[];(!r||r(s))&&o.push(t?s:s.fullpath());let h=new Set([s]);for(let l of h){let c=l.readdirSync();for(let p of c){(!r||r(p))&&o.push(t?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(i&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(h,a)&&h.add(d);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(s=this.cwd,e={}){return typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd),this.stream(s,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e;(!r||r(s))&&(yield t?s:s.fullpath());let o=new Set([s]);for(let h of o){let l=h.readdirSync();for(let c of l){(!r||r(c))&&(yield t?c:c.fullpath());let p=c;if(c.isSymbolicLink()){if(!(i&&(p=c.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(o,a)&&o.add(p);}}}stream(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=new oi({objectMode:true});(!r||r(s))&&o.write(t?s:s.fullpath());let h=new Set,l=[s],c=0,p=()=>{let d=false;for(;!d;){let f=l.shift();if(!f){c===0&&o.end();return}c++,h.add(f);let S=(x,b,y=false)=>{if(x)return o.emit("error",x);if(i&&!y){let _=[];for(let N of b)N.isSymbolicLink()&&_.push(N.realpath().then(P=>P?.isUnknown()?P.lstat():P));if(_.length){Promise.all(_).then(()=>S(null,b,true));return}}for(let _ of b)_&&(!r||r(_))&&(o.write(t?_:_.fullpath())||(d=true));c--;for(let _ of b){let N=_.realpathCached()||_;N.shouldWalk(h,a)&&l.push(N);}d&&!o.flowing?o.once("drain",p):w||p();},w=true;f.readdirCB(S,true),w=false;}};return p(),o}streamSync(s=this.cwd,e={}){typeof s=="string"?s=this.cwd.resolve(s):s instanceof he||(e=s,s=this.cwd);let{withFileTypes:t=true,follow:i=false,filter:r,walkFilter:a}=e,o=new oi({objectMode:true}),h=new Set;(!r||r(s))&&o.write(t?s:s.fullpath());let l=[s],c=0,p=()=>{let d=false;for(;!d;){let f=l.shift();if(!f){c===0&&o.end();return}c++,h.add(f);let S=f.readdirSync();for(let w of S)(!r||r(w))&&(o.write(t?w:w.fullpath())||(d=true));c--;for(let w of S){let x=w;if(w.isSymbolicLink()){if(!(i&&(x=w.realpathSync())))continue;x.isUnknown()&&x.lstatSync();}x.shouldWalk(h,a)&&l.push(x);}}d&&!o.flowing&&o.once("drain",p);};return p(),o}chdir(s=this.cwd){let e=this.cwd;this.cwd=typeof s=="string"?this.cwd.resolve(s):s,this.cwd[fn](e);}},qt=new WeakMap,Ht=new WeakMap,As=new WeakMap,Ms=new WeakMap,zr),$i=class extends _n{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,Kt.win32,"\\",{...t,nocase:i});u(this,"sep","\\");this.nocase=i;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase;}parseRootPath(e){return Kt.win32.parse(e).root.toUpperCase()}newRoot(e){return new En(this.rootPath,Ae,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Bi=class extends _n{constructor(e=process.cwd(),t={}){let{nocase:i=false}=t;super(e,Kt.posix,"/",{...t,nocase:i});u(this,"sep","/");this.nocase=i;}parseRootPath(e){return "/"}newRoot(e){return new xn(this.rootPath,Ae,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Nn=class extends Bi{constructor(s=process.cwd(),e={}){let{nocase:t=true}=e;super(s,{...e,nocase:t});}};process.platform==="win32"?En:xn;var Po=process.platform==="win32"?$i:process.platform==="darwin"?Nn:Bi,Oo=s=>s.length>=1,Lo=s=>s.length>=1,Io=Symbol.for("nodejs.util.inspect.custom"),B,le,U,vt,Le,ks,nt,at,ot,Xt,Qt,Tn=(Qt=class{constructor(e,t,i,r){E(this,B);E(this,le);E(this,U);u(this,"length");E(this,vt);E(this,Le);E(this,ks);E(this,nt);E(this,at);E(this,ot);E(this,Xt,true);if(!Oo(e))throw new TypeError("empty pattern list");if(!Lo(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,i<0||i>=this.length)throw new TypeError("index out of range");if(g(this,B,e),g(this,le,t),g(this,U,i),g(this,vt,r),n(this,U)===0){if(this.isUNC()){let[a,o,h,l,...c]=n(this,B),[p,d,f,S,...w]=n(this,le);c[0]===""&&(c.shift(),w.shift());let x=[a,o,h,l,""].join("/"),b=[p,d,f,S,""].join("/");g(this,B,[x,...c]),g(this,le,[b,...w]),this.length=n(this,B).length;}else if(this.isDrive()||this.isAbsolute()){let[a,...o]=n(this,B),[h,...l]=n(this,le);o[0]===""&&(o.shift(),l.shift());let c=a+"/",p=h+"/";g(this,B,[c,...o]),g(this,le,[p,...l]),this.length=n(this,B).length;}}}[Io](){return "Pattern <"+n(this,le).slice(n(this,U)).join("/")+">"}pattern(){return n(this,B)[n(this,U)]}isString(){return typeof n(this,B)[n(this,U)]=="string"}isGlobstar(){return n(this,B)[n(this,U)]===ne}isRegExp(){return n(this,B)[n(this,U)]instanceof RegExp}globString(){return g(this,ks,n(this,ks)||(n(this,U)===0?this.isAbsolute()?n(this,le)[0]+n(this,le).slice(1).join("/"):n(this,le).join("/"):n(this,le).slice(n(this,U)).join("/")))}hasMore(){return this.length>n(this,U)+1}rest(){return n(this,Le)!==void 0?n(this,Le):this.hasMore()?(g(this,Le,new Qt(n(this,B),n(this,le),n(this,U)+1,n(this,vt))),g(n(this,Le),ot,n(this,ot)),g(n(this,Le),at,n(this,at)),g(n(this,Le),nt,n(this,nt)),n(this,Le)):g(this,Le,null)}isUNC(){let e=n(this,B);return n(this,at)!==void 0?n(this,at):g(this,at,n(this,vt)==="win32"&&n(this,U)===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3])}isDrive(){let e=n(this,B);return n(this,nt)!==void 0?n(this,nt):g(this,nt,n(this,vt)==="win32"&&n(this,U)===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]))}isAbsolute(){let e=n(this,B);return n(this,ot)!==void 0?n(this,ot):g(this,ot,e[0]===""&&e.length>1||this.isDrive()||this.isUNC())}root(){let e=n(this,B)[0];return typeof e=="string"&&this.isAbsolute()&&n(this,U)===0?e:""}checkFollowGlobstar(){return !(n(this,U)===0||!this.isGlobstar()||!n(this,Xt))}markFollowGlobstar(){return n(this,U)===0||!this.isGlobstar()||!n(this,Xt)?false:(g(this,Xt,false),true)}},B=new WeakMap,le=new WeakMap,U=new WeakMap,vt=new WeakMap,Le=new WeakMap,ks=new WeakMap,nt=new WeakMap,at=new WeakMap,ot=new WeakMap,Xt=new WeakMap,Qt),Ao=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ur=class{constructor(s,{nobrace:e,nocase:t,noext:i,noglobstar:r,platform:a=Ao}){u(this,"relative");u(this,"relativeChildren");u(this,"absolute");u(this,"absoluteChildren");u(this,"platform");u(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:true,nobrace:e,nocase:t,noext:i,noglobstar:r,optimizationLevel:2,platform:a,nocomment:true,nonegate:true};for(let o of s)this.add(o);}add(s){let e=new lt(s,this.mmopts);for(let t=0;t<e.set.length;t++){let i=e.set[t],r=e.globParts[t];if(!i||!r)throw new Error("invalid pattern object");for(;i[0]==="."&&r[0]===".";)i.shift(),r.shift();let a=new Tn(i,r,0,this.platform),o=new lt(a.globString(),this.mmopts),h=r[r.length-1]==="**",l=a.isAbsolute();l?this.absolute.push(o):this.relative.push(o),h&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(s){let e=s.fullpath(),t=`${e}/`,i=s.relative()||".",r=`${i}/`;for(let a of this.relative)if(a.match(i)||a.match(r))return true;for(let a of this.absolute)if(a.match(e)||a.match(t))return true;return false}childrenIgnored(s){let e=s.fullpath()+"/",t=(s.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(t))return true;for(let i of this.absoluteChildren)if(i.match(e))return true;return false}},Mo=class Cn{constructor(e=new Map){u(this,"store");this.store=e;}copy(){return new Cn(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let i=e.fullpath(),r=this.store.get(i);r?r.add(t.globString()):this.store.set(i,new Set([t.globString()]));}},ko=class{constructor(){u(this,"store",new Map);}add(s,e,t){let i=(e?2:0)|(t?1:0),r=this.store.get(s);this.store.set(s,r===void 0?i:i&r);}entries(){return [...this.store.entries()].map(([s,e])=>[s,!!(e&2),!!(e&1)])}},Do=class{constructor(){u(this,"store",new Map);}add(s,e){if(!s.canReaddir())return;let t=this.store.get(s);t?t.find(i=>i.globString()===e.globString())||t.push(e):this.store.set(s,[e]);}get(s){let e=this.store.get(s);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(s=>[s,this.store.get(s)])}keys(){return [...this.store.keys()].filter(s=>s.canReaddir())}},pr=class Rn{constructor(e,t){u(this,"hasWalkedCache");u(this,"matches",new ko);u(this,"subwalks",new Do);u(this,"patterns");u(this,"follow");u(this,"dot");u(this,"opts");this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Mo;}processPatterns(e,t){this.patterns=t;let i=t.map(r=>[e,r]);for(let[r,a]of i){this.hasWalkedCache.storeWalked(r,a);let o=a.root(),h=a.isAbsolute()&&this.opts.absolute!==false;if(o){r=r.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=a.rest();if(d)a=d;else {this.matches.add(r,true,false);continue}}if(r.isENOENT())continue;let l,c,p=false;for(;typeof(l=a.pattern())=="string"&&(c=a.rest());)r=r.resolve(l),a=c,p=true;if(l=a.pattern(),c=a.rest(),p){if(this.hasWalkedCache.hasWalked(r,a))continue;this.hasWalkedCache.storeWalked(r,a);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(r.resolve(l),h,d);continue}else if(l===ne){(!r.isSymbolicLink()||this.follow||a.checkFollowGlobstar())&&this.subwalks.add(r,a);let d=c?.pattern(),f=c?.rest();if(!c||(d===""||d===".")&&!f)this.matches.add(r,h,d===""||d===".");else if(d===".."){let S=r.parent||r;f?this.hasWalkedCache.hasWalked(S,f)||this.subwalks.add(S,f):this.matches.add(S,h,true);}}else l instanceof RegExp&&this.subwalks.add(r,a);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Rn(this.opts,this.hasWalkedCache)}filterEntries(e,t){let i=this.subwalks.get(e),r=this.child();for(let a of t)for(let o of i){let h=o.isAbsolute(),l=o.pattern(),c=o.rest();l===ne?r.testGlobstar(a,o,c,h):l instanceof RegExp?r.testRegExp(a,l,c,h):r.testString(a,l,c,h);}return r}testGlobstar(e,t,i,r){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,r,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(i&&t.checkFollowGlobstar()?this.subwalks.add(e,i):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),i){let a=i.pattern();if(typeof a=="string"&&a!==".."&&a!==""&&a!==".")this.testString(e,a,i.rest(),r);else if(a===".."){let o=e.parent||e;this.subwalks.add(o,i);}else a instanceof RegExp&&this.testRegExp(e,a,i.rest(),r);}}testRegExp(e,t,i,r){t.test(e.name)&&(i?this.subwalks.add(e,i):this.matches.add(e,r,false));}testString(e,t,i,r){e.isNamed(t)&&(i?this.subwalks.add(e,i):this.matches.add(e,r,false));}},Wo=(s,e)=>typeof s=="string"?new ur([s],e):Array.isArray(s)?new ur(s,e):s,Vt,Xe,_t,Ee,gt,Di,jr,Fn=(jr=class{constructor(s,e,t){E(this,Ee);u(this,"path");u(this,"patterns");u(this,"opts");u(this,"seen",new Set);u(this,"paused",false);u(this,"aborted",false);E(this,Vt,[]);E(this,Xe);E(this,_t);u(this,"signal");u(this,"maxDepth");u(this,"includeChildMatches");if(this.patterns=s,this.path=e,this.opts=t,g(this,_t,!t.posix&&t.platform==="win32"?"\\":"/"),this.includeChildMatches=t.includeChildMatches!==false,(t.ignore||!this.includeChildMatches)&&(g(this,Xe,Wo(t.ignore??[],t)),!this.includeChildMatches&&typeof n(this,Xe).add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=t.maxDepth||1/0,t.signal&&(this.signal=t.signal,this.signal.addEventListener("abort",()=>{n(this,Vt).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let s;for(;!this.paused&&(s=n(this,Vt).shift());)s();}onResume(s){this.signal?.aborted||(this.paused?n(this,Vt).push(s):s());}async matchCheck(s,e){if(e&&this.opts.nodir)return;let t;if(this.opts.realpath){if(t=s.realpathCached()||await s.realpath(),!t)return;s=t;}let i=s.isUnknown()||this.opts.stat?await s.lstat():s;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let r=await i.realpath();r&&(r.isUnknown()||this.opts.stat)&&await r.lstat();}return this.matchCheckTest(i,e)}matchCheckTest(s,e){return s&&(this.maxDepth===1/0||s.depth()<=this.maxDepth)&&(!e||s.canReaddir())&&(!this.opts.nodir||!s.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!s.isSymbolicLink()||!s.realpathCached()?.isDirectory())&&!m(this,Ee,gt).call(this,s)?s:void 0}matchCheckSync(s,e){if(e&&this.opts.nodir)return;let t;if(this.opts.realpath){if(t=s.realpathCached()||s.realpathSync(),!t)return;s=t;}let i=s.isUnknown()||this.opts.stat?s.lstatSync():s;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let r=i.realpathSync();r&&(r?.isUnknown()||this.opts.stat)&&r.lstatSync();}return this.matchCheckTest(i,e)}matchFinish(s,e){if(m(this,Ee,gt).call(this,s))return;if(!this.includeChildMatches&&n(this,Xe)?.add){let r=`${s.relativePosix()}/**`;n(this,Xe).add(r);}let t=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(s);let i=this.opts.mark&&s.isDirectory()?n(this,_t):"";if(this.opts.withFileTypes)this.matchEmit(s);else if(t){let r=this.opts.posix?s.fullpathPosix():s.fullpath();this.matchEmit(r+i);}else {let r=this.opts.posix?s.relativePosix():s.relative(),a=this.opts.dotRelative&&!r.startsWith(".."+n(this,_t))?"."+n(this,_t):"";this.matchEmit(r?a+r+i:"."+i);}}async match(s,e,t){let i=await this.matchCheck(s,t);i&&this.matchFinish(i,e);}matchSync(s,e,t){let i=this.matchCheckSync(s,t);i&&this.matchFinish(i,e);}walkCB(s,e,t){this.signal?.aborted&&t(),this.walkCB2(s,e,new pr(this.opts),t);}walkCB2(s,e,t,i){if(m(this,Ee,Di).call(this,s))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(s,e,t,i));return}t.processPatterns(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,gt).call(this,o)||(r++,this.match(o,h,l).then(()=>a()));for(let o of t.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let h=o.readdirCached();o.calledReaddir()?this.walkCB3(o,h,t,a):o.readdirCB((l,c)=>this.walkCB3(o,c,t,a),true);}a();}walkCB3(s,e,t,i){t=t.filterEntries(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,gt).call(this,o)||(r++,this.match(o,h,l).then(()=>a()));for(let[o,h]of t.subwalks.entries())r++,this.walkCB2(o,h,t.child(),a);a();}walkCBSync(s,e,t){this.signal?.aborted&&t(),this.walkCB2Sync(s,e,new pr(this.opts),t);}walkCB2Sync(s,e,t,i){if(m(this,Ee,Di).call(this,s))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(s,e,t,i));return}t.processPatterns(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,gt).call(this,o)||this.matchSync(o,h,l);for(let o of t.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let h=o.readdirSync();this.walkCB3Sync(o,h,t,a);}a();}walkCB3Sync(s,e,t,i){t=t.filterEntries(s,e);let r=1,a=()=>{--r===0&&i();};for(let[o,h,l]of t.matches.entries())m(this,Ee,gt).call(this,o)||this.matchSync(o,h,l);for(let[o,h]of t.subwalks.entries())r++,this.walkCB2Sync(o,h,t.child(),a);a();}},Vt=new WeakMap,Xe=new WeakMap,_t=new WeakMap,Ee=new WeakSet,gt=function(s){return this.seen.has(s)||!!n(this,Xe)?.ignored?.(s)},Di=function(s){return !!n(this,Xe)?.childrenIgnored?.(s)},jr),gr=class extends Fn{constructor(e,t,i){super(e,t,i);u(this,"matches",new Set);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(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}},fr=class extends Fn{constructor(e,t,i){super(e,t,i);u(this,"results");this.results=new oi({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(e){this.results.write(e),this.results.flowing||this.pause();}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end());}):this.walkCB(e,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}},zo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Tt=class{constructor(s,e){u(this,"absolute");u(this,"cwd");u(this,"root");u(this,"dot");u(this,"dotRelative");u(this,"follow");u(this,"ignore");u(this,"magicalBraces");u(this,"mark");u(this,"matchBase");u(this,"maxDepth");u(this,"nobrace");u(this,"nocase");u(this,"nodir");u(this,"noext");u(this,"noglobstar");u(this,"pattern");u(this,"platform");u(this,"realpath");u(this,"scurry");u(this,"stat");u(this,"signal");u(this,"windowsPathsNoEscape");u(this,"withFileTypes");u(this,"includeChildMatches");u(this,"opts");u(this,"patterns");if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=url.fileURLToPath(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==false,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof s=="string"&&(s=[s]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===false,this.windowsPathsNoEscape&&(s=s.map(h=>h.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");s=s.map(h=>h.includes("/")?h:`./**/${h}`);}if(this.pattern=s,this.platform=e.platform||zo,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let h=e.platform==="win32"?$i:e.platform==="darwin"?Nn:e.platform?Bi:Po;this.scurry=new h(this.cwd,{nocase:e.nocase,fs:e.fs});}this.nocase=this.scurry.nocase;let t=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:t,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(h=>new lt(h,i)),[a,o]=r.reduce((h,l)=>(h[0].push(...l.set),h[1].push(...l.globParts),h),[[],[]]);this.patterns=a.map((h,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Tn(h,c,0,this.platform)});}async walk(){return [...await new gr(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 gr(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 fr(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 fr(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()}},jo=(s,e={})=>{Array.isArray(s)||(s=[s]);for(let t of s)if(new lt(t,e).hasMagic())return true;return false};function ci(s,e={}){return new Tt(s,e).streamSync()}function Pn(s,e={}){return new Tt(s,e).stream()}function On(s,e={}){return new Tt(s,e).walkSync()}async function mr(s,e={}){return new Tt(s,e).walk()}function di(s,e={}){return new Tt(s,e).iterateSync()}function Ln(s,e={}){return new Tt(s,e).iterate()}var $o=ci,Bo=Object.assign(Pn,{sync:ci}),Uo=di,Go=Object.assign(Ln,{sync:di}),qo=Object.assign(On,{stream:ci,iterate:di}),hi=Object.assign(mr,{glob:mr,globSync:On,sync:qo,globStream:Pn,stream:Bo,globStreamSync:ci,streamSync:$o,globIterate:Ln,iterate:Go,globIterateSync:di,iterateSync:Uo,Glob:Tt,hasMagic:jo,escape:Yr,unescape:kt});hi.glob=hi;var Qe;(P=>{P.Level=Xo__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let e={DEBUG:0,INFO:1,WARN:2,ERROR:3},t="INFO";function i(T){return e[T]>=e[t]}function r(){return t}P.getLevel=r;let a=new Map;P.Default=N({service:"default"});let h="";function l(){return h}P.file=l;let c,p,d=false,f=()=>{},S=false;async function w(T){if(d)return;if(T.print){d=true;return}T.level&&(t=T.level);let O=T.logDir||Kt__default.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");T.logFile?h=Kt__default.default.join(O,T.logFile??"codebase.log"):h=Kt__default.default.join(O,"codebase.log");try{await Gi__default.default.mkdir(O,{recursive:!0}),c=await Gi__default.default.open(h,"a"),p=In.createWriteStream("",{fd:c.fd,autoClose:!1}),f=k=>{if(!(S||!p||p.destroyed))try{if(!p.writable)return;p.write(k,J=>{J&&!S&&(S=!0,setTimeout(()=>{S=!1;},1e3));});}catch{S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},d=!0;}catch{f=k=>{try{process.stderr.write(k);}catch{}},d=true;}}P.init=w;async function x(){d&&(p&&!p.destroyed&&(await new Promise((T,O)=>{p.end(k=>{k?O(k):T();});}).catch(()=>{}),p=void 0),c&&(await c.close().catch(()=>{}),c=void 0),f=T=>{try{process.stderr.write(T);}catch{}},d=false);}P.close=x;function y(T,O=0){let k=T.message;return T.cause instanceof Error&&O<10?k+" Caused by: "+y(T.cause,O+1):k}let _=Date.now();function N(T){T=T||{};let O=T.service;if(O&&typeof O=="string"){let M=a.get(O);if(M)return M}function k(M,G){let pi=Object.entries({...T,...G}).filter(([Hi,Ve])=>Ve!=null).map(([Hi,Ve])=>{let gi=`${Hi}=`;return Ve instanceof Error?gi+y(Ve):typeof Ve=="object"?gi+JSON.stringify(Ve):gi+Ve}).join(" "),Se=new Date,qn=Se.getTime()-_;return _=Se.getTime(),[Se.getFullYear()+"-"+String(Se.getMonth()+1).padStart(2,"0")+"-"+String(Se.getDate()).padStart(2,"0")+"T"+String(Se.getHours()).padStart(2,"0")+":"+String(Se.getMinutes()).padStart(2,"0")+":"+String(Se.getSeconds()).padStart(2,"0"),"+"+qn+"ms",pi,M].filter(Boolean).join(" ")+`
4
- `}let J={debug(M,G){i("DEBUG")&&f("DEBUG "+k(M,G));},info(M,G){i("INFO")&&f("INFO "+k(M,G));},error(M,G){i("ERROR")&&f("ERROR "+k(M,G));},warn(M,G){i("WARN")&&f("WARN "+k(M,G));},tag(M,G){return T&&(T[M]=G),J},clone(){return P.create({...T})},time(M,G){let pi=Date.now();J.info(M,{status:"started",...G});function Se(){J.info(M,{status:"completed",duration:Date.now()-pi,...G});}return {stop:Se,[Symbol.dispose](){Se();}}}};return O&&typeof O=="string"&&a.set(O,J),J}P.create=N;})(Qe||(Qe={}));var ct=utils.Filesystem.toUnixPath,Ds=Qe.create({service:"codebase-database"}),Yt=class{constructor(e){u(this,"db");u(this,"dbPath");u(this,"closed",false);u(this,"ftsAvailable",false);this.dbPath=utils.Filesystem.toUnixPath(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=Kt__default.default.dirname(this.dbPath);In__namespace.default.existsSync(e)||In__namespace.default.mkdirSync(e,{recursive:true});let t=new Vo__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
1
+ 'use strict';var chunkQ66UAC5Z_cjs=require('./chunks/chunk-Q66UAC5Z.cjs'),$=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),ne=require('fs'),ye=require('better-sqlite3'),utils=require('@easbot/utils'),url=require('url'),Ie=require('fs/promises'),crypto=require('crypto'),Ce=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var $__default=/*#__PURE__*/_interopDefault($);var ne__default=/*#__PURE__*/_interopDefault(ne);var ye__default=/*#__PURE__*/_interopDefault(ye);var Ie__default=/*#__PURE__*/_interopDefault(Ie);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var re={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var A=class h extends Error{constructor(t,r,s){super(t);chunkQ66UAC5Z_cjs.a(this,"name","ParserError");chunkQ66UAC5Z_cjs.a(this,"filePath");chunkQ66UAC5Z_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},C=class h extends Error{constructor(t,r,s){super(t);chunkQ66UAC5Z_cjs.a(this,"name","DatabaseError");chunkQ66UAC5Z_cjs.a(this,"operation");chunkQ66UAC5Z_cjs.a(this,"cause");this.operation=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},j=class h extends Error{constructor(t,r,s){super(t);chunkQ66UAC5Z_cjs.a(this,"name","FileSystemError");chunkQ66UAC5Z_cjs.a(this,"filePath");chunkQ66UAC5Z_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},X=class h extends Error{constructor(t,r){super(t);chunkQ66UAC5Z_cjs.a(this,"name","SchemaError");chunkQ66UAC5Z_cjs.a(this,"missing");this.missing=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},q=class h extends Error{constructor(t,r){super(t);chunkQ66UAC5Z_cjs.a(this,"name","ConfigError");chunkQ66UAC5Z_cjs.a(this,"field");this.field=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Q=class h extends Error{constructor(t,r,s){super(t);chunkQ66UAC5Z_cjs.a(this,"name","IndexError");chunkQ66UAC5Z_cjs.a(this,"filePath");chunkQ66UAC5Z_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},H=class h extends Error{constructor(t,r,s){super(t);chunkQ66UAC5Z_cjs.a(this,"name","QueryError");chunkQ66UAC5Z_cjs.a(this,"params");chunkQ66UAC5Z_cjs.a(this,"cause");this.params=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},G=class h extends Error{constructor(t,r){super(`Unsupported language: ${t}`);chunkQ66UAC5Z_cjs.a(this,"name","UnsupportedLanguageError");chunkQ66UAC5Z_cjs.a(this,"extension");chunkQ66UAC5Z_cjs.a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,h.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var v=utils.Filesystem.toUnixPath,D=chunkQ66UAC5Z_cjs.c.create({service:"codebase-database"}),k=class{constructor(e){chunkQ66UAC5Z_cjs.a(this,"db");chunkQ66UAC5Z_cjs.a(this,"dbPath");chunkQ66UAC5Z_cjs.a(this,"closed",false);chunkQ66UAC5Z_cjs.a(this,"ftsAvailable",false);this.dbPath=utils.Filesystem.toUnixPath(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=$__default.default.dirname(this.dbPath);ne__default.default.existsSync(e)||ne__default.default.mkdirSync(e,{recursive:true});let t=new ye__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
5
2
  CREATE TABLE IF NOT EXISTS nodes (
6
3
  id TEXT PRIMARY KEY,
7
4
  name TEXT NOT NULL,
@@ -58,19 +55,19 @@ globstar while`,s,d,e,f,S),this.matchOne(s.slice(d),e.slice(f),t))return this.de
58
55
  embedding BLOB NOT NULL,
59
56
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
60
57
  )
61
- `);}catch(t){throw new js("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:ct(e.file_path)};this.db.prepare(`
58
+ `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of t)r.run(s,n);}catch(t){throw new X("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:v(e.file_path)};this.db.prepare(`
62
59
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
63
60
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(a=>({...a,file_path:ct(a.file_path)})),i=this.db.prepare(`
61
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:v(n.file_path)})),r=this.db.prepare(`
65
62
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
66
63
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
67
- `);this.db.transaction(a=>{for(let o of a)i.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.start_line,o.start_col,o.end_line,o.end_col,o.text,o.created_at);})(t),this.ftsAvailable&&this.updateFtsNodes(t);}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){Ds.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),i=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(o=>{for(let h of o)try{let l=i.get(h.id);l&&t.run(l.rowid),r.run(h.id,h.name,h.ast_type,h.language,h.file_path,h.text);}catch(l){Ds.warn("FTS update failed for node",{nodeId:h.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
64
+ `);this.db.transaction(n=>{for(let i of n)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let i=r.get(n.id);i&&t.run(i.rowid),s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){D.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){D.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),s.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){D.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
68
65
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
69
66
  VALUES (?, ?, ?, ?, ?)
70
67
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
71
68
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
72
69
  VALUES (?, ?, ?, ?, ?)
73
- `);this.db.transaction(r=>{for(let a of r)t.run(a.id,a.source,a.target,a.relation,a.created_at);})(e);}queryNodes(e){let t=[],i=[];e.filePath&&(t.push("file_path LIKE ?"),i.push(`%${ct(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),i.push(e.astType)),e.name&&(t.push("name LIKE ?"),i.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),i.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",i.push(e.limit)),e.offset&&(r+=" OFFSET ?",i.push(e.offset));try{return this.db.prepare(r).all(...i)}catch(a){throw new dt("Failed to query nodes","queryNodes",a instanceof Error?a:new Error(String(a)))}}queryEdges(e){let t=[],i=[];e.source&&(t.push("source = ?"),i.push(e.source)),e.target&&(t.push("target = ?"),i.push(e.target)),e.relation&&(t.push("relation = ?"),i.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",i.push(e.limit)),e.offset&&(r+=" OFFSET ?",i.push(e.offset));try{return this.db.prepare(r).all(...i)}catch(a){throw new dt("Failed to query edges","queryEdges",a instanceof Error?a:new Error(String(a)))}}queryAll(e,t){try{let i=this.db.prepare(e);return t?i.all(...t):i.all()}catch(i){throw new dt("Failed to execute query","queryAll",i instanceof Error?i:new Error(String(i)))}}searchNodesFts(e,t=20){if(!this.ftsAvailable)return [];try{let i=e.split(/\s+/).map(o=>`${o}*`).join(" ");return this.db.prepare(`
70
+ `);this.db.transaction(s=>{for(let n of s)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${v(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let s="SELECT * FROM nodes";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY file_path, start_line",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new C("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let s="SELECT * FROM edges";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY created_at DESC",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new C("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new C("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(!this.ftsAvailable)return [];try{let r=e.split(/\s+/).map(i=>`${i}*`).join(" ");return this.db.prepare(`
74
71
  SELECT
75
72
  f.id,
76
73
  f.name,
@@ -88,24 +85,24 @@ globstar while`,s,d,e,f,S),this.matchOne(s.slice(d),e.slice(f),t))return this.de
88
85
  WHERE nodes_fts MATCH ?
89
86
  ORDER BY score DESC
90
87
  LIMIT ?
91
- `).all(i,t)}catch{return []}}deleteNodesByFile(e){let t=ct(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let a of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(a.rowid);}catch(r){Ds.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=ct(e);return this.db.prepare(`
88
+ `).all(r,t)}catch{return []}}deleteNodesByFile(e){let t=v(e);if(this.ftsAvailable)try{let s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of s)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(s){D.warn("FTS delete failed for file",{filePath:t,error:String(s)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=v(e);return this.db.prepare(`
92
89
  DELETE FROM edges
93
90
  WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
94
91
  OR target IN (SELECT id FROM nodes WHERE file_path = ?)
95
- `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(ct(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
92
+ `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(v(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
96
93
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
97
- VALUES (?, ?, datetime('now'))
98
- `).run(ct(e),t);}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(ct(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),i=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),r=this.db.prepare("SELECT value FROM meta WHERE key = 'lastSync'").get();return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:i?.c??0,dbPath:this.dbPath,workspaceDir:"",lastSync:r?.value??null}}setLastSync(){this.db.prepare(`
94
+ VALUES (?, ?, ?)
95
+ `).run(v(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(v(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),s=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let i of s)n[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:n}}setLastSync(){this.db.prepare(`
99
96
  INSERT OR REPLACE INTO meta (key, value)
100
- VALUES ('lastSync', datetime('now'))
101
- `).run();}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let i=this.db.prepare(`
97
+ VALUES ('lastSync', ?)
98
+ `).run(new Date().toISOString());}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let r=this.db.prepare(`
102
99
  SELECT embedding FROM embedding_cache WHERE content_hash = ?
103
- `).get(e);return i?new Float32Array(i.embedding.buffer,i.embedding.byteOffset,i.embedding.length/4):null}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.db.prepare(`
100
+ `).get(e);return r?new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
104
101
  INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
105
102
  VALUES (?, ?)
106
- `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;let t=this.db.prepare(`
103
+ `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
107
104
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
108
105
  VALUES (?, ?, ?)
109
- `);this.db.transaction(r=>{for(let a of r)try{t.run(a.nodeId,a.embeddingText,a.embedding);}catch(o){Ds.warn("Failed to store embedding for node",{nodeId:a.nodeId,error:String(o)});}})(e);}initialize(){if(this.closed)throw new dt("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){Ds.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}};var Mn=Qe.create({service:"codebase-parser"}),Jo={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function Zo(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&oe?Kt__default.default.dirname(url.fileURLToPath(oe)):typeof __dirname<"u"?__dirname:process.cwd()}function eh(s,e){let t=Zo(),i=t;for(let r=0;r<10;r++){let a=Kt__default.default.join(i,"node_modules",s,e);if(utils.Filesystem.stat(a)!==void 0)return a;let o=Kt__default.default.dirname(i);if(o===i)break;i=o;}return Kt__default.default.join(t,"node_modules",s,e)}var Rt=class{constructor(){u(this,"parsers",new Map);u(this,"initialized",false);u(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,i=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof i!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof i}`);let r=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],a=await Promise.allSettled(r.map(async o=>{try{let h=Jo[o];if(!h)return Mn.warn("No WASM config for language",{lang:o}),null;let l=eh(h.package,h.wasmFile),c=await i.load(l),p=new t;return p.setLanguage(c),{lang:o,parser:p,language:c}}catch(h){return Mn.warn("Failed to load parser",{lang:o,error:String(h)}),null}}));for(let o of a)if(o.status==="fulfilled"&&o.value){let{lang:h,parser:l,language:c}=o.value;this.parsers.set(h,{parser:l,language:c});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=Kt__default.default.extname(e).toLowerCase();return Qi[t]??null}parse(e,t){if(!this.initialized)throw new It("Parser not initialized","");let i=this.parsers.get(t);if(!i)throw new It(`No parser available for language: ${t}`,"");try{return i.parser.parse(e)}catch(r){throw new It("Failed to parse code","",r instanceof Error?r:new Error(String(r)))}}parseFile(e,t){let i=this.detectLanguage(e);if(!i)throw new Bs(Kt__default.default.extname(e),e);return this.parse(t,i)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let i of t)e[i]=this.parsers.has(i);return e}dispose(){this.parsers.clear(),this.initialized=false;}},Ct=null;async function kn(){return Ct||(Ct=new Rt,await Ct.initialize()),Ct}function Dn(){Ct&&(Ct.dispose(),Ct=null);}var th={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},sh=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),Ft=class{extractNodes(e,t,i,r){let a=[],o=t.split(`
110
- `);return this.walkTree(e.rootNode,a,i,r,o),a}walkTree(e,t,i,r,a,o){if(sh.has(e.type)){let h=this.extractNode(e,i,r,a,o);h&&(t.push(h),o=h.name?this.generateNodeId(h):o);}for(let h=0;h<e.childCount;h++){let l=e.children[h];l&&this.walkTree(l,t,i,r,a,o);}}extractNode(e,t,i,r,a){let o=this.getNodeName(e);if(!o)return null;let h=e.startPosition,l=e.endPosition,c=this.getNodeText(e,r);return {name:o,ast_type:this.normalizeAstType(e.type),language:t,file_path:i,start_line:h.row,start_col:h.column,end_line:l.row,end_col:l.column,text:c,parent_id:a}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let i of t){let r=e.childForFieldName?.(i);if(r?.text)return r.text}for(let i of e.children)if(i.type==="identifier"||i.type==="type_identifier"||i.type==="property_identifier"||i.type==="field_identifier"||i.type==="name")return i.text;return null}findNameInGrandchildren(e,t,i){for(let r of e.children)if(t.includes(r.type)){let a=this.findNameInChildren(r,i);if(a)return a}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let i=t.text;return (i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1,-1)),i}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,i]of Object.entries(th))if(i.includes(e))return t;return e}getNodeText(e,t){let i=e.startPosition.row,r=e.endPosition.row;return i===r?t[i]?.trim()??"":t.slice(i,r+1).join(`
111
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function Wn(){return new Ft}var Pt=class{extractEdges(e,t,i,r){let a=[],o=new Map;for(let h of t){let l=this.generateNodeId(h);o.set(l,h);}return this.extractContainsEdges(t,a),this.extractCallEdges(e.rootNode,t,a,i,r,o),this.extractInheritanceEdges(e.rootNode,t,a,i,r,o),this.extractImportEdges(e.rootNode,t,a,i,r),a}extractContainsEdges(e,t){for(let i of e)i.parent_id&&t.push({source:i.parent_id,target:this.generateNodeId(i),relation:"CONTAINS"});}extractCallEdges(e,t,i,r,a,o){let h=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,l=>{if(h.includes(l.type)){let c=this.findEnclosingFunction(l,t),p=this.extractCalleeName(l);if(c&&p){let d=`${r}:${a}:function_declaration:${p}`;i.push({source:c.id,target:d,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,i,r,a,o){let h=["class_declaration","class_definition","class_specifier"];this.walkTree(e,l=>{if(h.includes(l.type)){let c=this.findNameInChildren(l);if(!c)return;let p=`${r}:${a}:class_declaration:${c}`,d=this.findDescendantByType(l,["class_heritage","extends_clause","superclass"]);if(d){let w=this.findChildByType(d,["extends_clause","superclass"])??d,x=this.extractIdentifier(w);if(x&&x!==c){let b=`${r}:${a}:class_declaration:${x}`;i.push({source:p,target:b,relation:"INHERITS_FROM"});}}let f=this.findDescendantByType(l,["implements_clause","interface_list","implements"]);if(f){let S=this.extractIdentifiers(f);for(let w of S){let x=`${r}:${a}:interface_declaration:${w}`;i.push({source:p,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,i,r,a){let o=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,h=>{if(o.includes(h.type)){let l=this.extractImportPath(h);if(l){let c=`${r}:${a}:module:file`;i.push({source:c,target:l,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let i of e.children)this.walkTree(i,t);}findEnclosingFunction(e,t){let i=e;for(;i;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(i.type)){let a=this.findNameInChildren(i);if(a){let o=t.find(d=>d.name===a);if(o)return {id:this.generateNodeId(o),name:a};i.startPosition;let l=t[0],c=l?.language??"ts",p=l?.file_path??"";return {id:`${c}:${p}:function_declaration:${a}`,name:a}}}i=i.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let i=t.childForFieldName?.("property");if(i)return i.text;let r=t.children[t.children.length-1];if(r)return r.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let i of e.children)if(t.includes(i.type))return i;return null}findDescendantByType(e,t){for(let i of e.children){if(t.includes(i.type))return i;if(!["class_declaration","class_definition"].includes(i.type)){let a=this.findDescendantByType(i,t);if(a)return a}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let i of e.children)(i.type==="identifier"||i.type==="type_identifier")&&t.push(i.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let i=t.text;return (i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1,-1)),i}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function zn(){return new Pt}var Ot=class{constructor(e,t,i){u(this,"db");u(this,"parserManager");u(this,"nodeExtractor");u(this,"edgeExtractor");u(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new Ft,this.edgeExtractor=new Pt,this.config=i;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),i=this.db.getCachedEmbedding?.(t);if(i)return new Float32Array(i.buffer,i.byteOffset,i.length/4);let a=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(a){let o=new Float32Array(a);return this.db.cacheEmbedding?.(t,o),o}return null}catch{return null}}async indexFile(e,t){let i=Date.now(),r=[],a=0,o=0;try{let h=this.parserManager.detectLanguage(e);if(!h)throw new $s("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let l=await this.readFile(e),c=this.computeHash(l);if(this.config.incremental&&this.db.getFileHash(e)===c)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-i};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let p=this.parserManager.parse(l,h),d=this.nodeExtractor.extractNodes(p,l,h,e);a=d.length;let f=this.edgeExtractor.extractEdges(p,d,h,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(d);let S=this.getValidEdgeCount(f,d);this.storeEdges(f,d),o=S,this.config.embedding&&d.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(d)),this.db.setFileHash(e,c),p.delete();}catch(h){let l=h instanceof Error?h.message:String(h);r.push({filePath:e,error:l});}return {success:r.length===0,filesProcessed:1,nodesCreated:a,edgesCreated:o,errors:r,duration:Date.now()-i}}async indexDirectory(e,t){let i=Date.now(),r=e??this.config.workspaceDir,a=[],o=0,h=0,l=0;try{let c=await this.scanFiles(r),p=c.length;for(let d=0;d<c.length;d+=this.config.batchSize){let f=c.slice(d,d+this.config.batchSize);for(let S of f){let w=await this.indexFile(S.filePath,t);o++,h+=w.nodesCreated,l+=w.edgesCreated,!w.success&&w.errors.length>0&&a.push(...w.errors);}}}catch(c){let p=c instanceof Error?c.message:String(c);a.push({filePath:r,error:p});}return this.db.setLastSync(),{success:a.length===0,filesProcessed:o,nodesCreated:h,edgesCreated:l,errors:a,duration:Date.now()-i}}async sync(e){let t=Date.now(),i=[],r=0,a=0,o=0,h=0,l=0,c=0;try{let p=await this.scanFiles(this.config.workspaceDir),d=new Set(p.map(w=>w.filePath)),f=this.db.getAllFileHashes(),S=new Set(f.map(w=>w.file_path));for(let w of f)d.has(w.file_path)||(this.db.deleteNodesByFile(w.file_path),this.db.deleteEdgesByFile(w.file_path),this.db.deleteFileHash(w.file_path),o++);for(let w of p){let x=this.db.getFileHash(w.filePath);if(x)if(x!==w.contentHash){let b=await this.indexFile(w.filePath,e);b.success?(a++,l+=b.nodesCreated,c+=b.edgesCreated):i.push(...b.errors);}else h++;else {let b=await this.indexFile(w.filePath,e);b.success?(r++,l+=b.nodesCreated,c+=b.edgesCreated):i.push(...b.errors);}}}catch(p){let d=p instanceof Error?p.message:String(p);i.push({filePath:this.config.workspaceDir,error:d});}return this.db.setLastSync(),{success:i.length===0,filesAdded:r,filesUpdated:a,filesDeleted:o,filesSkipped:h,nodesCreated:l,edgesCreated:c,errors:i,duration:Date.now()-t}}async scanFiles(e){let t=[],r=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(p=>`**/*${p}`),a=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],o=this.config.ignorePatterns.map(p=>p.includes("/")||p.includes("*")?p:`**/${p}/**`),h=[...a,...o],l=e.replace(/\\/g,"/"),c=await ah__default.default(r,{cwd:l,absolute:true,ignore:h,onlyFiles:true});for(let p of c){let d=utils.Filesystem.toUnixPath(Kt__default.default.normalize(p)),f=this.parserManager.detectLanguage(d);if(f)try{let S=await this.readFile(d),w=this.computeHash(S);t.push({filePath:d,language:f,contentHash:w,content:S});}catch{}}return t}async readFile(e){try{return await Gi__default.default.readFile(e,"utf-8")}catch(t){throw new zs("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(i=>({id:this.nodeExtractor.generateNodeId(i),name:i.name,ast_type:i.ast_type,language:i.language,file_path:i.file_path,start_line:i.start_line,start_col:i.start_col,end_line:i.end_line,end_col:i.end_col,text:i.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let i=new Set(t.map(a=>this.nodeExtractor.generateNodeId(a))),r=e.filter(a=>i.has(a.source)&&i.has(a.target)).map((a,o)=>({id:`${a.source}:${a.relation}:${a.target}:${o}`,source:a.source,target:a.target,relation:a.relation,created_at:new Date().toISOString()}));r.length>0&&this.db.insertEdges(r);}getValidEdgeCount(e,t){let i=new Set(t.map(r=>this.nodeExtractor.generateNodeId(r)));return e.filter(r=>i.has(r.source)&&i.has(r.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,i=this.chunkArray(e,t),r=[];for(let a of i){let o=a.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:o});for(let l=0;l<a.length;l++){let c=a[l];if(!c)continue;let p=h.embeddings[l];if(p){let d=new Float32Array(p),f=this.computeHash(this.generateNodeEmbeddingText(c));this.db.cacheEmbedding?.(f,d),r.push({nodeId:this.nodeExtractor.generateNodeId(c),embeddingText:o[l]||"",embedding:d});}}}catch{for(let l of a){if(!l)continue;let c=this.generateNodeEmbeddingText(l),p=await this.embedText(c);p&&r.push({nodeId:this.nodeExtractor.generateNodeId(l),embeddingText:c,embedding:p});}}}r.length>0&&this.db.storeNodeEmbeddings?.(r);}chunkArray(e,t){let i=[];for(let r=0;r<e.length;r+=t)i.push(e.slice(r,r+t));return i}};function jn(s,e,t){return new Ot(s,e,t)}var $n=utils.Filesystem.toUnixPath,Lt=class{constructor(e,t){u(this,"db");u(this,"embedding");this.db=e,this.embedding=t;}async search(e,t={}){let{maxResults:i=20,minScore:r=.1,language:a,filePath:o,astType:h,enableFts:l=true,includeEdges:c=true,edgesLimit:p=100,vectorWeight:d=.7,textWeight:f=.3}=t,S=[];if(this.embedding){let b=await this.vectorSearchNodes(e,i*2,r);for(let y of b)S.push({...y,source:"vector",vectorScore:y.score,hybridScore:y.score*d});}if(l&&this.db.isFtsAvailable()){let b=this.db.searchNodesFts(e,i*2);for(let y of b){if(a&&y.language!==a||o&&!y.file_path.includes($n(o))||h&&y.ast_type!==h)continue;let _=this.normalizeScore(y.score),N=S.find(P=>P.id===y.id);N?(N.ftsScore=_,N.hybridScore=N.vectorScore*d+_*f):S.push({id:y.id,name:y.name,astType:y.ast_type,language:y.language,filePath:y.file_path,text:y.text,snippet:y.text.slice(0,200),startLine:y.start_line,startCol:y.start_col,endLine:y.end_line,endCol:y.end_col,score:_,source:"fts",ftsScore:_,hybridScore:_*f});}}if(!l||!this.db.isFtsAvailable()||S.length===0)try{let b=this.db.queryNodes({limit:i,astType:h,language:a,filePath:o}),y=new Set(S.map(_=>_.id));for(let _ of b){if(y.has(_.id)||o&&!_.file_path.includes($n(o)))continue;let N=_.name.toLowerCase().includes(e.toLowerCase()),P=_.text.toLowerCase().includes(e.toLowerCase());if(N||P){let T=N?.9:.5;S.push({id:_.id,name:_.name,astType:_.ast_type,language:_.language,filePath:_.file_path,text:_.text,snippet:_.text.slice(0,200),startLine:_.start_line,startCol:_.start_col,endLine:_.end_line,endCol:_.end_col,score:T,source:"basic",hybridScore:T});}}}catch{}let x=S.filter(b=>b.hybridScore>=r).sort((b,y)=>y.hybridScore-b.hybridScore).slice(0,i).map(b=>({id:b.id,name:b.name,ast_type:b.astType,language:b.language,file_path:b.filePath,start_line:b.startLine,start_col:b.startCol,end_line:b.endLine,end_col:b.endCol,text:b.text,created_at:new Date().toISOString()}));if(c&&x.length>0){let b=x.map(N=>N.id),y=this.db.queryEdges({sourceOrTarget:b}),_=new Map;for(let N of y)N.source!==N.target&&(_.has(N.source)||_.set(N.source,[]),_.get(N.source).push(N));return x.map(N=>{let P=_.get(N.id)||[];return {...N,edges:P.slice(0,p)}})}return x.map(b=>({...b,edges:[]}))}async vectorSearchNodes(e,t,i,r){if(!this.embedding)return [];let a=await this.embedText(e);if(!a)return [];let o=new Float32Array(a),h;if(r&&r.length>0){let f=r.map(()=>"?").join(",");h=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${f})`,r);}else h=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);let l=[];for(let f of h){let S=new Float32Array(f.embedding.buffer,f.embedding.byteOffset,f.embedding.length/4),w=this.cosineSimilarity(o,S);w>=i&&l.push({nodeId:f.node_id,score:w});}l.sort((f,S)=>S.score-f.score);let c=l.slice(0,t).map(f=>f.nodeId),p=this.db.queryNodes({ids:c}),d=new Map(l.slice(0,t).map(f=>[f.nodeId,f.score]));return p.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text??"",snippet:(f.text??"").slice(0,200),startLine:f.start_line??0,startCol:f.start_col??0,endLine:f.end_line??0,endCol:f.end_col??0,score:d.get(f.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let i=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:i}}async embedText(e){if(!this.embedding)return null;try{let i=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return i?new Float32Array(i):null}catch{return null}}cosineSimilarity(e,t){let i=0,r=0,a=0;for(let o=0;o<e.length;o++){let h=e[o],l=t[o];i+=h*l,r+=h*h,a+=l*l;}return r===0||a===0?0:i/(Math.sqrt(r)*Math.sqrt(a))}structuralSearch(e,t){let i=[],r=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let a of r){let o=this.calculateNameSimilarity(e,a.name);i.push({id:a.id,name:a.name,astType:a.ast_type,language:a.language,filePath:a.file_path,text:a.text??"",snippet:(a.text??"").slice(0,200),startLine:a.start_line??0,startCol:a.start_col??0,endLine:a.end_line??0,endCol:a.end_col??0,score:o,source:"structural"});}return i}calculateNameSimilarity(e,t){let i=e.toLowerCase(),r=t.toLowerCase();if(i===r)return 1;if(r.startsWith(i))return .9;if(r.includes(i))return .7;let a=new Set(i.split("")),o=new Set(r.split("")),h=0;for(let l of a)o.has(l)&&h++;return h/a.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new Zt("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new Zt("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),i=[];for(let r of t){let a=this.db.getNodeById(r.source),o=this.db.getNodeById(r.target);a&&o&&i.push({edge:r,sourceNode:a,targetNode:o});}return i}queryNeighbors(e,t={}){let{relationTypes:i,direction:r="both",limit:a=100}=t,o=[],h=[],l=new Set;if(r==="outgoing"||r==="both"){let c=this.db.queryEdges({source:e,relation:i?.[0],limit:a});for(let p of c){if(i&&!i.includes(p.relation))continue;o.push(p);let d=this.db.getNodeById(p.target);d&&!l.has(d.id)&&(h.push(d),l.add(d.id));}}if(r==="incoming"||r==="both"){let c=this.db.queryEdges({target:e,relation:i?.[0],limit:a});for(let p of c){if(i&&!i.includes(p.relation))continue;o.push(p);let d=this.db.getNodeById(p.source);d&&!l.has(d.id)&&(h.push(d),l.add(d.id));}}return {nodes:h.slice(0,a),edges:o.slice(0,a)}}queryCallGraph(e,t=2){let i=new Map,r=new Set,a=(o,h)=>{if(h>t||r.has(o))return;r.add(o);let l=[],c=[],p=this.db.queryEdges({target:o,relation:"CALLS"});for(let f of p)l.push(f.source),a(f.source,h+1);let d=this.db.queryEdges({source:o,relation:"CALLS"});for(let f of d)c.push(f.target),a(f.target,h+1);i.set(o,{callers:l,callees:c});};return a(e,0),i}queryInheritance(e){let t=[],i=[],r=new Set,a=new Set,o=l=>{if(r.has(l))return;r.add(l);let c=this.db.queryEdges({source:l,relation:"INHERITS_FROM"}),p=this.db.queryEdges({source:l,relation:"IMPLEMENTS"});for(let d of [...c,...p]){let f=this.db.getNodeById(d.target);f&&(t.push(f),o(d.target));}},h=l=>{if(a.has(l))return;a.add(l);let c=this.db.queryEdges({target:l,relation:"INHERITS_FROM"}),p=this.db.queryEdges({target:l,relation:"IMPLEMENTS"});for(let d of [...c,...p]){let f=this.db.getNodeById(d.source);f&&(i.push(f),h(d.source));}};return o(e),h(e),{ancestors:t,descendants:i}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Bn(s){return new Lt(s)}var ph=Qe.create({service:"codebase"}),gh={database:{path:types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true}},ui=class{constructor(e={}){u(this,"config");u(this,"db");u(this,"parserManager");u(this,"indexer");u(this,"queryInterface");u(this,"initialized",false);this.config={...gh,...e};let t=e.workspaceDir??process.cwd(),i=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:i,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let r=this.resolveDbPath();this.db=new Yt(r),this.parserManager=new Rt;let a={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new Ot(this.db,this.parserManager,a),this.queryInterface=new Lt(this.db,this.config.embeddingLlm);}async initialize(){this.initialized||(this.db.initialize(),await Qe.init({logDir:this.config.logDir||Kt__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),await this.parserManager.initialize(),this.initialized=true);}validateConfig(){if(!this.config.workspaceDir)throw new Jt("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new Jt("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Kt__default.default.isAbsolute(e)?e:Kt__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){return await this.ensureInitialized(),this.indexer.sync(e)}async search(e,t){return await this.ensureInitialized(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){return {...this.db.getStatus(),workspaceDir:this.config.workspaceDir}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.db.close(),this.parserManager.dispose(),this.initialized=false,ph.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function fh(s){let e=new ui(s);return await e.initialize(),e}exports.CodeBase=ui;exports.ConfigError=Jt;exports.DatabaseError=dt;exports.DatabaseManager=Yt;exports.EdgeExtractor=Pt;exports.FILE_EXTENSION_MAP=Qi;exports.FileSystemError=zs;exports.IndexError=$s;exports.Indexer=Ot;exports.NodeExtractor=Ft;exports.ParserError=It;exports.ParserManager=Rt;exports.QueryError=Zt;exports.QueryInterface=Lt;exports.SchemaError=js;exports.UnsupportedLanguageError=Bs;exports.createCodebase=fh;exports.createEdgeExtractor=zn;exports.createIndexer=jn;exports.createNodeExtractor=Wn;exports.createQueryInterface=Bn;exports.getParserManager=kn;exports.resetParserManager=Dn;
106
+ `);this.db.transaction(s=>{for(let n of s)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){D.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new C("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){D.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ie=chunkQ66UAC5Z_cjs.c.create({service:"codebase-parser"}),_e={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function xe(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&chunkQ66UAC5Z_cjs.b?$__default.default.dirname(url.fileURLToPath(chunkQ66UAC5Z_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function Ne(h,e){let t=xe(),r=t;for(let s=0;s<10;s++){let n=$__default.default.join(r,"node_modules",h,e);if(utils.Filesystem.stat(n)!==void 0)return n;let i=$__default.default.dirname(r);if(i===r)break;r=i;}return $__default.default.join(t,"node_modules",h,e)}var F=class{constructor(){chunkQ66UAC5Z_cjs.a(this,"parsers",new Map);chunkQ66UAC5Z_cjs.a(this,"initialized",false);chunkQ66UAC5Z_cjs.a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let s=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],n=await Promise.allSettled(s.map(async i=>{try{let o=_e[i];if(!o)return ie.warn("No WASM config for language",{lang:i}),null;let a=Ne(o.package,o.wasmFile),d=await r.load(a),l=new t;return l.setLanguage(d),{lang:i,parser:l,language:d}}catch(o){return ie.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of n)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=$__default.default.extname(e).toLowerCase();return re[t]??null}parse(e,t){if(!this.initialized)throw new A("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new A(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(s){throw new A("Failed to parse code","",s instanceof Error?s:new Error(String(s)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new G($__default.default.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},R=null;async function ae(){return R||(R=new F,await R.initialize()),R}function oe(){R&&(R.dispose(),R=null);}var Se={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Te=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),P=class{extractNodes(e,t,r,s){let n=[],i=t.split(`
107
+ `);return this.walkTree(e.rootNode,n,r,s,i),n}walkTree(e,t,r,s,n,i){if(Te.has(e.type)){let o=this.extractNode(e,r,s,n,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,s,n,i);}}extractNode(e,t,r,s,n){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,s);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:n}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let s=e.childForFieldName?.(r);if(s?.text)return s.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let s of e.children)if(t.includes(s.type)){let n=this.findNameInChildren(s,r);if(n)return n}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Se))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,s=e.endPosition.row;return r===s?t[r]?.trim()??"":t.slice(r,s+1).join(`
108
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function de(){return new P}var L=class{extractEdges(e,t,r,s){let n=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,n),this.extractCallEdges(e.rootNode,t,n,r,s,i),this.extractInheritanceEdges(e.rootNode,t,n,r,s,i),this.extractImportEdges(e.rootNode,t,n,r,s),this.extractTypeReferences(e.rootNode,t,n,r,s,i),this.extractParameterEdges(e.rootNode,t,n,r,s,i),this.extractDefinesEdges(t,n,r,s,i),this.extractAnnotationEdges(e.rootNode,t,n,r,s),n}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,s,n,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),l=this.extractCalleeName(a);if(d&&l){let g=`${s}:${n}:function_declaration:${l}`;r.push({source:d.id,target:g,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,s,n,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=`${s}:${n}:class_declaration:${d}`,g=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(g){let u=this.findChildByType(g,["extends_clause","superclass"])??g,_=this.extractIdentifier(u);if(_&&_!==d){let x=`${s}:${n}:class_declaration:${_}`;r.push({source:l,target:x,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let u of m){let _=`${s}:${n}:interface_declaration:${u}`;r.push({source:l,target:_,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,s,n){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${s}:${n}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let n=this.findNameInChildren(r);if(n){let i=t.find(g=>g.name===n);if(i)return {id:this.generateNodeId(i),name:n};r.startPosition;let a=t[0],d=a?.language??"ts",l=a?.file_path??"";return {id:`${d}:${l}:function_declaration:${n}`,name:n}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let s=t.children[t.children.length-1];if(s)return s.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let n=this.findDescendantByType(r,t);if(n)return n}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,s,n,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let g=this.findNameInChildren(d);if(!g)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let u=this.extractTypeName(c);if(u&&u!=="void"&&u!=="any"&&u!=="null"){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let u=this.extractTypeName(m);if(u){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let g of d.children)if(g.type==="type_annotation"||g.type==="annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findEnclosingFunction(d,t);u&&r.push({source:u.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let g of d.children)if(g.type==="type_annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findNameInChildren(d);u&&r.push({source:this.generateNodeIdFromName(u,"variable_declaration",s,n),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,s,n,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=this.generateNodeIdFromName(d,a.type,s,n),g=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of g)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let u=this.findNameInChildren(m);if(u&&u!=="self"&&u!=="this"){let _=`${s}:${n}:parameter:${d}:${u}`;r.push({source:l,target:_,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,s,n){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let l of e)if(l.file_path===a.file_path&&o.includes(l.ast_type)&&l.start_line>=a.start_line&&l.end_line<=a.end_line){let g=this.generateNodeId(l);d!==g&&t.push({source:d,target:g,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,s,n){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let l=a.parent;for(;l;){if(o.includes(l.type)){let g=this.findNameInChildren(l);if(g){let c=this.generateNodeIdFromName(g,l.type,s,n),m=`${s}:${n}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}l=l.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let s=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let n of s)return `${t}:${r}:${n}:${e}`;return null}generateNodeIdFromName(e,t,r,s){return `${r}:${s}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let s of e.children)t.includes(s.type)&&r.push(s);return r}};function ce(){return new L}var O=class{constructor(e,t,r){chunkQ66UAC5Z_cjs.a(this,"db");chunkQ66UAC5Z_cjs.a(this,"parserManager");chunkQ66UAC5Z_cjs.a(this,"nodeExtractor");chunkQ66UAC5Z_cjs.a(this,"edgeExtractor");chunkQ66UAC5Z_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new P,this.edgeExtractor=new L,this.config=r;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let i=new Float32Array(n);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),s=[],n=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Q("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let l=this.parserManager.parse(a,o),g=this.nodeExtractor.extractNodes(l,a,o,e);n=g.length;let c=this.edgeExtractor.extractEdges(l,g,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(g);let m=this.getValidEdgeCount(c,g);this.storeEdges(c,g),i=m,this.config.embedding&&g.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(g)),this.db.setFileHash(e,d),l.delete();}catch(o){let a=o instanceof Error?o.message:String(o);s.push({filePath:e,error:a});}return {success:s.length===0,filesProcessed:1,nodesCreated:n,edgesCreated:i,errors:s,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),s=e??this.config.workspaceDir,n=[],i=0,o=0,a=0;try{let d=await this.scanFiles(s),l=d.length;for(let g=0;g<d.length;g+=this.config.batchSize){let c=d.slice(g,g+this.config.batchSize);for(let m of c){let u=await this.indexFile(m.filePath,t);i++,o+=u.nodesCreated,a+=u.edgesCreated,!u.success&&u.errors.length>0&&n.push(...u.errors);}}}catch(d){let l=d instanceof Error?d.message:String(d);n.push({filePath:s,error:l});}return this.db.setLastSync(),{success:n.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:n,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],s=0,n=0,i=0,o=0,a=0,d=0;try{let l=await this.scanFiles(this.config.workspaceDir),g=new Set(l.map(u=>u.filePath)),c=this.db.getAllFileHashes(),m=new Set(c.map(u=>u.file_path));for(let u of c)g.has(u.file_path)||(this.db.deleteNodesByFile(u.file_path),this.db.deleteEdgesByFile(u.file_path),this.db.deleteFileHash(u.file_path),i++);for(let u of l){let _=this.db.getFileHash(u.filePath);if(_)if(_!==u.contentHash){let x=await this.indexFile(u.filePath,e);x.success?(n++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}else o++;else {let x=await this.indexFile(u.filePath,e);x.success?(s++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}}}catch(l){let g=l instanceof Error?l.message:String(l);r.push({filePath:this.config.workspaceDir,error:g});}return this.db.setLastSync(),{success:r.length===0,filesAdded:s,filesUpdated:n,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:Date.now()-t}}async scanFiles(e){let t=[],s=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(l=>`**/*${l}`),n=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(l=>l.includes("/")||l.includes("*")?l:`**/${l}/**`),o=[...n,...i],a=e.replace(/\\/g,"/"),d=await Ce__default.default(s,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let l of d){let g=utils.Filesystem.toUnixPath($__default.default.normalize(l)),c=this.parserManager.detectLanguage(g);if(c)try{let m=await this.readFile(g),u=this.computeHash(m);t.push({filePath:g,language:c,contentHash:u,content:m});}catch{}}return t}async readFile(e){try{return await Ie__default.default.readFile(e,"utf-8")}catch(t){throw new j("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n))),s=e.filter(n=>r.has(n.source)&&r.has(n.target)).map((n,i)=>({id:`${n.source}:${n.relation}:${n.target}:${i}`,source:n.source,target:n.target,relation:n.relation,created_at:new Date().toISOString()}));s.length>0&&this.db.insertEdges(s);}getValidEdgeCount(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s)));return e.filter(s=>r.has(s.source)&&r.has(s.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),s=[];for(let n of r){let i=n.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let l=o.embeddings[a];if(l){let g=new Float32Array(l),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,g),s.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:g});}}}catch{for(let a of n){if(!a)continue;let d=this.generateNodeEmbeddingText(a),l=await this.embedText(d);l&&s.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:l});}}}s.length>0&&this.db.storeNodeEmbeddings?.(s);}chunkArray(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}};function le(h,e,t){return new O(h,e,t)}var ge=utils.Filesystem.toUnixPath,M=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkQ66UAC5Z_cjs.a(this,"db");chunkQ66UAC5Z_cjs.a(this,"embedding");chunkQ66UAC5Z_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:s=this.config.minScore,language:n,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:l=100,vectorWeight:g=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t,u=[];if(m&&this.embedding){let y=await this.vectorSearchNodes(e,r*2,s);for(let f of y)u.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*g});}if(a&&this.db.isFtsAvailable()){let y=this.db.searchNodesFts(e,r*2);for(let f of y){if(n&&f.language!==n||i&&!f.file_path.includes(ge(i))||o&&f.ast_type!==o)continue;let N=this.normalizeScore(f.score),E=u.find(w=>w.id===f.id);E?(E.ftsScore=N,E.hybridScore=E.vectorScore*g+N*c):u.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:N,source:"fts",ftsScore:N,hybridScore:N*c});}}if(!a||!this.db.isFtsAvailable()||u.length===0)try{let y=this.db.queryNodes({limit:r*2,astType:o,language:n,filePath:i}),f=new Set(u.map(b=>b.id)),N=e.toLowerCase(),E=N.split(/\s+/).filter(b=>b.length>0),w=[];for(let b of y){if(f.has(b.id)||i&&!b.file_path.includes(ge(i)))continue;let z=b.name.toLowerCase(),B=b.text.toLowerCase(),ee=0;if(E.some(T=>z.includes(T))){let T=0;for(let U of E){let J=new RegExp(U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),W=z.match(J);T+=W?W.length:0;}ee=.8*Math.min(T/E.length,1);}let Y=0;if(E.some(T=>B.includes(T))){let T=0;for(let W of E){let me=new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),te=B.match(me);T+=te?te.length:0;}Y=.5*Math.min(T/E.length,1);let U=B.indexOf(N),J=U===-1?0:Math.max(0,1-U/B.length)*.2;Y+=J;}let K=Math.max(ee,Y);K>0&&w.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:K,source:"basic",hybridScore:K});}w.sort((b,z)=>z.score-b.score),u.push(...w.slice(0,r));}catch{}let x=u.filter(y=>y.hybridScore>=s).sort((y,f)=>f.hybridScore-y.hybridScore).slice(0,r).map(y=>({id:y.id,name:y.name,ast_type:y.astType,language:y.language,file_path:y.filePath,start_line:y.startLine,start_col:y.startCol,end_line:y.endLine,end_col:y.endCol,text:y.text,created_at:new Date().toISOString()}));if(d&&x.length>0){let y=x.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:y}),N=new Map;for(let E of f)E.source!==E.target&&(N.has(E.source)||N.set(E.source,[]),N.get(E.source).push(E));return x.map(E=>{let w=N.get(E.id)||[];return {...E,edges:w.slice(0,l)}})}return x.map(y=>({...y,edges:[]}))}async vectorSearchNodes(e,t,r,s){if(!this.embedding)return [];let n=await this.embedText(e);if(!n)return [];let i=new Float32Array(n),o;if(s&&s.length>0){let c=s.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,s);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),u=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:u});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId),l=this.db.queryNodes({ids:d}),g=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return l.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:g.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,s=0,n=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,s+=o*o,n+=a*a;}return s===0||n===0?0:r/(Math.sqrt(s)*Math.sqrt(n))}structuralSearch(e,t){let r=[],s=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let n of s){let i=this.calculateNameSimilarity(e,n.name);r.push({id:n.id,name:n.name,astType:n.ast_type,language:n.language,filePath:n.file_path,text:n.text??"",snippet:(n.text??"").slice(0,200),startLine:n.start_line??0,startCol:n.start_col??0,endLine:n.end_line??0,endCol:n.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),s=t.toLowerCase();if(r===s)return 1;if(s.startsWith(r))return .9;if(s.includes(r))return .7;let n=new Set(r.split("")),i=new Set(s.split("")),o=0;for(let a of n)i.has(a)&&o++;return o/n.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new H("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new H("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let s of t){let n=this.db.getNodeById(s.source),i=this.db.getNodeById(s.target);n&&i&&r.push({edge:s,sourceNode:n,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:s="both",limit:n=100}=t,i=[],o=[],a=new Set;if(s==="outgoing"||s==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.target);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}if(s==="incoming"||s==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.source);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}return {nodes:o.slice(0,n),edges:i.slice(0,n)}}queryCallGraph(e,t=2){let r=new Map,s=new Set,n=(i,o)=>{if(o>t||s.has(i))return;s.add(i);let a=[],d=[],l=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of l)a.push(c.source),n(c.source,o+1);let g=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of g)d.push(c.target),n(c.target,o+1);r.set(i,{callers:a,callees:d});};return n(e,0),r}queryInheritance(e){let t=[],r=[],s=new Set,n=new Set,i=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.target);c&&(t.push(c),i(g.target));}},o=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.source);c&&(r.push(c),o(g.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function ue(h){return new M(h)}var De=chunkQ66UAC5Z_cjs.c.create({service:"codebase"}),ke={database:{path:types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:types.DEFAULT_SYNC_CONFIG},V=class{constructor(e={}){chunkQ66UAC5Z_cjs.a(this,"config");chunkQ66UAC5Z_cjs.a(this,"db");chunkQ66UAC5Z_cjs.a(this,"parserManager");chunkQ66UAC5Z_cjs.a(this,"indexer");chunkQ66UAC5Z_cjs.a(this,"queryInterface");chunkQ66UAC5Z_cjs.a(this,"initialized",false);chunkQ66UAC5Z_cjs.a(this,"dirty",false);chunkQ66UAC5Z_cjs.a(this,"syncTimer");chunkQ66UAC5Z_cjs.a(this,"syncingInProgress",false);chunkQ66UAC5Z_cjs.a(this,"log",chunkQ66UAC5Z_cjs.c.create({service:"codebase"}));this.config={...ke,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let s=this.resolveDbPath();this.db=new k(s),this.parserManager=new F;let n={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new O(this.db,this.parserManager,n),this.queryInterface=new M(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunkQ66UAC5Z_cjs.c.init({logDir:this.config.logDir||$__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>De.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true);}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){this.log.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{this.log.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{this.log.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new q("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new q("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return $__default.default.isAbsolute(e)?e:$__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return this.log.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{return await this.indexer.sync(e)}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,this.log.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(h){let e=new V(h);return await e.initialize(),e}async function tr(h){let{Log:e}=await import('./chunks/log-GDUMUNYJ.cjs'),t=false;await e.init({logDir:h.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:h.print??false,dev:h.dev??t,level:h.level??("INFO")});}exports.CodeBase=V;exports.ConfigError=q;exports.DatabaseError=C;exports.DatabaseManager=k;exports.EdgeExtractor=L;exports.FILE_EXTENSION_MAP=re;exports.FileSystemError=j;exports.IndexError=Q;exports.Indexer=O;exports.NodeExtractor=P;exports.ParserError=A;exports.ParserManager=F;exports.QueryError=H;exports.QueryInterface=M;exports.SchemaError=X;exports.UnsupportedLanguageError=G;exports.createCodebase=$e;exports.createEdgeExtractor=ce;exports.createIndexer=le;exports.createNodeExtractor=de;exports.createQueryInterface=ue;exports.getParserManager=ae;exports.initLog=tr;exports.resetParserManager=oe;