mirror of
https://github.com/thedotmack/claude-mem.git
synced 2026-07-03 12:32:32 +08:00
29 lines
146 KiB
JavaScript
Executable File
29 lines
146 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
"use strict";var mn=Object.create;var Ur=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var Sn=Object.getOwnPropertyNames;var En=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var yn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Sn(e))!wn.call(t,i)&&i!==r&&Ur(t,i,{get:()=>e[i],enumerable:!(s=gn(e,i))||s.enumerable});return t};var te=(t,e,r)=>(r=t!=null?mn(En(t)):{},yn(e||!t||!t.__esModule?Ur(r,"default",{value:t,enumerable:!0}):r,t));var se=require("fs"),tr=require("os"),Ne=require("path");var _=require("path"),er=require("os"),Le=require("fs");var $r=require("url");var re=require("fs"),Wr=require("path");var _n=null;function qt(t){return(_n??process.stderr.write.bind(process.stderr))(t)}var tt=null;function Vt(t){qt(t)}function Fr(t,e={}){tt&&tt.length>0&&(qt(tt.join("")),tt=[]),qt(t.endsWith(`
|
|
`)?t:`${t}
|
|
`),e.skipExit||process.exit(2)}var Qt=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(Qt||{}),Zt=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=k.logsDir();(0,re.existsSync)(e)||(0,re.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Wr.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=k.settings();if((0,re.existsSync)(e)){let r=(0,re.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Qt[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(e,r,s,i,n){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=Qt[e].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
|
|
${n.message}
|
|
${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{u=`
|
|
`+JSON.stringify(n,null,2)}catch{u=" "+this.formatData(n)}else u=" "+this.formatData(n);let h="";if(i){let{sessionId:f,memorySessionId:m,correlationId:g,...w}=i;Object.keys(w).length>0&&(h=` {${Object.entries(w).map(([E,y])=>`${E}=${y}`).join(", ")}}`)}let p=`[${o}] [${a}] [${l}] ${c}${s}${h}${u}`;if(this.logFilePath)try{(0,re.appendFileSync)(this.logFilePath,p+`
|
|
`,"utf8")}catch(f){Vt(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
|
|
`)}else Vt(p+`
|
|
`)}debug(e,r,s,i){this.log(0,e,r,s,i)}info(e,r,s,i){this.log(1,e,r,s,i)}warn(e,r,s,i){this.log(2,e,r,s,i)}error(e,r,s,i){this.log(3,e,r,s,i)}dataIn(e,r,s,i){this.info(e,`\u2192 ${r}`,s,i)}dataOut(e,r,s,i){this.info(e,`\u2190 ${r}`,s,i)}success(e,r,s,i){this.info(e,`\u2713 ${r}`,s,i)}failure(e,r,s,i){this.error(e,`\u2717 ${r}`,s,i)}timing(e,r,s,i){this.info(e,`\u23F1 ${r}`,i,{duration:`${s}ms`})}happyPathError(e,r,s,i,n=""){let c=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,h,i),n}},d=new Zt;var On={};function bn(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,$r.fileURLToPath)(On.url))}var xl=bn();function rt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,_.join)((0,er.homedir)(),".claude-mem"),e=(0,_.join)(t,"settings.json");try{if((0,Le.existsSync)(e)){let r=JSON.parse((0,Le.readFileSync)(e,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var v=rt(),st=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,er.homedir)(),".claude"),it=(0,_.join)(st,"plugins","marketplaces","thedotmack"),vn=(0,_.join)(v,"archives"),Tn=(0,_.join)(v,"logs"),Mn=(0,_.join)(v,"trash"),Cn=(0,_.join)(v,"backups"),An=(0,_.join)(v,"modes"),nt=(0,_.join)(v,"settings.json"),Ll=(0,_.join)(v,"claude-mem.db"),Rn=(0,_.join)(v,"vector-db"),ot=(0,_.join)(v,"observer-sessions"),kn=(0,_.basename)(ot),Nl=(0,_.join)(st,"settings.json"),Ul=(0,_.join)(st,"commands"),Fl=(0,_.join)(st,"CLAUDE.md");var k={dataDir:()=>v,workerPid:()=>(0,_.join)(v,"worker.pid"),serverBetaPid:()=>(0,_.join)(v,".server-beta.pid"),serverBetaPort:()=>(0,_.join)(v,".server-beta.port"),serverBetaRuntime:()=>(0,_.join)(v,".server-beta.runtime.json"),settings:()=>(0,_.join)(v,"settings.json"),database:()=>(0,_.join)(v,"claude-mem.db"),chroma:()=>(0,_.join)(v,"chroma"),combinedCerts:()=>(0,_.join)(v,"combined_certs.pem"),transcriptsConfig:()=>(0,_.join)(v,"transcript-watch.json"),transcriptsState:()=>(0,_.join)(v,"transcript-watch-state.json"),corpora:()=>(0,_.join)(v,"corpora"),supervisorRegistry:()=>(0,_.join)(v,"supervisor.json"),envFile:()=>(0,_.join)(v,".env"),logsDir:()=>Tn,archives:()=>vn,trash:()=>Mn,backups:()=>Cn,modes:()=>An,vectorDb:()=>Rn,observerSessions:()=>ot};var Ae=k.transcriptsConfig(),at=k.transcriptsState();var In={version:1,schemas:{},watches:[],stateFile:at};function Dn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,Ne.join)((0,tr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function Hr(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&Dn(t)}function N(t){return t&&(t.startsWith("~")?(0,Ne.join)((0,tr.homedir)(),t.slice(1)):t)}function Ue(t=Ae){let e=N(t);if(!(0,se.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,se.readFileSync)(e,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${e}`);return s.stateFile||(s.stateFile=at),s}function lt(t=Ae){let e=N(t),r=(0,Ne.dirname)(e);(0,se.existsSync)(r)||(0,se.mkdirSync)(r,{recursive:!0}),(0,se.writeFileSync)(e,JSON.stringify(In,null,2))}var x=require("fs"),z=require("path");var vs=require("node:url"),Ie=require("node:path"),Rs=require("node:url"),q=require("fs"),Wo=te(require("node:fs"),1),fe=require("node:fs/promises"),vt=require("node:events"),pr=te(require("node:stream"),1),ks=require("node:string_decoder"),hs=(t,e,r)=>{let s=t instanceof RegExp?jr(t,r):t,i=e instanceof RegExp?jr(e,r):e,n=s!==null&&i!=null&&Pn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},jr=(t,e)=>{let r=e.match(t);return r?r[0]:null},Pn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},ds="\0SLASH"+Math.random()+"\0",ps="\0OPEN"+Math.random()+"\0",hr="\0CLOSE"+Math.random()+"\0",fs="\0COMMA"+Math.random()+"\0",ms="\0PERIOD"+Math.random()+"\0",xn=new RegExp(ds,"g"),Ln=new RegExp(ps,"g"),Nn=new RegExp(hr,"g"),Un=new RegExp(fs,"g"),Fn=new RegExp(ms,"g"),Wn=/\\\\/g,$n=/\\{/g,Hn=/\\}/g,jn=/\\,/g,Bn=/\\./g,Gn=1e5;function rr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Kn(t){return t.replace(Wn,ds).replace($n,ps).replace(Hn,hr).replace(jn,fs).replace(Bn,ms)}function Yn(t){return t.replace(xn,"\\").replace(Ln,"{").replace(Nn,"}").replace(Un,",").replace(Fn,".")}function gs(t){if(!t)return[""];let e=[],r=hs("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=gs(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function zn(t,e={}){if(!t)return[];let{max:r=Gn}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Ge(Kn(t),r,!0).map(Yn)}function Jn(t){return"{"+t+"}"}function Xn(t){return/^-?0\d/.test(t)}function qn(t,e){return t<=e}function Vn(t,e){return t>=e}function Ge(t,e,r){let s=[],i=hs("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?Ge(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+hr+i.post,Ge(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=gs(i.body),h.length===1&&h[0]!==void 0&&(h=Ge(h[0],e,!1).map(Jn),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=rr(h[0]),m=rr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(rr(h[2])):1,S=qn;m<f&&(w*=-1,S=Vn);let E=h.some(Xn);p=[];for(let y=f;S(y,m);y+=w){let b;if(l)b=String.fromCharCode(y),b==="\\"&&(b="");else if(b=String(y),E){let T=g-b.length;if(T>0){let ue=new Array(T+1).join("0");y<0?b="-"+ue+b.slice(1):b=ue+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Ge(h[f],e,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<e;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var wt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},Qn={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Fe=t=>t.replace(/[[\]\\-]/g,"\\$&"),Zn=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Br=t=>t.join(""),eo=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(Qn))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Fe(h)+"-"+Fe(m)):m===h&&s.push(Fe(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Fe(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Fe(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[Zn(m),!1,u-r,!1]}let p="["+(c?"^":"")+Br(s)+"]",f="["+(c?"":"^")+Br(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},Oe=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),to=new Set(["!","?","+","*","@"]),Gr=t=>to.has(t),ro="(?!(?:^|/)\\.\\.?(?:$|/))",ct="(?!\\.)",so=new Set(["[","."]),io=new Set(["..","."]),no=new Set("().*{}+?[]^$\\!"),oo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),dr="[^/]",Kr=dr+"*?",Yr=dr+"+?",Ss=class F{type;#e;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(e,r,s={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#S=this.#e===this?[]:this.#e.#S,e==="!"&&!this.#e.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#d=this.#i.map(e=>String(e)).join("")}#l(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#S.pop();){if(e.type!=="!")continue;let r=e,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of e.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let e=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let e=this.#o;for(let r=0;r<this.#y;r++){let s=e.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#i.length:0;return this.#y===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new F(this.type,e);for(let s of this.#i)r.copyIn(s);return r}static#s(e,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<e.length;){let g=e.charAt(f++);if(n||g==="\\"){n=!n,m+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(f===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=f,l=!1,m+=g;continue}if(!i.noext&&Gr(g)&&e.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(e,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new F(null,r),h=[],p="";for(;c<e.length;){let f=e.charAt(c++);if(n||f==="\\"){n=!n,p+=f;continue}if(o){c===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(c===a+2&&l)&&(o=!1),p+=f;continue}else if(f==="["){o=!0,a=c,l=!1,p+=f;continue}if(Gr(f)&&e.charAt(c)==="("){u.push(p),p="";let m=new F(f,u);u.push(m),c=F.#s(e,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[e.substring(s-1)],c}static fromGlob(e,r={}){let s=new F(null,void 0,r);return F.#s(e,s,0,r),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#e===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?F.#_(p,this.#r,l):p.toRegExpSource(e);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&io.has(this.#i[0]))){let p=so,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?ro:m?ct:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,Oe(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,Oe(this.toString()),!1,!1]}let o=!s||e||r||!ct?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?ct:"")+Yr;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?ct:"")+Kr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Oe(n),this.#r=!!this.#r,this.#n]}#p(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(e);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(e,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(i){i=!1,n+=(no.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?Yr:Kr,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=eo(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=dr,r=!0;continue}n+=oo(c)}return[n,Oe(e),!!r,o]}},Es=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),P=(t,e,r={})=>(wt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new pe(e,r).match(t)),ao=/^\*+([^+@!?\*\[\(]*)$/,lo=t=>e=>!e.startsWith(".")&&e.endsWith(t),co=t=>e=>e.endsWith(t),uo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),ho=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),po=/^\*+\.\*+$/,fo=t=>!t.startsWith(".")&&t.includes("."),mo=t=>t!=="."&&t!==".."&&t.includes("."),go=/^\.\*+$/,So=t=>t!=="."&&t!==".."&&t.startsWith("."),Eo=/^\*+$/,wo=t=>t.length!==0&&!t.startsWith("."),yo=t=>t.length!==0&&t!=="."&&t!=="..",_o=/^\?+([^+@!?\*\[\(]*)?$/,bo=([t,e=""])=>{let r=ws([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},vo=([t,e=""])=>{let r=ys([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},To=([t,e=""])=>{let r=ys([t]);return e?s=>r(s)&&s.endsWith(e):r},Mo=([t,e=""])=>{let r=ws([t]);return e?s=>r(s)&&s.endsWith(e):r},ws=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},ys=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},_s=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",zr={win32:{sep:"\\"},posix:{sep:"/"}},Co=_s==="win32"?zr.win32.sep:zr.posix.sep;P.sep=Co;var D=Symbol("globstar **");P.GLOBSTAR=D;var Ao="[^/]",Ro=Ao+"*?",ko="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Oo="(?:(?!(?:\\/|^)\\.).)*?",Io=(t,e={})=>r=>P(r,t,e);P.filter=Io;var $=(t,e={})=>Object.assign({},t,e),Do=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return P;let e=P;return Object.assign((r,s,i={})=>e(r,s,$(t,i)),{Minimatch:class extends e.Minimatch{constructor(r,s={}){super(r,$(t,s))}static defaults(r){return e.defaults($(t,r)).Minimatch}},AST:class extends e.AST{constructor(r,s,i={}){super(r,s,$(t,i))}static fromGlob(r,s={}){return e.AST.fromGlob(r,$(t,s))}},unescape:(r,s={})=>e.unescape(r,$(t,s)),escape:(r,s={})=>e.escape(r,$(t,s)),filter:(r,s={})=>e.filter(r,$(t,s)),defaults:r=>e.defaults($(t,r)),makeRe:(r,s={})=>e.makeRe(r,$(t,s)),braceExpand:(r,s={})=>e.braceExpand(r,$(t,s)),match:(r,s,i={})=>e.match(r,s,$(t,i)),sep:e.sep,GLOBSTAR:D})};P.defaults=Do;var bs=(t,e={})=>(wt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:zn(t,{max:e.braceExpandMax}));P.braceExpand=bs;var Po=(t,e={})=>new pe(t,e).makeRe();P.makeRe=Po;var xo=(t,e,r={})=>{let s=new pe(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};P.match=xo;var Jr=/[?*]|[+@!]\(.*?\)|\[|\]/,Lo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){wt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||_s,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,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!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!Jr.test(i[2]))&&!Jr.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r=0;r<t.length;r++)for(let s=0;s<t[r].length;s++)t[r][s]==="**"&&(t[r][s]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let r=-1;for(;(r=e.indexOf("**",r+1))!==-1;){let s=r;for(;e[s+1]==="**";)s++;s!==r&&e.splice(r,s-r)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){let i=t[s];s===1&&i===""&&t[0]===""||(i==="."||i==="")&&(e=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let s=t[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(e=!0,t.splice(r-1,2),r-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let r of t){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",t.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(e=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(e=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){e=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++){let s=this.partsMatch(t[e],t[r],!this.preserveMultipleSlashes);if(s){t[e]=[],t[r]=s;break}}return t.filter(e=>e.length)}partsMatch(t,e,r=!1){let s=0,i=0,n=[],o="";for(;s<t.length&&i<e.length;)if(t[s]===e[i])n.push(o==="b"?e[i]:t[s]),s++,i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="b")return!1;o="a",n.push(t[s]),s++,i++}else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="a")return!1;o="b",n.push(e[i]),s++,i++}else return!1;return t.length===e.length&&n}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,r=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)e=!e,r++;r&&(this.pattern=t.slice(r)),this.negate=e}matchOne(t,e,r=!1){let s=this.options;if(this.isWindows){let m=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),g=!m&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),w=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!w&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=g?3:m?0:void 0,y=S?3:w?0:void 0;if(typeof E=="number"&&typeof y=="number"){let[b,T]=[t[E],e[y]];b.toLowerCase()===T.toLowerCase()&&(e[y]=b,y>E?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var n=0,o=0,a=t.length,l=e.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=e[o],u=t[n];if(this.debug(e,c,u),c===!1)return!1;if(c===D){this.debug("GLOBSTAR",[e,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(t[n]==="."||t[n]===".."||!s.dot&&t[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=t[h];if(this.debug(`
|
|
globstar while`,t,h,e,p,f),this.matchOne(t.slice(h),e.slice(p),r))return this.debug("globstar found match!",h,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",t,h,e,p);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(r&&(this.debug(`
|
|
>>> no match, partial?`,t,h,e,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&t[n]==="";throw new Error("wtf?")}braceExpand(){return bs(this.pattern,this.options)}parse(t){wt(t);let e=this.options;if(t==="**")return D;if(t==="")return"";let r,s=null;(r=t.match(Eo))?s=e.dot?yo:wo:(r=t.match(ao))?s=(e.nocase?e.dot?ho:uo:e.dot?co:lo)(r[1]):(r=t.match(_o))?s=(e.nocase?e.dot?vo:bo:e.dot?To:Mo)(r):(r=t.match(po))?s=e.dot?mo:fo:(r=t.match(go))&&(s=So);let i=Ss.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?Ro:e.dot?ko:Oo,s=new Set(e.nocase?["i"]:[]),i=t.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Lo(u):u===D?D:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==D||f===D||(f===void 0?p!==void 0&&p!==D?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==D&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=D))});let c=l.filter(u=>u!==D);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=t.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let s=this.slashSplit(t);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,e))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return P.defaults(t).Minimatch}};P.AST=Ss;P.Minimatch=pe;P.escape=Es;P.unescape=Oe;var No=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ts=new Set,ur=typeof process=="object"&&process?process:{},Ms=(t,e,r,s)=>{typeof ur.emitWarning=="function"?ur.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},yt=globalThis.AbortController,Xr=globalThis.AbortSignal;if(typeof yt>"u"){Xr=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},yt=class{constructor(){e()}signal=new Xr;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let t=ur.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Ms("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 Uo=t=>!Ts.has(t),de=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Cs=t=>de(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?St:null:null,St=class extends Array{constructor(t){super(t),this.fill(0)}},Fo=class Ke{heap;length;static#e=!1;static create(e){let r=Cs(e);if(!r)return[];Ke.#e=!0;let s=new Ke(e,r);return Ke.#e=!1,s}constructor(e,r){if(!Ke.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},bt=class As{#e;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#R;#m;#T;#M;#g;#E;#b;#C;#t;#x;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#g,autopurgeTimers:e.#E,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#s,next:e.#p,prev:e.#_,get head(){return e.#w},get tail(){return e.#f},free:e.#R,isBackgroundFetch:r=>e.#c(r),backgroundFetch:(r,s,i,n)=>e.#j(r,s,i,n),moveToTail:r=>e.#N(r),indexes:r=>e.#O(r),rindexes:r=>e.#I(r),isStale:r=>e.#v(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#y}get memoMethod(){return this.#S}get dispose(){return this.#n}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:ue,ignoreFetchAbort:Te,perf:Me}=e;if(Me!==void 0&&typeof Me?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=Me??No,r!==0&&!de(r))throw new TypeError("max option must be a nonnegative integer");let Ce=r?Cs(r):Array;if(!Ce)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=g||this.#r,this.sizeCalculation=w,this.sizeCalculation){if(!this.#r&&!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(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=E,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#y=S,this.#C=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Ce(r),this.#_=new Ce(r),this.#w=0,this.#f=0,this.#R=Fo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!ue,this.ignoreFetchAbort=!!Te,this.maxEntrySize!==0){if(this.#r!==0&&!de(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!de(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=de(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!de(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let Xt="LRU_CACHE_UNBOUNDED";Uo(Xt)&&(Ts.add(Xt),Ms("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Xt,As))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#D(){let e=new St(this.#e),r=new St(this.#e);this.#g=e,this.#M=r;let s=this.ttlAutopurge?new Array(this.#e):void 0;this.#E=s,this.#F=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,e[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#v(o)&&this.#k(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#A=o=>{r[o]=e[o]!==0?this.#u.now():0},this.#P=(o,a)=>{if(e[a]){let l=e[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#v=o=>{let a=r[o],l=e[o];return!!l&&!!a&&(i||n())-a>l}}#A=()=>{};#P=()=>{};#F=()=>{};#v=()=>!1;#G(){let e=new St(this.#e);this.#d=0,this.#T=e,this.#U=r=>{this.#d-=e[r],e[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!de(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!de(i))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 i},this.#L=(r,s,i)=>{if(e[r]=s,this.#r){let n=this.#r-e[r];for(;this.#d>n;)this.#H(!0)}this.#d+=e[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=e=>{};#L=(e,r,s)=>{};#W=(e,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#O())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*rentries(){for(let e of this.#I())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*keys(){for(let e of this.#O()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*rkeys(){for(let e of this.#I()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*values(){for(let e of this.#O())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#I())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&e(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(e,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}rforEach(e,r=this){for(let s of this.#I()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}purgeStale(){let e=!1;for(let r of this.#I({allowStale:!0}))this.#v(r)&&(this.#k(this.#l[r],"expire"),e=!0);return e}info(e){let r=this.#h.get(e);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#u.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),e.unshift([s,o])}return e}load(e){this.clear();for(let[r,s]of e){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(e,r,s={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(e,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let h=this.#a===0?void 0:this.#h.get(e);if(h===void 0)h=this.#a===0?this.#f:this.#R.length!==0?this.#R.pop():this.#a===this.#e?this.#H(!1):this.#a,this.#l[h]=e,this.#s[h]=r,this.#h.set(e,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,e,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#C&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#b&&this.#n?.(f,e,"set"),this.#t&&this.#m?.push([f,e,"set"]))}else o||(this.#b&&this.#n?.(p,e,"set"),this.#t&&this.#m?.push([p,e,"set"]));if(this.#U(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#D(),this.#g&&(c||this.#F(h,i,n),l&&this.#P(l,h)),!o&&this.#t&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#s[this.#w];if(this.#H(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#o?.(...r)}}}#H(e){let r=this.#w,s=this.#l[r],i=this.#s[r];return this.#C&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(i,s,"evict"),this.#t&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),e&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#R.push(r)),this.#a===1?(this.#w=this.#f=0,this.#R.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(e,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(e);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#P(i,n));else return s&&this.#A(n),i&&(i.has="hit",this.#P(i,n)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(e);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#j(e,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new yt,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let b=f,T=this.#s[r];return(T===f||E&&w&&T===void 0)&&(g===void 0?b.__staleWhileFetching!==void 0?this.#s[r]=b.__staleWhileFetching:this.#k(e,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(e,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,b=y||s.noDeleteOnFetchRejection,T=f;if(this.#s[r]===f&&(!b||!w&&T.__staleWhileFetching===void 0?this.#k(e,"fetch"):E||(this.#s[r]=T.__staleWhileFetching)),y)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},p=(g,w)=>{let S=this.#y?.(e,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(e,m,{...l.options,status:void 0}),r=this.#h.get(e)):this.#s[r]=m,m}#c(e){if(!this.#C)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof yt}async fetch(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#C)return S&&(S.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#h.get(e);if(b===void 0){S&&(S.fetch="miss");let T=this.#j(e,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Ce=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Ce&&(S.returnedStale=!0)),Ce?T.__staleWhileFetching:T.__returned=T}let ue=this.#v(b);if(!w&&!ue)return S&&(S.fetch="hit"),this.#N(b),i&&this.#A(b),S&&this.#P(S,b),T;let Te=this.#j(e,b,y,g),Me=Te.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=ue?"stale":"refresh",Me&&ue&&(S.returnedStale=!0)),Me?Te.__staleWhileFetching:Te.__returned=Te}}async forceFetch(e,r={}){let s=await this.fetch(e,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(e,o);if(!n&&a!==void 0)return a;let l=s(e,a,{options:o,context:i});return this.set(e,l,o),l}get(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(e);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#P(o,a),this.#v(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#k(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#A(a),l))}else o&&(o.get="miss")}#B(e,r){this.#_[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#B(this.#_[e],this.#p[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#k(e,"delete")}#k(e,r){let s=!1;if(this.#a!==0){let i=this.#h.get(e);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#U(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(n,e,r),this.#t&&this.#m?.push([n,e,r])),this.#h.delete(e),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#R.push(i)}}if(this.#t&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(e){for(let r of this.#I({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#b&&this.#n?.(s,i,e),this.#t&&this.#m?.push([s,i,e])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#M){this.#g.fill(0),this.#M.fill(0);for(let r of this.#E??[])r!==void 0&&clearTimeout(r);this.#E?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#w=0,this.#f=0,this.#R.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},qr=typeof process=="object"&&process?process:{stdout:null,stderr:null},$o=t=>!!t&&typeof t=="object"&&(t instanceof _t||t instanceof pr.default||Ho(t)||jo(t)),Ho=t=>!!t&&typeof t=="object"&&t instanceof vt.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==pr.default.Writable.prototype.pipe,jo=t=>!!t&&typeof t=="object"&&t instanceof vt.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",ie=Symbol("EOF"),ne=Symbol("maybeEmitEnd"),he=Symbol("emittedEnd"),ut=Symbol("emittingEnd"),We=Symbol("emittedError"),ht=Symbol("closed"),Vr=Symbol("read"),dt=Symbol("flush"),Qr=Symbol("flushChunk"),G=Symbol("encoding"),Re=Symbol("decoder"),C=Symbol("flowing"),$e=Symbol("paused"),ke=Symbol("resume"),A=Symbol("buffer"),I=Symbol("pipes"),R=Symbol("bufferLength"),sr=Symbol("bufferPush"),pt=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),ir=Symbol("error"),nr=Symbol("emitData"),Zr=Symbol("emitEnd"),or=Symbol("emitEnd2"),J=Symbol("async"),ar=Symbol("abort"),ft=Symbol("aborted"),He=Symbol("signal"),Ee=Symbol("dataListeners"),U=Symbol("discarded"),je=t=>Promise.resolve().then(t),Bo=t=>t(),Go=t=>t==="end"||t==="finish"||t==="prefinish",Ko=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Yo=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Os=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[ke](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},zo=class extends Os{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},Jo=t=>!!t.objectMode,Xo=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",_t=class extends vt.EventEmitter{[C]=!1;[$e]=!1;[I]=[];[A]=[];[O];[G];[J];[Re];[ie]=!1;[he]=!1;[ut]=!1;[ht]=!1;[We]=null;[R]=0;[M]=!1;[He];[ft]=!1;[Ee]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Jo(e)?(this[O]=!0,this[G]=null):Xo(e)?(this[G]=e.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[J]=!!e.async,this[Re]=this[G]?new ks.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:r}=e;r&&(this[He]=r,r.aborted?this[ar]():r.addEventListener("abort",()=>this[ar]()))}get bufferLength(){return this[R]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[J]}set async(t){this[J]=this[J]||!!t}[ar](){this[ft]=!0,this.emit("abort",this[He]?.reason),this.destroy(this[He]?.reason)}get aborted(){return this[ft]}set aborted(t){}write(t,e,r){if(this[ft])return!1;if(this[ie])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let s=this[J]?je:Bo;if(!this[O]&&!Buffer.isBuffer(t)){if(Yo(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Ko(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[C]&&this[R]!==0&&this[dt](!0),this[C]?this.emit("data",t):this[sr](t),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[Re]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[Re].write(t)),this[C]&&this[R]!==0&&this[dt](!0),this[C]?this.emit("data",t):this[sr](t),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):(this[R]!==0&&this.emit("readable"),r&&s(r),this[C])}read(t){if(this[M])return null;if(this[U]=!1,this[R]===0||t===0||t&&t>this[R])return this[ne](),null;this[O]&&(t=null),this[A].length>1&&!this[O]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[R])]);let e=this[Vr](t||null,this[A][0]);return this[ne](),e}[Vr](t,e){if(this[O])this[pt]();else{let r=e;t===r.length||t===null?this[pt]():typeof r=="string"?(this[A][0]=r.slice(t),e=r.slice(0,t),this[R]-=t):(this[A][0]=r.subarray(t),e=r.subarray(0,t),this[R]-=t)}return this.emit("data",e),!this[A].length&&!this[ie]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[ie]=!0,this.writable=!1,(this[C]||!this[$e])&&this[ne](),this}[ke](){this[M]||(!this[Ee]&&!this[I].length&&(this[U]=!0),this[$e]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[dt]():this[ie]?this[ne]():this.emit("drain"))}resume(){return this[ke]()}pause(){this[C]=!1,this[$e]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[C]}get paused(){return this[$e]}[sr](t){this[O]?this[R]+=1:this[R]+=t.length,this[A].push(t)}[pt](){return this[O]?this[R]-=1:this[R]-=this[A][0].length,this[A].shift()}[dt](t=!1){do;while(this[Qr](this[pt]())&&this[A].length);!t&&!this[A].length&&!this[ie]&&this.emit("drain")}[Qr](t){return this.emit("data",t),this[C]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[he];return e=e||{},t===qr.stdout||t===qr.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[I].push(e.proxyErrors?new zo(this,t,e):new Os(this,t,e)),this[J]?je(()=>this[ke]()):this[ke]()),t}unpipe(t){let e=this[I].find(r=>r.dest===t);e&&(this[I].length===1?(this[C]&&this[Ee]===0&&(this[C]=!1),this[I]=[]):this[I].splice(this[I].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[U]=!1,this[Ee]++,!this[I].length&&!this[C]&&this[ke]();else if(t==="readable"&&this[R]!==0)super.emit("readable");else if(Go(t)&&this[he])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[We]){let s=e;this[J]?je(()=>s.call(this,this[We])):s.call(this,this[We])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ee]=this.listeners("data").length,this[Ee]===0&&!this[U]&&!this[I].length&&(this[C]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ee]=0,!this[U]&&!this[I].length&&(this[C]=!1)),e}get emittedEnd(){return this[he]}[ne](){!this[ut]&&!this[he]&&!this[M]&&this[A].length===0&&this[ie]&&(this[ut]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ht]&&this.emit("close"),this[ut]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==M&&this[M])return!1;if(t==="data")return!this[O]&&!r?!1:this[J]?(je(()=>this[nr](r)),!0):this[nr](r);if(t==="end")return this[Zr]();if(t==="close"){if(this[ht]=!0,!this[he]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[We]=r,super.emit(ir,r);let i=!this[He]||this.listeners("error").length?super.emit("error",r):!1;return this[ne](),i}else if(t==="resume"){let i=super.emit("resume");return this[ne](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let s=super.emit(t,...e);return this[ne](),s}[nr](t){for(let r of this[I])r.dest.write(t)===!1&&this.pause();let e=this[U]?!1:super.emit("data",t);return this[ne](),e}[Zr](){return this[he]?!1:(this[he]=!0,this.readable=!1,this[J]?(je(()=>this[or]()),!0):this[or]())}[or](){if(this[Re]){let e=this[Re].end();if(e){for(let r of this[I])r.dest.write(e);this[U]||super.emit("data",e)}}for(let e of this[I])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[O]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[O]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(M,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[U]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[ie])return e();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),e(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[ie]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),e(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let t=!1,e=()=>(this.pause(),this.off(ir,e),this.off(M,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let s=this.read();return s===null?e():{done:!1,value:s}};return this.once("end",e),this.once(ir,e),this.once(M,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[M])return t?this.emit("error",t):this.emit(M),this;this[M]=!0,this[U]=!0,this[A].length=0,this[R]=0;let e=this;return typeof e.close=="function"&&!this[ht]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return $o}},qo=q.realpathSync.native,Ye={lstatSync:q.lstatSync,readdir:q.readdir,readdirSync:q.readdirSync,readlinkSync:q.readlinkSync,realpathSync:qo,promises:{lstat:fe.lstat,readdir:fe.readdir,readlink:fe.readlink,realpath:fe.realpath}},Is=t=>!t||t===Ye||t===Wo?Ye:{...Ye,...t,promises:{...Ye.promises,...t.promises||{}}},Ds=/^\\\\\?\\([a-z]:)\\?$/i,Vo=t=>t.replace(/\//g,"\\").replace(Ds,"$1\\"),Qo=/[\\\/]/,j=0,Ps=1,xs=2,X=4,Ls=6,Ns=8,we=10,Us=12,H=15,Be=~H,lr=16,es=32,ze=64,K=128,mt=256,Et=512,ts=ze|K|Et,Zo=1023,cr=t=>t.isFile()?Ns:t.isDirectory()?X:t.isSymbolicLink()?we:t.isCharacterDevice()?xs:t.isBlockDevice()?Ls:t.isSocket()?Us:t.isFIFO()?Ps:j,rs=new bt({max:2**12}),Je=t=>{let e=rs.get(t);if(e)return e;let r=t.normalize("NFKD");return rs.set(t,r),r},ss=new bt({max:2**12}),gt=t=>{let e=ss.get(t);if(e)return e;let r=Je(t.toLowerCase());return ss.set(t,r),r},is=class extends bt{constructor(){super({max:256})}},ea=class extends bt{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Fs=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#b;#C;#t;#x;#D;#A;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=j,r,s,i,n,o){this.name=t,this.#T=i?gt(t):Je(t),this.#t=e&Zo,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#C=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Is(o.fs)}depth(){return this.#M!==void 0?this.#M:this.parent?this.#M=this.parent.depth()+1:this.#M=0}childrenCache(){return this.#x}resolve(t){if(!t)return this;let e=this.getRootString(t),r=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#P(r):this.#P(r)}#P(t){let e=this;for(let r of t)e=e.child(r);return e}children(){let t=this.#x.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#x.set(this,e),this.#t&=~lr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?gt(t):Je(t);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+t:void 0,o=this.newChild(t,j,{...e,parent:this,fullpath:n});return this.canReaddir()||(o.#t|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let t=this.name,e=this.parent;if(!e)return this.#b=this.name;let r=e.relative();return r+(!r||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#C!==void 0)return this.#C;let t=this.name,e=this.parent;if(!e)return this.#C=this.fullpathPosix();let r=e.relativePosix();return r+(!r||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let r=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=r}fullpathPosix(){if(this.#E!==void 0)return this.#E;if(this.sep==="/")return this.#E=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let t=this.parent,e=t.fullpathPosix(),r=e+(!e||!t.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#t&H)===j}isType(t){return this[`is${t}`]()}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(this.#t&H)===Ns}isDirectory(){return(this.#t&H)===X}isCharacterDevice(){return(this.#t&H)===xs}isBlockDevice(){return(this.#t&H)===Ls}isFIFO(){return(this.#t&H)===Ps}isSocket(){return(this.#t&H)===Us}isSymbolicLink(){return(this.#t&we)===we}lstatCached(){return this.#t&es?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#A}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let t=this.#t&H;return!(t!==j&&t!==we||this.#t&mt||this.#t&K)}calledReaddir(){return!!(this.#t&lr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===gt(t):this.#T===Je(t)}async readlink(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}readlinkSync(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}#F(t){this.#t|=lr;for(let e=t.provisional;e<t.length;e++){let r=t[e];r&&r.#v()}}#v(){this.#t&K||(this.#t=(this.#t|K)&Be,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=Et,this.#L()}#L(){if(this.#t&ze)return;let t=this.#t;(t&H)===X&&(t&=Be),this.#t=t|ze,this.#G()}#W(t=""){t==="ENOTDIR"||t==="EPERM"?this.#L():t==="ENOENT"?this.#v():this.children().provisional=0}#O(t=""){t==="ENOTDIR"?this.parent.#L():t==="ENOENT"&&this.#v()}#I(t=""){let e=this.#t;e|=mt,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Be),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(t,e){return this.#j(t,e)||this.#H(t,e)}#H(t,e){let r=cr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&H;return i!==X&&i!==we&&i!==j&&(s.#t|=ze),e.unshift(s),e.provisional++,s}#j(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?gt(t.name):Je(t.name))===s.#T)return this.#c(t,s,r,e)}}#c(t,e,r,s){let i=e.name;return e.#t=e.#t&Be|cr(t),i!==t.name&&(e.name=t.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(e)),s.provisional++,e}async lstat(){if((this.#t&K)===0)try{return this.#B(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#B(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#B(t){let{atime:e,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=t;this.#w=e,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#R=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=cr(t);this.#t=this.#t&Be|y|es,y!==j&&y!==X&&y!==we&&(this.#t|=ze)}#N=[];#k=!1;#K(t){this.#k=!1;let e=this.#N.slice();this.#N.length=0,e.forEach(r=>r(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);e?t(null,i):queueMicrotask(()=>t(null,i));return}if(this.#N.push(t),this.#k)return;this.#k=!0;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#F(r)}this.#K(r.slice(0,r.provisional))})}#Y;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#Y)await this.#Y;else{let r=()=>{};this.#Y=new Promise(s=>r=s);try{for(let s of await this.#e.promises.readdir(e,{withFileTypes:!0}))this.#$(s,t);this.#F(t)}catch(s){this.#W(s.code),t.provisional=0}this.#Y=void 0,r()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let r of this.#e.readdirSync(e,{withFileTypes:!0}))this.#$(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&ts)return!1;let t=H&this.#t;return t===j||t===X||t===we}shouldWalk(t,e){return(this.#t&X)===X&&!(this.#t&ts)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#A)return this.#A;if(!((Et|mt|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#A=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#A)return this.#A;if(!((Et|mt|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#A=this.resolve(t)}catch{this.#U()}}[Fs](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),r=[],s=this;for(;s&&s.parent;)e.add(s),s.#b=r.join(this.sep),s.#C=r.join("/"),s=s.parent,r.push("..");for(s=t;s&&s.parent&&!e.has(s);)s.#b=void 0,s.#C=void 0,s=s.parent}},Ws=class $s extends L{sep="\\";splitSep=Qo;constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=j,s={}){return new $s(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Ie.win32.parse(e).root}getRoot(e){if(e=Vo(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new fr(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Ds,"$1\\"),e===r}},Hs=class js extends L{splitSep="/";sep="/";constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=j,s={}){return new js(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Bs=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Ye}={}){this.#i=Is(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Rs.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new is,this.#r=new is,this.#n=new ea(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new _t({objectMode:!0});(!i||i(t))&&o.write(r?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new _t({objectMode:!0}),a=new Set;(!i||i(t))&&o.write(r?t:t.fullpath());let l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[Fs](e)}},fr=class extends Bs{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Ie.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Ie.win32.parse(t).root.toUpperCase()}newRoot(t){return new Ws(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},mr=class extends Bs{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Ie.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new Hs(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Gs=class extends mr{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},jl=process.platform==="win32"?Ws:Hs,ta=process.platform==="win32"?fr:process.platform==="darwin"?Gs:mr,ra=t=>t.length>=1,sa=t=>t.length>=1,ia=Symbol.for("nodejs.util.inspect.custom"),Ks=class Ys{#e;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!ra(e))throw new TypeError("empty pattern list");if(!sa(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[ia](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===D}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#y=this.#y||(this.#n===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new Ys(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},na=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ns=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=na}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new pe(t,this.mmopts);for(let r=0;r<e.set.length;r++){let s=e.set[r],i=e.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new Ks(s,i,0,this.platform),o=new pe(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},oa=class zs{store;constructor(e=new Map){this.store=e}copy(){return new zs(new Map(this.store))}hasWalked(e,r){return this.store.get(e.fullpath())?.has(r.globString())}storeWalked(e,r){let s=e.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},aa=class{store=new Map;add(t,e,r){let s=(e?2:0)|(r?1:0),i=this.store.get(t);this.store.set(t,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},la=class{store=new Map;add(t,e){if(!t.canReaddir())return;let r=this.store.get(t);r?r.find(s=>s.globString()===e.globString())||r.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},os=class Js{hasWalkedCache;matches=new aa;subwalks=new la;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new oa}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===D){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Js(this.opts,this.hasWalkedCache)}filterEntries(e,r){let s=this.subwalks.get(e),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===D?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(e,r,s,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(e,s):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(e,n,s.rest(),i);else if(n===".."){let o=e.parent||e;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(e,n,s.rest(),i)}}testRegExp(e,r,s,i){r.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}testString(e,r,s,i){e.isNamed(r)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}},ca=(t,e)=>typeof t=="string"?new ns([t],e):Array.isArray(t)?new ns(t,e):t,Xs=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ca(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new os(this.opts),r)}walkCB2(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(t,e,r){this.signal?.aborted&&r(),this.walkCB2Sync(t,e,new os(this.opts),r)}walkCB2Sync(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},as=class extends Xs{matches=new Set;constructor(t,e,r){super(t,e,r)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},ls=class extends Xs{results;constructor(t,e,r){super(t,e,r),this.results=new _t({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},ua=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ye=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){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=(0,vs.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!==!1,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 t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||ua,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 a=e.platform==="win32"?fr:e.platform==="darwin"?Gs:e.platform?mr:ta;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new pe(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Ks(a,c,0,this.platform)})}async walk(){return[...await new as(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 as(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 ls(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 ls(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()}},ha=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new pe(r,e).hasMagic())return!0;return!1};function Tt(t,e={}){return new ye(t,e).streamSync()}function qs(t,e={}){return new ye(t,e).stream()}function Xe(t,e={}){return new ye(t,e).walkSync()}async function cs(t,e={}){return new ye(t,e).walk()}function Mt(t,e={}){return new ye(t,e).iterateSync()}function Vs(t,e={}){return new ye(t,e).iterate()}var da=Tt,pa=Object.assign(qs,{sync:Tt}),fa=Mt,ma=Object.assign(Vs,{sync:Mt}),ga=Object.assign(Xe,{stream:Tt,iterate:Mt}),us=Object.assign(cs,{glob:cs,globSync:Xe,sync:ga,globStream:qs,stream:pa,globStreamSync:Tt,streamSync:da,globIterate:Vs,iterate:ma,globIterateSync:Mt,iterateSync:fa,Glob:ye,hasMagic:ha,escape:Es,unescape:Oe});us.glob=us;var oe=require("fs"),Qs=require("path");function Zs(t){try{if(!(0,oe.existsSync)(t))return{offsets:{}};let e=(0,oe.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function ei(t,e){try{let r=(0,Qs.dirname)(t);(0,oe.existsSync)(r)||(0,oe.mkdirSync)(r,{recursive:!0}),(0,oe.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var et=te(require("path"),1);var Pe=te(require("path"),1),B=require("fs"),xi=require("child_process");var ti=require("node:child_process");function Ct(t,e,r){return(0,ti.spawn)(t,e??[],{windowsHide:!0,...r})}var W={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},me={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ae(t){return process.platform==="win32"?Math.round(t*W.WINDOWS_MULTIPLIER):t}var V=require("fs"),qe=require("path"),gr=require("os");var Q=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(ae(W.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,qe.join)((0,gr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,qe.join)((0,gr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(e,r=!0){try{if(!(0,V.existsSync)(e)){let a=this.getAllDefaults();try{let l=(0,qe.dirname)(e);(0,V.existsSync)(l)||(0,V.mkdirSync)(l,{recursive:!0}),(0,V.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,V.readFileSync)(e,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,V.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let o={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(o[a]=n[a]);return r?this.applyEnvOverrides(o):o}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var At=null;function le(){return At!==null||(At=Q.loadFromFile(nt)),At}var _e=require("fs");var _r=require("child_process");var ee=require("fs"),wr=te(require("path"),1);var Sa=["CLAUDECODE_","CLAUDE_CODE_"],Ea=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),wa=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),ya=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Rt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(ya.has(r)){e[r]=s;continue}Ea.has(r)||wa.has(r)||Sa.some(i=>r.startsWith(i))||(e[r]=s)}return e}var _a=5e3,ba=1e3,va=k.supervisorRegistry();function Z(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}var Ta=5e3,ri=new Map;function Ma(t){let e=ri.get(t);if(e&&Date.now()-e.capturedAtMs<Ta)return e.token;let r=null;try{let s=(0,_r.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Rt(process.env),LC_ALL:"C",LANG:"C"}});if(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:s instanceof Error?s.message:String(s)}),r=null}return ri.set(t,{token:r,capturedAtMs:Date.now()}),r}function si(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,ee.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return Ma(t);try{let e=(0,_r.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Rt(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function br(t){if(!t||!Z(t.pid))return!1;if(!t.startToken)return!0;let e=si(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var yr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=va){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,ee.mkdirSync)(wr.default.dirname(this.registryPath),{recursive:!0}),!(0,ee.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,ee.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,s){this.initialize(),this.entries.set(e,r),s&&this.runtimeProcesses.set(e,s),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Er()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let s=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[s,i]of this.entries)Z(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let s=0;s<r;s+=1)Er();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let s=typeof e=="number"?e:Number(e)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:s,pids:r.map(a=>a.pid)});let i=r.filter(a=>Z(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}let n=Date.now()+_a;for(;Date.now()<n&&i.filter(l=>Z(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let o=i.filter(a=>Z(a.pid));for(let a of o){d.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:s});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+ba;for(;Date.now()<a&&o.filter(c=>Z(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Er();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:s,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,ee.mkdirSync)(wr.default.dirname(this.registryPath),{recursive:!0}),(0,ee.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Sr=null;function kt(){return Sr||(Sr=new yr),Sr}var Ca=[];function Er(){let t=Ca.shift();t&&t()}var oi=require("child_process"),ai=require("fs"),li=require("util");var Aa=(0,li.promisify)(oi.execFile),Ra=k.workerPid();async function ci(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Ra,s=t.registry.getAll(),i=[...s].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!Z(o.pid)){t.registry.unregister(o.id);continue}try{await ni(o,"SIGTERM")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await ii(i,5e3);let n=i.filter(o=>Z(o.pid));for(let o of n)try{await ni(o,"SIGKILL")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await ii(n,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===e))t.registry.unregister(o.id);try{(0,ai.rmSync)(r,{force:!0})}catch(o){o instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},o):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(o)})}t.registry.pruneDeadEntries()}async function ii(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(i=>Z(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function ni(t,e){let{pid:r,pgid:s}=t;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await ka();if(i){await new Promise((o,a)=>{i(r,e,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await Aa("taskkill",n,{timeout:W.POWERSHELL_COMMAND,windowsHide:!0})}async function ka(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var ui=3e4,De=null;function Oa(){let e=kt().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function hi(){De===null&&(De=setInterval(Oa,ui),De.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:ui}))}function di(){De!==null&&(clearInterval(De),De=null,d.debug("SYSTEM","Health checker stopped"))}var Ia=k.workerPid(),vr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ot({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,hi()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}di(),this.stopPromise=ci({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,s){this.registry.register(e,r,s)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},jc=new vr(kt());function Ot(t={}){let e=t.pidFilePath??Ia;if(!(0,_e.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,_e.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,_e.rmSync)(e,{force:!0}),"invalid"}return br(r)&&r?((t.logAlive??!0)&&d.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(d.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,_e.rmSync)(e,{force:!0}),"stale")}var Tr=require("path"),Dt=require("fs"),fi=require("crypto");var It=require("fs");function pi(t,e){if(!(0,It.existsSync)(t))return e;try{return JSON.parse((0,It.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var mi="telemetry.json";function Da(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Pa(t,e){if(Da(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function gi(t,e){return Pa(t,e).enabled}function xa(){return(0,Tr.join)(rt(),mi)}function Mr(){try{let t=pi(xa(),null);return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}catch{return null}}function La(t){let e=rt();(0,Dt.mkdirSync)(e,{recursive:!0}),(0,Dt.writeFileSync)((0,Tr.join)(e,mi),JSON.stringify(t,null,2)+`
|
|
`)}function Si(){let t=Mr();if(t?.installId)return t.installId;let e=(0,fi.randomUUID)();return La({installId:e,decidedAt:""}),e}var Na=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","fabrication_detected","fabricated_count","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped"]),Ei=200;function wi(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!Na.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>Ei?s.slice(0,Ei):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Cr=te(require("os"),1),Ua="13.5.5",Fa="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Wa="https://us.i.posthog.com";function yi(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Fa}function _i(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Wa}var $a=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function bi(t){let e={};for(let r of $a)t[r]!==void 0&&(e[r]=t[r]);return e}function Ha(){try{return Cr.default.release()}catch{return"unknown"}}function ja(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Cr.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function vi(){return{version:Ua,os:process.platform,os_version:Ha(),is_wsl:ja(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Ba=2e3;async function Ti(t,e,r){try{if(!gi(process.env,Mr()))return;let s=wi({...vi(),...e??{}});if(r?.person?s.$set=bi(s):s.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:s})+`
|
|
`);return}let i=yi();if(!i)return;let n=new AbortController,o=setTimeout(()=>n.abort(),Ba);try{await fetch(`${_i()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:Si(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Pt=require("child_process");var Mi=require("util");var ou=(0,Mi.promisify)(Pt.exec),au=k.dataDir(),lu=k.workerPid();var Ci=te(require("path"),1);var Ai=require("fs");async function Ka(t,e,r="GET"){let s=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function Ya(){try{let t=Ci.default.join(it,"package.json");return JSON.parse((0,Ai.readFileSync)(t,"utf-8")).version}catch(t){if(t instanceof Error){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}throw t}}async function za(t){try{let e=await Ka(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Ri(t){let e=Ya(),r=await za(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}function Rr(t,e,r){let s=process.env[t];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max})}return e}var kr=Rr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ae(W.HEALTH_CHECK),{min:500,max:3e5}),Iu=Rr("CLAUDE_MEM_API_TIMEOUT_MS",ae(W.API_REQUEST),{min:500,max:3e5}),Ja=Rr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ae(W.HOOK_READINESS_WAIT),{min:0,max:3e5}),Xa={min:500,max:3e5};function Or(t,e={},r){return new Promise((s,i)=>{let n=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(o=>{clearTimeout(n),s(o)},o=>{clearTimeout(n),i(o)})})}var xt=null,Lt=null,Nt=null,Ut=null;function qa(){return Pe.default.join(Q.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Ir(){return Nt!==null||(Nt=Q.loadFromFile(qa())),Nt}function ki(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Va(t,e,r){let s=process.env[t];if(s!==void 0){let o=ki(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max}),e)}let i=Ir()[t],n=ki(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:i,min:r.min,max:r.max}),e)}function Li(){if(xt!==null)return xt;let t=Ir();return xt=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),xt}function Qa(){return Lt!==null||(Lt=Ir().CLAUDE_MEM_WORKER_HOST),Lt}function Za(){return Ut!==null||(Ut=Va("CLAUDE_MEM_API_TIMEOUT_MS",ae(W.API_REQUEST),Xa)),Ut}function el(t){return`http://${Qa()}:${Li()}${t}`}function ge(t,e={}){let r=e.method??"GET",s=e.timeoutMs??Za(),i=el(t),n={method:r};return e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),s>0?Or(i,n,s):fetch(i,n)}async function tl(){return(await ge("/api/health",{timeoutMs:kr})).ok}async function Oi(){return(await ge("/api/readiness",{timeoutMs:kr})).ok}function rl(){let t=[Pe.default.join(it,"plugin","scripts","worker-service.cjs"),Pe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,B.existsSync)(e))return e;return null}function sl(){if(process.env.BUN&&(0,B.existsSync)(process.env.BUN))return process.env.BUN;try{let t=process.platform==="win32"?"where bun":"which bun";return(0,xi.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0}).split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}catch{return null}}async function il(t){let e=t.backoffMs;for(let r=1;r<=t.attempts;r++){if(await Ni())return!0;r<t.attempts&&(await new Promise(s=>setTimeout(s,e)),e*=2)}return!1}async function Ii(t=Ja){if(t<=0)try{return await Oi()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await Oi())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Ni(){let t;try{t=await tl()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!t)return!1;let e=Ot({logAlive:!1});return e==="missing"||e==="alive"}async function Wt(){if(await Ni()){let{matches:i,pluginVersion:n,workerVersion:o}=await Ri(Li());if(i)return await Ii()?!0:(d.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);d.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:n,workerVersion:o});try{await ge("/api/admin/restart",{method:"POST",timeoutMs:kr})}catch(a){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:a instanceof Error?a.message:String(a)})}}let t=sl(),e=rl();if(!t)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:e});try{Ct(t,[e,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(i){return i instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:e},i):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,scriptPath:e,error:String(i)}),!1}return await il({attempts:6,backoffMs:500})?await Ii()?!0:(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1):(d.warn("SYSTEM","Worker port did not open after lazy-spawn within the cold-boot wait (~15s)"),!1)}var Ft=null;async function nl(){return Ft!==null||(Ft=await Wt()),Ft}var ol=3;function Ui(){return Pe.default.join(v,"state")}function Fi(){return Pe.default.join(Ui(),"hook-failures.json")}function Wi(){try{let t=(0,B.readFileSync)(Fi(),"utf-8"),e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function $i(t){let e=Ui(),r=Fi(),s=`${r}.tmp`;try{(0,B.existsSync)(e)||(0,B.mkdirSync)(e,{recursive:!0}),(0,B.writeFileSync)(s,JSON.stringify(t),"utf-8"),(0,B.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function al(){try{let e=le().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return ol}var Di=null;async function ll(){let e={consecutiveFailures:Wi().consecutiveFailures+1,lastFailureAt:Date.now()};$i(e);let r=al();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Ti("hook_failed",{...Di!==null?{hook_type:Di}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Fr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Pi(){Wi().consecutiveFailures!==0&&$i({consecutiveFailures:0,lastFailureAt:0})}var Ar=Symbol.for("claude-mem/worker-fallback");function Ve(t){return typeof t=="object"&&t!==null&&t[Ar]===!0}async function Qe(t,e,r,s={}){if(!await nl())return await ll(),{continue:!0,reason:"worker_unreachable",[Ar]:!0};let n={method:e};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await ge(t,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Pi(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${e} ${t} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Ar]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}Pi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var ji=require("os"),Bi=te(require("path"),1),Gi=require("child_process");var Ht=require("fs"),$t=te(require("path"),1);var Ze={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Hi(t){let e=$t.default.join(t,".git"),r;try{r=(0,Ht.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),Ze}if(!r.isFile())return Ze;let s;try{s=(0,Ht.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),Ze}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return Ze;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Ze;let a=o[1],l=$t.default.basename(t),c=$t.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function Ki(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,ji.homedir)()):t}function cl(t){try{return(0,Gi.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ul(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=Ki(t),s=cl(e)??e,i=Bi.default.basename(s);if(i===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return i}function be(t){let e=ul(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=Ki(t),s=Hi(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${e}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var ve=require("path");var Yi=require("os"),zi=require("path");function hl(t){let e=t.startsWith("~")?(0,Yi.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function jt(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),s=(0,zi.basename)(r),i=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=hl(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function dl(t,e){let r=(0,ve.normalize)(t),s=(0,ve.normalize)(e);if(r===s)return!0;let i=(0,ve.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,ve.isAbsolute)(i)}function Bt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(dl(t,ot))return!1;let e=le();return!jt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ji="claude";function pl(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Se(t){if(!t)return Ji;let e=pl(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ji}var Vi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Xi=new RegExp(`<(${Vi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var qi=100;function fl(t){let e=Object.fromEntries(Vi.map(i=>[i,0]));Xi.lastIndex=0;let r=0,s=t.replace(Xi,(i,n)=>(e[n]=(e[n]??0)+1,r+=1,""));return r>qi&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:qi,contentLength:t.length}),{stripped:s.trim(),counts:e}}function Dr(t){return fl(t).stripped}var ml=["task-notification"],gl=new RegExp(`^\\s*<(${ml.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Sl=256*1024;function Qi(t){return!t||t.length>Sl?!1:gl.test(t)}var El=ae(W.API_REQUEST),ce=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Gt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=wl(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??El}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(e){if(!e.sessionId)throw new ce("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new ce("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,s=e.kind??"manual",i=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new ce("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Or(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new ce(u?"timeout":"transport",`Server beta ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new ce("http_error",`Server beta ${e} ${r} returned ${o.status}: ${yl(l,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(l){throw new ce("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:l})}}};function Zi(t){return t instanceof ce}function wl(t){return t.replace(/\/+$/,"")}function yl(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function _l(){return(le().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function bl(){let t=le(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return d.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return d.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new Gt(i),projectId:s,serverBaseUrl:e}}function en(){if(_l()!=="server-beta")return{runtime:"worker"};let t=bl();return t||{runtime:"worker"}}function tn(t,e){d.warn("HOOK",`[server-beta-fallback] reason=${t}`,e??{})}var rn={async execute(t){let{sessionId:e,prompt:r}=t,s=t.cwd??process.cwd();if(!e)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS};if(!Bt(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&Qi(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=be(s).primary,o=Se(t.platform),a=en();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:e,contentSessionId:e,agentId:t.agentId??null,agentType:t.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(Zi(m)&&m.isFallbackEligible())tn(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server beta session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let l=await Qe("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(Ve(l))return{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS};let c=l.sessionDbId,u=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:u,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${u} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let h=le(),p=String(h.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=h.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await Qe("/api/context/semantic","POST",{q:i,project:n,limit:m});!Ve(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:c,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var sn={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=Se(t.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${s}`);if(!Bt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS};let o=await Qe("/api/sessions/observations","POST",{contentSessionId:e,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return Ve(o)?{continue:!0,suppressOutput:!0,exitCode:me.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var Y=require("fs"),Kt=require("path");var Ih=k.settings();function nn(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
|
|
${e}
|
|
${s}`;let i=t.indexOf(r),n=t.indexOf(s);return i!==-1&&n!==-1?t.substring(0,i)+`${r}
|
|
${e}
|
|
${s}`+t.substring(n+s.length):t+`
|
|
|
|
${r}
|
|
${e}
|
|
${s}`}function on(t,e){if(!t)return;let r=(0,Kt.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,Kt.dirname)(t);(0,Y.existsSync)(s)||(0,Y.mkdirSync)(s,{recursive:!0});let i="";(0,Y.existsSync)(t)&&(i=(0,Y.readFileSync)(t,"utf-8"));let n=`# Memory Context
|
|
|
|
${e}`,o=nn(i,n),a=`${t}.tmp`;try{(0,Y.writeFileSync)(a,o),(0,Y.renameSync)(a,t)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},l instanceof Error?l:new Error(String(l)))}}function vl(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],s=e.split(".");for(let i of s){let n=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=n.exec(i))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function Pr(t,e){if(!e)return;let r=vl(e),s=t;for(let i of r){if(s==null)return;s=s[i]}return s}function an(t){return t==null||t===""}function ln(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function xe(t,e,r){if(t!==void 0){if(typeof t=="string"){let s=ln(t,r);return s!==void 0?s:Pr(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let s of t.coalesce){let i=xe(s,e,r);if(!an(i))return i}if(t.path){let s=ln(t.path,r);if(s!==void 0)return s;let i=Pr(e,t.path);if(!an(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function cn(t,e,r){let s={};if(!t)return s;for(let[i,n]of Object.entries(t))s[i]=xe(n,e,r);return s}function un(t,e,r){if(!e)return!0;let s=e.path||r.eventTypePath||"type",i=s?Pr(t,s):void 0,n=i==null||i==="";if(e.exists!==void 0&&(e.exists&&n||!e.exists&&!n)||e.equals!==void 0&&i!==e.equals||e.not_equals!==void 0&&i===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(i)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(i)||e.contains!==void 0&&(typeof i!="string"||!i.includes(e.contains))||e.not_contains!==void 0&&typeof i=="string"&&i.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}var Yt=class{static checkUserPromptPrivacy(e,r,s,i,n,o){let a=e.getUserPrompt(r,s);return a===null?(d.warn("HOOK",`${i}: no user_prompts row for prompt #${s} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:n,contentSessionId:r,promptNumber:s,...o}),{allow:!0,prompt:""}):a.trim()===""?(d.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:n,promptNumber:s,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var dn=require("events"),xr=class t extends dn.EventEmitter{recentStored=new Map;static RECENT_EVENT_TTL_MS=6e4;constructor(){super(),this.setMaxListeners(0),this.on("summaryStoredEvent",e=>{this.recentStored.set(e.sessionId,{event:e,at:Date.now()}),this.evictExpiredStored()})}takeRecentSummaryStored(e){let r=this.recentStored.get(e);if(r){if(Date.now()-r.at>t.RECENT_EVENT_TTL_MS){this.recentStored.delete(e);return}return r.event}}evictExpiredStored(){let e=Date.now()-t.RECENT_EVENT_TTL_MS;for(let[r,s]of this.recentStored)s.at<e&&this.recentStored.delete(r)}},Jh=new xr,hn=null;function Tl(){if(!hn)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return hn}async function pn(t){let{sessionManager:e,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=Tl(),n=Se(t.platformSource),o=typeof t.cwd=="string"?t.cwd:"",a=o.trim()?be(o).primary:"",l=Q.loadFromFile(nt);if(o&&jt(o,l.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(l.CLAUDE_MEM_SKIP_TOOLS.split(",").map(S=>S.trim()).filter(Boolean)).has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let S=t.toolInput,E=S.file_path||S.notebook_path;if(E&&E.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let h=r.getSessionStore(),p,f;try{p=h.createSDKSession(t.contentSessionId,a,"",void 0,n),f=h.getPromptNumberFromUserPrompts(t.contentSessionId)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!Yt.checkUserPromptPrivacy(h,t.contentSessionId,f,"observation",p,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=t.toolInput!==void 0?Dr(JSON.stringify(t.toolInput)):"{}",w=t.toolResponse!==void 0?Dr(JSON.stringify(t.toolResponse)):"{}";return await e.queueObservation(p,{tool_name:t.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var zt=class{sessions=new Map;async processEntry(e,r,s,i){for(let n of s.events)un(e,n.match,s)&&await this.handleEvent(e,r,s,n,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let s=this.getSessionKey(e,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:Se(e.name)},this.sessions.set(s,i)),i}resolveSessionId(e,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=xe(a,e,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=xe(a,e,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=xe(a,e,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?be(n.cwd).primary:n.project}async handleEvent(e,r,s,i,n){let o=this.resolveSessionId(e,r,s,i,n);if(!o){d.debug("TRANSCRIPT","Skipping event without sessionId",{event:i.name,watch:r.name});return}let a=this.getOrCreateSession(r,o),l=this.resolveCwd(e,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(e,r,s,i,a);c&&(a.project=c);let u=cn(i.fields,e,{watch:r,schema:s,session:a});switch(i.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,u);break;case"tool_result":await this.handleToolResult(a,u);break;case"observation":await this.sendObservation(a,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(e,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(e.cwd=s),i&&(e.project=i)}async handleSessionInit(e,r){let s=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();s&&(e.lastUserMessage=s),await rn.execute({sessionId:e.sessionId,cwd:i,prompt:s,platform:e.platformSource})}async handleToolUse(e,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolInput),o=this.maybeParseJson(r.toolResponse);if(i==="apply_patch"&&typeof n=="string"){let a=this.parseApplyPatchFiles(n);for(let l of a)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(e,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(e,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolResponse),o=this.maybeParseJson(r.toolInput);if(s&&e.pendingTools){let a=e.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await pn({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:e.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await sn.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;try{return JSON.parse(r)}catch(s){return d.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:r.slice(0,120)},s instanceof Error?s:void 0),e}}parseApplyPatchFiles(e){let r=[],s=e.split(`
|
|
`);for(let i of s){let n=i.trim();if(n.startsWith("*** Update File: "))r.push(n.replace("*** Update File: ","").trim());else if(n.startsWith("*** Add File: "))r.push(n.replace("*** Add File: ","").trim());else if(n.startsWith("*** Delete File: "))r.push(n.replace("*** Delete File: ","").trim());else if(n.startsWith("*** Move to: "))r.push(n.replace("*** Move to: ","").trim());else if(n.startsWith("+++ ")){let o=n.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(e,r){await this.queueSummary(e),await this.updateContext(e,r),e.pendingTools?.clear();let s=this.getSessionKey(r,e.sessionId);this.sessions.delete(s)}async queueSummary(e){if(!await Wt())return;let s=e.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:s,platformSource:e.platformSource});try{await ge("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:i})}catch(n){d.warn("TRANSCRIPT","Summary request failed",{error:n instanceof Error?n.message:String(n)})}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||Hr(r)||!await Wt())return;let i=e.cwd??r.workspace;if(!i)return;let o=be(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}`,l=N(r.context.path??`${i}/AGENTS.md`),c=et.default.resolve(l),u=[et.default.resolve(i),et.default.resolve(v)];if(!u.some(m=>c.startsWith(m+et.default.sep)||c===m)){d.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:r.context.path,resolved:c,allowedRoots:u});return}let p;try{p=await ge(a)}catch(m){d.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!p.ok)return;let f=(await p.text()).trim();f&&(on(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var Lr=class{constructor(e,r,s,i){this.filePath=e;this.onLine=s;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,x.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,x.existsSync)(this.filePath))return;let e=0;try{e=(0,x.statSync)(this.filePath).size}catch(o){d.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let r=(0,x.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
|
|
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},Jt=class{constructor(e,r){this.config=e;this.statePath=r;this.state=Zs(r)}config;statePath;processor=new zt;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let s=N(e.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,e,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,x.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:n});return}try{let o=(0,x.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,z.resolve)(n,l).replace(/\\/g,"/"),u=this.tailers.get(c);if(u){u.poke();return}let h=this.resolveWatchFiles(s);for(let p of h)this.tailers.has(p)||this.addTailer(p,e,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,x.existsSync)(e))try{return(0,x.statSync)(e).isDirectory()?e:(0,z.resolve)(e,"..")}catch{return(0,z.resolve)(e,"..")}return e}let r=e.split(/[/\\]/),s=[];for(let i of r){if(/[*?[\]{}()]/.test(i))break;s.push(i)}return s.length===0||s.length===1&&s[0]===""?"":s.join(z.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return Xe(this.normalizeGlobPattern(e),{nodir:!0,absolute:!0});if((0,x.existsSync)(e))try{if((0,x.statSync)(e).isDirectory()){let s=(0,z.join)(e,"**","*.jsonl");return Xe(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[e]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,s){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),n=this.state.offsets[e]??0;if(n===0&&r.startAtEnd)try{n=(0,x.statSync)(e).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),n=0}let o=new Lr(e,n,async a=>{await this.handleLine(a,r,s,e,i)},a=>{this.state.offsets[e]=a,ei(this.statePath,this.state)});o.start(),this.tailers.set(e,o),d.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:s.name})}async handleLine(e,r,s,i,n){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,s,n??void 0)}catch(o){o instanceof Error?d.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,z.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,z.basename)(i),error:String(o)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Nr(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}async function fn(t,e){switch(t){case"init":{let r=Nr(e,"--config")??Ae;return lt(r),console.log(`Created sample config: ${N(r)}`),0}case"watch":{let r=Nr(e,"--config")??Ae,s;try{s=Ue(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))lt(r),console.log(`Created sample config: ${N(r)}`),s=Ue(r);else throw a}let i=N(s.stateFile??at),n=new Jt(s,i);await n.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{n.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let r=Nr(e,"--config")??Ae;try{Ue(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))lt(r),console.log(`Created sample config: ${N(r)}`),Ue(r);else throw s}return console.log(`Config OK: ${N(r)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ml=process.argv[2],Cl=process.argv.slice(3);fn(Ml,Cl).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
|