claude-mem 13.4.2 → 13.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +3 -3
- package/dist/npx-cli/index.js +359 -353
- package/dist/opencode-plugin/index.js +8 -8
- package/openclaw/dist/index.js +19 -14
- package/openclaw/openclaw.plugin.json +1 -1
- package/openclaw/src/index.test.ts +54 -0
- package/openclaw/src/index.ts +47 -3
- package/package.json +2 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/hooks/codex-hooks.json +7 -7
- package/plugin/hooks/hooks.json +7 -7
- package/plugin/package.json +1 -1
- package/plugin/scripts/context-generator.cjs +92 -79
- package/plugin/scripts/mcp-server.cjs +30 -30
- package/plugin/scripts/server-beta-service.cjs +125 -125
- package/plugin/scripts/transcript-watcher.cjs +11 -11
- package/plugin/scripts/worker-service.cjs +299 -273
- package/plugin/skills/standup/SKILL.md +1 -16
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var Xi=Object.create;var Ir=Object.defineProperty;var qi=Object.getOwnPropertyDescriptor;var Vi=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var tn=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Vi(t))!Zi.call(e,i)&&i!==r&&Ir(e,i,{get:()=>t[i],enumerable:!(s=qi(t,i))||s.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?Xi(Qi(e)):{},tn(t||!e||!e.__esModule?Ir(r,"default",{value:e,enumerable:!0}):r,e));var rt=require("fs"),Qe=require("os"),Nt=require("path");var _=require("path"),Ve=require("os"),Lt=require("fs");var xr=require("url");var et=require("fs"),Pr=require("path");var en=null;function Ye(e){return(en??process.stderr.write.bind(process.stderr))(e)}var ee=null;function Je(e){Ye(e)}function Dr(e,t={}){ee&&ee.length>0&&(Ye(ee.join("")),ee=[]),Ye(e.endsWith(`
|
|
3
3
|
`)?e:`${e}
|
|
4
|
-
`),t.skipExit||process.exit(2)}var
|
|
5
|
-
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let r=Object.keys(t);return r.length===0?"{}":r.length<=3?JSON.stringify(t):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,r){if(!r)return t;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(t==="Bash"&&s.command)return`${t}(${s.command})`;if(s.file_path)return`${t}(${s.file_path})`;if(s.notebook_path)return`${t}(${s.notebook_path})`;if(t==="Glob"&&s.pattern)return`${t}(${s.pattern})`;if(t==="Grep"&&s.pattern)return`${t}(${s.pattern})`;if(s.url)return`${t}(${s.url})`;if(s.query)return`${t}(${s.query})`;if(t==="Task"){if(s.subagent_type)return`${t}(${s.subagent_type})`;if(s.description)return`${t}(${s.description})`}return t==="Skill"&&s.skill?`${t}(${s.skill})`:t==="LSP"&&s.operation?`${t}(${s.operation})`:t}formatTimestamp(t){let r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),l=String(t.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(t,r,s,i,n){if(t<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=
|
|
4
|
+
`),t.skipExit||process.exit(2)}var Xe=(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))(Xe||{}),qe=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let t=k.logsDir();(0,et.existsSync)(t)||(0,et.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Pr.join)(t,`claude-mem-${r}.log`)}catch(t){console.error("[LOGGER] Failed to initialize log file:",t instanceof Error?t.message:String(t)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let t=k.settings();if((0,et.existsSync)(t)){let r=(0,et.readFileSync)(t,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Xe[i]??1}else this.level=1}catch(t){console.error("[LOGGER] Failed to load log level from settings:",t instanceof Error?t.message:String(t)),this.level=1}return this.level}correlationId(t,r){return`obs-${t}-${r}`}sessionId(t){return`session-${t}`}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message}
|
|
5
|
+
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let r=Object.keys(t);return r.length===0?"{}":r.length<=3?JSON.stringify(t):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,r){if(!r)return t;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(t==="Bash"&&s.command)return`${t}(${s.command})`;if(s.file_path)return`${t}(${s.file_path})`;if(s.notebook_path)return`${t}(${s.notebook_path})`;if(t==="Glob"&&s.pattern)return`${t}(${s.pattern})`;if(t==="Grep"&&s.pattern)return`${t}(${s.pattern})`;if(s.url)return`${t}(${s.url})`;if(s.query)return`${t}(${s.query})`;if(t==="Task"){if(s.subagent_type)return`${t}(${s.subagent_type})`;if(s.description)return`${t}(${s.description})`}return t==="Skill"&&s.skill?`${t}(${s.skill})`:t==="LSP"&&s.operation?`${t}(${s.operation})`:t}formatTimestamp(t){let r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),l=String(t.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(t,r,s,i,n){if(t<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=Xe[t].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let h="";if(n!=null)if(n instanceof Error)h=this.getLevel()===0?`
|
|
6
6
|
${n.message}
|
|
7
7
|
${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{h=`
|
|
8
8
|
`+JSON.stringify(n,null,2)}catch{h=" "+this.formatData(n)}else h=" "+this.formatData(n);let u="";if(i){let{sessionId:f,memorySessionId:m,correlationId:g,...w}=i;Object.keys(w).length>0&&(u=` {${Object.entries(w).map(([E,y])=>`${E}=${y}`).join(", ")}}`)}let p=`[${o}] [${a}] [${l}] ${c}${s}${u}${h}`;if(this.logFilePath)try{(0,et.appendFileSync)(this.logFilePath,p+`
|
|
9
|
-
`,"utf8")}catch(f){
|
|
10
|
-
`)}else
|
|
9
|
+
`,"utf8")}catch(f){Je(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
|
|
10
|
+
`)}else Je(p+`
|
|
11
11
|
`)}debug(t,r,s,i){this.log(0,t,r,s,i)}info(t,r,s,i){this.log(1,t,r,s,i)}warn(t,r,s,i){this.log(2,t,r,s,i)}error(t,r,s,i){this.log(3,t,r,s,i)}dataIn(t,r,s,i){this.info(t,`\u2192 ${r}`,s,i)}dataOut(t,r,s,i){this.info(t,`\u2190 ${r}`,s,i)}success(t,r,s,i){this.info(t,`\u2713 ${r}`,s,i)}failure(t,r,s,i){this.error(t,`\u2717 ${r}`,s,i)}timing(t,r,s,i){this.info(t,`\u23F1 ${r}`,i,{duration:`${s}ms`})}happyPathError(t,r,s,i,n=""){let c=((new Error().stack||"").split(`
|
|
12
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),h=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",u={...s,location:h};return this.warn(t,`[HAPPY-PATH] ${r}`,u,i),n}},d=new Je;var an={};function Vi(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Or.fileURLToPath)(an.url))}var Xa=Vi();function Qi(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let e=(0,_.join)((0,Xe.homedir)(),".claude-mem"),t=(0,_.join)(e,"settings.json");try{if((0,Lt.existsSync)(t)){let r=JSON.parse((0,Lt.readFileSync)(t,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return e}var v=Qi(),ee=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,Xe.homedir)(),".claude"),re=(0,_.join)(ee,"plugins","marketplaces","thedotmack"),Zi=(0,_.join)(v,"archives"),tn=(0,_.join)(v,"logs"),en=(0,_.join)(v,"trash"),rn=(0,_.join)(v,"backups"),sn=(0,_.join)(v,"modes"),se=(0,_.join)(v,"settings.json"),qa=(0,_.join)(v,"claude-mem.db"),nn=(0,_.join)(v,"vector-db"),ie=(0,_.join)(v,"observer-sessions"),on=(0,_.basename)(ie),Va=(0,_.join)(ee,"settings.json"),Qa=(0,_.join)(ee,"commands"),Za=(0,_.join)(ee,"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:()=>Zi,trash:()=>en,backups:()=>rn,modes:()=>sn,vectorDb:()=>nn,observerSessions:()=>ie};var At=k.transcriptsConfig(),oe=k.transcriptsState();var ln={version:1,schemas:{},watches:[],stateFile:oe};function F(e){return e&&(e.startsWith("~")?(0,ne.join)((0,Ir.homedir)(),e.slice(1)):e)}function Nt(e=At){let t=F(e);if(!(0,rt.existsSync)(t))throw new Error(`Transcript watch config not found: ${t}`);let r=(0,rt.readFileSync)(t,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${t}`);return s.stateFile||(s.stateFile=oe),s}function ae(e=At){let t=F(e),r=(0,ne.dirname)(t);(0,rt.existsSync)(r)||(0,rt.mkdirSync)(r,{recursive:!0}),(0,rt.writeFileSync)(t,JSON.stringify(ln,null,2))}var x=require("fs"),Y=require("path");var ps=require("node:url"),It=require("node:path"),Es=require("node:url"),q=require("fs"),mo=ct(require("node:fs"),1),pt=require("node:fs/promises"),be=require("node:events"),ar=ct(require("node:stream"),1),ws=require("node:string_decoder"),es=(e,t,r)=>{let s=e instanceof RegExp?Dr(e,r):e,i=t instanceof RegExp?Dr(t,r):t,n=s!==null&&i!=null&&cn(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)}},Dr=(e,t)=>{let r=t.match(e);return r?r[0]:null},cn=(e,t,r)=>{let s,i,n,o,a,l=r.indexOf(e),c=r.indexOf(t,l+1),h=l;if(l>=0&&c>0){if(e===t)return[l,c];for(s=[],n=r.length;h>=0&&!a;){if(h===l)s.push(h),l=r.indexOf(e,h+1);else if(s.length===1){let u=s.pop();u!==void 0&&(a=[u,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(t,h+1);h=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},rs="\0SLASH"+Math.random()+"\0",ss="\0OPEN"+Math.random()+"\0",nr="\0CLOSE"+Math.random()+"\0",is="\0COMMA"+Math.random()+"\0",ns="\0PERIOD"+Math.random()+"\0",hn=new RegExp(rs,"g"),un=new RegExp(ss,"g"),dn=new RegExp(nr,"g"),pn=new RegExp(is,"g"),fn=new RegExp(ns,"g"),mn=/\\\\/g,gn=/\\{/g,Sn=/\\}/g,En=/\\,/g,wn=/\\./g,yn=1e5;function qe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function _n(e){return e.replace(mn,rs).replace(gn,ss).replace(Sn,nr).replace(En,is).replace(wn,ns)}function bn(e){return e.replace(hn,"\\").replace(un,"{").replace(dn,"}").replace(pn,",").replace(fn,".")}function os(e){if(!e)return[""];let t=[],r=es("{","}",e);if(!r)return e.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=os(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function vn(e,t={}){if(!e)return[];let{max:r=yn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Bt(_n(e),r,!0).map(bn)}function Tn(e){return"{"+e+"}"}function Mn(e){return/^-?0\d/.test(e)}function Cn(e,t){return e<=t}function An(e,t){return e>=t}function Bt(e,t,r){let s=[],i=es("{","}",e);if(!i)return[e];let n=i.pre,o=i.post.length?Bt(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<t;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,h=i.body.indexOf(",")>=0;if(!c&&!h)return i.post.match(/,(?!,).*\}/)?(e=i.pre+"{"+i.body+nr+i.post,Bt(e,t,!0)):[e];let u;if(c)u=i.body.split(/\.\./);else if(u=os(i.body),u.length===1&&u[0]!==void 0&&(u=Bt(u[0],t,!1).map(Tn),u.length===1))return o.map(f=>i.pre+u[0]+f);let p;if(c&&u[0]!==void 0&&u[1]!==void 0){let f=qe(u[0]),m=qe(u[1]),g=Math.max(u[0].length,u[1].length),w=u.length===3&&u[2]!==void 0?Math.abs(qe(u[2])):1,S=Cn;m<f&&(w*=-1,S=An);let E=u.some(Mn);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 lt=new Array(T+1).join("0");y<0?b="-"+lt+b.slice(1):b=lt+b}}p.push(b)}}else{p=[];for(let f=0;f<u.length;f++)p.push.apply(p,Bt(u[f],t,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<t;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Ee=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Rn={"[: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]},Ut=e=>e.replace(/[[\]\\-]/g,"\\$&"),kn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Pr=e=>e.join(""),On=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,h=r,u="";t:for(;n<e.length;){let m=e.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){h=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(Rn))if(e.startsWith(g,n)){if(u)return["$.",!1,e.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue t}}if(l=!1,u){m>u?s.push(Ut(u)+"-"+Ut(m)):m===u&&s.push(Ut(m)),u="",n++;continue}if(e.startsWith("-]",n+1)){s.push(Ut(m+"-")),n+=2;continue}if(e.startsWith("-",n+1)){u=m,n+=2;continue}s.push(Ut(m)),n++}if(h<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,e.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[kn(m),!1,h-r,!1]}let p="["+(c?"^":"")+Pr(s)+"]",f="["+(c?"":"^")+Pr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,h-r,!0]},Ot=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),In=new Set(["!","?","+","*","@"]),xr=e=>In.has(e),Dn="(?!(?:^|/)\\.\\.?(?:$|/))",le="(?!\\.)",Pn=new Set(["[","."]),xn=new Set(["..","."]),Ln=new Set("().*{}+?[]^$\\!"),Nn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),or="[^/]",Lr=or+"*?",Nr=or+"+?",as=class U{type;#t;#r;#n=!1;#i=[];#o;#y;#S;#h=!1;#a;#d;#u=!1;constructor(t,r,s={}){this.type=t,t&&(this.#r=!0),this.#o=r,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?s:this.#t.#a,this.#S=this.#t===this?[]:this.#t.#S,t==="!"&&!this.#t.#h&&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 t of this.#i)if(typeof t!="string"&&(t.type||t.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(t=>String(t)).join("|")+")":this.#d=this.#i.map(t=>String(t)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#h)return this;this.toString(),this.#h=!0;let t;for(;t=this.#S.pop();){if(t.type!=="!")continue;let r=t,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of t.#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(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof U&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let t=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&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#h&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let t=this.#o;for(let r=0;r<this.#y;r++){let s=t.#i[r];if(!(s instanceof U&&s.type==="!"))return!1}return!0}isEnd(){if(this.#t===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#i.length:0;return this.#y===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new U(this.type,t);for(let s of this.#i)r.copyIn(s);return r}static#s(t,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<t.length;){let g=t.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&&xr(g)&&t.charAt(f)==="("){r.push(m),m="";let w=new U(g,r);f=U.#s(t,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,h=new U(null,r),u=[],p="";for(;c<t.length;){let f=t.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(xr(f)&&t.charAt(c)==="("){h.push(p),p="";let m=new U(f,h);h.push(m),c=U.#s(t,m,c,i);continue}if(f==="|"){h.push(p),p="",u.push(h),h=new U(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#u=!0),h.push(p),p="",r.push(...u,h),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[t.substring(s-1)],c}static fromGlob(t,r={}){let s=new U(null,void 0,r);return U.#s(t,s,0,r),s}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let t=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#t===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"?U.#_(p,this.#r,l):p.toRegExpSource(t);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),h="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&xn.has(this.#i[0]))){let p=Pn,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!t&&p.has(c.charAt(0));h=f?Dn:m?le:""}let u="";return this.isEnd()&&this.#t.#h&&this.#o?.type==="!"&&(u="(?:$|\\/)"),[h+c+u,Ot(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,Ot(this.toString()),!1,!1]}let o=!s||t||r||!le?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#u)a=(this.isStart()&&!r?le:"")+Nr;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?le:"")+Lr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Ot(n),this.#r=!!this.#r,this.#n]}#p(t){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(t,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,n+=(Ln.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(t)?Nr:Lr,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[h,u,p,f]=On(t,l);if(p){n+=h,o=o||u,l+=p-1,r=r||f;continue}}if(c==="?"){n+=or,r=!0;continue}n+=Nn(c)}return[n,Ot(t),!!r,o]}},ls=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),P=(e,t,r={})=>(Ee(t),!r.nocomment&&t.charAt(0)==="#"?!1:new dt(t,r).match(e)),Un=/^\*+([^+@!?\*\[\(]*)$/,Fn=e=>t=>!t.startsWith(".")&&t.endsWith(e),Wn=e=>t=>t.endsWith(e),$n=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),jn=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Hn=/^\*+\.\*+$/,Bn=e=>!e.startsWith(".")&&e.includes("."),Gn=e=>e!=="."&&e!==".."&&e.includes("."),Kn=/^\.\*+$/,zn=e=>e!=="."&&e!==".."&&e.startsWith("."),Yn=/^\*+$/,Jn=e=>e.length!==0&&!e.startsWith("."),Xn=e=>e.length!==0&&e!=="."&&e!=="..",qn=/^\?+([^+@!?\*\[\(]*)?$/,Vn=([e,t=""])=>{let r=cs([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},Qn=([e,t=""])=>{let r=hs([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},Zn=([e,t=""])=>{let r=hs([e]);return t?s=>r(s)&&s.endsWith(t):r},to=([e,t=""])=>{let r=cs([e]);return t?s=>r(s)&&s.endsWith(t):r},cs=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},hs=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},us=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ur={win32:{sep:"\\"},posix:{sep:"/"}},eo=us==="win32"?Ur.win32.sep:Ur.posix.sep;P.sep=eo;var D=Symbol("globstar **");P.GLOBSTAR=D;var ro="[^/]",so=ro+"*?",io="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",no="(?:(?!(?:\\/|^)\\.).)*?",oo=(e,t={})=>r=>P(r,e,t);P.filter=oo;var W=(e,t={})=>Object.assign({},e,t),ao=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return P;let t=P;return Object.assign((r,s,i={})=>t(r,s,W(e,i)),{Minimatch:class extends t.Minimatch{constructor(r,s={}){super(r,W(e,s))}static defaults(r){return t.defaults(W(e,r)).Minimatch}},AST:class extends t.AST{constructor(r,s,i={}){super(r,s,W(e,i))}static fromGlob(r,s={}){return t.AST.fromGlob(r,W(e,s))}},unescape:(r,s={})=>t.unescape(r,W(e,s)),escape:(r,s={})=>t.escape(r,W(e,s)),filter:(r,s={})=>t.filter(r,W(e,s)),defaults:r=>t.defaults(W(e,r)),makeRe:(r,s={})=>t.makeRe(r,W(e,s)),braceExpand:(r,s={})=>t.braceExpand(r,W(e,s)),match:(r,s,i={})=>t.match(r,s,W(e,i)),sep:t.sep,GLOBSTAR:D})};P.defaults=ao;var ds=(e,t={})=>(Ee(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:vn(e,{max:t.braceExpandMax}));P.braceExpand=ds;var lo=(e,t={})=>new dt(e,t).makeRe();P.makeRe=lo;var co=(e,t,r={})=>{let s=new dt(t,r);return e=e.filter(i=>s.match(i)),s.options.nonull&&!e.length&&e.push(t),e};P.match=co;var Fr=/[?*]|[+@!]\(.*?\)|\[|\]/,ho=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),dt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Ee(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||us,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.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]==="?"||!Fr.test(i[2]))&&!Fr.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(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.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)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){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;t=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",e.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==="")&&(t=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,i=0,n=[],o="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])n.push(o==="b"?t[i]:e[s]),s++,i++;else if(r&&e[s]==="**"&&t[i]===e[s+1])n.push(e[s]),s++;else if(r&&t[i]==="**"&&e[s]===t[i+1])n.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(o==="b")return!1;o="a",n.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return!1;o="b",n.push(t[i]),s++,i++}else return!1;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=this.options;if(this.isWindows){let m=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!m&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),w=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!w&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[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]=[e[E],t[y]];b.toLowerCase()===T.toLowerCase()&&(t[y]=b,y>E?t=t.slice(y):E>y&&(e=e.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=t[o],h=e[n];if(this.debug(t,c,h),c===!1)return!1;if(c===D){this.debug("GLOBSTAR",[t,c,h]);var u=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return!1;return!0}for(;u<a;){var f=e[u];if(this.debug(`
|
|
12
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),h=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",u={...s,location:h};return this.warn(t,`[HAPPY-PATH] ${r}`,u,i),n}},d=new qe;var dn={};function rn(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,xr.fileURLToPath)(dn.url))}var il=rn();function sn(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let e=(0,_.join)((0,Ve.homedir)(),".claude-mem"),t=(0,_.join)(e,"settings.json");try{if((0,Lt.existsSync)(t)){let r=JSON.parse((0,Lt.readFileSync)(t,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return e}var v=sn(),re=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,Ve.homedir)(),".claude"),se=(0,_.join)(re,"plugins","marketplaces","thedotmack"),nn=(0,_.join)(v,"archives"),on=(0,_.join)(v,"logs"),an=(0,_.join)(v,"trash"),ln=(0,_.join)(v,"backups"),cn=(0,_.join)(v,"modes"),ie=(0,_.join)(v,"settings.json"),nl=(0,_.join)(v,"claude-mem.db"),hn=(0,_.join)(v,"vector-db"),ne=(0,_.join)(v,"observer-sessions"),un=(0,_.basename)(ne),ol=(0,_.join)(re,"settings.json"),al=(0,_.join)(re,"commands"),ll=(0,_.join)(re,"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:()=>on,archives:()=>nn,trash:()=>an,backups:()=>ln,modes:()=>cn,vectorDb:()=>hn,observerSessions:()=>ne};var At=k.transcriptsConfig(),oe=k.transcriptsState();var pn={version:1,schemas:{},watches:[],stateFile:oe};function fn(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name;if(!(e.name==="codex"||t==="codex")||!e.path)return!1;let s=N(e.path).replace(/\\/g,"/"),i=(0,Nt.join)((0,Qe.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function Lr(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name,r=e.name==="codex"&&(!t||t==="codex");return e.context?.mode==="agents"&&r&&fn(e)}function N(e){return e&&(e.startsWith("~")?(0,Nt.join)((0,Qe.homedir)(),e.slice(1)):e)}function Ut(e=At){let t=N(e);if(!(0,rt.existsSync)(t))throw new Error(`Transcript watch config not found: ${t}`);let r=(0,rt.readFileSync)(t,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${t}`);return s.stateFile||(s.stateFile=oe),s}function ae(e=At){let t=N(e),r=(0,Nt.dirname)(t);(0,rt.existsSync)(r)||(0,rt.mkdirSync)(r,{recursive:!0}),(0,rt.writeFileSync)(t,JSON.stringify(pn,null,2))}var x=require("fs"),Y=require("path");var Ss=require("node:url"),It=require("node:path"),bs=require("node:url"),q=require("fs"),_o=ht(require("node:fs"),1),ft=require("node:fs/promises"),be=require("node:events"),hr=ht(require("node:stream"),1),vs=require("node:string_decoder"),ns=(e,t,r)=>{let s=e instanceof RegExp?Nr(e,r):e,i=t instanceof RegExp?Nr(t,r):t,n=s!==null&&i!=null&&mn(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)}},Nr=(e,t)=>{let r=t.match(e);return r?r[0]:null},mn=(e,t,r)=>{let s,i,n,o,a,l=r.indexOf(e),c=r.indexOf(t,l+1),h=l;if(l>=0&&c>0){if(e===t)return[l,c];for(s=[],n=r.length;h>=0&&!a;){if(h===l)s.push(h),l=r.indexOf(e,h+1);else if(s.length===1){let u=s.pop();u!==void 0&&(a=[u,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(t,h+1);h=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},os="\0SLASH"+Math.random()+"\0",as="\0OPEN"+Math.random()+"\0",lr="\0CLOSE"+Math.random()+"\0",ls="\0COMMA"+Math.random()+"\0",cs="\0PERIOD"+Math.random()+"\0",gn=new RegExp(os,"g"),Sn=new RegExp(as,"g"),En=new RegExp(lr,"g"),wn=new RegExp(ls,"g"),yn=new RegExp(cs,"g"),_n=/\\\\/g,bn=/\\{/g,vn=/\\}/g,Tn=/\\,/g,Mn=/\\./g,Cn=1e5;function Ze(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function An(e){return e.replace(_n,os).replace(bn,as).replace(vn,lr).replace(Tn,ls).replace(Mn,cs)}function Rn(e){return e.replace(gn,"\\").replace(Sn,"{").replace(En,"}").replace(wn,",").replace(yn,".")}function hs(e){if(!e)return[""];let t=[],r=ns("{","}",e);if(!r)return e.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=hs(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function kn(e,t={}){if(!e)return[];let{max:r=Cn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Gt(An(e),r,!0).map(Rn)}function On(e){return"{"+e+"}"}function In(e){return/^-?0\d/.test(e)}function Dn(e,t){return e<=t}function Pn(e,t){return e>=t}function Gt(e,t,r){let s=[],i=ns("{","}",e);if(!i)return[e];let n=i.pre,o=i.post.length?Gt(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<t;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,h=i.body.indexOf(",")>=0;if(!c&&!h)return i.post.match(/,(?!,).*\}/)?(e=i.pre+"{"+i.body+lr+i.post,Gt(e,t,!0)):[e];let u;if(c)u=i.body.split(/\.\./);else if(u=hs(i.body),u.length===1&&u[0]!==void 0&&(u=Gt(u[0],t,!1).map(On),u.length===1))return o.map(f=>i.pre+u[0]+f);let p;if(c&&u[0]!==void 0&&u[1]!==void 0){let f=Ze(u[0]),m=Ze(u[1]),g=Math.max(u[0].length,u[1].length),w=u.length===3&&u[2]!==void 0?Math.abs(Ze(u[2])):1,S=Dn;m<f&&(w*=-1,S=Pn);let E=u.some(In);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 ct=new Array(T+1).join("0");y<0?b="-"+ct+b.slice(1):b=ct+b}}p.push(b)}}else{p=[];for(let f=0;f<u.length;f++)p.push.apply(p,Gt(u[f],t,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<t;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Ee=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},xn={"[: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]},Ft=e=>e.replace(/[[\]\\-]/g,"\\$&"),Ln=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ur=e=>e.join(""),Nn=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,h=r,u="";t:for(;n<e.length;){let m=e.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){h=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(xn))if(e.startsWith(g,n)){if(u)return["$.",!1,e.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue t}}if(l=!1,u){m>u?s.push(Ft(u)+"-"+Ft(m)):m===u&&s.push(Ft(m)),u="",n++;continue}if(e.startsWith("-]",n+1)){s.push(Ft(m+"-")),n+=2;continue}if(e.startsWith("-",n+1)){u=m,n+=2;continue}s.push(Ft(m)),n++}if(h<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,e.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[Ln(m),!1,h-r,!1]}let p="["+(c?"^":"")+Ur(s)+"]",f="["+(c?"":"^")+Ur(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,h-r,!0]},Ot=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),Un=new Set(["!","?","+","*","@"]),Fr=e=>Un.has(e),Fn="(?!(?:^|/)\\.\\.?(?:$|/))",le="(?!\\.)",Wn=new Set(["[","."]),$n=new Set(["..","."]),jn=new Set("().*{}+?[]^$\\!"),Hn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),cr="[^/]",Wr=cr+"*?",$r=cr+"+?",us=class F{type;#t;#r;#n=!1;#i=[];#o;#y;#S;#h=!1;#a;#d;#u=!1;constructor(t,r,s={}){this.type=t,t&&(this.#r=!0),this.#o=r,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?s:this.#t.#a,this.#S=this.#t===this?[]:this.#t.#S,t==="!"&&!this.#t.#h&&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 t of this.#i)if(typeof t!="string"&&(t.type||t.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(t=>String(t)).join("|")+")":this.#d=this.#i.map(t=>String(t)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#h)return this;this.toString(),this.#h=!0;let t;for(;t=this.#S.pop();){if(t.type!=="!")continue;let r=t,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of t.#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(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let t=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&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#h&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let t=this.#o;for(let r=0;r<this.#y;r++){let s=t.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#t===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#i.length:0;return this.#y===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new F(this.type,t);for(let s of this.#i)r.copyIn(s);return r}static#s(t,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<t.length;){let g=t.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&&Fr(g)&&t.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(t,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,h=new F(null,r),u=[],p="";for(;c<t.length;){let f=t.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(Fr(f)&&t.charAt(c)==="("){h.push(p),p="";let m=new F(f,h);h.push(m),c=F.#s(t,m,c,i);continue}if(f==="|"){h.push(p),p="",u.push(h),h=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#u=!0),h.push(p),p="",r.push(...u,h),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[t.substring(s-1)],c}static fromGlob(t,r={}){let s=new F(null,void 0,r);return F.#s(t,s,0,r),s}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let t=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#t===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(t);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),h="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&$n.has(this.#i[0]))){let p=Wn,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!t&&p.has(c.charAt(0));h=f?Fn:m?le:""}let u="";return this.isEnd()&&this.#t.#h&&this.#o?.type==="!"&&(u="(?:$|\\/)"),[h+c+u,Ot(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,Ot(this.toString()),!1,!1]}let o=!s||t||r||!le?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#u)a=(this.isStart()&&!r?le:"")+$r;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?le:"")+Wr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Ot(n),this.#r=!!this.#r,this.#n]}#p(t){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(t,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,n+=(jn.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(t)?$r:Wr,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[h,u,p,f]=Nn(t,l);if(p){n+=h,o=o||u,l+=p-1,r=r||f;continue}}if(c==="?"){n+=cr,r=!0;continue}n+=Hn(c)}return[n,Ot(t),!!r,o]}},ds=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),P=(e,t,r={})=>(Ee(t),!r.nocomment&&t.charAt(0)==="#"?!1:new pt(t,r).match(e)),Bn=/^\*+([^+@!?\*\[\(]*)$/,Gn=e=>t=>!t.startsWith(".")&&t.endsWith(e),Kn=e=>t=>t.endsWith(e),zn=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Yn=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Jn=/^\*+\.\*+$/,Xn=e=>!e.startsWith(".")&&e.includes("."),qn=e=>e!=="."&&e!==".."&&e.includes("."),Vn=/^\.\*+$/,Qn=e=>e!=="."&&e!==".."&&e.startsWith("."),Zn=/^\*+$/,to=e=>e.length!==0&&!e.startsWith("."),eo=e=>e.length!==0&&e!=="."&&e!=="..",ro=/^\?+([^+@!?\*\[\(]*)?$/,so=([e,t=""])=>{let r=ps([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},io=([e,t=""])=>{let r=fs([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},no=([e,t=""])=>{let r=fs([e]);return t?s=>r(s)&&s.endsWith(t):r},oo=([e,t=""])=>{let r=ps([e]);return t?s=>r(s)&&s.endsWith(t):r},ps=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},fs=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},ms=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",jr={win32:{sep:"\\"},posix:{sep:"/"}},ao=ms==="win32"?jr.win32.sep:jr.posix.sep;P.sep=ao;var D=Symbol("globstar **");P.GLOBSTAR=D;var lo="[^/]",co=lo+"*?",ho="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",uo="(?:(?!(?:\\/|^)\\.).)*?",po=(e,t={})=>r=>P(r,e,t);P.filter=po;var $=(e,t={})=>Object.assign({},e,t),fo=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return P;let t=P;return Object.assign((r,s,i={})=>t(r,s,$(e,i)),{Minimatch:class extends t.Minimatch{constructor(r,s={}){super(r,$(e,s))}static defaults(r){return t.defaults($(e,r)).Minimatch}},AST:class extends t.AST{constructor(r,s,i={}){super(r,s,$(e,i))}static fromGlob(r,s={}){return t.AST.fromGlob(r,$(e,s))}},unescape:(r,s={})=>t.unescape(r,$(e,s)),escape:(r,s={})=>t.escape(r,$(e,s)),filter:(r,s={})=>t.filter(r,$(e,s)),defaults:r=>t.defaults($(e,r)),makeRe:(r,s={})=>t.makeRe(r,$(e,s)),braceExpand:(r,s={})=>t.braceExpand(r,$(e,s)),match:(r,s,i={})=>t.match(r,s,$(e,i)),sep:t.sep,GLOBSTAR:D})};P.defaults=fo;var gs=(e,t={})=>(Ee(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:kn(e,{max:t.braceExpandMax}));P.braceExpand=gs;var mo=(e,t={})=>new pt(e,t).makeRe();P.makeRe=mo;var go=(e,t,r={})=>{let s=new pt(t,r);return e=e.filter(i=>s.match(i)),s.options.nonull&&!e.length&&e.push(t),e};P.match=go;var Hr=/[?*]|[+@!]\(.*?\)|\[|\]/,So=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Ee(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||ms,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.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]==="?"||!Hr.test(i[2]))&&!Hr.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(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.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)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){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;t=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",e.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==="")&&(t=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,i=0,n=[],o="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])n.push(o==="b"?t[i]:e[s]),s++,i++;else if(r&&e[s]==="**"&&t[i]===e[s+1])n.push(e[s]),s++;else if(r&&t[i]==="**"&&e[s]===t[i+1])n.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(o==="b")return!1;o="a",n.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return!1;o="b",n.push(t[i]),s++,i++}else return!1;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=this.options;if(this.isWindows){let m=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!m&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),w=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!w&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[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]=[e[E],t[y]];b.toLowerCase()===T.toLowerCase()&&(t[y]=b,y>E?t=t.slice(y):E>y&&(e=e.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=t[o],h=e[n];if(this.debug(t,c,h),c===!1)return!1;if(c===D){this.debug("GLOBSTAR",[t,c,h]);var u=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return!1;return!0}for(;u<a;){var f=e[u];if(this.debug(`
|
|
13
13
|
globstar while`,e,u,t,p,f),this.matchOne(e.slice(u),t.slice(p),r))return this.debug("globstar found match!",u,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",e,u,t,p);break}this.debug("globstar swallow a segment, and continue"),u++}return!!(r&&(this.debug(`
|
|
14
|
-
>>> no match, partial?`,e,u,t,p),u===a))}let m;if(typeof c=="string"?(m=h===c,this.debug("string match",c,h,m)):(m=c.test(h),this.debug("pattern match",c,h,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return ds(this.pattern,this.options)}parse(e){Ee(e);let t=this.options;if(e==="**")return D;if(e==="")return"";let r,s=null;(r=e.match(Yn))?s=t.dot?Xn:Jn:(r=e.match(Un))?s=(t.nocase?t.dot?jn:$n:t.dot?Wn:Fn)(r[1]):(r=e.match(qn))?s=(t.nocase?t.dot?Qn:Vn:t.dot?Zn:to)(r):(r=e.match(Hn))?s=t.dot?Gn:Bn:(r=e.match(Kn))&&(s=zn);let i=as.fromGlob(e,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 e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?so:t.dot?io:no,s=new Set(t.nocase?["i"]:[]),i=e.map(a=>{let l=a.map(h=>{if(h instanceof RegExp)for(let u of h.flags.split(""))s.add(u);return typeof h=="string"?ho(h):h===D?D:h._src});l.forEach((h,u)=>{let p=l[u+1],f=l[u-1];h!==D||f===D||(f===void 0?p!==void 0&&p!==D?l[u+1]="(?:\\/|"+r+"\\/)?"+p:l[u]=r:p===void 0?l[u-1]=f+"(?:\\/|\\/"+r+")?":p!==D&&(l[u-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[u+1]=D))});let c=l.filter(h=>h!==D);if(this.partial&&c.length>=1){let h=[];for(let u=1;u<=c.length;u++)h.push(c.slice(0,u).join("/"));return"(?:"+h.join("|")+")"}return c.join("/")}).join("|"),[n,o]=e.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(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);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,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return P.defaults(e).Minimatch}};P.AST=as;P.Minimatch=dt;P.escape=ls;P.unescape=Ot;var uo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,fs=new Set,ir=typeof process=="object"&&process?process:{},ms=(e,t,r,s)=>{typeof ir.emitWarning=="function"?ir.emitWarning(e,t,r,s):console.error(`[${r}] ${t}: ${e}`)},we=globalThis.AbortController,Wr=globalThis.AbortSignal;if(typeof we>"u"){Wr=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},we=class{constructor(){t()}signal=new Wr;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 e=ir.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!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",t))}}var po=e=>!fs.has(e),ut=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),gs=e=>ut(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ge:null:null,ge=class extends Array{constructor(e){super(e),this.fill(0)}},fo=class Gt{heap;length;static#t=!1;static create(t){let r=gs(t);if(!r)return[];Gt.#t=!0;let s=new Gt(t,r);return Gt.#t=!1,s}constructor(t,r){if(!Gt.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},_e=class Ss{#t;#r;#n;#i;#o;#y;#S;#h;get perf(){return this.#h}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#u;#l;#s;#p;#_;#w;#f;#R;#m;#T;#M;#g;#E;#b;#C;#e;#x;static unsafeExposeInternals(t){return{starts:t.#M,ttls:t.#g,autopurgeTimers:t.#E,sizes:t.#T,keyMap:t.#u,keyList:t.#l,valList:t.#s,next:t.#p,prev:t.#_,get head(){return t.#w},get tail(){return t.#f},free:t.#R,isBackgroundFetch:r=>t.#c(r),backgroundFetch:(r,s,i,n)=>t.#H(r,s,i,n),moveToTail:r=>t.#N(r),indexes:r=>t.#O(r),rindexes:r=>t.#I(r),isStale:r=>t.#v(r)}}get max(){return this.#t}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(t){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:h,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:lt,ignoreFetchAbort:Tt,perf:Mt}=t;if(Mt!==void 0&&typeof Mt?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#h=Mt??uo,r!==0&&!ut(r))throw new TypeError("max option must be a nonnegative integer");let Ct=r?gs(r):Array;if(!Ct)throw new Error("invalid max value: "+r);if(this.#t=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.#u=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Ct(r),this.#_=new Ct(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 h=="function"&&(this.#i=h),typeof u=="function"?(this.#o=u,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#e=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!lt,this.ignoreFetchAbort=!!Tt,this.maxEntrySize!==0){if(this.#r!==0&&!ut(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!ut(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=ut(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!ut(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let Ge="LRU_CACHE_UNBOUNDED";po(Ge)&&(fs.add(Ge),ms("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Ge,Ss))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#D(){let t=new ge(this.#t),r=new ge(this.#t);this.#g=t,this.#M=r;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=s,this.#F=(o,a,l=this.#h.now())=>{if(r[o]=a!==0?l:0,t[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]=t[o]!==0?this.#h.now():0},this.#P=(o,a)=>{if(t[a]){let l=t[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let h=o.now-c;o.remainingTTL=l-h}};let i=0,n=()=>{let o=this.#h.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.#u.get(o);if(a===void 0)return 0;let l=t[a],c=r[a];if(!l||!c)return 1/0;let h=(i||n())-c;return l-h},this.#v=o=>{let a=r[o],l=t[o];return!!l&&!!a&&(i||n())-a>l}}#A=()=>{};#P=()=>{};#F=()=>{};#v=()=>!1;#G(){let t=new ge(this.#t);this.#d=0,this.#T=t,this.#U=r=>{this.#d-=t[r],t[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!ut(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!ut(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(t[r]=s,this.#r){let n=this.#r-t[r];for(;this.#d>n;)this.#j(!0)}this.#d+=t[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=t=>{};#L=(t,r,s)=>{};#W=(t,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((t||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#I({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((t||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(t){return t!==void 0&&this.#u.get(this.#l[t])===t}*entries(){for(let t of this.#O())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*rentries(){for(let t of this.#I())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*keys(){for(let t of this.#O()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*rkeys(){for(let t of this.#I()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*values(){for(let t of this.#O())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#I())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(t,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}rforEach(t,r=this){for(let s of this.#I()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}purgeStale(){let t=!1;for(let r of this.#I({allowStale:!0}))this.#v(r)&&(this.#k(this.#l[r],"expire"),t=!0);return t}info(t){let r=this.#u.get(t);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.#h.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let t=[];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.#h.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),t.unshift([s,o])}return t}load(t){this.clear();for(let[r,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#h.now()-i}this.set(r,s.value,s)}}set(t,r,s={}){if(r===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,h=this.#W(t,r,s.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#k(t,"set"),this;let u=this.#a===0?void 0:this.#u.get(t);if(u===void 0)u=this.#a===0?this.#f:this.#R.length!==0?this.#R.pop():this.#a===this.#t?this.#j(!1):this.#a,this.#l[u]=t,this.#s[u]=r,this.#u.set(t,u),this.#p[this.#f]=u,this.#_[u]=this.#f,this.#f=u,this.#a++,this.#L(u,h,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,t,"add");else{this.#N(u);let p=this.#s[u];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,t,"set"),this.#e&&this.#m?.push([f,t,"set"]))}else o||(this.#b&&this.#n?.(p,t,"set"),this.#e&&this.#m?.push([p,t,"set"]));if(this.#U(u),this.#L(u,h,l),this.#s[u]=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,t,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#D(),this.#g&&(c||this.#F(u,i,n),l&&this.#P(l,u)),!o&&this.#e&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let t=this.#s[this.#w];if(this.#j(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,r;for(;r=t?.shift();)this.#o?.(...r)}}}#j(t){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.#e)&&(this.#b&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),t&&(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.#u.delete(s),this.#a--,r}has(t,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#u.get(t);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(t,r={}){let{allowStale:s=this.allowStale}=r,i=this.#u.get(t);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#H(t,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new we,{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 u(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(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,g,l.options))),g},h=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),u(g,!1)),u=(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(t,"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?.(t,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,h),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(t,m,{...l.options,status:void 0}),r=this.#u.get(t)):this.#s[r]=m,m}#c(t){if(!this.#C)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof we}async fetch(t,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:h=this.noUpdateTTL,noDeleteOnFetchRejection:u=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(t,{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:h,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#u.get(t);if(b===void 0){S&&(S.fetch="miss");let T=this.#H(t,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Ct=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Ct&&(S.returnedStale=!0)),Ct?T.__staleWhileFetching:T.__returned=T}let lt=this.#v(b);if(!w&&!lt)return S&&(S.fetch="hit"),this.#N(b),i&&this.#A(b),S&&this.#P(S,b),T;let Tt=this.#H(t,b,y,g),Mt=Tt.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=lt?"stale":"refresh",Mt&<&&(S.returnedStale=!0)),Mt?Tt.__staleWhileFetching:Tt.__returned=Tt}}async forceFetch(t,r={}){let s=await this.fetch(t,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,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(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:i});return this.set(t,l,o),l}get(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#u.get(t);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(t,"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(t,r){this.#_[r]=t,this.#p[t]=r}#N(t){t!==this.#f&&(t===this.#w?this.#w=this.#p[t]:this.#B(this.#_[t],this.#p[t]),this.#B(this.#f,t),this.#f=t)}delete(t){return this.#k(t,"delete")}#k(t,r){let s=!1;if(this.#a!==0){let i=this.#u.get(t);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.#e)&&(this.#b&&this.#n?.(n,t,r),this.#e&&this.#m?.push([n,t,r])),this.#u.delete(t),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.#e&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(t){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,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.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.#e&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},$r=typeof process=="object"&&process?process:{stdout:null,stderr:null},go=e=>!!e&&typeof e=="object"&&(e instanceof ye||e instanceof ar.default||So(e)||Eo(e)),So=e=>!!e&&typeof e=="object"&&e instanceof be.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==ar.default.Writable.prototype.pipe,Eo=e=>!!e&&typeof e=="object"&&e instanceof be.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",st=Symbol("EOF"),it=Symbol("maybeEmitEnd"),ht=Symbol("emittedEnd"),ce=Symbol("emittingEnd"),Ft=Symbol("emittedError"),he=Symbol("closed"),jr=Symbol("read"),ue=Symbol("flush"),Hr=Symbol("flushChunk"),G=Symbol("encoding"),Rt=Symbol("decoder"),C=Symbol("flowing"),Wt=Symbol("paused"),kt=Symbol("resume"),A=Symbol("buffer"),I=Symbol("pipes"),R=Symbol("bufferLength"),Ve=Symbol("bufferPush"),de=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),Qe=Symbol("error"),Ze=Symbol("emitData"),Br=Symbol("emitEnd"),tr=Symbol("emitEnd2"),J=Symbol("async"),er=Symbol("abort"),pe=Symbol("aborted"),$t=Symbol("signal"),St=Symbol("dataListeners"),N=Symbol("discarded"),jt=e=>Promise.resolve().then(e),wo=e=>e(),yo=e=>e==="end"||e==="finish"||e==="prefinish",_o=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,bo=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),ys=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[kt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},vo=class extends ys{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors)}},To=e=>!!e.objectMode,Mo=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",ye=class extends be.EventEmitter{[C]=!1;[Wt]=!1;[I]=[];[A]=[];[O];[G];[J];[Rt];[st]=!1;[ht]=!1;[ce]=!1;[he]=!1;[Ft]=null;[R]=0;[M]=!1;[$t];[pe]=!1;[St]=0;[N]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");To(t)?(this[O]=!0,this[G]=null):Mo(t)?(this[G]=t.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[J]=!!t.async,this[Rt]=this[G]?new ws.StringDecoder(this[G]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:r}=t;r&&(this[$t]=r,r.aborted?this[er]():r.addEventListener("abort",()=>this[er]()))}get bufferLength(){return this[R]}get encoding(){return this[G]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[J]}set async(e){this[J]=this[J]||!!e}[er](){this[pe]=!0,this.emit("abort",this[$t]?.reason),this.destroy(this[$t]?.reason)}get aborted(){return this[pe]}set aborted(e){}write(e,t,r){if(this[pe])return!1;if(this[st])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 t=="function"&&(r=t,t="utf8"),t||(t="utf8");let s=this[J]?jt:wo;if(!this[O]&&!Buffer.isBuffer(e)){if(bo(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(_o(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[C]&&this[R]!==0&&this[ue](!0),this[C]?this.emit("data",e):this[Ve](e),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):e.length?(typeof e=="string"&&!(t===this[G]&&!this[Rt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[G]&&(e=this[Rt].write(e)),this[C]&&this[R]!==0&&this[ue](!0),this[C]?this.emit("data",e):this[Ve](e),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):(this[R]!==0&&this.emit("readable"),r&&s(r),this[C])}read(e){if(this[M])return null;if(this[N]=!1,this[R]===0||e===0||e&&e>this[R])return this[it](),null;this[O]&&(e=null),this[A].length>1&&!this[O]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[R])]);let t=this[jr](e||null,this[A][0]);return this[it](),t}[jr](e,t){if(this[O])this[de]();else{let r=t;e===r.length||e===null?this[de]():typeof r=="string"?(this[A][0]=r.slice(e),t=r.slice(0,e),this[R]-=e):(this[A][0]=r.subarray(e),t=r.subarray(0,e),this[R]-=e)}return this.emit("data",t),!this[A].length&&!this[st]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[st]=!0,this.writable=!1,(this[C]||!this[Wt])&&this[it](),this}[kt](){this[M]||(!this[St]&&!this[I].length&&(this[N]=!0),this[Wt]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[ue]():this[st]?this[it]():this.emit("drain"))}resume(){return this[kt]()}pause(){this[C]=!1,this[Wt]=!0,this[N]=!1}get destroyed(){return this[M]}get flowing(){return this[C]}get paused(){return this[Wt]}[Ve](e){this[O]?this[R]+=1:this[R]+=e.length,this[A].push(e)}[de](){return this[O]?this[R]-=1:this[R]-=this[A][0].length,this[A].shift()}[ue](e=!1){do;while(this[Hr](this[de]())&&this[A].length);!e&&!this[A].length&&!this[st]&&this.emit("drain")}[Hr](e){return this.emit("data",e),this[C]}pipe(e,t){if(this[M])return e;this[N]=!1;let r=this[ht];return t=t||{},e===$r.stdout||e===$r.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[I].push(t.proxyErrors?new vo(this,e,t):new ys(this,e,t)),this[J]?jt(()=>this[kt]()):this[kt]()),e}unpipe(e){let t=this[I].find(r=>r.dest===e);t&&(this[I].length===1?(this[C]&&this[St]===0&&(this[C]=!1),this[I]=[]):this[I].splice(this[I].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[N]=!1,this[St]++,!this[I].length&&!this[C]&&this[kt]();else if(e==="readable"&&this[R]!==0)super.emit("readable");else if(yo(e)&&this[ht])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Ft]){let s=t;this[J]?jt(()=>s.call(this,this[Ft])):s.call(this,this[Ft])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[St]=this.listeners("data").length,this[St]===0&&!this[N]&&!this[I].length&&(this[C]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[St]=0,!this[N]&&!this[I].length&&(this[C]=!1)),t}get emittedEnd(){return this[ht]}[it](){!this[ce]&&!this[ht]&&!this[M]&&this[A].length===0&&this[st]&&(this[ce]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[he]&&this.emit("close"),this[ce]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==M&&this[M])return!1;if(e==="data")return!this[O]&&!r?!1:this[J]?(jt(()=>this[Ze](r)),!0):this[Ze](r);if(e==="end")return this[Br]();if(e==="close"){if(this[he]=!0,!this[ht]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Ft]=r,super.emit(Qe,r);let i=!this[$t]||this.listeners("error").length?super.emit("error",r):!1;return this[it](),i}else if(e==="resume"){let i=super.emit("resume");return this[it](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let s=super.emit(e,...t);return this[it](),s}[Ze](e){for(let r of this[I])r.dest.write(e)===!1&&this.pause();let t=this[N]?!1:super.emit("data",e);return this[it](),t}[Br](){return this[ht]?!1:(this[ht]=!0,this.readable=!1,this[J]?(jt(()=>this[tr]()),!0):this[tr]())}[tr](){if(this[Rt]){let t=this[Rt].end();if(t){for(let r of this[I])r.dest.write(t);this[N]||super.emit("data",t)}}for(let t of this[I])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[O]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[O]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[G]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(M,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[N]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[st])return t();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),t(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[st]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),t(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,h)=>{i=h,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[N]=!1;let e=!1,t=()=>(this.pause(),this.off(Qe,t),this.off(M,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let s=this.read();return s===null?t():{done:!1,value:s}};return this.once("end",t),this.once(Qe,t),this.once(M,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[M])return e?this.emit("error",e):this.emit(M),this;this[M]=!0,this[N]=!0,this[A].length=0,this[R]=0;let t=this;return typeof t.close=="function"&&!this[he]&&t.close(),e?this.emit("error",e):this.emit(M),this}static get isStream(){return go}},Co=q.realpathSync.native,Kt={lstatSync:q.lstatSync,readdir:q.readdir,readdirSync:q.readdirSync,readlinkSync:q.readlinkSync,realpathSync:Co,promises:{lstat:pt.lstat,readdir:pt.readdir,readlink:pt.readlink,realpath:pt.realpath}},_s=e=>!e||e===Kt||e===mo?Kt:{...Kt,...e,promises:{...Kt.promises,...e.promises||{}}},bs=/^\\\\\?\\([a-z]:)\\?$/i,Ao=e=>e.replace(/\//g,"\\").replace(bs,"$1\\"),Ro=/[\\\/]/,j=0,vs=1,Ts=2,X=4,Ms=6,Cs=8,Et=10,As=12,$=15,Ht=~$,rr=16,Gr=32,zt=64,K=128,fe=256,Se=512,Kr=zt|K|Se,ko=1023,sr=e=>e.isFile()?Cs:e.isDirectory()?X:e.isSymbolicLink()?Et:e.isCharacterDevice()?Ts:e.isBlockDevice()?Ms:e.isSocket()?As:e.isFIFO()?vs:j,zr=new _e({max:2**12}),Yt=e=>{let t=zr.get(e);if(t)return t;let r=e.normalize("NFKD");return zr.set(e,r),r},Yr=new _e({max:2**12}),me=e=>{let t=Yr.get(e);if(t)return t;let r=Yt(e.toLowerCase());return Yr.set(e,r),r},Jr=class extends _e{constructor(){super({max:256})}},Oo=class extends _e{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Rs=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#t;#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}#h;get blksize(){return this.#h}#a;get ino(){return this.#a}#d;get size(){return this.#d}#u;get blocks(){return this.#u}#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;#e;#x;#D;#A;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=j,r,s,i,n,o){this.name=e,this.#T=i?me(e):Yt(e),this.#e=t&ko,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.#t=this.parent.#t:this.#t=_s(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(e){if(!e)return this;let t=this.getRootString(e),r=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#P(r):this.#P(r)}#P(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#x.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#x.set(this,t),this.#e&=~rr,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),s=this.nocase?me(e):Yt(e);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+e:void 0,o=this.newChild(e,j,{...t,parent:this,fullpath:n});return this.canReaddir()||(o.#e|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let e=this.name,t=this.parent;if(!t)return this.#b=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#C!==void 0)return this.#C;let e=this.name,t=this.parent;if(!t)return this.#C=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#g!==void 0)return this.#g;let e=this.name,t=this.parent;if(!t)return this.#g=this.name;let r=t.fullpath()+(t.parent?this.sep:"")+e;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 e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#e&$)===j}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&$)===Cs}isDirectory(){return(this.#e&$)===X}isCharacterDevice(){return(this.#e&$)===Ts}isBlockDevice(){return(this.#e&$)===Ms}isFIFO(){return(this.#e&$)===vs}isSocket(){return(this.#e&$)===As}isSymbolicLink(){return(this.#e&Et)===Et}lstatCached(){return this.#e&Gr?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#A}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let e=this.#e&$;return!(e!==j&&e!==Et||this.#e&fe||this.#e&K)}calledReaddir(){return!!(this.#e&rr)}isENOENT(){return!!(this.#e&K)}isNamed(e){return this.nocase?this.#T===me(e):this.#T===Yt(e)}async readlink(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#t.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#D=r}catch(t){this.#I(t.code);return}}readlinkSync(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#t.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#D=r}catch(t){this.#I(t.code);return}}#F(e){this.#e|=rr;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#v()}}#v(){this.#e&K||(this.#e=(this.#e|K)&Ht,this.#G())}#G(){let e=this.children();e.provisional=0;for(let t of e)t.#v()}#U(){this.#e|=Se,this.#L()}#L(){if(this.#e&zt)return;let e=this.#e;(e&$)===X&&(e&=Ht),this.#e=e|zt,this.#G()}#W(e=""){e==="ENOTDIR"||e==="EPERM"?this.#L():e==="ENOENT"?this.#v():this.children().provisional=0}#O(e=""){e==="ENOTDIR"?this.parent.#L():e==="ENOENT"&&this.#v()}#I(e=""){let t=this.#e;t|=fe,e==="ENOENT"&&(t|=K),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Ht),this.#e=t,e==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(e,t){return this.#H(e,t)||this.#j(e,t)}#j(e,t){let r=sr(e),s=this.newChild(e.name,r,{parent:this}),i=s.#e&$;return i!==X&&i!==Et&&i!==j&&(s.#e|=zt),t.unshift(s),t.provisional++,s}#H(e,t){for(let r=t.provisional;r<t.length;r++){let s=t[r];if((this.nocase?me(e.name):Yt(e.name))===s.#T)return this.#c(e,s,r,t)}}#c(e,t,r,s){let i=t.name;return t.#e=t.#e&Ht|sr(e),i!==e.name&&(t.name=e.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#e&K)===0)try{return this.#B(await this.#t.promises.lstat(this.fullpath())),this}catch(e){this.#O(e.code)}}lstatSync(){if((this.#e&K)===0)try{return this.#B(this.#t.lstatSync(this.fullpath())),this}catch(e){this.#O(e.code)}}#B(e){let{atime:t,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:h,ino:u,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=e;this.#w=t,this.#l=r,this.#m=s,this.#_=i,this.#h=n,this.#u=o,this.#R=a,this.#p=l,this.#r=c,this.#y=h,this.#a=u,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=sr(e);this.#e=this.#e&Ht|y|Gr,y!==j&&y!==X&&y!==Et&&(this.#e|=zt)}#N=[];#k=!1;#K(e){this.#k=!1;let t=this.#N.slice();this.#N.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#N.push(e),this.#k)return;this.#k=!0;let s=this.fullpath();this.#t.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))})}#z;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#z)await this.#z;else{let r=()=>{};this.#z=new Promise(s=>r=s);try{for(let s of await this.#t.promises.readdir(t,{withFileTypes:!0}))this.#$(s,e);this.#F(e)}catch(s){this.#W(s.code),e.provisional=0}this.#z=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#t.readdirSync(t,{withFileTypes:!0}))this.#$(r,e);this.#F(e)}catch(r){this.#W(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#e&Kr)return!1;let e=$&this.#e;return e===j||e===X||e===Et}shouldWalk(e,t){return(this.#e&X)===X&&!(this.#e&Kr)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#A)return this.#A;if(!((Se|fe|K)&this.#e))try{let e=await this.#t.promises.realpath(this.fullpath());return this.#A=this.resolve(e)}catch{this.#U()}}realpathSync(){if(this.#A)return this.#A;if(!((Se|fe|K)&this.#e))try{let e=this.#t.realpathSync(this.fullpath());return this.#A=this.resolve(e)}catch{this.#U()}}[Rs](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],s=this;for(;s&&s.parent;)t.add(s),s.#b=r.join(this.sep),s.#C=r.join("/"),s=s.parent,r.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#b=void 0,s.#C=void 0,s=s.parent}},ks=class Os extends L{sep="\\";splitSep=Ro;constructor(t,r=j,s,i,n,o,a){super(t,r,s,i,n,o,a)}newChild(t,r=j,s={}){return new Os(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return It.win32.parse(t).root}getRoot(t){if(t=Ao(t.toUpperCase()),t===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(t,r))return this.roots[t]=s;return this.roots[t]=new lr(t,this).root}sameRoot(t,r=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(bs,"$1\\"),t===r}},Is=class Ds extends L{splitSep="/";sep="/";constructor(t,r=j,s,i,n,o,a){super(t,r,s,i,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,r=j,s={}){return new Ds(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Ps=class{root;rootPath;roots;cwd;#t;#r;#n;nocase;#i;constructor(e=process.cwd(),t,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Kt}={}){this.#i=_s(n),(e instanceof URL||e.startsWith("file://"))&&(e=(0,Es.fileURLToPath)(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new Jr,this.#r=new Jr,this.#n=new Oo(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,h=t.sep,u=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(h),relativePosix:new Array(m).fill("..").join("/"),fullpath:u+=(p?"":h)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#t.get(t);if(r!==void 0)return r;let s=this.cwd.resolve(t).fullpath();return this.#t.set(t,s),s}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#r.get(t);if(r!==void 0)return r;let s=this.cwd.resolve(t).fullpathPosix();return this.#r.set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let s=await e.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set,l=(h,u)=>{a.add(h),h.readdirCB((p,f)=>{if(p)return u(p);let m=f.length;if(!m)return u();let g=()=>{--m===0&&u()};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=e;return new Promise((h,u)=>{l(c,p=>{if(p)return u(p);h(o)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let h of c){(!i||i(h))&&o.push(r?h:h.fullpath());let u=h;if(h.isSymbolicLink()){if(!(s&&(u=h.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(a,n)&&a.add(u)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t;(!i||i(e))&&(yield r?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let h=c;if(c.isSymbolicLink()){if(!(s&&(h=c.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(o,n)&&o.add(h)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=new ye({objectMode:!0});(!i||i(e))&&o.write(r?e:e.fullpath());let a=new Set,l=[e],c=0,h=()=>{let u=!1;for(;!u;){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())||(u=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}u&&!o.flowing?o.once("drain",h):m||h()},m=!0;p.readdirCB(f,!0),m=!1}};return h(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=new ye({objectMode:!0}),a=new Set;(!i||i(e))&&o.write(r?e:e.fullpath());let l=[e],c=0,h=()=>{let u=!1;for(;!u;){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())||(u=!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)}}u&&!o.flowing&&o.once("drain",h)};return h(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Rs](t)}},lr=class extends Ps{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,It.win32,"\\",{...t,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(e){return It.win32.parse(e).root.toUpperCase()}newRoot(e){return new ks(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},cr=class extends Ps{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,It.posix,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Is(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},xs=class extends cr{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},sl=process.platform==="win32"?ks:Is,Io=process.platform==="win32"?lr:process.platform==="darwin"?xs:cr,Do=e=>e.length>=1,Po=e=>e.length>=1,xo=Symbol.for("nodejs.util.inspect.custom"),Ls=class Ns{#t;#r;#n;length;#i;#o;#y;#S;#h;#a;#d=!0;constructor(t,r,s,i){if(!Do(t))throw new TypeError("empty pattern list");if(!Po(r))throw new TypeError("empty glob list");if(r.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#t,[h,u,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[h,u,p,f,""].join("/");this.#t=[g,...c],this.#r=[w,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",h=a+"/";this.#t=[c,...o],this.#r=[h,...l],this.length=this.#t.length}}}[xo](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===D}isRegExp(){return this.#t[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 Ns(this.#t,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#h=this.#h,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#i==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#a!==void 0?this.#a:this.#a=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},Lo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Xr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:s,noglobstar:i,platform:n=Lo}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of e)this.add(o)}add(e){let t=new dt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let s=t.set[r],i=t.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new Ls(s,i,0,this.platform),o=new dt(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(e){let t=e.fullpath(),r=`${t}/`,s=e.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(t)||n.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(t))return!0;return!1}},No=class Us{store;constructor(t=new Map){this.store=t}copy(){return new Us(new Map(this.store))}hasWalked(t,r){return this.store.get(t.fullpath())?.has(r.globString())}storeWalked(t,r){let s=t.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},Uo=class{store=new Map;add(e,t,r){let s=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Fo=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(s=>s.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},qr=class Fs{hasWalkedCache;matches=new Uo;subwalks=new Fo;patterns;follow;dot;opts;constructor(t,r){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=r?r.copy():new No}processPatterns(t,r){this.patterns=r;let s=r.map(i=>[t,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 u=n.rest();if(u)n=u;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,h=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,h=!0;if(l=n.pattern(),c=n.rest(),h){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let u=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,u);continue}else if(l===D){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let u=c?.pattern(),p=c?.rest();if(!c||(u===""||u===".")&&!p)this.matches.add(i,a,u===""||u===".");else if(u===".."){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 Fs(this.opts,this.hasWalkedCache)}filterEntries(t,r){let s=this.subwalks.get(t),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(t,r,s,i){if((this.dot||!t.name.startsWith("."))&&(r.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,r):t.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(t,s):r.markFollowGlobstar()&&this.subwalks.add(t,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),i)}}testRegExp(t,r,s,i){r.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,r,s,i){t.isNamed(r)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}},Wo=(e,t)=>typeof e=="string"?new Xr([e],t):Array.isArray(e)?new Xr(e,t):e,Ws=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=Wo(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.#t.length=0}))}#i(e){return this.seen.has(e)||!!this.#r?.ignored?.(e)}#o(e){return!!this.#r?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#t.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#t.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;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,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#i(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;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,t)}matchFinish(e,t){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${e.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(e,t,r){let s=await this.matchCheck(e,r);s&&this.matchFinish(s,t)}matchSync(e,t,r){let s=this.matchCheckSync(e,r);s&&this.matchFinish(s,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new qr(this.opts),r)}walkCB2(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,s));return}r.processPatterns(e,t);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(e,t,r,s){r=r.filterEntries(e,t);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(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new qr(this.opts),r)}walkCB2Sync(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,s));return}r.processPatterns(e,t);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(e,t,r,s){r=r.filterEntries(e,t);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()}},Vr=class extends Ws{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Qr=class extends Ws{results;constructor(e,t,r){super(e,t,r),this.results=new ye({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},$o=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",wt=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(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=(0,ps.fileURLToPath)(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=e,this.platform=t.platform||$o,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=t.platform==="win32"?lr:t.platform==="darwin"?xs:t.platform?cr:Io;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,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 dt(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 Ls(a,c,0,this.platform)})}async walk(){return[...await new Vr(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 Vr(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 Qr(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 Qr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},jo=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let r of e)if(new dt(r,t).hasMagic())return!0;return!1};function ve(e,t={}){return new wt(e,t).streamSync()}function $s(e,t={}){return new wt(e,t).stream()}function Jt(e,t={}){return new wt(e,t).walkSync()}async function Zr(e,t={}){return new wt(e,t).walk()}function Te(e,t={}){return new wt(e,t).iterateSync()}function js(e,t={}){return new wt(e,t).iterate()}var Ho=ve,Bo=Object.assign($s,{sync:ve}),Go=Te,Ko=Object.assign(js,{sync:Te}),zo=Object.assign(Jt,{stream:ve,iterate:Te}),ts=Object.assign(Zr,{glob:Zr,globSync:Jt,sync:zo,globStream:$s,stream:Bo,globStreamSync:ve,streamSync:Ho,globIterate:js,iterate:Ko,globIterateSync:Te,iterateSync:Go,Glob:wt,hasMagic:jo,escape:ls,unescape:Ot});ts.glob=ts;var nt=require("fs"),Hs=require("path");function Bs(e){try{if(!(0,nt.existsSync)(e))return{offsets:{}};let t=(0,nt.readFileSync)(e,"utf-8"),r=JSON.parse(t);return r.offsets?r:{offsets:{}}}catch(t){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:e,error:t instanceof Error?t.message:String(t)}),{offsets:{}}}}function Gs(e,t){try{let r=(0,Hs.dirname)(e);(0,nt.existsSync)(r)||(0,nt.mkdirSync)(r,{recursive:!0}),(0,nt.writeFileSync)(e,JSON.stringify(t,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:e,error:r instanceof Error?r.message:String(r)})}}var Zt=ct(require("path"),1);var _t=ct(require("path"),1),B=require("fs"),hi=require("child_process");var Ks=require("node:child_process");function Me(e,t,r){return(0,Ks.spawn)(e,t??[],{windowsHide:!0,...r})}var V={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},ft={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function Dt(e){return process.platform==="win32"?Math.round(e*V.WINDOWS_MULTIPLIER):e}var Q=require("fs"),Xt=require("path"),hr=require("os"),H=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_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,Xt.join)((0,hr.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,Xt.join)((0,hr.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(t){return process.env[t]??this.DEFAULTS[t]}static getInt(t){let r=this.get(t);return parseInt(r,10)}static getBool(t){let r=this.get(t);return r==="true"||r===!0}static applyEnvOverrides(t){let r={...t};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(t){try{if(!(0,Q.existsSync)(t)){let o=this.getAllDefaults();try{let a=(0,Xt.dirname)(t);(0,Q.existsSync)(a)||(0,Q.mkdirSync)(a,{recursive:!0}),(0,Q.writeFileSync)(t,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",t)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",t,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(o)}let r=(0,Q.readFileSync)(t,"utf-8"),s=JSON.parse(r.replace(/^\uFEFF/,"")),i=s;if(s.env&&typeof s.env=="object"){i=s.env;try{(0,Q.writeFileSync)(t,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(o){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,o instanceof Error?o.message:String(o))}}let n={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(n[o]=i[o]);return this.applyEnvOverrides(n)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",t,r instanceof Error?r.message:String(r)),this.applyEnvOverrides(this.getAllDefaults())}}};var Ce=null;function ot(){return Ce!==null||(Ce=H.loadFromFile(se)),Ce}var yt=require("fs");var mr=require("child_process");var tt=require("fs"),pr=ct(require("path"),1);var Yo=["CLAUDECODE_","CLAUDE_CODE_"],Jo=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Xo=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"]),qo=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 Ae(e=process.env){let t={};for(let[r,s]of Object.entries(e))if(s!==void 0){if(qo.has(r)){t[r]=s;continue}Jo.has(r)||Xo.has(r)||Yo.some(i=>r.startsWith(i))||(t[r]=s)}return t}var Vo=5e3,Qo=1e3,Zo=k.supervisorRegistry();function Z(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}var ta=5e3,zs=new Map;function ea(e){let t=zs.get(e);if(t&&Date.now()-t.capturedAtMs<ta)return t.token;let r=null;try{let s=(0,mr.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ae(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:e,error:s instanceof Error?s.message:String(s)}),r=null}return zs.set(e,{token:r,capturedAtMs:Date.now()}),r}function Ys(e){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux")try{let t=(0,tt.readFileSync)(`/proc/${e}/stat`,"utf-8"),r=t.lastIndexOf(") ");if(r<0)return null;let i=t.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}if(process.platform==="win32")return ea(e);try{let t=(0,mr.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ae(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}}function gr(e){if(!e||!Z(e.pid))return!1;if(!e.startToken)return!0;let t=Ys(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var fr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=Zo){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,tt.mkdirSync)(pr.default.dirname(this.registryPath),{recursive:!0}),!(0,tt.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,tt.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 t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,s){this.initialize(),this.entries.set(t,r),s&&this.runtimeProcesses.set(t,s),this.persist()}unregister(t){this.initialize();let r=this.entries.get(t);this.entries.delete(t),this.runtimeProcesses.delete(t),this.persist(),r?.type==="sdk"&&dr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let s=Date.parse(t.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(t){let r=String(t);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}getByPid(t){return this.getAll().filter(r=>r.pid===t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[s,i]of this.entries)Z(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),t+=1,i.type==="sdk"&&(r+=1));t>0&&this.persist();for(let s=0;s<r;s+=1)dr();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let s=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{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()+Vo;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()+Qo;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"&&dr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:s,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};(0,tt.mkdirSync)(pr.default.dirname(this.registryPath),{recursive:!0}),(0,tt.writeFileSync)(this.registryPath,JSON.stringify(t,null,2))}},ur=null;function Re(){return ur||(ur=new fr),ur}var ra=[];function dr(){let e=ra.shift();e&&e()}var qs=require("child_process"),Vs=require("fs"),Qs=require("util");var sa=(0,Qs.promisify)(qs.execFile),ia=k.workerPid();async function Zs(e){let t=e.currentPid??process.pid,r=e.pidFilePath??ia,s=e.registry.getAll(),i=[...s].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!Z(o.pid)){e.registry.unregister(o.id);continue}try{await Xs(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 Js(i,5e3);let n=i.filter(o=>Z(o.pid));for(let o of n)try{await Xs(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 Js(n,1e3);for(let o of i)e.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===t))e.registry.unregister(o.id);try{(0,Vs.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)})}e.registry.pruneDeadEntries()}async function Js(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.filter(i=>Z(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function Xs(e,t){let{pid:r,pgid:s}=e;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(t==="SIGTERM"){try{process.kill(r,t)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await na();if(i){await new Promise((o,a)=>{i(r,t,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];t==="SIGKILL"&&n.push("/F"),await sa("taskkill",n,{timeout:V.POWERSHELL_COMMAND,windowsHide:!0})}async function na(){let e="tree-kill";try{let t=await import(e);return t.default??t}catch(t){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},t instanceof Error?t:void 0),null}}var ti=3e4,Pt=null;function oa(){let t=Re().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function ei(){Pt===null&&(Pt=setInterval(oa,ti),Pt.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:ti}))}function ri(){Pt!==null&&(clearInterval(Pt),Pt=null,d.debug("SYSTEM","Health checker stopped"))}var aa=k.workerPid(),Sr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),ke({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ei()}configureSignalHandlers(t){if(this.shutdownHandler=t,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}ri(),this.stopPromise=Zs({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,s){this.registry.register(t,r,s)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},rc=new Sr(Re());function ke(e={}){let t=e.pidFilePath??aa;if(!(0,yt.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,yt.readFileSync)(t,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(i)}),(0,yt.rmSync)(t,{force:!0}),"invalid"}return gr(r)&&r?((e.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,yt.rmSync)(t,{force:!0}),"stale")}var Oe=require("child_process");var si=require("util");var hc=(0,si.promisify)(Oe.exec),uc=k.dataDir(),dc=k.workerPid();var ii=ct(require("path"),1);var ni=require("fs");async function ca(e,t,r="GET"){let s=await fetch(`http://127.0.0.1:${e}${t}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function ha(){try{let e=ii.default.join(re,"package.json");return JSON.parse((0,ni.readFileSync)(e,"utf-8")).version}catch(e){if(e instanceof Error){let t=e.code;if(t==="ENOENT"||t==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:t}),"unknown";throw e}throw e}}async function ua(e){try{let t=await ca(e,"/api/version");return t.ok?JSON.parse(t.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function oi(e){let t=ha(),r=await ua(e);return!r||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:r}:{matches:t===r,pluginVersion:t,workerVersion:r}}function wr(e,t,r){let s=process.env[e];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max})}return t}var yr=wr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Dt(V.HEALTH_CHECK),{min:500,max:3e5}),da=wr("CLAUDE_MEM_API_TIMEOUT_MS",Dt(V.API_REQUEST),{min:500,max:3e5}),pa=wr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Dt(V.HOOK_READINESS_WAIT),{min:0,max:3e5});function _r(e,t={},r){return new Promise((s,i)=>{let n=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(e,t).then(o=>{clearTimeout(n),s(o)},o=>{clearTimeout(n),i(o)})})}var Ie=null,De=null;function ui(){if(Ie!==null)return Ie;let e=_t.default.join(H.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=H.loadFromFile(e);return Ie=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ie}function fa(){if(De!==null)return De;let e=_t.default.join(H.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return De=H.loadFromFile(e).CLAUDE_MEM_WORKER_HOST,De}function ma(e){return`http://${fa()}:${ui()}${e}`}function mt(e,t={}){let r=t.method??"GET",s=t.timeoutMs??da,i=ma(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),s>0?_r(i,n,s):fetch(i,n)}async function ga(){return(await mt("/api/health",{timeoutMs:yr})).ok}async function ai(){return(await mt("/api/readiness",{timeoutMs:yr})).ok}function Sa(){let e=[_t.default.join(re,"plugin","scripts","worker-service.cjs"),_t.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,B.existsSync)(t))return t;return null}function Ea(){if(process.env.BUN&&(0,B.existsSync)(process.env.BUN))return process.env.BUN;try{let e=process.platform==="win32"?"where bun":"which bun";return(0,hi.execSync)(e,{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 wa(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await di())return!0;r<e.attempts&&(await new Promise(s=>setTimeout(s,t)),t*=2)}return!1}async function li(e=pa){if(e<=0)try{return await ai()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await ai())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function di(){let e;try{e=await ga()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!e)return!1;let t=ke({logAlive:!1});return t==="missing"||t==="alive"}async function xe(){if(await di()){let{matches:i,pluginVersion:n,workerVersion:o}=await oi(ui());if(i)return await li()?!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 mt("/api/admin/restart",{method:"POST",timeoutMs:yr})}catch(a){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:a instanceof Error?a.message:String(a)})}}let e=Ea(),t=Sa();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!t)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:e,scriptPath:t});try{Me(e,[t,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(i){return i instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:t},i):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:t,error:String(i)}),!1}return await wa({attempts:6,backoffMs:500})?await li()?!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 Pe=null;async function ya(){return Pe!==null||(Pe=await xe()),Pe}var _a=3;function pi(){return _t.default.join(v,"state")}function fi(){return _t.default.join(pi(),"hook-failures.json")}function mi(){try{let e=(0,B.readFileSync)(fi(),"utf-8"),t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function gi(e){let t=pi(),r=fi(),s=`${r}.tmp`;try{(0,B.existsSync)(t)||(0,B.mkdirSync)(t,{recursive:!0}),(0,B.writeFileSync)(s,JSON.stringify(e),"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 ba(){try{let t=ot().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return _a}function va(){let t={consecutiveFailures:mi().consecutiveFailures+1,lastFailureAt:Date.now()};gi(t);let r=ba();return t.consecutiveFailures>=r&&Rr(`claude-mem worker unreachable for ${t.consecutiveFailures} consecutive hooks.`),t.consecutiveFailures}function ci(){mi().consecutiveFailures!==0&&gi({consecutiveFailures:0,lastFailureAt:0})}var Er=Symbol.for("claude-mem/worker-fallback");function qt(e){return typeof e=="object"&&e!==null&&e[Er]===!0}async function Vt(e,t,r,s={}){if(!await ya())return va(),{continue:!0,reason:"worker_unreachable",[Er]:!0};let n={method:t};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 mt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(ci(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${t} ${e} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Er]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}ci();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var Ei=require("os"),wi=ct(require("path"),1),yi=require("child_process");var Ne=require("fs"),Le=ct(require("path"),1);var Qt={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Si(e){let t=Le.default.join(e,".git"),r;try{r=(0,Ne.statSync)(t)}catch(h){return h instanceof Error&&h.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:h instanceof Error?h.message:String(h)}),Qt}if(!r.isFile())return Qt;let s;try{s=(0,Ne.readFileSync)(t,"utf-8").trim()}catch(h){return d.warn("GIT","Failed to read .git file",{error:h instanceof Error?h.message:String(h)}),Qt}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return Qt;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Qt;let a=o[1],l=Le.default.basename(e),c=Le.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function _i(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,Ei.homedir)()):e}function Ta(e){try{return(0,yi.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Ma(e){if(!e||e.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),"unknown-project";let t=_i(e),s=Ta(t)??t,i=wi.default.basename(s);if(i===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),"unknown-project"}return i}function bt(e){let t=Ma(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=_i(e),s=Si(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var vt=require("path");var bi=require("os"),vi=require("path");function Ca(e){let t=e.startsWith("~")?(0,bi.homedir)()+e.slice(1):e;t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Ue(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),s=(0,vi.basename)(r),i=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=Ca(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 Aa(e,t){let r=(0,vt.normalize)(e),s=(0,vt.normalize)(t);if(r===s)return!0;let i=(0,vt.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,vt.isAbsolute)(i)}function Fe(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(Aa(e,ie))return!1;let t=ot();return!Ue(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ti="claude";function Ra(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function gt(e){if(!e)return Ti;let t=Ra(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:Ti}var Ai=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Mi=new RegExp(`<(${Ai.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Ci=100;function ka(e){let t=Object.fromEntries(Ai.map(i=>[i,0]));Mi.lastIndex=0;let r=0,s=e.replace(Mi,(i,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Ci&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Ci,contentLength:e.length}),{stripped:s.trim(),counts:t}}function br(e){return ka(e).stripped}var Oa=["task-notification"],Ia=new RegExp(`^\\s*<(${Oa.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Da=256*1024;function Ri(e){return!e||e.length>Da?!1:Ia.test(e)}var Pa=Dt(V.API_REQUEST),at=class extends Error{kind;status;cause;constructor(t,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=t,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)}},We=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=xa(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??Pa}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),s=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(t){if(!t.sessionId)throw new at("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new at("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,s=t.kind??"manual",i=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,s){if(!this.apiKey||!this.apiKey.trim())throw new at("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await _r(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),h=/timed out|timeout/i.test(c);throw new at(h?"timeout":"transport",`Server beta ${t} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new at("http_error",`Server beta ${t} ${r} returned ${o.status}: ${La(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 at("invalid_response",`Server beta ${t} ${r} returned non-JSON response`,{cause:l})}}};function ki(e){return e instanceof at}function xa(e){return e.replace(/\/+$/,"")}function La(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function Na(){return(ot().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function Ua(){let e=ot(),t=(e.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(e.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!t)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:t,apiKey:r};return{runtime:"server-beta",client:new We(i),projectId:s,serverBaseUrl:t}}function Oi(){if(Na()!=="server-beta")return{runtime:"worker"};let e=Ua();return e||{runtime:"worker"}}function Ii(e,t){d.warn("HOOK",`[server-beta-fallback] reason=${e}`,t??{})}var Di={async execute(e){let{sessionId:t,prompt:r}=e,s=e.cwd??process.cwd();if(!t)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:ft.SUCCESS};if(!Fe(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&Ri(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=bt(s).primary,o=gt(e.platform),a=Oi();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(ki(m)&&m.isFallbackEligible())Ii(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:ft.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:t,project:n});let l=await Vt("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:i,platformSource:o});if(qt(l))return{continue:!0,suppressOutput:!0,exitCode:ft.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:ft.SUCCESS};let c=l.sessionDbId,h=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:h,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${h} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${h} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let u=ot(),p=String(u.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=u.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await Vt("/api/context/semantic","POST",{q:i,project:n,limit:m});!qt(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=${h} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var Pi={async execute(e){let{sessionId:t,cwd:r,filePath:s,edits:i}=e,n=gt(e.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 ${t}, file ${s}`);if(!Fe(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:ft.SUCCESS};let o=await Vt("/api/sessions/observations","POST",{contentSessionId:t,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return qt(o)?{continue:!0,suppressOutput:!0,exitCode:ft.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),$e=require("path");var Ph=k.settings();function xi(e,t){let r="<claude-mem-context>",s="</claude-mem-context>";if(!e)return`${r}
|
|
14
|
+
>>> no match, partial?`,e,u,t,p),u===a))}let m;if(typeof c=="string"?(m=h===c,this.debug("string match",c,h,m)):(m=c.test(h),this.debug("pattern match",c,h,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return gs(this.pattern,this.options)}parse(e){Ee(e);let t=this.options;if(e==="**")return D;if(e==="")return"";let r,s=null;(r=e.match(Zn))?s=t.dot?eo:to:(r=e.match(Bn))?s=(t.nocase?t.dot?Yn:zn:t.dot?Kn:Gn)(r[1]):(r=e.match(ro))?s=(t.nocase?t.dot?io:so:t.dot?no:oo)(r):(r=e.match(Jn))?s=t.dot?qn:Xn:(r=e.match(Vn))&&(s=Qn);let i=us.fromGlob(e,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 e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?co:t.dot?ho:uo,s=new Set(t.nocase?["i"]:[]),i=e.map(a=>{let l=a.map(h=>{if(h instanceof RegExp)for(let u of h.flags.split(""))s.add(u);return typeof h=="string"?So(h):h===D?D:h._src});l.forEach((h,u)=>{let p=l[u+1],f=l[u-1];h!==D||f===D||(f===void 0?p!==void 0&&p!==D?l[u+1]="(?:\\/|"+r+"\\/)?"+p:l[u]=r:p===void 0?l[u-1]=f+"(?:\\/|\\/"+r+")?":p!==D&&(l[u-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[u+1]=D))});let c=l.filter(h=>h!==D);if(this.partial&&c.length>=1){let h=[];for(let u=1;u<=c.length;u++)h.push(c.slice(0,u).join("/"));return"(?:"+h.join("|")+")"}return c.join("/")}).join("|"),[n,o]=e.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(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);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,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return P.defaults(e).Minimatch}};P.AST=us;P.Minimatch=pt;P.escape=ds;P.unescape=Ot;var Eo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Es=new Set,ar=typeof process=="object"&&process?process:{},ws=(e,t,r,s)=>{typeof ar.emitWarning=="function"?ar.emitWarning(e,t,r,s):console.error(`[${r}] ${t}: ${e}`)},we=globalThis.AbortController,Br=globalThis.AbortSignal;if(typeof we>"u"){Br=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},we=class{constructor(){t()}signal=new Br;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 e=ar.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,ws("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var wo=e=>!Es.has(e),dt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ys=e=>dt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ge:null:null,ge=class extends Array{constructor(e){super(e),this.fill(0)}},yo=class Kt{heap;length;static#t=!1;static create(t){let r=ys(t);if(!r)return[];Kt.#t=!0;let s=new Kt(t,r);return Kt.#t=!1,s}constructor(t,r){if(!Kt.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},_e=class _s{#t;#r;#n;#i;#o;#y;#S;#h;get perf(){return this.#h}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#u;#l;#s;#p;#_;#w;#f;#R;#m;#T;#M;#g;#E;#b;#C;#e;#x;static unsafeExposeInternals(t){return{starts:t.#M,ttls:t.#g,autopurgeTimers:t.#E,sizes:t.#T,keyMap:t.#u,keyList:t.#l,valList:t.#s,next:t.#p,prev:t.#_,get head(){return t.#w},get tail(){return t.#f},free:t.#R,isBackgroundFetch:r=>t.#c(r),backgroundFetch:(r,s,i,n)=>t.#H(r,s,i,n),moveToTail:r=>t.#N(r),indexes:r=>t.#O(r),rindexes:r=>t.#I(r),isStale:r=>t.#v(r)}}get max(){return this.#t}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(t){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:h,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:ct,ignoreFetchAbort:Tt,perf:Mt}=t;if(Mt!==void 0&&typeof Mt?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#h=Mt??Eo,r!==0&&!dt(r))throw new TypeError("max option must be a nonnegative integer");let Ct=r?ys(r):Array;if(!Ct)throw new Error("invalid max value: "+r);if(this.#t=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.#u=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Ct(r),this.#_=new Ct(r),this.#w=0,this.#f=0,this.#R=yo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof h=="function"&&(this.#i=h),typeof u=="function"?(this.#o=u,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#e=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!ct,this.ignoreFetchAbort=!!Tt,this.maxEntrySize!==0){if(this.#r!==0&&!dt(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!dt(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=dt(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!dt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let ze="LRU_CACHE_UNBOUNDED";wo(ze)&&(Es.add(ze),ws("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ze,_s))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#D(){let t=new ge(this.#t),r=new ge(this.#t);this.#g=t,this.#M=r;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=s,this.#F=(o,a,l=this.#h.now())=>{if(r[o]=a!==0?l:0,t[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]=t[o]!==0?this.#h.now():0},this.#P=(o,a)=>{if(t[a]){let l=t[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let h=o.now-c;o.remainingTTL=l-h}};let i=0,n=()=>{let o=this.#h.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.#u.get(o);if(a===void 0)return 0;let l=t[a],c=r[a];if(!l||!c)return 1/0;let h=(i||n())-c;return l-h},this.#v=o=>{let a=r[o],l=t[o];return!!l&&!!a&&(i||n())-a>l}}#A=()=>{};#P=()=>{};#F=()=>{};#v=()=>!1;#G(){let t=new ge(this.#t);this.#d=0,this.#T=t,this.#U=r=>{this.#d-=t[r],t[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!dt(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!dt(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(t[r]=s,this.#r){let n=this.#r-t[r];for(;this.#d>n;)this.#j(!0)}this.#d+=t[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=t=>{};#L=(t,r,s)=>{};#W=(t,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((t||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#I({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((t||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(t){return t!==void 0&&this.#u.get(this.#l[t])===t}*entries(){for(let t of this.#O())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*rentries(){for(let t of this.#I())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*keys(){for(let t of this.#O()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*rkeys(){for(let t of this.#I()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*values(){for(let t of this.#O())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#I())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(t,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}rforEach(t,r=this){for(let s of this.#I()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}purgeStale(){let t=!1;for(let r of this.#I({allowStale:!0}))this.#v(r)&&(this.#k(this.#l[r],"expire"),t=!0);return t}info(t){let r=this.#u.get(t);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.#h.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let t=[];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.#h.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),t.unshift([s,o])}return t}load(t){this.clear();for(let[r,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#h.now()-i}this.set(r,s.value,s)}}set(t,r,s={}){if(r===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,h=this.#W(t,r,s.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#k(t,"set"),this;let u=this.#a===0?void 0:this.#u.get(t);if(u===void 0)u=this.#a===0?this.#f:this.#R.length!==0?this.#R.pop():this.#a===this.#t?this.#j(!1):this.#a,this.#l[u]=t,this.#s[u]=r,this.#u.set(t,u),this.#p[this.#f]=u,this.#_[u]=this.#f,this.#f=u,this.#a++,this.#L(u,h,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,t,"add");else{this.#N(u);let p=this.#s[u];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,t,"set"),this.#e&&this.#m?.push([f,t,"set"]))}else o||(this.#b&&this.#n?.(p,t,"set"),this.#e&&this.#m?.push([p,t,"set"]));if(this.#U(u),this.#L(u,h,l),this.#s[u]=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,t,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#D(),this.#g&&(c||this.#F(u,i,n),l&&this.#P(l,u)),!o&&this.#e&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let t=this.#s[this.#w];if(this.#j(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,r;for(;r=t?.shift();)this.#o?.(...r)}}}#j(t){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.#e)&&(this.#b&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),t&&(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.#u.delete(s),this.#a--,r}has(t,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#u.get(t);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(t,r={}){let{allowStale:s=this.allowStale}=r,i=this.#u.get(t);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#H(t,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new we,{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 u(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(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,g,l.options))),g},h=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),u(g,!1)),u=(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(t,"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?.(t,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,h),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(t,m,{...l.options,status:void 0}),r=this.#u.get(t)):this.#s[r]=m,m}#c(t){if(!this.#C)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof we}async fetch(t,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:h=this.noUpdateTTL,noDeleteOnFetchRejection:u=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(t,{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:h,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#u.get(t);if(b===void 0){S&&(S.fetch="miss");let T=this.#H(t,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Ct=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Ct&&(S.returnedStale=!0)),Ct?T.__staleWhileFetching:T.__returned=T}let ct=this.#v(b);if(!w&&!ct)return S&&(S.fetch="hit"),this.#N(b),i&&this.#A(b),S&&this.#P(S,b),T;let Tt=this.#H(t,b,y,g),Mt=Tt.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=ct?"stale":"refresh",Mt&&ct&&(S.returnedStale=!0)),Mt?Tt.__staleWhileFetching:Tt.__returned=Tt}}async forceFetch(t,r={}){let s=await this.fetch(t,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,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(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:i});return this.set(t,l,o),l}get(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#u.get(t);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(t,"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(t,r){this.#_[r]=t,this.#p[t]=r}#N(t){t!==this.#f&&(t===this.#w?this.#w=this.#p[t]:this.#B(this.#_[t],this.#p[t]),this.#B(this.#f,t),this.#f=t)}delete(t){return this.#k(t,"delete")}#k(t,r){let s=!1;if(this.#a!==0){let i=this.#u.get(t);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.#e)&&(this.#b&&this.#n?.(n,t,r),this.#e&&this.#m?.push([n,t,r])),this.#u.delete(t),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.#e&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(t){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,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.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.#e&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},Gr=typeof process=="object"&&process?process:{stdout:null,stderr:null},bo=e=>!!e&&typeof e=="object"&&(e instanceof ye||e instanceof hr.default||vo(e)||To(e)),vo=e=>!!e&&typeof e=="object"&&e instanceof be.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==hr.default.Writable.prototype.pipe,To=e=>!!e&&typeof e=="object"&&e instanceof be.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",st=Symbol("EOF"),it=Symbol("maybeEmitEnd"),ut=Symbol("emittedEnd"),ce=Symbol("emittingEnd"),Wt=Symbol("emittedError"),he=Symbol("closed"),Kr=Symbol("read"),ue=Symbol("flush"),zr=Symbol("flushChunk"),G=Symbol("encoding"),Rt=Symbol("decoder"),C=Symbol("flowing"),$t=Symbol("paused"),kt=Symbol("resume"),A=Symbol("buffer"),I=Symbol("pipes"),R=Symbol("bufferLength"),tr=Symbol("bufferPush"),de=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),er=Symbol("error"),rr=Symbol("emitData"),Yr=Symbol("emitEnd"),sr=Symbol("emitEnd2"),J=Symbol("async"),ir=Symbol("abort"),pe=Symbol("aborted"),jt=Symbol("signal"),Et=Symbol("dataListeners"),U=Symbol("discarded"),Ht=e=>Promise.resolve().then(e),Mo=e=>e(),Co=e=>e==="end"||e==="finish"||e==="prefinish",Ao=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Ro=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Ts=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[kt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ko=class extends Ts{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors)}},Oo=e=>!!e.objectMode,Io=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",ye=class extends be.EventEmitter{[C]=!1;[$t]=!1;[I]=[];[A]=[];[O];[G];[J];[Rt];[st]=!1;[ut]=!1;[ce]=!1;[he]=!1;[Wt]=null;[R]=0;[M]=!1;[jt];[pe]=!1;[Et]=0;[U]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Oo(t)?(this[O]=!0,this[G]=null):Io(t)?(this[G]=t.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[J]=!!t.async,this[Rt]=this[G]?new vs.StringDecoder(this[G]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:r}=t;r&&(this[jt]=r,r.aborted?this[ir]():r.addEventListener("abort",()=>this[ir]()))}get bufferLength(){return this[R]}get encoding(){return this[G]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[J]}set async(e){this[J]=this[J]||!!e}[ir](){this[pe]=!0,this.emit("abort",this[jt]?.reason),this.destroy(this[jt]?.reason)}get aborted(){return this[pe]}set aborted(e){}write(e,t,r){if(this[pe])return!1;if(this[st])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 t=="function"&&(r=t,t="utf8"),t||(t="utf8");let s=this[J]?Ht:Mo;if(!this[O]&&!Buffer.isBuffer(e)){if(Ro(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Ao(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[C]&&this[R]!==0&&this[ue](!0),this[C]?this.emit("data",e):this[tr](e),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):e.length?(typeof e=="string"&&!(t===this[G]&&!this[Rt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[G]&&(e=this[Rt].write(e)),this[C]&&this[R]!==0&&this[ue](!0),this[C]?this.emit("data",e):this[tr](e),this[R]!==0&&this.emit("readable"),r&&s(r),this[C]):(this[R]!==0&&this.emit("readable"),r&&s(r),this[C])}read(e){if(this[M])return null;if(this[U]=!1,this[R]===0||e===0||e&&e>this[R])return this[it](),null;this[O]&&(e=null),this[A].length>1&&!this[O]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[R])]);let t=this[Kr](e||null,this[A][0]);return this[it](),t}[Kr](e,t){if(this[O])this[de]();else{let r=t;e===r.length||e===null?this[de]():typeof r=="string"?(this[A][0]=r.slice(e),t=r.slice(0,e),this[R]-=e):(this[A][0]=r.subarray(e),t=r.subarray(0,e),this[R]-=e)}return this.emit("data",t),!this[A].length&&!this[st]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[st]=!0,this.writable=!1,(this[C]||!this[$t])&&this[it](),this}[kt](){this[M]||(!this[Et]&&!this[I].length&&(this[U]=!0),this[$t]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[ue]():this[st]?this[it]():this.emit("drain"))}resume(){return this[kt]()}pause(){this[C]=!1,this[$t]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[C]}get paused(){return this[$t]}[tr](e){this[O]?this[R]+=1:this[R]+=e.length,this[A].push(e)}[de](){return this[O]?this[R]-=1:this[R]-=this[A][0].length,this[A].shift()}[ue](e=!1){do;while(this[zr](this[de]())&&this[A].length);!e&&!this[A].length&&!this[st]&&this.emit("drain")}[zr](e){return this.emit("data",e),this[C]}pipe(e,t){if(this[M])return e;this[U]=!1;let r=this[ut];return t=t||{},e===Gr.stdout||e===Gr.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[I].push(t.proxyErrors?new ko(this,e,t):new Ts(this,e,t)),this[J]?Ht(()=>this[kt]()):this[kt]()),e}unpipe(e){let t=this[I].find(r=>r.dest===e);t&&(this[I].length===1?(this[C]&&this[Et]===0&&(this[C]=!1),this[I]=[]):this[I].splice(this[I].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[U]=!1,this[Et]++,!this[I].length&&!this[C]&&this[kt]();else if(e==="readable"&&this[R]!==0)super.emit("readable");else if(Co(e)&&this[ut])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Wt]){let s=t;this[J]?Ht(()=>s.call(this,this[Wt])):s.call(this,this[Wt])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Et]=this.listeners("data").length,this[Et]===0&&!this[U]&&!this[I].length&&(this[C]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Et]=0,!this[U]&&!this[I].length&&(this[C]=!1)),t}get emittedEnd(){return this[ut]}[it](){!this[ce]&&!this[ut]&&!this[M]&&this[A].length===0&&this[st]&&(this[ce]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[he]&&this.emit("close"),this[ce]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==M&&this[M])return!1;if(e==="data")return!this[O]&&!r?!1:this[J]?(Ht(()=>this[rr](r)),!0):this[rr](r);if(e==="end")return this[Yr]();if(e==="close"){if(this[he]=!0,!this[ut]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Wt]=r,super.emit(er,r);let i=!this[jt]||this.listeners("error").length?super.emit("error",r):!1;return this[it](),i}else if(e==="resume"){let i=super.emit("resume");return this[it](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let s=super.emit(e,...t);return this[it](),s}[rr](e){for(let r of this[I])r.dest.write(e)===!1&&this.pause();let t=this[U]?!1:super.emit("data",e);return this[it](),t}[Yr](){return this[ut]?!1:(this[ut]=!0,this.readable=!1,this[J]?(Ht(()=>this[sr]()),!0):this[sr]())}[sr](){if(this[Rt]){let t=this[Rt].end();if(t){for(let r of this[I])r.dest.write(t);this[U]||super.emit("data",t)}}for(let t of this[I])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[O]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[O]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[G]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(M,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[U]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[st])return t();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),t(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[st]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),t(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,h)=>{i=h,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let e=!1,t=()=>(this.pause(),this.off(er,t),this.off(M,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let s=this.read();return s===null?t():{done:!1,value:s}};return this.once("end",t),this.once(er,t),this.once(M,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[M])return e?this.emit("error",e):this.emit(M),this;this[M]=!0,this[U]=!0,this[A].length=0,this[R]=0;let t=this;return typeof t.close=="function"&&!this[he]&&t.close(),e?this.emit("error",e):this.emit(M),this}static get isStream(){return bo}},Do=q.realpathSync.native,zt={lstatSync:q.lstatSync,readdir:q.readdir,readdirSync:q.readdirSync,readlinkSync:q.readlinkSync,realpathSync:Do,promises:{lstat:ft.lstat,readdir:ft.readdir,readlink:ft.readlink,realpath:ft.realpath}},Ms=e=>!e||e===zt||e===_o?zt:{...zt,...e,promises:{...zt.promises,...e.promises||{}}},Cs=/^\\\\\?\\([a-z]:)\\?$/i,Po=e=>e.replace(/\//g,"\\").replace(Cs,"$1\\"),xo=/[\\\/]/,H=0,As=1,Rs=2,X=4,ks=6,Os=8,wt=10,Is=12,j=15,Bt=~j,nr=16,Jr=32,Yt=64,K=128,fe=256,Se=512,Xr=Yt|K|Se,Lo=1023,or=e=>e.isFile()?Os:e.isDirectory()?X:e.isSymbolicLink()?wt:e.isCharacterDevice()?Rs:e.isBlockDevice()?ks:e.isSocket()?Is:e.isFIFO()?As:H,qr=new _e({max:2**12}),Jt=e=>{let t=qr.get(e);if(t)return t;let r=e.normalize("NFKD");return qr.set(e,r),r},Vr=new _e({max:2**12}),me=e=>{let t=Vr.get(e);if(t)return t;let r=Jt(e.toLowerCase());return Vr.set(e,r),r},Qr=class extends _e{constructor(){super({max:256})}},No=class extends _e{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Ds=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#t;#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}#h;get blksize(){return this.#h}#a;get ino(){return this.#a}#d;get size(){return this.#d}#u;get blocks(){return this.#u}#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;#e;#x;#D;#A;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=H,r,s,i,n,o){this.name=e,this.#T=i?me(e):Jt(e),this.#e=t&Lo,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.#t=this.parent.#t:this.#t=Ms(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(e){if(!e)return this;let t=this.getRootString(e),r=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#P(r):this.#P(r)}#P(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#x.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#x.set(this,t),this.#e&=~nr,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),s=this.nocase?me(e):Jt(e);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+e:void 0,o=this.newChild(e,H,{...t,parent:this,fullpath:n});return this.canReaddir()||(o.#e|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let e=this.name,t=this.parent;if(!t)return this.#b=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#C!==void 0)return this.#C;let e=this.name,t=this.parent;if(!t)return this.#C=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#g!==void 0)return this.#g;let e=this.name,t=this.parent;if(!t)return this.#g=this.name;let r=t.fullpath()+(t.parent?this.sep:"")+e;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 e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#e&j)===H}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&j)===Os}isDirectory(){return(this.#e&j)===X}isCharacterDevice(){return(this.#e&j)===Rs}isBlockDevice(){return(this.#e&j)===ks}isFIFO(){return(this.#e&j)===As}isSocket(){return(this.#e&j)===Is}isSymbolicLink(){return(this.#e&wt)===wt}lstatCached(){return this.#e&Jr?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#A}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let e=this.#e&j;return!(e!==H&&e!==wt||this.#e&fe||this.#e&K)}calledReaddir(){return!!(this.#e&nr)}isENOENT(){return!!(this.#e&K)}isNamed(e){return this.nocase?this.#T===me(e):this.#T===Jt(e)}async readlink(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#t.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#D=r}catch(t){this.#I(t.code);return}}readlinkSync(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#t.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#D=r}catch(t){this.#I(t.code);return}}#F(e){this.#e|=nr;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#v()}}#v(){this.#e&K||(this.#e=(this.#e|K)&Bt,this.#G())}#G(){let e=this.children();e.provisional=0;for(let t of e)t.#v()}#U(){this.#e|=Se,this.#L()}#L(){if(this.#e&Yt)return;let e=this.#e;(e&j)===X&&(e&=Bt),this.#e=e|Yt,this.#G()}#W(e=""){e==="ENOTDIR"||e==="EPERM"?this.#L():e==="ENOENT"?this.#v():this.children().provisional=0}#O(e=""){e==="ENOTDIR"?this.parent.#L():e==="ENOENT"&&this.#v()}#I(e=""){let t=this.#e;t|=fe,e==="ENOENT"&&(t|=K),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Bt),this.#e=t,e==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(e,t){return this.#H(e,t)||this.#j(e,t)}#j(e,t){let r=or(e),s=this.newChild(e.name,r,{parent:this}),i=s.#e&j;return i!==X&&i!==wt&&i!==H&&(s.#e|=Yt),t.unshift(s),t.provisional++,s}#H(e,t){for(let r=t.provisional;r<t.length;r++){let s=t[r];if((this.nocase?me(e.name):Jt(e.name))===s.#T)return this.#c(e,s,r,t)}}#c(e,t,r,s){let i=t.name;return t.#e=t.#e&Bt|or(e),i!==e.name&&(t.name=e.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#e&K)===0)try{return this.#B(await this.#t.promises.lstat(this.fullpath())),this}catch(e){this.#O(e.code)}}lstatSync(){if((this.#e&K)===0)try{return this.#B(this.#t.lstatSync(this.fullpath())),this}catch(e){this.#O(e.code)}}#B(e){let{atime:t,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:h,ino:u,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=e;this.#w=t,this.#l=r,this.#m=s,this.#_=i,this.#h=n,this.#u=o,this.#R=a,this.#p=l,this.#r=c,this.#y=h,this.#a=u,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=or(e);this.#e=this.#e&Bt|y|Jr,y!==H&&y!==X&&y!==wt&&(this.#e|=Yt)}#N=[];#k=!1;#K(e){this.#k=!1;let t=this.#N.slice();this.#N.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#N.push(e),this.#k)return;this.#k=!0;let s=this.fullpath();this.#t.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))})}#z;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#z)await this.#z;else{let r=()=>{};this.#z=new Promise(s=>r=s);try{for(let s of await this.#t.promises.readdir(t,{withFileTypes:!0}))this.#$(s,e);this.#F(e)}catch(s){this.#W(s.code),e.provisional=0}this.#z=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#t.readdirSync(t,{withFileTypes:!0}))this.#$(r,e);this.#F(e)}catch(r){this.#W(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#e&Xr)return!1;let e=j&this.#e;return e===H||e===X||e===wt}shouldWalk(e,t){return(this.#e&X)===X&&!(this.#e&Xr)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#A)return this.#A;if(!((Se|fe|K)&this.#e))try{let e=await this.#t.promises.realpath(this.fullpath());return this.#A=this.resolve(e)}catch{this.#U()}}realpathSync(){if(this.#A)return this.#A;if(!((Se|fe|K)&this.#e))try{let e=this.#t.realpathSync(this.fullpath());return this.#A=this.resolve(e)}catch{this.#U()}}[Ds](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],s=this;for(;s&&s.parent;)t.add(s),s.#b=r.join(this.sep),s.#C=r.join("/"),s=s.parent,r.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#b=void 0,s.#C=void 0,s=s.parent}},Ps=class xs extends L{sep="\\";splitSep=xo;constructor(t,r=H,s,i,n,o,a){super(t,r,s,i,n,o,a)}newChild(t,r=H,s={}){return new xs(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return It.win32.parse(t).root}getRoot(t){if(t=Po(t.toUpperCase()),t===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(t,r))return this.roots[t]=s;return this.roots[t]=new ur(t,this).root}sameRoot(t,r=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Cs,"$1\\"),t===r}},Ls=class Ns extends L{splitSep="/";sep="/";constructor(t,r=H,s,i,n,o,a){super(t,r,s,i,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,r=H,s={}){return new Ns(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Us=class{root;rootPath;roots;cwd;#t;#r;#n;nocase;#i;constructor(e=process.cwd(),t,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=zt}={}){this.#i=Ms(n),(e instanceof URL||e.startsWith("file://"))&&(e=(0,bs.fileURLToPath)(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new Qr,this.#r=new Qr,this.#n=new No(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,h=t.sep,u=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(h),relativePosix:new Array(m).fill("..").join("/"),fullpath:u+=(p?"":h)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#t.get(t);if(r!==void 0)return r;let s=this.cwd.resolve(t).fullpath();return this.#t.set(t,s),s}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#r.get(t);if(r!==void 0)return r;let s=this.cwd.resolve(t).fullpathPosix();return this.#r.set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let s=await e.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set,l=(h,u)=>{a.add(h),h.readdirCB((p,f)=>{if(p)return u(p);let m=f.length;if(!m)return u();let g=()=>{--m===0&&u()};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=e;return new Promise((h,u)=>{l(c,p=>{if(p)return u(p);h(o)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let h of c){(!i||i(h))&&o.push(r?h:h.fullpath());let u=h;if(h.isSymbolicLink()){if(!(s&&(u=h.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(a,n)&&a.add(u)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t;(!i||i(e))&&(yield r?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let h=c;if(c.isSymbolicLink()){if(!(s&&(h=c.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(o,n)&&o.add(h)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=new ye({objectMode:!0});(!i||i(e))&&o.write(r?e:e.fullpath());let a=new Set,l=[e],c=0,h=()=>{let u=!1;for(;!u;){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())||(u=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}u&&!o.flowing?o.once("drain",h):m||h()},m=!0;p.readdirCB(f,!0),m=!1}};return h(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof L||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=t,o=new ye({objectMode:!0}),a=new Set;(!i||i(e))&&o.write(r?e:e.fullpath());let l=[e],c=0,h=()=>{let u=!1;for(;!u;){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())||(u=!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)}}u&&!o.flowing&&o.once("drain",h)};return h(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Ds](t)}},ur=class extends Us{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,It.win32,"\\",{...t,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(e){return It.win32.parse(e).root.toUpperCase()}newRoot(e){return new Ps(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},dr=class extends Us{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,It.posix,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Ls(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Fs=class extends dr{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},dl=process.platform==="win32"?Ps:Ls,Uo=process.platform==="win32"?ur:process.platform==="darwin"?Fs:dr,Fo=e=>e.length>=1,Wo=e=>e.length>=1,$o=Symbol.for("nodejs.util.inspect.custom"),Ws=class $s{#t;#r;#n;length;#i;#o;#y;#S;#h;#a;#d=!0;constructor(t,r,s,i){if(!Fo(t))throw new TypeError("empty pattern list");if(!Wo(r))throw new TypeError("empty glob list");if(r.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#t,[h,u,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[h,u,p,f,""].join("/");this.#t=[g,...c],this.#r=[w,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",h=a+"/";this.#t=[c,...o],this.#r=[h,...l],this.length=this.#t.length}}}[$o](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===D}isRegExp(){return this.#t[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 $s(this.#t,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#h=this.#h,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#i==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#a!==void 0?this.#a:this.#a=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},jo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Zr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:s,noglobstar:i,platform:n=jo}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of e)this.add(o)}add(e){let t=new pt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let s=t.set[r],i=t.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new Ws(s,i,0,this.platform),o=new pt(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(e){let t=e.fullpath(),r=`${t}/`,s=e.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(t)||n.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(t))return!0;return!1}},Ho=class js{store;constructor(t=new Map){this.store=t}copy(){return new js(new Map(this.store))}hasWalked(t,r){return this.store.get(t.fullpath())?.has(r.globString())}storeWalked(t,r){let s=t.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},Bo=class{store=new Map;add(e,t,r){let s=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Go=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(s=>s.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},ts=class Hs{hasWalkedCache;matches=new Bo;subwalks=new Go;patterns;follow;dot;opts;constructor(t,r){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=r?r.copy():new Ho}processPatterns(t,r){this.patterns=r;let s=r.map(i=>[t,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 u=n.rest();if(u)n=u;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,h=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,h=!0;if(l=n.pattern(),c=n.rest(),h){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let u=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,u);continue}else if(l===D){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let u=c?.pattern(),p=c?.rest();if(!c||(u===""||u===".")&&!p)this.matches.add(i,a,u===""||u===".");else if(u===".."){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 Hs(this.opts,this.hasWalkedCache)}filterEntries(t,r){let s=this.subwalks.get(t),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(t,r,s,i){if((this.dot||!t.name.startsWith("."))&&(r.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,r):t.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(t,s):r.markFollowGlobstar()&&this.subwalks.add(t,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),i)}}testRegExp(t,r,s,i){r.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,r,s,i){t.isNamed(r)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}},Ko=(e,t)=>typeof e=="string"?new Zr([e],t):Array.isArray(e)?new Zr(e,t):e,Bs=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=Ko(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.#t.length=0}))}#i(e){return this.seen.has(e)||!!this.#r?.ignored?.(e)}#o(e){return!!this.#r?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#t.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#t.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;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,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#i(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;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,t)}matchFinish(e,t){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${e.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(e,t,r){let s=await this.matchCheck(e,r);s&&this.matchFinish(s,t)}matchSync(e,t,r){let s=this.matchCheckSync(e,r);s&&this.matchFinish(s,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new ts(this.opts),r)}walkCB2(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,s));return}r.processPatterns(e,t);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(e,t,r,s){r=r.filterEntries(e,t);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(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new ts(this.opts),r)}walkCB2Sync(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,s));return}r.processPatterns(e,t);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(e,t,r,s){r=r.filterEntries(e,t);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()}},es=class extends Bs{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},rs=class extends Bs{results;constructor(e,t,r){super(e,t,r),this.results=new ye({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},zo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",yt=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(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=(0,Ss.fileURLToPath)(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=e,this.platform=t.platform||zo,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=t.platform==="win32"?ur:t.platform==="darwin"?Fs:t.platform?dr:Uo;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,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 pt(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 Ws(a,c,0,this.platform)})}async walk(){return[...await new es(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 es(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 rs(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 rs(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()}},Yo=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let r of e)if(new pt(r,t).hasMagic())return!0;return!1};function ve(e,t={}){return new yt(e,t).streamSync()}function Gs(e,t={}){return new yt(e,t).stream()}function Xt(e,t={}){return new yt(e,t).walkSync()}async function ss(e,t={}){return new yt(e,t).walk()}function Te(e,t={}){return new yt(e,t).iterateSync()}function Ks(e,t={}){return new yt(e,t).iterate()}var Jo=ve,Xo=Object.assign(Gs,{sync:ve}),qo=Te,Vo=Object.assign(Ks,{sync:Te}),Qo=Object.assign(Xt,{stream:ve,iterate:Te}),is=Object.assign(ss,{glob:ss,globSync:Xt,sync:Qo,globStream:Gs,stream:Xo,globStreamSync:ve,streamSync:Jo,globIterate:Ks,iterate:Vo,globIterateSync:Te,iterateSync:qo,Glob:yt,hasMagic:Yo,escape:ds,unescape:Ot});is.glob=is;var nt=require("fs"),zs=require("path");function Ys(e){try{if(!(0,nt.existsSync)(e))return{offsets:{}};let t=(0,nt.readFileSync)(e,"utf-8"),r=JSON.parse(t);return r.offsets?r:{offsets:{}}}catch(t){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:e,error:t instanceof Error?t.message:String(t)}),{offsets:{}}}}function Js(e,t){try{let r=(0,zs.dirname)(e);(0,nt.existsSync)(r)||(0,nt.mkdirSync)(r,{recursive:!0}),(0,nt.writeFileSync)(e,JSON.stringify(t,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:e,error:r instanceof Error?r.message:String(r)})}}var te=ht(require("path"),1);var Pt=ht(require("path"),1),B=require("fs"),mi=require("child_process");var Xs=require("node:child_process");function Me(e,t,r){return(0,Xs.spawn)(e,t??[],{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},mt={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ot(e){return process.platform==="win32"?Math.round(e*W.WINDOWS_MULTIPLIER):e}var V=require("fs"),qt=require("path"),pr=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(ot(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,qt.join)((0,pr.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,qt.join)((0,pr.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(t){return process.env[t]??this.DEFAULTS[t]}static getInt(t){let r=this.get(t);return parseInt(r,10)}static getBool(t){let r=this.get(t);return r==="true"||r===!0}static applyEnvOverrides(t){let r={...t};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(t,r=!0){try{if(!(0,V.existsSync)(t)){let a=this.getAllDefaults();try{let l=(0,qt.dirname)(t);(0,V.existsSync)(l)||(0,V.mkdirSync)(l,{recursive:!0}),(0,V.writeFileSync)(t,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",t)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",t,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,V.readFileSync)(t,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,V.writeFileSync)(t,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,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:",t,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var Ce=null;function at(){return Ce!==null||(Ce=Q.loadFromFile(ie)),Ce}var _t=require("fs");var Er=require("child_process");var tt=require("fs"),gr=ht(require("path"),1);var Zo=["CLAUDECODE_","CLAUDE_CODE_"],ta=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),ea=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"]),ra=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 Ae(e=process.env){let t={};for(let[r,s]of Object.entries(e))if(s!==void 0){if(ra.has(r)){t[r]=s;continue}ta.has(r)||ea.has(r)||Zo.some(i=>r.startsWith(i))||(t[r]=s)}return t}var sa=5e3,ia=1e3,na=k.supervisorRegistry();function Z(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}var oa=5e3,qs=new Map;function aa(e){let t=qs.get(e);if(t&&Date.now()-t.capturedAtMs<oa)return t.token;let r=null;try{let s=(0,Er.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ae(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:e,error:s instanceof Error?s.message:String(s)}),r=null}return qs.set(e,{token:r,capturedAtMs:Date.now()}),r}function Vs(e){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux")try{let t=(0,tt.readFileSync)(`/proc/${e}/stat`,"utf-8"),r=t.lastIndexOf(") ");if(r<0)return null;let i=t.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}if(process.platform==="win32")return aa(e);try{let t=(0,Er.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ae(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}}function wr(e){if(!e||!Z(e.pid))return!1;if(!e.startToken)return!0;let t=Vs(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var Sr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=na){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,tt.mkdirSync)(gr.default.dirname(this.registryPath),{recursive:!0}),!(0,tt.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,tt.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 t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,s){this.initialize(),this.entries.set(t,r),s&&this.runtimeProcesses.set(t,s),this.persist()}unregister(t){this.initialize();let r=this.entries.get(t);this.entries.delete(t),this.runtimeProcesses.delete(t),this.persist(),r?.type==="sdk"&&mr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let s=Date.parse(t.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(t){let r=String(t);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}getByPid(t){return this.getAll().filter(r=>r.pid===t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[s,i]of this.entries)Z(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),t+=1,i.type==="sdk"&&(r+=1));t>0&&this.persist();for(let s=0;s<r;s+=1)mr();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let s=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{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()+sa;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()+ia;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"&&mr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:s,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};(0,tt.mkdirSync)(gr.default.dirname(this.registryPath),{recursive:!0}),(0,tt.writeFileSync)(this.registryPath,JSON.stringify(t,null,2))}},fr=null;function Re(){return fr||(fr=new Sr),fr}var la=[];function mr(){let e=la.shift();e&&e()}var ti=require("child_process"),ei=require("fs"),ri=require("util");var ca=(0,ri.promisify)(ti.execFile),ha=k.workerPid();async function si(e){let t=e.currentPid??process.pid,r=e.pidFilePath??ha,s=e.registry.getAll(),i=[...s].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!Z(o.pid)){e.registry.unregister(o.id);continue}try{await Zs(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 Qs(i,5e3);let n=i.filter(o=>Z(o.pid));for(let o of n)try{await Zs(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 Qs(n,1e3);for(let o of i)e.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===t))e.registry.unregister(o.id);try{(0,ei.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)})}e.registry.pruneDeadEntries()}async function Qs(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.filter(i=>Z(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function Zs(e,t){let{pid:r,pgid:s}=e;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(t==="SIGTERM"){try{process.kill(r,t)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await ua();if(i){await new Promise((o,a)=>{i(r,t,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];t==="SIGKILL"&&n.push("/F"),await ca("taskkill",n,{timeout:W.POWERSHELL_COMMAND,windowsHide:!0})}async function ua(){let e="tree-kill";try{let t=await import(e);return t.default??t}catch(t){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},t instanceof Error?t:void 0),null}}var ii=3e4,Dt=null;function da(){let t=Re().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function ni(){Dt===null&&(Dt=setInterval(da,ii),Dt.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:ii}))}function oi(){Dt!==null&&(clearInterval(Dt),Dt=null,d.debug("SYSTEM","Health checker stopped"))}var pa=k.workerPid(),yr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),ke({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ni()}configureSignalHandlers(t){if(this.shutdownHandler=t,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}oi(),this.stopPromise=si({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,s){this.registry.register(t,r,s)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},dc=new yr(Re());function ke(e={}){let t=e.pidFilePath??pa;if(!(0,_t.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,_t.readFileSync)(t,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(i)}),(0,_t.rmSync)(t,{force:!0}),"invalid"}return wr(r)&&r?((e.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,_t.rmSync)(t,{force:!0}),"stale")}var Oe=require("child_process");var ai=require("util");var yc=(0,ai.promisify)(Oe.exec),_c=k.dataDir(),bc=k.workerPid();var li=ht(require("path"),1);var ci=require("fs");async function ma(e,t,r="GET"){let s=await fetch(`http://127.0.0.1:${e}${t}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function ga(){try{let e=li.default.join(se,"package.json");return JSON.parse((0,ci.readFileSync)(e,"utf-8")).version}catch(e){if(e instanceof Error){let t=e.code;if(t==="ENOENT"||t==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:t}),"unknown";throw e}throw e}}async function Sa(e){try{let t=await ma(e,"/api/version");return t.ok?JSON.parse(t.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function hi(e){let t=ga(),r=await Sa(e);return!r||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:r}:{matches:t===r,pluginVersion:t,workerVersion:r}}function br(e,t,r){let s=process.env[e];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max})}return t}var vr=br("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ot(W.HEALTH_CHECK),{min:500,max:3e5}),Gc=br("CLAUDE_MEM_API_TIMEOUT_MS",ot(W.API_REQUEST),{min:500,max:3e5}),Ea=br("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ot(W.HOOK_READINESS_WAIT),{min:0,max:3e5}),wa={min:500,max:3e5};function Tr(e,t={},r){return new Promise((s,i)=>{let n=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(e,t).then(o=>{clearTimeout(n),s(o)},o=>{clearTimeout(n),i(o)})})}var Ie=null,De=null,Pe=null,xe=null;function ya(){return Pt.default.join(Q.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Mr(){return Pe!==null||(Pe=Q.loadFromFile(ya())),Pe}function ui(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function _a(e,t,r){let s=process.env[e];if(s!==void 0){let o=ui(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max}),t)}let i=Mr()[e],n=ui(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:i,min:r.min,max:r.max}),t)}function gi(){if(Ie!==null)return Ie;let e=Mr();return Ie=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Ie}function ba(){return De!==null||(De=Mr().CLAUDE_MEM_WORKER_HOST),De}function va(){return xe!==null||(xe=_a("CLAUDE_MEM_API_TIMEOUT_MS",ot(W.API_REQUEST),wa)),xe}function Ta(e){return`http://${ba()}:${gi()}${e}`}function gt(e,t={}){let r=t.method??"GET",s=t.timeoutMs??va(),i=Ta(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),s>0?Tr(i,n,s):fetch(i,n)}async function Ma(){return(await gt("/api/health",{timeoutMs:vr})).ok}async function di(){return(await gt("/api/readiness",{timeoutMs:vr})).ok}function Ca(){let e=[Pt.default.join(se,"plugin","scripts","worker-service.cjs"),Pt.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,B.existsSync)(t))return t;return null}function Aa(){if(process.env.BUN&&(0,B.existsSync)(process.env.BUN))return process.env.BUN;try{let e=process.platform==="win32"?"where bun":"which bun";return(0,mi.execSync)(e,{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 Ra(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await Si())return!0;r<e.attempts&&(await new Promise(s=>setTimeout(s,t)),t*=2)}return!1}async function pi(e=Ea){if(e<=0)try{return await di()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await di())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Si(){let e;try{e=await Ma()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!e)return!1;let t=ke({logAlive:!1});return t==="missing"||t==="alive"}async function Ne(){if(await Si()){let{matches:i,pluginVersion:n,workerVersion:o}=await hi(gi());if(i)return await pi()?!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 gt("/api/admin/restart",{method:"POST",timeoutMs:vr})}catch(a){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:a instanceof Error?a.message:String(a)})}}let e=Aa(),t=Ca();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!t)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:e,scriptPath:t});try{Me(e,[t,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(i){return i instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:t},i):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:t,error:String(i)}),!1}return await Ra({attempts:6,backoffMs:500})?await pi()?!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 Le=null;async function ka(){return Le!==null||(Le=await Ne()),Le}var Oa=3;function Ei(){return Pt.default.join(v,"state")}function wi(){return Pt.default.join(Ei(),"hook-failures.json")}function yi(){try{let e=(0,B.readFileSync)(wi(),"utf-8"),t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function _i(e){let t=Ei(),r=wi(),s=`${r}.tmp`;try{(0,B.existsSync)(t)||(0,B.mkdirSync)(t,{recursive:!0}),(0,B.writeFileSync)(s,JSON.stringify(e),"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 Ia(){try{let t=at().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return Oa}function Da(){let t={consecutiveFailures:yi().consecutiveFailures+1,lastFailureAt:Date.now()};_i(t);let r=Ia();return t.consecutiveFailures>=r&&Dr(`claude-mem worker unreachable for ${t.consecutiveFailures} consecutive hooks.`),t.consecutiveFailures}function fi(){yi().consecutiveFailures!==0&&_i({consecutiveFailures:0,lastFailureAt:0})}var _r=Symbol.for("claude-mem/worker-fallback");function Vt(e){return typeof e=="object"&&e!==null&&e[_r]===!0}async function Qt(e,t,r,s={}){if(!await ka())return Da(),{continue:!0,reason:"worker_unreachable",[_r]:!0};let n={method:t};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 gt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(fi(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${t} ${e} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[_r]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}fi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var vi=require("os"),Ti=ht(require("path"),1),Mi=require("child_process");var Fe=require("fs"),Ue=ht(require("path"),1);var Zt={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function bi(e){let t=Ue.default.join(e,".git"),r;try{r=(0,Fe.statSync)(t)}catch(h){return h instanceof Error&&h.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:h instanceof Error?h.message:String(h)}),Zt}if(!r.isFile())return Zt;let s;try{s=(0,Fe.readFileSync)(t,"utf-8").trim()}catch(h){return d.warn("GIT","Failed to read .git file",{error:h instanceof Error?h.message:String(h)}),Zt}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return Zt;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Zt;let a=o[1],l=Ue.default.basename(e),c=Ue.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function Ci(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,vi.homedir)()):e}function Pa(e){try{return(0,Mi.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function xa(e){if(!e||e.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),"unknown-project";let t=Ci(e),s=Pa(t)??t,i=Ti.default.basename(s);if(i===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),"unknown-project"}return i}function bt(e){let t=xa(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=Ci(e),s=bi(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var vt=require("path");var Ai=require("os"),Ri=require("path");function La(e){let t=e.startsWith("~")?(0,Ai.homedir)()+e.slice(1):e;t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function We(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),s=(0,Ri.basename)(r),i=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=La(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 Na(e,t){let r=(0,vt.normalize)(e),s=(0,vt.normalize)(t);if(r===s)return!0;let i=(0,vt.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,vt.isAbsolute)(i)}function $e(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(Na(e,ne))return!1;let t=at();return!We(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var ki="claude";function Ua(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function St(e){if(!e)return ki;let t=Ua(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:ki}var Di=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Oi=new RegExp(`<(${Di.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Ii=100;function Fa(e){let t=Object.fromEntries(Di.map(i=>[i,0]));Oi.lastIndex=0;let r=0,s=e.replace(Oi,(i,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Ii&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Ii,contentLength:e.length}),{stripped:s.trim(),counts:t}}function Cr(e){return Fa(e).stripped}var Wa=["task-notification"],$a=new RegExp(`^\\s*<(${Wa.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ja=256*1024;function Pi(e){return!e||e.length>ja?!1:$a.test(e)}var Ha=ot(W.API_REQUEST),lt=class extends Error{kind;status;cause;constructor(t,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=t,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)}},je=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=Ba(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??Ha}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),s=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(t){if(!t.sessionId)throw new lt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new lt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,s=t.kind??"manual",i=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,s){if(!this.apiKey||!this.apiKey.trim())throw new lt("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Tr(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),h=/timed out|timeout/i.test(c);throw new lt(h?"timeout":"transport",`Server beta ${t} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new lt("http_error",`Server beta ${t} ${r} returned ${o.status}: ${Ga(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 lt("invalid_response",`Server beta ${t} ${r} returned non-JSON response`,{cause:l})}}};function xi(e){return e instanceof lt}function Ba(e){return e.replace(/\/+$/,"")}function Ga(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function Ka(){return(at().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function za(){let e=at(),t=(e.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(e.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!t)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:t,apiKey:r};return{runtime:"server-beta",client:new je(i),projectId:s,serverBaseUrl:t}}function Li(){if(Ka()!=="server-beta")return{runtime:"worker"};let e=za();return e||{runtime:"worker"}}function Ni(e,t){d.warn("HOOK",`[server-beta-fallback] reason=${e}`,t??{})}var Ui={async execute(e){let{sessionId:t,prompt:r}=e,s=e.cwd??process.cwd();if(!t)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:mt.SUCCESS};if(!$e(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&Pi(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=bt(s).primary,o=St(e.platform),a=Li();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(xi(m)&&m.isFallbackEligible())Ni(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:mt.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:t,project:n});let l=await Qt("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:i,platformSource:o});if(Vt(l))return{continue:!0,suppressOutput:!0,exitCode:mt.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:mt.SUCCESS};let c=l.sessionDbId,h=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:h,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${h} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${h} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let u=at(),p=String(u.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=u.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await Qt("/api/context/semantic","POST",{q:i,project:n,limit:m});!Vt(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=${h} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var Fi={async execute(e){let{sessionId:t,cwd:r,filePath:s,edits:i}=e,n=St(e.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 ${t}, file ${s}`);if(!$e(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:mt.SUCCESS};let o=await Qt("/api/sessions/observations","POST",{contentSessionId:t,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return Vt(o)?{continue:!0,suppressOutput:!0,exitCode:mt.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),He=require("path");var Gh=k.settings();function Wi(e,t){let r="<claude-mem-context>",s="</claude-mem-context>";if(!e)return`${r}
|
|
15
15
|
${t}
|
|
16
16
|
${s}`;let i=e.indexOf(r),n=e.indexOf(s);return i!==-1&&n!==-1?e.substring(0,i)+`${r}
|
|
17
17
|
${t}
|
|
@@ -19,8 +19,8 @@ ${s}`+e.substring(n+s.length):e+`
|
|
|
19
19
|
|
|
20
20
|
${r}
|
|
21
21
|
${t}
|
|
22
|
-
${s}`}function
|
|
22
|
+
${s}`}function $i(e,t){if(!e)return;let r=(0,He.resolve)(e);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,He.dirname)(e);(0,z.existsSync)(s)||(0,z.mkdirSync)(s,{recursive:!0});let i="";(0,z.existsSync)(e)&&(i=(0,z.readFileSync)(e,"utf-8"));let n=`# Memory Context
|
|
23
23
|
|
|
24
|
-
${t}`,o=
|
|
25
|
-
`);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(t,r){await this.queueSummary(t),await this.updateContext(t,r),t.pendingTools?.clear();let s=this.getSessionKey(r,t.sessionId);this.sessions.delete(s)}async queueSummary(t){if(!await
|
|
26
|
-
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},
|
|
24
|
+
${t}`,o=Wi(i,n),a=`${e}.tmp`;try{(0,z.writeFileSync)(a,o),(0,z.renameSync)(a,e)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:e},l instanceof Error?l:new Error(String(l)))}}function Ya(e){let t=e.trim().replace(/^\$\.?/,"");if(!t)return[];let r=[],s=t.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 Ar(e,t){if(!t)return;let r=Ya(t),s=e;for(let i of r){if(s==null)return;s=s[i]}return s}function ji(e){return e==null||e===""}function Hi(e,t){if(e.startsWith("$watch.")){let r=e.slice(7);return t.watch[r]}if(e.startsWith("$schema.")){let r=e.slice(8);return t.schema[r]}if(e.startsWith("$session.")){let r=e.slice(9);return t.session?t.session[r]:void 0}if(e==="$cwd")return t.watch.workspace;if(e==="$project")return t.watch.project}function xt(e,t,r){if(e!==void 0){if(typeof e=="string"){let s=Hi(e,r);return s!==void 0?s:Ar(t,e)}if(e.coalesce&&Array.isArray(e.coalesce))for(let s of e.coalesce){let i=xt(s,t,r);if(!ji(i))return i}if(e.path){let s=Hi(e.path,r);if(s!==void 0)return s;let i=Ar(t,e.path);if(!ji(i))return i}if(e.value!==void 0)return e.value;if(e.default!==void 0)return e.default}}function Bi(e,t,r){let s={};if(!e)return s;for(let[i,n]of Object.entries(e))s[i]=xt(n,t,r);return s}function Gi(e,t,r){if(!t)return!0;let s=t.path||r.eventTypePath||"type",i=s?Ar(e,s):void 0,n=i==null||i==="";if(t.exists!==void 0&&(t.exists&&n||!t.exists&&!n)||t.equals!==void 0&&i!==t.equals||t.not_equals!==void 0&&i===t.not_equals||t.in&&Array.isArray(t.in)&&!t.in.includes(i)||t.not_in&&Array.isArray(t.not_in)&&t.not_in.includes(i)||t.contains!==void 0&&(typeof i!="string"||!i.includes(t.contains))||t.not_contains!==void 0&&typeof i=="string"&&i.includes(t.not_contains))return!1;if(t.regex)try{if(!new RegExp(t.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:t.regex},o instanceof Error?o:void 0),!1}return!0}var Be=class{static checkUserPromptPrivacy(t,r,s,i,n,o){let a=t.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 zi=require("events"),Rr=class e extends zi.EventEmitter{recentStored=new Map;static RECENT_EVENT_TTL_MS=6e4;constructor(){super(),this.setMaxListeners(0),this.on("summaryStoredEvent",t=>{this.recentStored.set(t.sessionId,{event:t,at:Date.now()}),this.evictExpiredStored()})}takeRecentSummaryStored(t){let r=this.recentStored.get(t);if(r){if(Date.now()-r.at>e.RECENT_EVENT_TTL_MS){this.recentStored.delete(t);return}return r.event}}evictExpiredStored(){let t=Date.now()-e.RECENT_EVENT_TTL_MS;for(let[r,s]of this.recentStored)s.at<t&&this.recentStored.delete(r)}},au=new Rr,Ki=null;function Ja(){if(!Ki)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return Ki}async function Yi(e){let{sessionManager:t,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=Ja(),n=St(e.platformSource),o=typeof e.cwd=="string"?e.cwd:"",a=o.trim()?bt(o).primary:"",l=Q.loadFromFile(ie);if(o&&We(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(e.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(e.toolName)&&e.toolInput&&typeof e.toolInput=="object"){let S=e.toolInput,E=S.file_path||S.notebook_path;if(E&&E.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let u=r.getSessionStore(),p,f;try{p=u.createSDKSession(e.contentSessionId,a,"",void 0,n),f=u.getPromptNumberFromUserPrompts(e.contentSessionId)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:e.contentSessionId,toolName:e.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!Be.checkUserPromptPrivacy(u,e.contentSessionId,f,"observation",p,{tool_name:e.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=e.toolInput!==void 0?Cr(JSON.stringify(e.toolInput)):"{}",w=e.toolResponse!==void 0?Cr(JSON.stringify(e.toolResponse)):"{}";return await t.queueObservation(p,{tool_name:e.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:e.toolName}),""),agentId:typeof e.agentId=="string"?e.agentId:void 0,agentType:typeof e.agentType=="string"?e.agentType:void 0,toolUseId:typeof e.toolUseId=="string"?e.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var Ge=class{sessions=new Map;async processEntry(t,r,s,i){for(let n of s.events)Gi(t,n.match,s)&&await this.handleEvent(t,r,s,n,i??void 0)}getSessionKey(t,r){return`${t.name}:${r}`}getOrCreateSession(t,r){let s=this.getSessionKey(t,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:St(t.name)},this.sessions.set(s,i)),i}resolveSessionId(t,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=xt(a,t,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(t,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=xt(a,t,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(t,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=xt(a,t,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?bt(n.cwd).primary:n.project}async handleEvent(t,r,s,i,n){let o=this.resolveSessionId(t,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(t,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(t,r,s,i,a);c&&(a.project=c);let h=Bi(i.fields,t,{watch:r,schema:s,session:a});switch(i.action){case"session_context":this.applySessionContext(a,h);break;case"session_init":await this.handleSessionInit(a,h),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof h.message=="string"&&(a.lastUserMessage=h.message),typeof h.prompt=="string"&&(a.lastUserMessage=h.prompt);break;case"assistant_message":typeof h.message=="string"&&(a.lastAssistantMessage=h.message);break;case"tool_use":await this.handleToolUse(a,h);break;case"tool_result":await this.handleToolResult(a,h);break;case"observation":await this.sendObservation(a,h);break;case"file_edit":await this.sendFileEdit(a,h);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(t,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(t.cwd=s),i&&(t.project=i)}async handleSessionInit(t,r){let s=typeof r.prompt=="string"?r.prompt:"",i=t.cwd??process.cwd();s&&(t.lastUserMessage=s),await Ui.execute({sessionId:t.sessionId,cwd:i,prompt:s,platform:t.platformSource})}async handleToolUse(t,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(t,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(t,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(t.pendingTools||(t.pendingTools=new Map),t.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(t,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&&t.pendingTools){let a=t.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),t.pendingTools.delete(s))}i?await this.sendObservation(t,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:t.sessionId,toolId:s})}async sendObservation(t,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await Yi({contentSessionId:t.sessionId,cwd:t.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:t.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(t,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await Fi.execute({sessionId:t.sessionId,cwd:t.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:t.platformSource})}maybeParseJson(t){if(typeof t!="string")return t;let r=t.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return t;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),t}}parseApplyPatchFiles(t){let r=[],s=t.split(`
|
|
25
|
+
`);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(t,r){await this.queueSummary(t),await this.updateContext(t,r),t.pendingTools?.clear();let s=this.getSessionKey(r,t.sessionId);this.sessions.delete(s)}async queueSummary(t){if(!await Ne())return;let s=t.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:t.sessionId,last_assistant_message:s,platformSource:t.platformSource});try{await gt("/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(t,r){if(!r.context||r.context.mode!=="agents"||Lr(r)||!await Ne())return;let i=t.cwd??r.workspace;if(!i)return;let o=bt(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}`,l=N(r.context.path??`${i}/AGENTS.md`),c=te.default.resolve(l),h=[te.default.resolve(i),te.default.resolve(v)];if(!h.some(m=>c.startsWith(m+te.default.sep)||c===m)){d.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:r.context.path,resolved:c,allowedRoots:h});return}let p;try{p=await gt(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&&($i(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var kr=class{constructor(t,r,s,i){this.filePath=t;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 t=0;try{t=(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(t<this.tailState.offset&&(this.tailState.offset=0),t===this.tailState.offset)return;let r=(0,x.createReadStream)(this.filePath,{start:this.tailState.offset,end:t-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=t,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
|
|
26
|
+
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},Ke=class{constructor(t,r){this.config=t;this.statePath=r;this.state=Ys(r)}config;statePath;processor=new Ge;tailers=new Map;state;rootWatchers=[];async start(){for(let t of this.config.watches)await this.setupWatch(t)}stop(){for(let t of this.tailers.values())t.close();this.tailers.clear();for(let t of this.rootWatchers)t.close();this.rootWatchers=[]}async setupWatch(t){let r=this.resolveSchema(t);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:t.name});return}let s=N(t.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,t,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,x.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:t.name,watchRoot:n});return}try{let o=(0,x.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,Y.resolve)(n,l).replace(/\\/g,"/"),h=this.tailers.get(c);if(h){h.poke();return}let u=this.resolveWatchFiles(s);for(let p of u)this.tailers.has(p)||this.addTailer(p,t,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:t.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:t.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(t){if(!this.hasGlob(t)){if((0,x.existsSync)(t))try{return(0,x.statSync)(t).isDirectory()?t:(0,Y.resolve)(t,"..")}catch{return(0,Y.resolve)(t,"..")}return t}let r=t.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(Y.sep)}resolveSchema(t){return typeof t.schema=="string"?this.config.schemas?.[t.schema]??null:t.schema}resolveWatchFiles(t){if(this.hasGlob(t))return Xt(this.normalizeGlobPattern(t),{nodir:!0,absolute:!0});if((0,x.existsSync)(t))try{if((0,x.statSync)(t).isDirectory()){let s=(0,Y.join)(t,"**","*.jsonl");return Xt(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[t]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:t},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(t){return t.replace(/\\/g,"/")}hasGlob(t){return/[*?[\]{}()]/.test(t)}async addTailer(t,r,s){if(this.tailers.has(t))return;let i=this.extractSessionIdFromPath(t),n=this.state.offsets[t]??0;if(n===0&&r.startAtEnd)try{n=(0,x.statSync)(t).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:t},a instanceof Error?a:void 0),n=0}let o=new kr(t,n,async a=>{await this.handleLine(a,r,s,t,i)},a=>{this.state.offsets[t]=a,Js(this.statePath,this.state)});o.start(),this.tailers.set(t,o),d.info("TRANSCRIPT","Watching transcript file",{file:t,watch:r.name,schema:s.name})}async handleLine(t,r,s,i,n){try{let o=JSON.parse(t);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,Y.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,Y.basename)(i),error:String(o)})}}extractSessionIdFromPath(t){let r=t.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 Or(e,t){let r=e.indexOf(t);return r===-1?null:e[r+1]??null}async function Ji(e,t){switch(e){case"init":{let r=Or(t,"--config")??At;return ae(r),console.log(`Created sample config: ${N(r)}`),0}case"watch":{let r=Or(t,"--config")??At,s;try{s=Ut(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))ae(r),console.log(`Created sample config: ${N(r)}`),s=Ut(r);else throw a}let i=N(s.stateFile??oe),n=new Ke(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=Or(t,"--config")??At;try{Ut(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))ae(r),console.log(`Created sample config: ${N(r)}`),Ut(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 Xa=process.argv[2],qa=process.argv.slice(3);Ji(Xa,qa).then(e=>{process.exit(e)}).catch(e=>{console.error(e),process.exit(1)});
|