@easbot/note 0.1.11 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,29 +1,31 @@
1
- import Gn from'better-sqlite3';import {loadTextFile,Filesystem,Markdown}from'@easbot/utils';import {GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS,getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_SEARCH_CONFIG}from'@easbot/types';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import Ve,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import*as ye from'path';import ye__default,{win32,posix,extname}from'path';import*as te from'jieba-wasm';import*as ha from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import qa from'zod';import {fileURLToPath}from'url';import {EventEmitter}from'events';import hn from'stream';import {StringDecoder}from'string_decoder';import {embed,embedMany,streamText,rerank}from'ai';import {createHash}from'crypto';import {xdgData}from'xdg-basedir';var Un=Object.defineProperty;var Xs=i=>{throw TypeError(i)};var $n=(i,t,e)=>t in i?Un(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var p=(i,t,e)=>$n(i,typeof t!="symbol"?t+"":t,e),bs=(i,t,e)=>t.has(i)||Xs("Cannot "+e);var n=(i,t,e)=>(bs(i,t,"read from private field"),e?e.call(i):t.get(i)),v=(i,t,e)=>t.has(i)?Xs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),f=(i,t,e,s)=>(bs(i,t,"write to private field"),t.set(i,e),e),m=(i,t,e)=>(bs(i,t,"access private method"),e);var zi=(i,t,e,s)=>({set _(r){f(i,t,r);},get _(){return n(i,t,s)}});var Pe=(u=>(u.DATABASE_INIT_FAILED="DATABASE_INIT_FAILED",u.DATABASE_NOT_INITIALIZED="DATABASE_NOT_INITIALIZED",u.DATABASE_QUERY_FAILED="DATABASE_QUERY_FAILED",u.DOCUMENT_PARSE_FAILED="DOCUMENT_PARSE_FAILED",u.EMBEDDING_FAILED="EMBEDDING_FAILED",u.ENTITY_EXTRACTION_FAILED="ENTITY_EXTRACTION_FAILED",u.SEARCH_FAILED="SEARCH_FAILED",u.NODE_NOT_FOUND="NODE_NOT_FOUND",u.EDGE_NOT_FOUND="EDGE_NOT_FOUND",u.INVALID_CONFIG="INVALID_CONFIG",u.MODEL_INJECTION_FAILED="MODEL_INJECTION_FAILED",u))(Pe||{}),j=class extends Error{constructor(e,s,r){super(e,{cause:r});this.code=s;this.cause=r;this.name="KnowledgeBaseError";}toString(){return `${this.name}: ${this.message} (${this.code})`}};var Bi=class{constructor(t){p(this,"db",null);p(this,"storagePath");p(this,"initialized",false);p(this,"initPromise",null);this.storagePath=Filesystem.toUnixPath(t);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initialized=true;}}async doInitialize(){try{this.db=await this.openDatabaseAsync(),this.createTables();}catch(t){throw new j(`Database initialization failed: ${t.message}`,"DATABASE_INIT_FAILED",t)}}async openDatabaseAsync(){return new Promise((t,e)=>{setImmediate(()=>{try{let s=new Gn(this.storagePath);s.pragma("journal_mode = WAL"),s.pragma("synchronous = NORMAL"),s.pragma("cache_size = -64000"),s.pragma("temp_store = MEMORY"),t(s);}catch(s){e(s);}});})}ensureInitialized(){if(!this.initialized||!this.db)throw new j("Database not initialized. Call initialize() first.","DATABASE_NOT_INITIALIZED")}createTables(){if(!this.db)throw new j("Database not initialized. Call initialize() first.","DATABASE_NOT_INITIALIZED");let t=this.db;t.exec(`
1
+ import {b,a}from'./chunks/chunk-NZXCGPUC.mjs';import ge from'better-sqlite3';import {loadTextFile,Filesystem,Markdown}from'@easbot/utils';import {GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS,getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_NOTE_CHUNK_CONFIG}from'@easbot/types';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import B,{readFile}from'fs/promises';import*as U from'path';import U__default,{extname}from'path';import*as F from'jieba-wasm';import {embed,embedMany,streamText,rerank}from'ai';import {createHash}from'crypto';import {xdgData}from'xdg-basedir';var z=(l=>(l.DATABASE_INIT_FAILED="DATABASE_INIT_FAILED",l.DATABASE_NOT_INITIALIZED="DATABASE_NOT_INITIALIZED",l.DATABASE_QUERY_FAILED="DATABASE_QUERY_FAILED",l.DOCUMENT_PARSE_FAILED="DOCUMENT_PARSE_FAILED",l.EMBEDDING_FAILED="EMBEDDING_FAILED",l.ENTITY_EXTRACTION_FAILED="ENTITY_EXTRACTION_FAILED",l.SEARCH_FAILED="SEARCH_FAILED",l.NODE_NOT_FOUND="NODE_NOT_FOUND",l.EDGE_NOT_FOUND="EDGE_NOT_FOUND",l.INVALID_CONFIG="INVALID_CONFIG",l.MODEL_INJECTION_FAILED="MODEL_INJECTION_FAILED",l))(z||{}),R=class extends Error{constructor(t,r,n){super(t,{cause:n});this.code=r;this.cause=n;this.name="KnowledgeBaseError";}toString(){return `${this.name}: ${this.message} (${this.code})`}};var X=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=Filesystem.toUnixPath(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initialized=true;}}async doInitialize(){try{this.db=await this.openDatabaseAsync(),this.createTables();}catch(e){throw new R(`Database initialization failed: ${e.message}`,"DATABASE_INIT_FAILED",e)}}async openDatabaseAsync(){return new Promise((e,t)=>{setImmediate(()=>{try{let r=new ge(this.storagePath);r.pragma("journal_mode = WAL"),r.pragma("synchronous = NORMAL"),r.pragma("cache_size = -64000"),r.pragma("temp_store = MEMORY"),e(r);}catch(r){t(r);}});})}ensureInitialized(){if(!this.initialized||!this.db)throw new R("Database not initialized. Call initialize() first.","DATABASE_NOT_INITIALIZED")}createTables(){if(!this.db)throw new R("Database not initialized. Call initialize() first.","DATABASE_NOT_INITIALIZED");let e=this.db;e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  id INTEGER PRIMARY KEY AUTOINCREMENT,
4
4
  name TEXT NOT NULL,
5
5
  type TEXT NOT NULL,
6
6
  properties TEXT,
7
- createdAt INTEGER DEFAULT (unixepoch()),
8
- updatedAt INTEGER DEFAULT (unixepoch())
7
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
8
+ updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
9
9
  );
10
10
  CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name);
11
11
  CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type);
12
- `),t.exec(`
12
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type);
13
+ `),e.exec(`
13
14
  CREATE TABLE IF NOT EXISTS edges (
14
15
  id INTEGER PRIMARY KEY AUTOINCREMENT,
15
16
  source INTEGER NOT NULL,
16
17
  target INTEGER NOT NULL,
17
18
  relation TEXT NOT NULL,
18
19
  properties TEXT,
19
- createdAt INTEGER DEFAULT (unixepoch()),
20
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
20
21
  FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
21
22
  FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
22
23
  );
23
24
  CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source);
24
25
  CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target);
25
26
  CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation);
26
- `),t.exec(`
27
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation);
28
+ `),e.exec(`
27
29
  CREATE TABLE IF NOT EXISTS documents (
28
30
  id INTEGER PRIMARY KEY AUTOINCREMENT,
29
31
  path TEXT NOT NULL UNIQUE,
@@ -31,70 +33,67 @@ import Gn from'better-sqlite3';import {loadTextFile,Filesystem,Markdown}from'@ea
31
33
  contentHash TEXT NOT NULL,
32
34
  summary TEXT,
33
35
  metadata TEXT,
34
- lastModified INTEGER,
35
- createdAt INTEGER DEFAULT (unixepoch()),
36
- updatedAt INTEGER DEFAULT (unixepoch())
36
+ lastModified DATETIME DEFAULT CURRENT_TIMESTAMP,
37
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
38
+ updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
37
39
  );
38
40
  CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path);
39
- `),t.exec(`
41
+ `),e.exec(`
40
42
  CREATE TABLE IF NOT EXISTS chunks (
41
43
  id INTEGER PRIMARY KEY AUTOINCREMENT,
42
44
  documentId INTEGER NOT NULL,
43
45
  startLine INTEGER NOT NULL,
44
46
  endLine INTEGER NOT NULL,
47
+ startChar INTEGER NOT NULL,
48
+ endChar INTEGER NOT NULL,
45
49
  content TEXT NOT NULL,
46
50
  contentHash TEXT NOT NULL,
47
51
  nodeIds TEXT, -- \u5B58\u50A8\u5173\u8054\u7684\u8282\u70B9 ID \u5217\u8868\uFF0CJSON \u683C\u5F0F
48
- createdAt INTEGER DEFAULT (unixepoch()),
52
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
49
53
  FOREIGN KEY (documentId) REFERENCES documents(id) ON DELETE CASCADE
50
54
  );
51
55
  CREATE INDEX IF NOT EXISTS idx_chunks_document ON chunks(documentId);
52
56
  CREATE INDEX IF NOT EXISTS idx_chunks_hash ON chunks(contentHash);
53
- `),t.exec(`
57
+ `),e.exec(`
54
58
  CREATE TABLE IF NOT EXISTS vectors (
55
59
  chunkId INTEGER PRIMARY KEY,
56
60
  embedding BLOB NOT NULL,
57
61
  FOREIGN KEY (chunkId) REFERENCES chunks(id) ON DELETE CASCADE
58
62
  );
59
- `),t.exec(`
63
+ `),e.exec(`
60
64
  CREATE TABLE IF NOT EXISTS meta (
61
65
  key TEXT PRIMARY KEY,
62
66
  value TEXT
63
67
  );
64
- `),t.exec(`
68
+ `),e.exec(`
65
69
  CREATE TABLE IF NOT EXISTS embedding_cache (
66
70
  contentHash TEXT PRIMARY KEY,
67
71
  embedding BLOB NOT NULL,
68
- createdAt INTEGER DEFAULT (unixepoch())
72
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
69
73
  );
70
- `),t.exec(`
74
+ `),e.exec(`
71
75
  CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
72
- documentId,
76
+ chunkId UNINDEXED,
77
+ documentId UNINDEXED,
73
78
  content,
74
- tokenize='porter unicode61',
75
- content='',
76
- content_rowid='rowid'
79
+ tokenize='porter unicode61'
77
80
  );
78
- `),t.pragma("foreign_keys = ON");}query(t,e){if(!this.db)throw new Error("Database not initialized");try{let s=this.db.prepare(t);return e?s.all(...e):s.all()}catch(s){throw new j(`Query failed: ${s.message}`,"DATABASE_QUERY_FAILED",s)}}run(t,e){if(!this.db)throw new Error("Database not initialized");try{let s=this.db.prepare(t),r=e?s.run(...e):s.run();return {lastID:Number(r.lastInsertRowid),changes:r.changes}}catch(s){throw new j(`Execution failed: ${s.message}`,"DATABASE_QUERY_FAILED",s)}}transaction(t){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(t)()}async close(){this.db&&(this.db.close(),this.db=null);}getPath(){return this.storagePath}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}async getDocumentsCount(){return (await this.query("SELECT COUNT(*) as count FROM documents"))[0]?.count??0}async getChunksCount(){return (await this.query("SELECT COUNT(*) as count FROM chunks"))[0]?.count??0}async getNodesCount(){return (await this.query("SELECT COUNT(*) as count FROM nodes"))[0]?.count??0}async getEdgesCount(){return (await this.query("SELECT COUNT(*) as count FROM edges"))[0]?.count??0}async isVectorSearchAvailable(){try{return ((await this.query("SELECT COUNT(*) as count FROM vectors"))[0]?.count??0)>0}catch{return false}}async healthCheck(){try{return this.db?(await this.query("SELECT 1"),!0):!1}catch{return false}}};var be=class{async parse(t){try{let e=await readFile(t,"utf-8"),s=extname(t).toLowerCase(),r=this.parseMarkdown(e);return {content:r.content,metadata:r.metadata}}catch(e){throw new j(`\u6587\u6863\u89E3\u6790\u5931\u8D25: ${e.message}`,"DOCUMENT_PARSE_FAILED",e)}}parseMarkdown(t){let{frontmatter:e,content:s}=Markdown.extractFrontmatter(t),r={};e.title!==void 0&&(r.title=String(e.title)),e.author!==void 0&&(r.author=String(e.author)),e.date!==void 0&&(r.date=String(e.date));for(let[a,h]of Object.entries(e))["title","author","date"].includes(a)||(r[a]=h);return {content:Markdown.format(s),metadata:r}}static computeHash(t){let e=0;for(let s=0;s<t.length;s++){let r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e;}return Math.abs(e).toString(16)}};var $r=(i,t,e)=>{let s=i instanceof RegExp?Js(i,e):i,r=t instanceof RegExp?Js(t,e):t,o=s!==null&&r!=null&&Yn(s,r,e);return o&&{start:o[0],end:o[1],pre:e.slice(0,o[0]),body:e.slice(o[0]+s.length,o[1]),post:e.slice(o[1]+r.length)}},Js=(i,t)=>{let e=t.match(i);return e?e[0]:null},Yn=(i,t,e)=>{let s,r,o,a,h,l=e.indexOf(i),c=e.indexOf(t,l+1),d=l;if(l>=0&&c>0){if(i===t)return [l,c];for(s=[],o=e.length;d>=0&&!h;){if(d===l)s.push(d),l=e.indexOf(i,d+1);else if(s.length===1){let u=s.pop();u!==void 0&&(h=[u,c]);}else r=s.pop(),r!==void 0&&r<o&&(o=r,a=c),c=e.indexOf(t,d+1);d=l<c&&l>=0?l:c;}s.length&&a!==void 0&&(h=[o,a]);}return h},Gr="\0SLASH"+Math.random()+"\0",Hr="\0OPEN"+Math.random()+"\0",Bs="\0CLOSE"+Math.random()+"\0",qr="\0COMMA"+Math.random()+"\0",Kr="\0PERIOD"+Math.random()+"\0",Xn=new RegExp(Gr,"g"),Qn=new RegExp(Hr,"g"),Jn=new RegExp(Bs,"g"),Vn=new RegExp(qr,"g"),Zn=new RegExp(Kr,"g"),to=/\\\\/g,eo=/\\{/g,io=/\\}/g,so=/\\,/g,ro=/\\./g,no=1e5;function ws(i){return isNaN(i)?i.charCodeAt(0):parseInt(i,10)}function oo(i){return i.replace(to,Gr).replace(eo,Hr).replace(io,Bs).replace(so,qr).replace(ro,Kr)}function ao(i){return i.replace(Xn,"\\").replace(Qn,"{").replace(Jn,"}").replace(Vn,",").replace(Zn,".")}function Yr(i){if(!i)return [""];let t=[],e=$r("{","}",i);if(!e)return i.split(",");let{pre:s,body:r,post:o}=e,a=s.split(",");a[a.length-1]+="{"+r+"}";let h=Yr(o);return o.length&&(a[a.length-1]+=h.shift(),a.push.apply(a,h)),t.push.apply(t,a),t}function ho(i,t={}){if(!i)return [];let{max:e=no}=t;return i.slice(0,2)==="{}"&&(i="\\{\\}"+i.slice(2)),ni(oo(i),e,true).map(ao)}function lo(i){return "{"+i+"}"}function co(i){return /^-?0\d/.test(i)}function uo(i,t){return i<=t}function po(i,t){return i>=t}function ni(i,t,e){let s=[],r=$r("{","}",i);if(!r)return [i];let o=r.pre,a=r.post.length?ni(r.post,t,false):[""];if(/\$$/.test(r.pre))for(let h=0;h<a.length&&h<t;h++){let l=o+"{"+r.body+"}"+a[h];s.push(l);}else {let h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=h||l,d=r.body.indexOf(",")>=0;if(!c&&!d)return r.post.match(/,(?!,).*\}/)?(i=r.pre+"{"+r.body+Bs+r.post,ni(i,t,true)):[i];let u;if(c)u=r.body.split(/\.\./);else if(u=Yr(r.body),u.length===1&&u[0]!==void 0&&(u=ni(u[0],t,false).map(lo),u.length===1))return a.map(y=>r.pre+u[0]+y);let g;if(c&&u[0]!==void 0&&u[1]!==void 0){let y=ws(u[0]),w=ws(u[1]),b=Math.max(u[0].length,u[1].length),S=u.length===3&&u[2]!==void 0?Math.abs(ws(u[2])):1,E=uo;w<y&&(S*=-1,E=po);let A=u.some(co);g=[];for(let I=y;E(I,w);I+=S){let N;if(l)N=String.fromCharCode(I),N==="\\"&&(N="");else if(N=String(I),A){let T=b-N.length;if(T>0){let L=new Array(T+1).join("0");I<0?N="-"+L+N.slice(1):N=L+N;}}g.push(N);}}else {g=[];for(let y=0;y<u.length;y++)g.push.apply(g,ni(u[y],t,false));}for(let y=0;y<g.length;y++)for(let w=0;w<a.length&&s.length<t;w++){let b=o+g[y]+a[w];(!e||c||b)&&s.push(b);}}return s}var rs=i=>{if(typeof i!="string")throw new TypeError("invalid pattern");if(i.length>65536)throw new TypeError("pattern is too long")},fo={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},Ze=i=>i.replace(/[[\]\\-]/g,"\\$&"),go=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Vs=i=>i.join(""),mo=(i,t)=>{let e=t;if(i.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],r=[],o=e+1,a=false,h=false,l=false,c=false,d=e,u="";t:for(;o<i.length;){let w=i.charAt(o);if((w==="!"||w==="^")&&o===e+1){c=true,o++;continue}if(w==="]"&&a&&!l){d=o+1;break}if(a=true,w==="\\"&&!l){l=true,o++;continue}if(w==="["&&!l){for(let[b,[S,E,A]]of Object.entries(fo))if(i.startsWith(b,o)){if(u)return ["$.",false,i.length-e,true];o+=b.length,A?r.push(S):s.push(S),h=h||E;continue t}}if(l=false,u){w>u?s.push(Ze(u)+"-"+Ze(w)):w===u&&s.push(Ze(w)),u="",o++;continue}if(i.startsWith("-]",o+1)){s.push(Ze(w+"-")),o+=2;continue}if(i.startsWith("-",o+1)){u=w,o+=2;continue}s.push(Ze(w)),o++;}if(d<o)return ["",false,0,false];if(!s.length&&!r.length)return ["$.",false,i.length-e,true];if(r.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let w=s[0].length===2?s[0].slice(-1):s[0];return [go(w),false,d-e,false]}let g="["+(c?"^":"")+Vs(s)+"]",y="["+(c?"":"^")+Vs(r)+"]";return [s.length&&r.length?"("+g+"|"+y+")":s.length?g:y,h,d-e,true]},ze=(i,{windowsPathsNoEscape:t=false,magicalBraces:e=true}={})=>e?t?i.replace(/\[([^\/\\])\]/g,"$1"):i.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?i.replace(/\[([^\/\\{}])\]/g,"$1"):i.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),yo=new Set(["!","?","+","*","@"]),Zs=i=>yo.has(i),bo="(?!(?:^|/)\\.\\.?(?:$|/))",Ui="(?!\\.)",wo=new Set(["[","."]),Eo=new Set(["..","."]),So=new Set("().*{}+?[]^$\\!"),vo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Us="[^/]",tr=Us+"*?",er=Us+"+?",G,J,Kt,M,U,ae,ve,he,Wt,Te,di,Ce,Qr,fe,tt,Qi,Is,Jr,Xr=(tt=class{constructor(t,e,s={}){v(this,Ce);p(this,"type");v(this,G);v(this,J);v(this,Kt,false);v(this,M,[]);v(this,U);v(this,ae);v(this,ve);v(this,he,false);v(this,Wt);v(this,Te);v(this,di,false);this.type=t,t&&f(this,J,true),f(this,U,e),f(this,G,n(this,U)?n(n(this,U),G):this),f(this,Wt,n(this,G)===this?s:n(n(this,G),Wt)),f(this,ve,n(this,G)===this?[]:n(n(this,G),ve)),t==="!"&&!n(n(this,G),he)&&n(this,ve).push(this),f(this,ae,n(this,U)?n(n(this,U),M).length:0);}get hasMagic(){if(n(this,J)!==void 0)return n(this,J);for(let t of n(this,M))if(typeof t!="string"&&(t.type||t.hasMagic))return f(this,J,true);return n(this,J)}toString(){return n(this,Te)!==void 0?n(this,Te):this.type?f(this,Te,this.type+"("+n(this,M).map(t=>String(t)).join("|")+")"):f(this,Te,n(this,M).map(t=>String(t)).join(""))}push(...t){for(let e of t)if(e!==""){if(typeof e!="string"&&!(e instanceof tt&&n(e,U)===this))throw new Error("invalid part: "+e);n(this,M).push(e);}}toJSON(){let t=this.type===null?n(this,M).slice().map(e=>typeof e=="string"?e:e.toJSON()):[this.type,...n(this,M).map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===n(this,G)||n(n(this,G),he)&&n(this,U)?.type==="!")&&t.push({}),t}isStart(){if(n(this,G)===this)return true;if(!n(this,U)?.isStart())return false;if(n(this,ae)===0)return true;let t=n(this,U);for(let e=0;e<n(this,ae);e++){let s=n(t,M)[e];if(!(s instanceof tt&&s.type==="!"))return false}return true}isEnd(){if(n(this,G)===this||n(this,U)?.type==="!")return true;if(!n(this,U)?.isEnd())return false;if(!this.type)return n(this,U)?.isEnd();let t=n(this,U)?n(n(this,U),M).length:0;return n(this,ae)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let e=new tt(this.type,t);for(let s of n(this,M))e.copyIn(s);return e}static fromGlob(t,e={}){var r;let s=new tt(null,void 0,e);return m(r=tt,fe,Qi).call(r,t,s,0,e),s}toMMPattern(){if(this!==n(this,G))return n(this,G).toMMPattern();let t=this.toString(),[e,s,r,o]=this.toRegExpSource();if(!(r||n(this,J)||n(this,Wt).nocase&&!n(this,Wt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let a=(n(this,Wt).nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${e}$`,a),{_src:e,_glob:t})}get options(){return n(this,Wt)}toRegExpSource(t){let e=t??!!n(this,Wt).dot;if(n(this,G)===this&&m(this,Ce,Qr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!n(this,M).some(g=>typeof g!="string"),c=n(this,M).map(g=>{var E;let[y,w,b,S]=typeof g=="string"?m(E=tt,fe,Jr).call(E,g,n(this,J),l):g.toRegExpSource(t);return f(this,J,n(this,J)||b),f(this,Kt,n(this,Kt)||S),y}).join(""),d="";if(this.isStart()&&typeof n(this,M)[0]=="string"&&!(n(this,M).length===1&&Eo.has(n(this,M)[0]))){let g=wo,y=e&&g.has(c.charAt(0))||c.startsWith("\\.")&&g.has(c.charAt(2))||c.startsWith("\\.\\.")&&g.has(c.charAt(4)),w=!e&&!t&&g.has(c.charAt(0));d=y?bo:w?Ui:"";}let u="";return this.isEnd()&&n(n(this,G),he)&&n(this,U)?.type==="!"&&(u="(?:$|\\/)"),[d+c+u,ze(c),f(this,J,!!n(this,J)),n(this,Kt)]}let s=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",o=m(this,Ce,Is).call(this,e);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString();return f(this,M,[l]),this.type=null,f(this,J,void 0),[l,ze(this.toString()),false,false]}let a=!s||t||e||!Ui?"":m(this,Ce,Is).call(this,true);a===o&&(a=""),a&&(o=`(?:${o})(?:${a})*?`);let h="";if(this.type==="!"&&n(this,di))h=(this.isStart()&&!e?Ui:"")+er;else {let l=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Ui:"")+tr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;h=r+o+l;}return [h,ze(o),f(this,J,!!n(this,J)),n(this,Kt)]}},G=new WeakMap,J=new WeakMap,Kt=new WeakMap,M=new WeakMap,U=new WeakMap,ae=new WeakMap,ve=new WeakMap,he=new WeakMap,Wt=new WeakMap,Te=new WeakMap,di=new WeakMap,Ce=new WeakSet,Qr=function(){if(this!==n(this,G))throw new Error("should only call on root");if(n(this,he))return this;this.toString(),f(this,he,true);let t;for(;t=n(this,ve).pop();){if(t.type!=="!")continue;let e=t,s=n(e,U);for(;s;){for(let r=n(e,ae)+1;!s.type&&r<n(s,M).length;r++)for(let o of n(t,M)){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n(s,M)[r]);}e=s,s=n(e,U);}}return this},fe=new WeakSet,Qi=function(t,e,s,r){var y,w;let o=false,a=false,h=-1,l=false;if(e.type===null){let b=s,S="";for(;b<t.length;){let E=t.charAt(b++);if(o||E==="\\"){o=!o,S+=E;continue}if(a){b===h+1?(E==="^"||E==="!")&&(l=true):E==="]"&&!(b===h+2&&l)&&(a=false),S+=E;continue}else if(E==="["){a=true,h=b,l=false,S+=E;continue}if(!r.noext&&Zs(E)&&t.charAt(b)==="("){e.push(S),S="";let A=new tt(E,e);b=m(y=tt,fe,Qi).call(y,t,A,b,r),e.push(A);continue}S+=E;}return e.push(S),b}let c=s+1,d=new tt(null,e),u=[],g="";for(;c<t.length;){let b=t.charAt(c++);if(o||b==="\\"){o=!o,g+=b;continue}if(a){c===h+1?(b==="^"||b==="!")&&(l=true):b==="]"&&!(c===h+2&&l)&&(a=false),g+=b;continue}else if(b==="["){a=true,h=c,l=false,g+=b;continue}if(Zs(b)&&t.charAt(c)==="("){d.push(g),g="";let S=new tt(b,d);d.push(S),c=m(w=tt,fe,Qi).call(w,t,S,c,r);continue}if(b==="|"){d.push(g),g="",u.push(d),d=new tt(null,e);continue}if(b===")")return g===""&&n(e,M).length===0&&f(e,di,true),d.push(g),g="",e.push(...u,d),c;g+=b;}return e.type=null,f(e,J,void 0),f(e,M,[t.substring(s-1)]),c},Is=function(t){return n(this,M).map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,r,o,a]=e.toRegExpSource(t);return f(this,Kt,n(this,Kt)||a),s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")},Jr=function(t,e,s=false){let r=false,o="",a=false,h=false;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(r){r=false,o+=(So.has(c)?"\\":"")+c;continue}if(c==="*"){if(h)continue;h=true,o+=s&&/^[*]+$/.test(t)?er:tr,e=true;continue}else h=false;if(c==="\\"){l===t.length-1?o+="\\\\":r=true;continue}if(c==="["){let[d,u,g,y]=mo(t,l);if(g){o+=d,a=a||u,l+=g-1,e=e||y;continue}}if(c==="?"){o+=Us,e=true;continue}o+=vo(c);}return [o,ze(t),!!e,a]},v(tt,fe),tt),Vr=(i,{windowsPathsNoEscape:t=false,magicalBraces:e=false}={})=>e?t?i.replace(/[?*()[\]{}]/g,"[$&]"):i.replace(/[?*()[\]\\{}]/g,"\\$&"):t?i.replace(/[?*()[\]]/g,"[$&]"):i.replace(/[?*()[\]\\]/g,"\\$&"),ht=(i,t,e={})=>(rs(t),!e.nocomment&&t.charAt(0)==="#"?false:new ge(t,e).match(i)),To=/^\*+([^+@!?\*\[\(]*)$/,Ro=i=>t=>!t.startsWith(".")&&t.endsWith(i),No=i=>t=>t.endsWith(i),Ao=i=>(i=i.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(i)),Io=i=>(i=i.toLowerCase(),t=>t.toLowerCase().endsWith(i)),ko=/^\*+\.\*+$/,Lo=i=>!i.startsWith(".")&&i.includes("."),xo=i=>i!=="."&&i!==".."&&i.includes("."),Oo=/^\.\*+$/,Co=i=>i!=="."&&i!==".."&&i.startsWith("."),Do=/^\*+$/,Fo=i=>i.length!==0&&!i.startsWith("."),Po=i=>i.length!==0&&i!=="."&&i!=="..",Mo=/^\?+([^+@!?\*\[\(]*)?$/,_o=([i,t=""])=>{let e=Zr([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},zo=([i,t=""])=>{let e=tn([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Wo=([i,t=""])=>{let e=tn([i]);return t?s=>e(s)&&s.endsWith(t):e},jo=([i,t=""])=>{let e=Zr([i]);return t?s=>e(s)&&s.endsWith(t):e},Zr=([i])=>{let t=i.length;return e=>e.length===t&&!e.startsWith(".")},tn=([i])=>{let t=i.length;return e=>e.length===t&&e!=="."&&e!==".."},en=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ir={win32:{sep:"\\"},posix:{sep:"/"}},Bo=en==="win32"?ir.win32.sep:ir.posix.sep;ht.sep=Bo;var at=Symbol("globstar **");ht.GLOBSTAR=at;var Uo="[^/]",$o=Uo+"*?",Go="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Ho="(?:(?!(?:\\/|^)\\.).)*?",qo=(i,t={})=>e=>ht(e,i,t);ht.filter=qo;var St=(i,t={})=>Object.assign({},i,t),Ko=i=>{if(!i||typeof i!="object"||!Object.keys(i).length)return ht;let t=ht;return Object.assign((e,s,r={})=>t(e,s,St(i,r)),{Minimatch:class extends t.Minimatch{constructor(e,s={}){super(e,St(i,s));}static defaults(e){return t.defaults(St(i,e)).Minimatch}},AST:class extends t.AST{constructor(e,s,r={}){super(e,s,St(i,r));}static fromGlob(e,s={}){return t.AST.fromGlob(e,St(i,s))}},unescape:(e,s={})=>t.unescape(e,St(i,s)),escape:(e,s={})=>t.escape(e,St(i,s)),filter:(e,s={})=>t.filter(e,St(i,s)),defaults:e=>t.defaults(St(i,e)),makeRe:(e,s={})=>t.makeRe(e,St(i,s)),braceExpand:(e,s={})=>t.braceExpand(e,St(i,s)),match:(e,s,r={})=>t.match(e,s,St(i,r)),sep:t.sep,GLOBSTAR:at})};ht.defaults=Ko;var sn=(i,t={})=>(rs(i),t.nobrace||!/\{(?:(?!\{).)*\}/.test(i)?[i]:ho(i,{max:t.braceExpandMax}));ht.braceExpand=sn;var Yo=(i,t={})=>new ge(i,t).makeRe();ht.makeRe=Yo;var Xo=(i,t,e={})=>{let s=new ge(t,e);return i=i.filter(r=>s.match(r)),s.options.nonull&&!i.length&&i.push(t),i};ht.match=Xo;var sr=/[?*]|[+@!]\(.*?\)|\[|\]/,Qo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ge=class{constructor(i,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");rs(i),t=t||{},this.options=t,this.pattern=i,this.platform=t.platform||en,this.isWindows=this.platform==="win32";let e="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[e]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let i of this.set)for(let t of i)if(typeof t!="string")return true;return false}debug(...i){}make(){let i=this.pattern,t=this.options;if(!t.nocomment&&i.charAt(0)==="#"){this.comment=true;return}if(!i){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let e=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(e),this.debug(this.pattern,this.globParts);let s=this.globParts.map((r,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let h=r[0]===""&&r[1]===""&&(r[2]==="?"||!sr.test(r[2]))&&!sr.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(h)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(l)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(h=>this.parse(h))});if(this.debug(this.pattern,s),this.set=s.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let o=this.set[r];o[0]===""&&o[1]===""&&this.globParts[r][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?");}this.debug(this.pattern,this.set);}preprocess(i){if(this.options.noglobstar)for(let e=0;e<i.length;e++)for(let s=0;s<i[e].length;s++)i[e][s]==="**"&&(i[e][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(i=this.firstPhasePreProcess(i),i=this.secondPhasePreProcess(i)):t>=1?i=this.levelOneOptimize(i):i=this.adjascentGlobstarOptimize(i),i}adjascentGlobstarOptimize(i){return i.map(t=>{let e=-1;for(;(e=t.indexOf("**",e+1))!==-1;){let s=e;for(;t[s+1]==="**";)s++;s!==e&&t.splice(e,s-e);}return t})}levelOneOptimize(i){return i.map(t=>(t=t.reduce((e,s)=>{let r=e[e.length-1];return s==="**"&&r==="**"?e:s===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(e.pop(),e):(e.push(s),e)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(i){Array.isArray(i)||(i=this.slashSplit(i));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<i.length-1;s++){let r=i[s];s===1&&r===""&&i[0]===""||(r==="."||r==="")&&(t=true,i.splice(s,1),s--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let e=0;for(;(e=i.indexOf("..",e+1))!==-1;){let s=i[e-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,i.splice(e-1,2),e-=2);}}while(t);return i.length===0?[""]:i}firstPhasePreProcess(i){let t=false;do{t=false;for(let e of i){let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let o=s;for(;e[o+1]==="**";)o++;o>s&&e.splice(s+1,o-s);let a=e[s+1],h=e[s+2],l=e[s+3];if(a!==".."||!h||h==="."||h===".."||!l||l==="."||l==="..")continue;t=true,e.splice(s,1);let c=e.slice(0);c[s]="**",i.push(c),s--;}if(!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let a=e[o];o===1&&a===""&&e[0]===""||(a==="."||a==="")&&(t=true,e.splice(o,1),o--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=true;let a=r===1&&e[r+1]==="**"?["."]:[];e.splice(r-1,2,...a),e.length===0&&e.push(""),r-=2;}}}}while(t);return i}secondPhasePreProcess(i){for(let t=0;t<i.length-1;t++)for(let e=t+1;e<i.length;e++){let s=this.partsMatch(i[t],i[e],!this.preserveMultipleSlashes);if(s){i[t]=[],i[e]=s;break}}return i.filter(t=>t.length)}partsMatch(i,t,e=false){let s=0,r=0,o=[],a="";for(;s<i.length&&r<t.length;)if(i[s]===t[r])o.push(a==="b"?t[r]:i[s]),s++,r++;else if(e&&i[s]==="**"&&t[r]===i[s+1])o.push(i[s]),s++;else if(e&&t[r]==="**"&&i[s]===t[r+1])o.push(t[r]),r++;else if(i[s]==="*"&&t[r]&&(this.options.dot||!t[r].startsWith("."))&&t[r]!=="**"){if(a==="b")return false;a="a",o.push(i[s]),s++,r++;}else if(t[r]==="*"&&i[s]&&(this.options.dot||!i[s].startsWith("."))&&i[s]!=="**"){if(a==="a")return false;a="b",o.push(t[r]),s++,r++;}else return false;return i.length===t.length&&o}parseNegate(){if(this.nonegate)return;let i=this.pattern,t=false,e=0;for(let s=0;s<i.length&&i.charAt(s)==="!";s++)t=!t,e++;e&&(this.pattern=i.slice(e)),this.negate=t;}matchOne(i,t,e=false){let s=this.options;if(this.isWindows){let w=typeof i[0]=="string"&&/^[a-z]:$/i.test(i[0]),b=!w&&i[0]===""&&i[1]===""&&i[2]==="?"&&/^[a-z]:$/i.test(i[3]),S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),E=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),A=b?3:w?0:void 0,I=E?3:S?0:void 0;if(typeof A=="number"&&typeof I=="number"){let[N,T]=[i[A],t[I]];N.toLowerCase()===T.toLowerCase()&&(t[I]=N,I>A?t=t.slice(I):A>I&&(i=i.slice(A)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(i=this.levelTwoFileOptimize(i)),this.debug("matchOne",this,{file:i,pattern:t}),this.debug("matchOne",i.length,t.length);for(var o=0,a=0,h=i.length,l=t.length;o<h&&a<l;o++,a++){this.debug("matchOne loop");var c=t[a],d=i[o];if(this.debug(t,c,d),c===false)return false;if(c===at){this.debug("GLOBSTAR",[t,c,d]);var u=o,g=a+1;if(g===l){for(this.debug("** at the end");o<h;o++)if(i[o]==="."||i[o]===".."||!s.dot&&i[o].charAt(0)===".")return false;return true}for(;u<h;){var y=i[u];if(this.debug(`
79
- globstar while`,i,u,t,g,y),this.matchOne(i.slice(u),t.slice(g),e))return this.debug("globstar found match!",u,h,y),true;if(y==="."||y===".."||!s.dot&&y.charAt(0)==="."){this.debug("dot detected!",i,u,t,g);break}this.debug("globstar swallow a segment, and continue"),u++;}return !!(e&&(this.debug(`
80
- >>> no match, partial?`,i,u,t,g),u===h))}let w;if(typeof c=="string"?(w=d===c,this.debug("string match",c,d,w)):(w=c.test(d),this.debug("pattern match",c,d,w)),!w)return false}if(o===h&&a===l)return true;if(o===h)return e;if(a===l)return o===h-1&&i[o]==="";throw new Error("wtf?")}braceExpand(){return sn(this.pattern,this.options)}parse(i){rs(i);let t=this.options;if(i==="**")return at;if(i==="")return "";let e,s=null;(e=i.match(Do))?s=t.dot?Po:Fo:(e=i.match(To))?s=(t.nocase?t.dot?Io:Ao:t.dot?No:Ro)(e[1]):(e=i.match(Mo))?s=(t.nocase?t.dot?zo:_o:t.dot?Wo:jo)(e):(e=i.match(ko))?s=t.dot?xo:Lo:(e=i.match(Oo))&&(s=Co);let r=Xr.fromGlob(i,this.options).toMMPattern();return s&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:s}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let i=this.set;if(!i.length)return this.regexp=false,this.regexp;let t=this.options,e=t.noglobstar?$o:t.dot?Go:Ho,s=new Set(t.nocase?["i"]:[]),r=i.map(h=>{let l=h.map(d=>{if(d instanceof RegExp)for(let u of d.flags.split(""))s.add(u);return typeof d=="string"?Qo(d):d===at?at:d._src});l.forEach((d,u)=>{let g=l[u+1],y=l[u-1];d!==at||y===at||(y===void 0?g!==void 0&&g!==at?l[u+1]="(?:\\/|"+e+"\\/)?"+g:l[u]=e:g===void 0?l[u-1]=y+"(?:\\/|\\/"+e+")?":g!==at&&(l[u-1]=y+"(?:\\/|\\/"+e+"\\/)"+g,l[u+1]=at));});let c=l.filter(d=>d!==at);if(this.partial&&c.length>=1){let d=[];for(let u=1;u<=c.length;u++)d.push(c.slice(0,u).join("/"));return "(?:"+d.join("|")+")"}return c.join("/")}).join("|"),[o,a]=i.length>1?["(?:",")"]:["",""];r="^"+o+r+a+"$",this.partial&&(r="^(?:\\/|"+o+r.slice(1,-1)+a+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(i){return this.preserveMultipleSlashes?i.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(i)?["",...i.split(/\/+/)]:i.split(/\/+/)}match(i,t=this.partial){if(this.debug("match",i,this.pattern),this.comment)return false;if(this.empty)return i==="";if(i==="/"&&t)return true;let e=this.options;this.isWindows&&(i=i.split("\\").join("/"));let s=this.slashSplit(i);this.debug(this.pattern,"split",s);let r=this.set;this.debug(this.pattern,"set",r);let o=s[s.length-1];if(!o)for(let a=s.length-2;!o&&a>=0;a--)o=s[a];for(let a=0;a<r.length;a++){let h=r[a],l=s;if(e.matchBase&&h.length===1&&(l=[o]),this.matchOne(l,h,t))return e.flipNegate?true:!this.negate}return e.flipNegate?false:this.negate}static defaults(i){return ht.defaults(i).Minimatch}};ht.AST=Xr;ht.Minimatch=ge;ht.escape=Vr;ht.unescape=ze;var Vo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,rn=new Set,ks=typeof process=="object"&&process?process:{},nn=(i,t,e,s)=>{typeof ks.emitWarning=="function"?ks.emitWarning(i,t,e,s):console.error(`[${e}] ${t}: ${i}`);},ns=globalThis.AbortController,rr=globalThis.AbortSignal;if(typeof ns>"u"){rr=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(e,s){this._onabort.push(s);}},ns=class{constructor(){p(this,"signal",new rr);t();}abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=true;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e);}}};let i=ks.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{i&&(i=false,nn("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 Zo=i=>!rn.has(i),se=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),on=i=>se(i)?i<=Math.pow(2,8)?Uint8Array:i<=Math.pow(2,16)?Uint16Array:i<=Math.pow(2,32)?Uint32Array:i<=Number.MAX_SAFE_INTEGER?Ji:null:null,Ji=class extends Array{constructor(i){super(i),this.fill(0);}},Ut,We,ta=(Ut=class{constructor(t,e){p(this,"heap");p(this,"length");if(!n(Ut,We))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}static create(t){let e=on(t);if(!e)return [];f(Ut,We,true);let s=new Ut(t,e);return f(Ut,We,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},We=new WeakMap,v(Ut,We,false),Ut),wr,Er,Tt,pt,kt,Re,Lt,je,Be,xt,H,Ot,$,_,O,rt,ft,it,V,Ct,Z,Dt,Ft,gt,mt,Pt,le,nt,Ue,R,Ls,Ne,Yt,pi,yt,an,Ae,$e,fi,re,ne,xs,Vi,Zi,P,Os,oi,oe,Cs,Ge,hs=(Ge=class{constructor(t){v(this,R);v(this,Tt);v(this,pt);v(this,kt);v(this,Re);v(this,Lt);v(this,je);v(this,Be);v(this,xt);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");v(this,H);v(this,Ot);v(this,$);v(this,_);v(this,O);v(this,rt);v(this,ft);v(this,it);v(this,V);v(this,Ct);v(this,Z);v(this,Dt);v(this,Ft);v(this,gt);v(this,mt);v(this,Pt);v(this,le);v(this,nt);v(this,Ue);v(this,Ne,()=>{});v(this,Yt,()=>{});v(this,pi,()=>{});v(this,yt,()=>false);v(this,Ae,t=>{});v(this,$e,(t,e,s)=>{});v(this,fi,(t,e,s,r)=>{if(s||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,wr,"LRUCache");let{max:e=0,ttl:s,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:a,updateAgeOnHas:h,allowStale:l,dispose:c,onInsert:d,disposeAfter:u,noDisposeOnSet:g,noUpdateTTL:y,maxSize:w=0,maxEntrySize:b=0,sizeCalculation:S,fetchMethod:E,memoMethod:A,noDeleteOnFetchRejection:I,noDeleteOnStaleGet:N,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:L,ignoreFetchAbort:C,perf:z}=t;if(z!==void 0&&typeof z?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(f(this,xt,z??Vo),e!==0&&!se(e))throw new TypeError("max option must be a nonnegative integer");let F=e?on(e):Array;if(!F)throw new Error("invalid max value: "+e);if(f(this,Tt,e),f(this,pt,w),this.maxEntrySize=b||n(this,pt),this.sizeCalculation=S,this.sizeCalculation){if(!n(this,pt)&&!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(A!==void 0&&typeof A!="function")throw new TypeError("memoMethod must be a function if defined");if(f(this,Be,A),E!==void 0&&typeof E!="function")throw new TypeError("fetchMethod must be a function if specified");if(f(this,je,E),f(this,le,!!E),f(this,$,new Map),f(this,_,new Array(e).fill(void 0)),f(this,O,new Array(e).fill(void 0)),f(this,rt,new F(e)),f(this,ft,new F(e)),f(this,it,0),f(this,V,0),f(this,Ct,ta.create(e)),f(this,H,0),f(this,Ot,0),typeof c=="function"&&f(this,kt,c),typeof d=="function"&&f(this,Re,d),typeof u=="function"?(f(this,Lt,u),f(this,Z,[])):(f(this,Lt,void 0),f(this,Z,void 0)),f(this,Pt,!!n(this,kt)),f(this,Ue,!!n(this,Re)),f(this,nt,!!n(this,Lt)),this.noDisposeOnSet=!!g,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!I,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(n(this,pt)!==0&&!se(n(this,pt)))throw new TypeError("maxSize must be a positive integer if specified");if(!se(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");m(this,R,an).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!N,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!h,this.ttlResolution=se(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!se(this.ttl))throw new TypeError("ttl must be a positive integer if specified");m(this,R,Ls).call(this);}if(n(this,Tt)===0&&this.ttl===0&&n(this,pt)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,Tt)&&!n(this,pt)){let W="LRU_CACHE_UNBOUNDED";Zo(W)&&(rn.add(W),nn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",W,Ge));}}get perf(){return n(this,xt)}static unsafeExposeInternals(t){return {starts:n(t,Ft),ttls:n(t,gt),autopurgeTimers:n(t,mt),sizes:n(t,Dt),keyMap:n(t,$),keyList:n(t,_),valList:n(t,O),next:n(t,rt),prev:n(t,ft),get head(){return n(t,it)},get tail(){return n(t,V)},free:n(t,Ct),isBackgroundFetch:e=>{var s;return m(s=t,R,P).call(s,e)},backgroundFetch:(e,s,r,o)=>{var a;return m(a=t,R,Zi).call(a,e,s,r,o)},moveToTail:e=>{var s;return m(s=t,R,oi).call(s,e)},indexes:e=>{var s;return m(s=t,R,re).call(s,e)},rindexes:e=>{var s;return m(s=t,R,ne).call(s,e)},isStale:e=>{var s;return n(s=t,yt).call(s,e)}}}get max(){return n(this,Tt)}get maxSize(){return n(this,pt)}get calculatedSize(){return n(this,Ot)}get size(){return n(this,H)}get fetchMethod(){return n(this,je)}get memoMethod(){return n(this,Be)}get dispose(){return n(this,kt)}get onInsert(){return n(this,Re)}get disposeAfter(){return n(this,Lt)}getRemainingTTL(t){return n(this,$).has(t)?1/0:0}*entries(){for(let t of m(this,R,re).call(this))n(this,O)[t]!==void 0&&n(this,_)[t]!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield [n(this,_)[t],n(this,O)[t]]);}*rentries(){for(let t of m(this,R,ne).call(this))n(this,O)[t]!==void 0&&n(this,_)[t]!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield [n(this,_)[t],n(this,O)[t]]);}*keys(){for(let t of m(this,R,re).call(this)){let e=n(this,_)[t];e!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield e);}}*rkeys(){for(let t of m(this,R,ne).call(this)){let e=n(this,_)[t];e!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield e);}}*values(){for(let t of m(this,R,re).call(this))n(this,O)[t]!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield n(this,O)[t]);}*rvalues(){for(let t of m(this,R,ne).call(this))n(this,O)[t]!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield n(this,O)[t]);}[(Er=Symbol.iterator,wr=Symbol.toStringTag,Er)](){return this.entries()}find(t,e={}){for(let s of m(this,R,re).call(this)){let r=n(this,O)[s],o=m(this,R,P).call(this,r)?r.__staleWhileFetching:r;if(o!==void 0&&t(o,n(this,_)[s],this))return this.get(n(this,_)[s],e)}}forEach(t,e=this){for(let s of m(this,R,re).call(this)){let r=n(this,O)[s],o=m(this,R,P).call(this,r)?r.__staleWhileFetching:r;o!==void 0&&t.call(e,o,n(this,_)[s],this);}}rforEach(t,e=this){for(let s of m(this,R,ne).call(this)){let r=n(this,O)[s],o=m(this,R,P).call(this,r)?r.__staleWhileFetching:r;o!==void 0&&t.call(e,o,n(this,_)[s],this);}}purgeStale(){let t=false;for(let e of m(this,R,ne).call(this,{allowStale:true}))n(this,yt).call(this,e)&&(m(this,R,oe).call(this,n(this,_)[e],"expire"),t=true);return t}info(t){let e=n(this,$).get(t);if(e===void 0)return;let s=n(this,O)[e],r=m(this,R,P).call(this,s)?s.__staleWhileFetching:s;if(r===void 0)return;let o={value:r};if(n(this,gt)&&n(this,Ft)){let a=n(this,gt)[e],h=n(this,Ft)[e];if(a&&h){let l=a-(n(this,xt).now()-h);o.ttl=l,o.start=Date.now();}}return n(this,Dt)&&(o.size=n(this,Dt)[e]),o}dump(){let t=[];for(let e of m(this,R,re).call(this,{allowStale:true})){let s=n(this,_)[e],r=n(this,O)[e],o=m(this,R,P).call(this,r)?r.__staleWhileFetching:r;if(o===void 0||s===void 0)continue;let a={value:o};if(n(this,gt)&&n(this,Ft)){a.ttl=n(this,gt)[e];let h=n(this,xt).now()-n(this,Ft)[e];a.start=Math.floor(Date.now()-h);}n(this,Dt)&&(a.size=n(this,Dt)[e]),t.unshift([s,a]);}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let r=Date.now()-s.start;s.start=n(this,xt).now()-r;}this.set(e,s.value,s);}}set(t,e,s={}){var g,y,w,b;if(e===void 0)return this.delete(t),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,d=n(this,fi).call(this,t,e,s.size||0,h);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),m(this,R,oe).call(this,t,"set"),this;let u=n(this,H)===0?void 0:n(this,$).get(t);if(u===void 0)u=n(this,H)===0?n(this,V):n(this,Ct).length!==0?n(this,Ct).pop():n(this,H)===n(this,Tt)?m(this,R,Vi).call(this,false):n(this,H),n(this,_)[u]=t,n(this,O)[u]=e,n(this,$).set(t,u),n(this,rt)[n(this,V)]=u,n(this,ft)[u]=n(this,V),f(this,V,u),zi(this,H)._++,n(this,$e).call(this,u,d,l),l&&(l.set="add"),c=false,n(this,Ue)&&((g=n(this,Re))==null||g.call(this,e,t,"add"));else {m(this,R,oi).call(this,u);let S=n(this,O)[u];if(e!==S){if(n(this,le)&&m(this,R,P).call(this,S)){S.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:E}=S;E!==void 0&&!a&&(n(this,Pt)&&((y=n(this,kt))==null||y.call(this,E,t,"set")),n(this,nt)&&n(this,Z)?.push([E,t,"set"]));}else a||(n(this,Pt)&&((w=n(this,kt))==null||w.call(this,S,t,"set")),n(this,nt)&&n(this,Z)?.push([S,t,"set"]));if(n(this,Ae).call(this,u),n(this,$e).call(this,u,d,l),n(this,O)[u]=e,l){l.set="replace";let E=S&&m(this,R,P).call(this,S)?S.__staleWhileFetching:S;E!==void 0&&(l.oldValue=E);}}else l&&(l.set="update");n(this,Ue)&&this.onInsert?.(e,t,e===S?"update":"replace");}if(r!==0&&!n(this,gt)&&m(this,R,Ls).call(this),n(this,gt)&&(c||n(this,pi).call(this,u,r,o),l&&n(this,Yt).call(this,l,u)),!a&&n(this,nt)&&n(this,Z)){let S=n(this,Z),E;for(;E=S?.shift();)(b=n(this,Lt))==null||b.call(this,...E);}return this}pop(){var t;try{for(;n(this,H);){let e=n(this,O)[n(this,it)];if(m(this,R,Vi).call(this,!0),m(this,R,P).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(n(this,nt)&&n(this,Z)){let e=n(this,Z),s;for(;s=e?.shift();)(t=n(this,Lt))==null||t.call(this,...s);}}}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:r}=e,o=n(this,$).get(t);if(o!==void 0){let a=n(this,O)[o];if(m(this,R,P).call(this,a)&&a.__staleWhileFetching===void 0)return false;if(n(this,yt).call(this,o))r&&(r.has="stale",n(this,Yt).call(this,r,o));else return s&&n(this,Ne).call(this,o),r&&(r.has="hit",n(this,Yt).call(this,r,o)),true}else r&&(r.has="miss");return false}peek(t,e={}){let{allowStale:s=this.allowStale}=e,r=n(this,$).get(t);if(r===void 0||!s&&n(this,yt).call(this,r))return;let o=n(this,O)[r];return m(this,R,P).call(this,o)?o.__staleWhileFetching:o}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:g=this.allowStaleOnFetchRejection,ignoreFetchAbort:y=this.ignoreFetchAbort,allowStaleOnFetchAbort:w=this.allowStaleOnFetchAbort,context:b,forceRefresh:S=false,status:E,signal:A}=e;if(!n(this,le))return E&&(E.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:E});let I={allowStale:s,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:a,noDisposeOnSet:h,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:g,allowStaleOnFetchAbort:w,ignoreFetchAbort:y,status:E,signal:A},N=n(this,$).get(t);if(N===void 0){E&&(E.fetch="miss");let T=m(this,R,Zi).call(this,t,N,I,b);return T.__returned=T}else {let T=n(this,O)[N];if(m(this,R,P).call(this,T)){let F=s&&T.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",F&&(E.returnedStale=true)),F?T.__staleWhileFetching:T.__returned=T}let L=n(this,yt).call(this,N);if(!S&&!L)return E&&(E.fetch="hit"),m(this,R,oi).call(this,N),r&&n(this,Ne).call(this,N),E&&n(this,Yt).call(this,E,N),T;let C=m(this,R,Zi).call(this,t,N,I,b),z=C.__staleWhileFetching!==void 0&&s;return E&&(E.fetch=L?"stale":"refresh",z&&L&&(E.returnedStale=true)),z?C.__staleWhileFetching:C.__returned=C}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=n(this,Be);if(!s)throw new Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...a}=e,h=this.get(t,a);if(!o&&h!==void 0)return h;let l=s(t,h,{options:a,context:r});return this.set(t,l,a),l}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:a}=e,h=n(this,$).get(t);if(h!==void 0){let l=n(this,O)[h],c=m(this,R,P).call(this,l);return a&&n(this,Yt).call(this,a,h),n(this,yt).call(this,h)?(a&&(a.get="stale"),c?(a&&s&&l.__staleWhileFetching!==void 0&&(a.returnedStale=true),s?l.__staleWhileFetching:void 0):(o||m(this,R,oe).call(this,t,"expire"),a&&s&&(a.returnedStale=true),s?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(m(this,R,oi).call(this,h),r&&n(this,Ne).call(this,h),l))}else a&&(a.get="miss");}delete(t){return m(this,R,oe).call(this,t,"delete")}clear(){return m(this,R,Cs).call(this,"delete")}},Tt=new WeakMap,pt=new WeakMap,kt=new WeakMap,Re=new WeakMap,Lt=new WeakMap,je=new WeakMap,Be=new WeakMap,xt=new WeakMap,H=new WeakMap,Ot=new WeakMap,$=new WeakMap,_=new WeakMap,O=new WeakMap,rt=new WeakMap,ft=new WeakMap,it=new WeakMap,V=new WeakMap,Ct=new WeakMap,Z=new WeakMap,Dt=new WeakMap,Ft=new WeakMap,gt=new WeakMap,mt=new WeakMap,Pt=new WeakMap,le=new WeakMap,nt=new WeakMap,Ue=new WeakMap,R=new WeakSet,Ls=function(){let t=new Ji(n(this,Tt)),e=new Ji(n(this,Tt));f(this,gt,t),f(this,Ft,e);let s=this.ttlAutopurge?new Array(n(this,Tt)):void 0;f(this,mt,s),f(this,pi,(a,h,l=n(this,xt).now())=>{if(e[a]=h!==0?l:0,t[a]=h,s?.[a]&&(clearTimeout(s[a]),s[a]=void 0),h!==0&&s){let c=setTimeout(()=>{n(this,yt).call(this,a)&&m(this,R,oe).call(this,n(this,_)[a],"expire");},h+1);c.unref&&c.unref(),s[a]=c;}}),f(this,Ne,a=>{e[a]=t[a]!==0?n(this,xt).now():0;}),f(this,Yt,(a,h)=>{if(t[h]){let l=t[h],c=e[h];if(!l||!c)return;a.ttl=l,a.start=c,a.now=r||o();let d=a.now-c;a.remainingTTL=l-d;}});let r=0,o=()=>{let a=n(this,xt).now();if(this.ttlResolution>0){r=a;let h=setTimeout(()=>r=0,this.ttlResolution);h.unref&&h.unref();}return a};this.getRemainingTTL=a=>{let h=n(this,$).get(a);if(h===void 0)return 0;let l=t[h],c=e[h];if(!l||!c)return 1/0;let d=(r||o())-c;return l-d},f(this,yt,a=>{let h=e[a],l=t[a];return !!l&&!!h&&(r||o())-h>l});},Ne=new WeakMap,Yt=new WeakMap,pi=new WeakMap,yt=new WeakMap,an=function(){let t=new Ji(n(this,Tt));f(this,Ot,0),f(this,Dt,t),f(this,Ae,e=>{f(this,Ot,n(this,Ot)-t[e]),t[e]=0;}),f(this,fi,(e,s,r,o)=>{if(m(this,R,P).call(this,s))return 0;if(!se(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(s,e),!se(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r}),f(this,$e,(e,s,r)=>{if(t[e]=s,n(this,pt)){let o=n(this,pt)-t[e];for(;n(this,Ot)>o;)m(this,R,Vi).call(this,true);}f(this,Ot,n(this,Ot)+t[e]),r&&(r.entrySize=s,r.totalCalculatedSize=n(this,Ot));});},Ae=new WeakMap,$e=new WeakMap,fi=new WeakMap,re=function*({allowStale:t=this.allowStale}={}){if(n(this,H))for(let e=n(this,V);!(!m(this,R,xs).call(this,e)||((t||!n(this,yt).call(this,e))&&(yield e),e===n(this,it)));)e=n(this,ft)[e];},ne=function*({allowStale:t=this.allowStale}={}){if(n(this,H))for(let e=n(this,it);!(!m(this,R,xs).call(this,e)||((t||!n(this,yt).call(this,e))&&(yield e),e===n(this,V)));)e=n(this,rt)[e];},xs=function(t){return t!==void 0&&n(this,$).get(n(this,_)[t])===t},Vi=function(t){var o;let e=n(this,it),s=n(this,_)[e],r=n(this,O)[e];return n(this,le)&&m(this,R,P).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Pt)||n(this,nt))&&(n(this,Pt)&&((o=n(this,kt))==null||o.call(this,r,s,"evict")),n(this,nt)&&n(this,Z)?.push([r,s,"evict"])),n(this,Ae).call(this,e),n(this,mt)?.[e]&&(clearTimeout(n(this,mt)[e]),n(this,mt)[e]=void 0),t&&(n(this,_)[e]=void 0,n(this,O)[e]=void 0,n(this,Ct).push(e)),n(this,H)===1?(f(this,it,f(this,V,0)),n(this,Ct).length=0):f(this,it,n(this,rt)[e]),n(this,$).delete(s),zi(this,H)._--,e},Zi=function(t,e,s,r){let o=e===void 0?void 0:n(this,O)[e];if(m(this,R,P).call(this,o))return o;let a=new ns,{signal:h}=s;h?.addEventListener("abort",()=>a.abort(h.reason),{signal:a.signal});let l={signal:a.signal,options:s,context:r},c=(b,S=false)=>{let{aborted:E}=a.signal,A=s.ignoreFetchAbort&&b!==void 0,I=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&b!==void 0);if(s.status&&(E&&!S?(s.status.fetchAborted=true,s.status.fetchError=a.signal.reason,A&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),E&&!A&&!S)return u(a.signal.reason,I);let N=y,T=n(this,O)[e];return (T===y||A&&S&&T===void 0)&&(b===void 0?N.__staleWhileFetching!==void 0?n(this,O)[e]=N.__staleWhileFetching:m(this,R,oe).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,b,l.options))),b},d=b=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=b),u(b,false)),u=(b,S)=>{let{aborted:E}=a.signal,A=E&&s.allowStaleOnFetchAbort,I=A||s.allowStaleOnFetchRejection,N=I||s.noDeleteOnFetchRejection,T=y;if(n(this,O)[e]===y&&(!N||!S&&T.__staleWhileFetching===void 0?m(this,R,oe).call(this,t,"fetch"):A||(n(this,O)[e]=T.__staleWhileFetching)),I)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),T.__staleWhileFetching;if(T.__returned===T)throw b},g=(b,S)=>{var A;let E=(A=n(this,je))==null?void 0:A.call(this,t,o,l);E&&E instanceof Promise&&E.then(I=>b(I===void 0?void 0:I),S),a.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(b(void 0),s.allowStaleOnFetchAbort&&(b=I=>c(I,true)));});};s.status&&(s.status.fetchDispatched=true);let y=new Promise(g).then(c,d),w=Object.assign(y,{__abortController:a,__staleWhileFetching:o,__returned:void 0});return e===void 0?(this.set(t,w,{...l.options,status:void 0}),e=n(this,$).get(t)):n(this,O)[e]=w,w},P=function(t){if(!n(this,le))return false;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof ns},Os=function(t,e){n(this,ft)[e]=t,n(this,rt)[t]=e;},oi=function(t){t!==n(this,V)&&(t===n(this,it)?f(this,it,n(this,rt)[t]):m(this,R,Os).call(this,n(this,ft)[t],n(this,rt)[t]),m(this,R,Os).call(this,n(this,V),t),f(this,V,t));},oe=function(t,e){var r,o;let s=false;if(n(this,H)!==0){let a=n(this,$).get(t);if(a!==void 0)if(n(this,mt)?.[a]&&(clearTimeout(n(this,mt)?.[a]),n(this,mt)[a]=void 0),s=true,n(this,H)===1)m(this,R,Cs).call(this,e);else {n(this,Ae).call(this,a);let h=n(this,O)[a];if(m(this,R,P).call(this,h)?h.__abortController.abort(new Error("deleted")):(n(this,Pt)||n(this,nt))&&(n(this,Pt)&&((r=n(this,kt))==null||r.call(this,h,t,e)),n(this,nt)&&n(this,Z)?.push([h,t,e])),n(this,$).delete(t),n(this,_)[a]=void 0,n(this,O)[a]=void 0,a===n(this,V))f(this,V,n(this,ft)[a]);else if(a===n(this,it))f(this,it,n(this,rt)[a]);else {let l=n(this,ft)[a];n(this,rt)[l]=n(this,rt)[a];let c=n(this,rt)[a];n(this,ft)[c]=n(this,ft)[a];}zi(this,H)._--,n(this,Ct).push(a);}}if(n(this,nt)&&n(this,Z)?.length){let a=n(this,Z),h;for(;h=a?.shift();)(o=n(this,Lt))==null||o.call(this,...h);}return s},Cs=function(t){var e,s;for(let r of m(this,R,ne).call(this,{allowStale:true})){let o=n(this,O)[r];if(m(this,R,P).call(this,o))o.__abortController.abort(new Error("deleted"));else {let a=n(this,_)[r];n(this,Pt)&&((e=n(this,kt))==null||e.call(this,o,a,t)),n(this,nt)&&n(this,Z)?.push([o,a,t]);}}if(n(this,$).clear(),n(this,O).fill(void 0),n(this,_).fill(void 0),n(this,gt)&&n(this,Ft)){n(this,gt).fill(0),n(this,Ft).fill(0);for(let r of n(this,mt)??[])r!==void 0&&clearTimeout(r);n(this,mt)?.fill(void 0);}if(n(this,Dt)&&n(this,Dt).fill(0),f(this,it,0),f(this,V,0),n(this,Ct).length=0,f(this,Ot,0),f(this,H,0),n(this,nt)&&n(this,Z)){let r=n(this,Z),o;for(;o=r?.shift();)(s=n(this,Lt))==null||s.call(this,...o);}},Ge),nr=typeof process=="object"&&process?process:{stdout:null,stderr:null},fa=i=>!!i&&typeof i=="object"&&(i instanceof os||i instanceof hn||ga(i)||ma(i)),ga=i=>!!i&&typeof i=="object"&&i instanceof EventEmitter&&typeof i.pipe=="function"&&i.pipe!==hn.Writable.prototype.pipe,ma=i=>!!i&&typeof i=="object"&&i instanceof EventEmitter&&typeof i.write=="function"&&typeof i.end=="function",Ht=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),ie=Symbol("emittedEnd"),$i=Symbol("emittingEnd"),ti=Symbol("emittedError"),Gi=Symbol("closed"),or=Symbol("read"),Hi=Symbol("flush"),ar=Symbol("flushChunk"),At=Symbol("encoding"),Me=Symbol("decoder"),Y=Symbol("flowing"),ei=Symbol("paused"),_e=Symbol("resume"),X=Symbol("buffer"),st=Symbol("pipes"),Q=Symbol("bufferLength"),Es=Symbol("bufferPush"),qi=Symbol("bufferShift"),et=Symbol("objectMode"),B=Symbol("destroyed"),Ss=Symbol("error"),vs=Symbol("emitData"),hr=Symbol("emitEnd"),Ts=Symbol("emitEnd2"),_t=Symbol("async"),Rs=Symbol("abort"),Ki=Symbol("aborted"),ii=Symbol("signal"),we=Symbol("dataListeners"),dt=Symbol("discarded"),si=i=>Promise.resolve().then(i),ya=i=>i(),ba=i=>i==="end"||i==="finish"||i==="prefinish",wa=i=>i instanceof ArrayBuffer||!!i&&typeof i=="object"&&i.constructor&&i.constructor.name==="ArrayBuffer"&&i.byteLength>=0,Ea=i=>!Buffer.isBuffer(i)&&ArrayBuffer.isView(i),ln=class{constructor(i,t,e){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=i,this.dest=t,this.opts=e,this.ondrain=()=>i[_e](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(i){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Sa=class extends ln{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(i,t,e){super(i,t,e),this.proxyErrors=s=>this.dest.emit("error",s),i.on("error",this.proxyErrors);}},va=i=>!!i.objectMode,Ta=i=>!i.objectMode&&!!i.encoding&&i.encoding!=="buffer",Sr,vr,Tr,Rr,Nr,Ar,Ir,kr,Lr,xr,Or,Cr,Dr,Fr,Pr,Mr,_r,zr,Wr,os=class extends EventEmitter{constructor(...t){let e=t[0]||{};super();p(this,Wr,false);p(this,zr,false);p(this,_r,[]);p(this,Mr,[]);p(this,Pr);p(this,Fr);p(this,Dr);p(this,Cr);p(this,Or,false);p(this,xr,false);p(this,Lr,false);p(this,kr,false);p(this,Ir,null);p(this,Ar,0);p(this,Nr,false);p(this,Rr);p(this,Tr,false);p(this,vr,0);p(this,Sr,false);p(this,"writable",true);p(this,"readable",true);if(e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");va(e)?(this[et]=true,this[At]=null):Ta(e)?(this[At]=e.encoding,this[et]=false):(this[et]=false,this[At]=null),this[_t]=!!e.async,this[Me]=this[At]?new StringDecoder(this[At]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[X]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[st]});let{signal:s}=e;s&&(this[ii]=s,s.aborted?this[Rs]():s.addEventListener("abort",()=>this[Rs]()));}get bufferLength(){return this[Q]}get encoding(){return this[At]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[et]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[_t]}set async(t){this[_t]=this[_t]||!!t;}[(Wr=Y,zr=ei,_r=st,Mr=X,Pr=et,Fr=At,Dr=_t,Cr=Me,Or=Ht,xr=ie,Lr=$i,kr=Gi,Ir=ti,Ar=Q,Nr=B,Rr=ii,Tr=Ki,vr=we,Sr=dt,Rs)](){this[Ki]=true,this.emit("abort",this[ii]?.reason),this.destroy(this[ii]?.reason);}get aborted(){return this[Ki]}set aborted(t){}write(t,e,s){if(this[Ki])return false;if(this[Ht])throw new Error("write after end");if(this[B])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let r=this[_t]?si:ya;if(!this[et]&&!Buffer.isBuffer(t)){if(Ea(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(wa(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[et]?(this[Y]&&this[Q]!==0&&this[Hi](true),this[Y]?this.emit("data",t):this[Es](t),this[Q]!==0&&this.emit("readable"),s&&r(s),this[Y]):t.length?(typeof t=="string"&&!(e===this[At]&&!this[Me]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[At]&&(t=this[Me].write(t)),this[Y]&&this[Q]!==0&&this[Hi](true),this[Y]?this.emit("data",t):this[Es](t),this[Q]!==0&&this.emit("readable"),s&&r(s),this[Y]):(this[Q]!==0&&this.emit("readable"),s&&r(s),this[Y])}read(t){if(this[B])return null;if(this[dt]=false,this[Q]===0||t===0||t&&t>this[Q])return this[qt](),null;this[et]&&(t=null),this[X].length>1&&!this[et]&&(this[X]=[this[At]?this[X].join(""):Buffer.concat(this[X],this[Q])]);let e=this[or](t||null,this[X][0]);return this[qt](),e}[or](t,e){if(this[et])this[qi]();else {let s=e;t===s.length||t===null?this[qi]():typeof s=="string"?(this[X][0]=s.slice(t),e=s.slice(0,t),this[Q]-=t):(this[X][0]=s.subarray(t),e=s.subarray(0,t),this[Q]-=t);}return this.emit("data",e),!this[X].length&&!this[Ht]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[Ht]=true,this.writable=false,(this[Y]||!this[ei])&&this[qt](),this}[_e](){this[B]||(!this[we]&&!this[st].length&&(this[dt]=true),this[ei]=false,this[Y]=true,this.emit("resume"),this[X].length?this[Hi]():this[Ht]?this[qt]():this.emit("drain"));}resume(){return this[_e]()}pause(){this[Y]=false,this[ei]=true,this[dt]=false;}get destroyed(){return this[B]}get flowing(){return this[Y]}get paused(){return this[ei]}[Es](t){this[et]?this[Q]+=1:this[Q]+=t.length,this[X].push(t);}[qi](){return this[et]?this[Q]-=1:this[Q]-=this[X][0].length,this[X].shift()}[Hi](t=false){do;while(this[ar](this[qi]())&&this[X].length);!t&&!this[X].length&&!this[Ht]&&this.emit("drain");}[ar](t){return this.emit("data",t),this[Y]}pipe(t,e){if(this[B])return t;this[dt]=false;let s=this[ie];return e=e||{},t===nr.stdout||t===nr.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[st].push(e.proxyErrors?new Sa(this,t,e):new ln(this,t,e)),this[_t]?si(()=>this[_e]()):this[_e]()),t}unpipe(t){let e=this[st].find(s=>s.dest===t);e&&(this[st].length===1?(this[Y]&&this[we]===0&&(this[Y]=false),this[st]=[]):this[st].splice(this[st].indexOf(e),1),e.unpipe());}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[dt]=false,this[we]++,!this[st].length&&!this[Y]&&this[_e]();else if(t==="readable"&&this[Q]!==0)super.emit("readable");else if(ba(t)&&this[ie])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ti]){let r=e;this[_t]?si(()=>r.call(this,this[ti])):r.call(this,this[ti]);}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[we]=this.listeners("data").length,this[we]===0&&!this[dt]&&!this[st].length&&(this[Y]=false)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[we]=0,!this[dt]&&!this[st].length&&(this[Y]=false)),e}get emittedEnd(){return this[ie]}[qt](){!this[$i]&&!this[ie]&&!this[B]&&this[X].length===0&&this[Ht]&&(this[$i]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Gi]&&this.emit("close"),this[$i]=false);}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==B&&this[B])return false;if(t==="data")return !this[et]&&!s?false:this[_t]?(si(()=>this[vs](s)),true):this[vs](s);if(t==="end")return this[hr]();if(t==="close"){if(this[Gi]=true,!this[ie]&&!this[B])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ti]=s,super.emit(Ss,s);let o=!this[ii]||this.listeners("error").length?super.emit("error",s):false;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let r=super.emit(t,...e);return this[qt](),r}[vs](t){for(let s of this[st])s.dest.write(t)===false&&this.pause();let e=this[dt]?false:super.emit("data",t);return this[qt](),e}[hr](){return this[ie]?false:(this[ie]=true,this.readable=false,this[_t]?(si(()=>this[Ts]()),true):this[Ts]())}[Ts](){if(this[Me]){let e=this[Me].end();if(e){for(let s of this[st])s.dest.write(e);this[dt]||super.emit("data",e);}}for(let e of this[st])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[et]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[et]||(t.dataLength+=s.length);}),await e,t}async concat(){if(this[et])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[At]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(B,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[dt]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return e();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[Ht])return e();let r,o,a=d=>{this.off("data",h),this.off("end",l),this.off(B,c),e(),o(d);},h=d=>{this.off("error",a),this.off("end",l),this.off(B,c),this.pause(),r({value:d,done:!!this[Ht]});},l=()=>{this.off("error",a),this.off("data",h),this.off(B,c),e(),r({done:true,value:void 0});},c=()=>a(new Error("stream destroyed"));return new Promise((d,u)=>{o=u,r=d,this.once(B,c),this.once("error",a),this.once("end",l),this.once("data",h);})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[dt]=false;let t=false,e=()=>(this.pause(),this.off(Ss,e),this.off(B,e),this.off("end",e),t=true,{done:true,value:void 0}),s=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(Ss,e),this.once(B,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[B])return t?this.emit("error",t):this.emit(B),this;this[B]=true,this[dt]=true,this[X].length=0,this[Q]=0;let e=this;return typeof e.close=="function"&&!this[Gi]&&e.close(),t?this.emit("error",t):this.emit(B),this}static get isStream(){return fa}},Ra=realpathSync.native,ai={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Ra,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},cn=i=>!i||i===ai||i===ha?ai:{...ai,...i,promises:{...ai.promises,...i.promises||{}}},un=/^\\\\\?\\([a-z]:)\\?$/i,Na=i=>i.replace(/\//g,"\\").replace(un,"$1\\"),Aa=/[\\\/]/,Rt=0,dn=1,pn=2,zt=4,fn=6,gn=8,Ee=10,mn=12,vt=15,ri=~vt,Ns=16,lr=32,hi=64,It=128,Yi=256,ts=512,cr=hi|It|ts,Ia=1023,As=i=>i.isFile()?gn:i.isDirectory()?zt:i.isSymbolicLink()?Ee:i.isCharacterDevice()?pn:i.isBlockDevice()?fn:i.isSocket()?mn:i.isFIFO()?dn:Rt,ur=new hs({max:2**12}),li=i=>{let t=ur.get(i);if(t)return t;let e=i.normalize("NFKD");return ur.set(i,e),e},dr=new hs({max:2**12}),Xi=i=>{let t=dr.get(i);if(t)return t;let e=li(i.toLowerCase());return dr.set(i,e),e},pr=class extends hs{constructor(){super({max:256});}},ka=class extends hs{constructor(i=16*1024){super({maxSize:i,sizeCalculation:t=>t.length+1});}},yn=Symbol("PathScurry setAsCwd"),ot,gi,mi,yi,bi,wi,Ei,Si,vi,Ti,Ri,Ni,Ai,Ii,ki,Li,xi,Oi,Ci,ce,Ie,jt,Xt,Qt,Jt,x,ke,Vt,Bt,k,Fs,es,ci,Ps,Ms,ui,is,_s,zs,ss,bn,wn,En,Ws,He,qe,Sn,Le,jr,lt=(jr=class{constructor(i,t=Rt,e,s,r,o,a){v(this,k);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);v(this,ot);v(this,gi);v(this,mi);v(this,yi);v(this,bi);v(this,wi);v(this,Ei);v(this,Si);v(this,vi);v(this,Ti);v(this,Ri);v(this,Ni);v(this,Ai);v(this,Ii);v(this,ki);v(this,Li);v(this,xi);v(this,Oi);v(this,Ci);v(this,ce);v(this,Ie);v(this,jt);v(this,Xt);v(this,Qt);v(this,Jt);v(this,x);v(this,ke);v(this,Vt);v(this,Bt);v(this,He,[]);v(this,qe,false);v(this,Le);this.name=i,f(this,ce,r?Xi(i):li(i)),f(this,x,t&Ia),this.nocase=r,this.roots=s,this.root=e||this,f(this,ke,o),f(this,jt,a.fullpath),f(this,Qt,a.relative),f(this,Jt,a.relativePosix),this.parent=a.parent,this.parent?f(this,ot,n(this.parent,ot)):f(this,ot,cn(a.fs));}get dev(){return n(this,gi)}get mode(){return n(this,mi)}get nlink(){return n(this,yi)}get uid(){return n(this,bi)}get gid(){return n(this,wi)}get rdev(){return n(this,Ei)}get blksize(){return n(this,Si)}get ino(){return n(this,vi)}get size(){return n(this,Ti)}get blocks(){return n(this,Ri)}get atimeMs(){return n(this,Ni)}get mtimeMs(){return n(this,Ai)}get ctimeMs(){return n(this,Ii)}get birthtimeMs(){return n(this,ki)}get atime(){return n(this,Li)}get mtime(){return n(this,xi)}get ctime(){return n(this,Oi)}get birthtime(){return n(this,Ci)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,Ie)!==void 0?n(this,Ie):this.parent?f(this,Ie,this.parent.depth()+1):f(this,Ie,0)}childrenCache(){return n(this,ke)}resolve(i){var s;if(!i)return this;let t=this.getRootString(i),e=i.substring(t.length).split(this.splitSep);return t?m(s=this.getRoot(t),k,Fs).call(s,e):m(this,k,Fs).call(this,e)}children(){let i=n(this,ke).get(this);if(i)return i;let t=Object.assign([],{provisional:0});return n(this,ke).set(this,t),f(this,x,n(this,x)&~Ns),t}child(i,t){if(i===""||i===".")return this;if(i==="..")return this.parent||this;let e=this.children(),s=this.nocase?Xi(i):li(i);for(let h of e)if(n(h,ce)===s)return h;let r=this.parent?this.sep:"",o=n(this,jt)?n(this,jt)+r+i:void 0,a=this.newChild(i,Rt,{...t,parent:this,fullpath:o});return this.canReaddir()||f(a,x,n(a,x)|It),e.push(a),a}relative(){if(this.isCWD)return "";if(n(this,Qt)!==void 0)return n(this,Qt);let i=this.name,t=this.parent;if(!t)return f(this,Qt,this.name);let e=t.relative();return e+(!e||!t.parent?"":this.sep)+i}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(n(this,Jt)!==void 0)return n(this,Jt);let i=this.name,t=this.parent;if(!t)return f(this,Jt,this.fullpathPosix());let e=t.relativePosix();return e+(!e||!t.parent?"":"/")+i}fullpath(){if(n(this,jt)!==void 0)return n(this,jt);let i=this.name,t=this.parent;if(!t)return f(this,jt,this.name);let e=t.fullpath()+(t.parent?this.sep:"")+i;return f(this,jt,e)}fullpathPosix(){if(n(this,Xt)!==void 0)return n(this,Xt);if(this.sep==="/")return f(this,Xt,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?f(this,Xt,`//?/${s}`):f(this,Xt,s)}let i=this.parent,t=i.fullpathPosix(),e=t+(!t||!i.parent?"":"/")+this.name;return f(this,Xt,e)}isUnknown(){return (n(this,x)&vt)===Rt}isType(i){return this[`is${i}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (n(this,x)&vt)===gn}isDirectory(){return (n(this,x)&vt)===zt}isCharacterDevice(){return (n(this,x)&vt)===pn}isBlockDevice(){return (n(this,x)&vt)===fn}isFIFO(){return (n(this,x)&vt)===dn}isSocket(){return (n(this,x)&vt)===mn}isSymbolicLink(){return (n(this,x)&Ee)===Ee}lstatCached(){return n(this,x)&lr?this:void 0}readlinkCached(){return n(this,Vt)}realpathCached(){return n(this,Bt)}readdirCached(){let i=this.children();return i.slice(0,i.provisional)}canReadlink(){if(n(this,Vt))return true;if(!this.parent)return false;let i=n(this,x)&vt;return !(i!==Rt&&i!==Ee||n(this,x)&Yi||n(this,x)&It)}calledReaddir(){return !!(n(this,x)&Ns)}isENOENT(){return !!(n(this,x)&It)}isNamed(i){return this.nocase?n(this,ce)===Xi(i):n(this,ce)===li(i)}async readlink(){let i=n(this,Vt);if(i)return i;if(this.canReadlink()&&this.parent)try{let t=await n(this,ot).promises.readlink(this.fullpath()),e=(await this.parent.realpath())?.resolve(t);if(e)return f(this,Vt,e)}catch(t){m(this,k,zs).call(this,t.code);return}}readlinkSync(){let i=n(this,Vt);if(i)return i;if(this.canReadlink()&&this.parent)try{let t=n(this,ot).readlinkSync(this.fullpath()),e=this.parent.realpathSync()?.resolve(t);if(e)return f(this,Vt,e)}catch(t){m(this,k,zs).call(this,t.code);return}}async lstat(){if((n(this,x)&It)===0)try{return m(this,k,Ws).call(this,await n(this,ot).promises.lstat(this.fullpath())),this}catch(i){m(this,k,_s).call(this,i.code);}}lstatSync(){if((n(this,x)&It)===0)try{return m(this,k,Ws).call(this,n(this,ot).lstatSync(this.fullpath())),this}catch(i){m(this,k,_s).call(this,i.code);}}readdirCB(i,t=false){if(!this.canReaddir()){t?i(null,[]):queueMicrotask(()=>i(null,[]));return}let e=this.children();if(this.calledReaddir()){let r=e.slice(0,e.provisional);t?i(null,r):queueMicrotask(()=>i(null,r));return}if(n(this,He).push(i),n(this,qe))return;f(this,qe,true);let s=this.fullpath();n(this,ot).readdir(s,{withFileTypes:true},(r,o)=>{if(r)m(this,k,is).call(this,r.code),e.provisional=0;else {for(let a of o)m(this,k,ss).call(this,a,e);m(this,k,es).call(this,e);}m(this,k,Sn).call(this,e.slice(0,e.provisional));});}async readdir(){if(!this.canReaddir())return [];let i=this.children();if(this.calledReaddir())return i.slice(0,i.provisional);let t=this.fullpath();if(n(this,Le))await n(this,Le);else {let e=()=>{};f(this,Le,new Promise(s=>e=s));try{for(let s of await n(this,ot).promises.readdir(t,{withFileTypes:!0}))m(this,k,ss).call(this,s,i);m(this,k,es).call(this,i);}catch(s){m(this,k,is).call(this,s.code),i.provisional=0;}f(this,Le,void 0),e();}return i.slice(0,i.provisional)}readdirSync(){if(!this.canReaddir())return [];let i=this.children();if(this.calledReaddir())return i.slice(0,i.provisional);let t=this.fullpath();try{for(let e of n(this,ot).readdirSync(t,{withFileTypes:!0}))m(this,k,ss).call(this,e,i);m(this,k,es).call(this,i);}catch(e){m(this,k,is).call(this,e.code),i.provisional=0;}return i.slice(0,i.provisional)}canReaddir(){if(n(this,x)&cr)return false;let i=vt&n(this,x);return i===Rt||i===zt||i===Ee}shouldWalk(i,t){return (n(this,x)&zt)===zt&&!(n(this,x)&cr)&&!i.has(this)&&(!t||t(this))}async realpath(){if(n(this,Bt))return n(this,Bt);if(!((ts|Yi|It)&n(this,x)))try{let i=await n(this,ot).promises.realpath(this.fullpath());return f(this,Bt,this.resolve(i))}catch{m(this,k,Ms).call(this);}}realpathSync(){if(n(this,Bt))return n(this,Bt);if(!((ts|Yi|It)&n(this,x)))try{let i=n(this,ot).realpathSync(this.fullpath());return f(this,Bt,this.resolve(i))}catch{m(this,k,Ms).call(this);}}[yn](i){if(i===this)return;i.isCWD=false,this.isCWD=true;let t=new Set([]),e=[],s=this;for(;s&&s.parent;)t.add(s),f(s,Qt,e.join(this.sep)),f(s,Jt,e.join("/")),s=s.parent,e.push("..");for(s=i;s&&s.parent&&!t.has(s);)f(s,Qt,void 0),f(s,Jt,void 0),s=s.parent;}},ot=new WeakMap,gi=new WeakMap,mi=new WeakMap,yi=new WeakMap,bi=new WeakMap,wi=new WeakMap,Ei=new WeakMap,Si=new WeakMap,vi=new WeakMap,Ti=new WeakMap,Ri=new WeakMap,Ni=new WeakMap,Ai=new WeakMap,Ii=new WeakMap,ki=new WeakMap,Li=new WeakMap,xi=new WeakMap,Oi=new WeakMap,Ci=new WeakMap,ce=new WeakMap,Ie=new WeakMap,jt=new WeakMap,Xt=new WeakMap,Qt=new WeakMap,Jt=new WeakMap,x=new WeakMap,ke=new WeakMap,Vt=new WeakMap,Bt=new WeakMap,k=new WeakSet,Fs=function(i){let t=this;for(let e of i)t=t.child(e);return t},es=function(i){var t;f(this,x,n(this,x)|Ns);for(let e=i.provisional;e<i.length;e++){let s=i[e];s&&m(t=s,k,ci).call(t);}},ci=function(){n(this,x)&It||(f(this,x,(n(this,x)|It)&ri),m(this,k,Ps).call(this));},Ps=function(){var t;let i=this.children();i.provisional=0;for(let e of i)m(t=e,k,ci).call(t);},Ms=function(){f(this,x,n(this,x)|ts),m(this,k,ui).call(this);},ui=function(){if(n(this,x)&hi)return;let i=n(this,x);(i&vt)===zt&&(i&=ri),f(this,x,i|hi),m(this,k,Ps).call(this);},is=function(i=""){i==="ENOTDIR"||i==="EPERM"?m(this,k,ui).call(this):i==="ENOENT"?m(this,k,ci).call(this):this.children().provisional=0;},_s=function(i=""){var t;i==="ENOTDIR"?m(t=this.parent,k,ui).call(t):i==="ENOENT"&&m(this,k,ci).call(this);},zs=function(i=""){var e;let t=n(this,x);t|=Yi,i==="ENOENT"&&(t|=It),(i==="EINVAL"||i==="UNKNOWN")&&(t&=ri),f(this,x,t),i==="ENOTDIR"&&this.parent&&m(e=this.parent,k,ui).call(e);},ss=function(i,t){return m(this,k,wn).call(this,i,t)||m(this,k,bn).call(this,i,t)},bn=function(i,t){let e=As(i),s=this.newChild(i.name,e,{parent:this}),r=n(s,x)&vt;return r!==zt&&r!==Ee&&r!==Rt&&f(s,x,n(s,x)|hi),t.unshift(s),t.provisional++,s},wn=function(i,t){for(let e=t.provisional;e<t.length;e++){let s=t[e];if((this.nocase?Xi(i.name):li(i.name))===n(s,ce))return m(this,k,En).call(this,i,s,e,t)}},En=function(i,t,e,s){let r=t.name;return f(t,x,n(t,x)&ri|As(i)),r!==i.name&&(t.name=i.name),e!==s.provisional&&(e===s.length-1?s.pop():s.splice(e,1),s.unshift(t)),s.provisional++,t},Ws=function(i){let{atime:t,atimeMs:e,birthtime:s,birthtimeMs:r,blksize:o,blocks:a,ctime:h,ctimeMs:l,dev:c,gid:d,ino:u,mode:g,mtime:y,mtimeMs:w,nlink:b,rdev:S,size:E,uid:A}=i;f(this,Li,t),f(this,Ni,e),f(this,Ci,s),f(this,ki,r),f(this,Si,o),f(this,Ri,a),f(this,Oi,h),f(this,Ii,l),f(this,gi,c),f(this,wi,d),f(this,vi,u),f(this,mi,g),f(this,xi,y),f(this,Ai,w),f(this,yi,b),f(this,Ei,S),f(this,Ti,E),f(this,bi,A);let I=As(i);f(this,x,n(this,x)&ri|I|lr),I!==Rt&&I!==zt&&I!==Ee&&f(this,x,n(this,x)|hi);},He=new WeakMap,qe=new WeakMap,Sn=function(i){f(this,qe,false);let t=n(this,He).slice();n(this,He).length=0,t.forEach(e=>e(null,i));},Le=new WeakMap,jr),vn=class Tn extends lt{constructor(e,s=Rt,r,o,a,h,l){super(e,s,r,o,a,h,l);p(this,"sep","\\");p(this,"splitSep",Aa);}newChild(e,s=Rt,r={}){return new Tn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=Na(e.toUpperCase()),e===this.root.name)return this.root;for(let[s,r]of Object.entries(this.roots))if(this.sameRoot(e,s))return this.roots[e]=r;return this.roots[e]=new Gs(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(un,"$1\\"),e===s}},Rn=class Nn extends lt{constructor(e,s=Rt,r,o,a,h,l){super(e,s,r,o,a,h,l);p(this,"splitSep","/");p(this,"sep","/");}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,s=Rt,r={}){return new Nn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Ke,Ye,Di,Fi,Br,An=(Br=class{constructor(i=process.cwd(),t,e,{nocase:s,childrenCacheSize:r=16*1024,fs:o=ai}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");v(this,Ke);v(this,Ye);v(this,Di);p(this,"nocase");v(this,Fi);f(this,Fi,cn(o)),(i instanceof URL||i.startsWith("file://"))&&(i=fileURLToPath(i));let a=t.resolve(i);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),f(this,Ke,new pr),f(this,Ye,new pr),f(this,Di,new ka(r));let h=a.substring(this.rootPath.length).split(e);if(h.length===1&&!h[0]&&h.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(n(this,Fi)),this.roots[this.rootPath]=this.root;let l=this.root,c=h.length-1,d=t.sep,u=this.rootPath,g=false;for(let y of h){let w=c--;l=l.child(y,{relative:new Array(w).fill("..").join(d),relativePosix:new Array(w).fill("..").join("/"),fullpath:u+=(g?"":d)+y}),g=true;}this.cwd=l;}depth(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.depth()}childrenCache(){return n(this,Di)}resolve(...i){let t="";for(let r=i.length-1;r>=0;r--){let o=i[r];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let e=n(this,Ke).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpath();return n(this,Ke).set(t,s),s}resolvePosix(...i){let t="";for(let r=i.length-1;r>=0;r--){let o=i[r];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let e=n(this,Ye).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpathPosix();return n(this,Ye).set(t,s),s}relative(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.relative()}relativePosix(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.relativePosix()}basename(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.name}dirname(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),(i.parent||i).fullpath()}async readdir(i=this.cwd,t={withFileTypes:true}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e}=t;if(i.canReaddir()){let s=await i.readdir();return e?s:s.map(r=>r.name)}else return []}readdirSync(i=this.cwd,t={withFileTypes:true}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true}=t;return i.canReaddir()?e?i.readdirSync():i.readdirSync().map(s=>s.name):[]}async lstat(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.lstat()}lstatSync(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.lstatSync()}async readlink(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i.withFileTypes,i=this.cwd);let e=await i.readlink();return t?e:e?.fullpath()}readlinkSync(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i.withFileTypes,i=this.cwd);let e=i.readlinkSync();return t?e:e?.fullpath()}async realpath(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i.withFileTypes,i=this.cwd);let e=await i.realpath();return t?e:e?.fullpath()}realpathSync(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i.withFileTypes,i=this.cwd);let e=i.realpathSync();return t?e:e?.fullpath()}async walk(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=[];(!r||r(i))&&a.push(e?i:i.fullpath());let h=new Set,l=(d,u)=>{h.add(d),d.readdirCB((g,y)=>{if(g)return u(g);let w=y.length;if(!w)return u();let b=()=>{--w===0&&u();};for(let S of y)(!r||r(S))&&a.push(e?S:S.fullpath()),s&&S.isSymbolicLink()?S.realpath().then(E=>E?.isUnknown()?E.lstat():E).then(E=>E?.shouldWalk(h,o)?l(E,b):b()):S.shouldWalk(h,o)?l(S,b):b();},true);},c=i;return new Promise((d,u)=>{l(c,g=>{if(g)return u(g);d(a);});})}walkSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=[];(!r||r(i))&&a.push(e?i:i.fullpath());let h=new Set([i]);for(let l of h){let c=l.readdirSync();for(let d of c){(!r||r(d))&&a.push(e?d:d.fullpath());let u=d;if(d.isSymbolicLink()){if(!(s&&(u=d.realpathSync())))continue;u.isUnknown()&&u.lstatSync();}u.shouldWalk(h,o)&&h.add(u);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(i=this.cwd,t={}){return typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd),this.stream(i,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t;(!r||r(i))&&(yield e?i:i.fullpath());let a=new Set([i]);for(let h of a){let l=h.readdirSync();for(let c of l){(!r||r(c))&&(yield e?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(s&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(a,o)&&a.add(d);}}}stream(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new os({objectMode:true});(!r||r(i))&&a.write(e?i:i.fullpath());let h=new Set,l=[i],c=0,d=()=>{let u=false;for(;!u;){let g=l.shift();if(!g){c===0&&a.end();return}c++,h.add(g);let y=(b,S,E=false)=>{if(b)return a.emit("error",b);if(s&&!E){let A=[];for(let I of S)I.isSymbolicLink()&&A.push(I.realpath().then(N=>N?.isUnknown()?N.lstat():N));if(A.length){Promise.all(A).then(()=>y(null,S,true));return}}for(let A of S)A&&(!r||r(A))&&(a.write(e?A:A.fullpath())||(u=true));c--;for(let A of S){let I=A.realpathCached()||A;I.shouldWalk(h,o)&&l.push(I);}u&&!a.flowing?a.once("drain",d):w||d();},w=true;g.readdirCB(y,true),w=false;}};return d(),a}streamSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof lt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new os({objectMode:true}),h=new Set;(!r||r(i))&&a.write(e?i:i.fullpath());let l=[i],c=0,d=()=>{let u=false;for(;!u;){let g=l.shift();if(!g){c===0&&a.end();return}c++,h.add(g);let y=g.readdirSync();for(let w of y)(!r||r(w))&&(a.write(e?w:w.fullpath())||(u=true));c--;for(let w of y){let b=w;if(w.isSymbolicLink()){if(!(s&&(b=w.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(h,o)&&l.push(b);}}u&&!a.flowing&&a.once("drain",d);};return d(),a}chdir(i=this.cwd){let t=this.cwd;this.cwd=typeof i=="string"?this.cwd.resolve(i):i,this.cwd[yn](t);}},Ke=new WeakMap,Ye=new WeakMap,Di=new WeakMap,Fi=new WeakMap,Br),Gs=class extends An{constructor(t=process.cwd(),e={}){let{nocase:s=true}=e;super(t,win32,"\\",{...e,nocase:s});p(this,"sep","\\");this.nocase=s;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase;}parseRootPath(t){return win32.parse(t).root.toUpperCase()}newRoot(t){return new vn(this.rootPath,zt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Hs=class extends An{constructor(t=process.cwd(),e={}){let{nocase:s=false}=e;super(t,posix,"/",{...e,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Rn(this.rootPath,zt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},In=class extends Hs{constructor(i=process.cwd(),t={}){let{nocase:e=true}=t;super(i,{...t,nocase:e});}};process.platform==="win32"?vn:Rn;var La=process.platform==="win32"?Gs:process.platform==="darwin"?In:Hs,xa=i=>i.length>=1,Oa=i=>i.length>=1,Ca=Symbol.for("nodejs.util.inspect.custom"),q,ct,K,xe,Mt,Pi,ue,de,pe,Xe,Qe,kn=(Qe=class{constructor(t,e,s,r){v(this,q);v(this,ct);v(this,K);p(this,"length");v(this,xe);v(this,Mt);v(this,Pi);v(this,ue);v(this,de);v(this,pe);v(this,Xe,true);if(!xa(t))throw new TypeError("empty pattern list");if(!Oa(e))throw new TypeError("empty glob list");if(e.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(f(this,q,t),f(this,ct,e),f(this,K,s),f(this,xe,r),n(this,K)===0){if(this.isUNC()){let[o,a,h,l,...c]=n(this,q),[d,u,g,y,...w]=n(this,ct);c[0]===""&&(c.shift(),w.shift());let b=[o,a,h,l,""].join("/"),S=[d,u,g,y,""].join("/");f(this,q,[b,...c]),f(this,ct,[S,...w]),this.length=n(this,q).length;}else if(this.isDrive()||this.isAbsolute()){let[o,...a]=n(this,q),[h,...l]=n(this,ct);a[0]===""&&(a.shift(),l.shift());let c=o+"/",d=h+"/";f(this,q,[c,...a]),f(this,ct,[d,...l]),this.length=n(this,q).length;}}}[Ca](){return "Pattern <"+n(this,ct).slice(n(this,K)).join("/")+">"}pattern(){return n(this,q)[n(this,K)]}isString(){return typeof n(this,q)[n(this,K)]=="string"}isGlobstar(){return n(this,q)[n(this,K)]===at}isRegExp(){return n(this,q)[n(this,K)]instanceof RegExp}globString(){return f(this,Pi,n(this,Pi)||(n(this,K)===0?this.isAbsolute()?n(this,ct)[0]+n(this,ct).slice(1).join("/"):n(this,ct).join("/"):n(this,ct).slice(n(this,K)).join("/")))}hasMore(){return this.length>n(this,K)+1}rest(){return n(this,Mt)!==void 0?n(this,Mt):this.hasMore()?(f(this,Mt,new Qe(n(this,q),n(this,ct),n(this,K)+1,n(this,xe))),f(n(this,Mt),pe,n(this,pe)),f(n(this,Mt),de,n(this,de)),f(n(this,Mt),ue,n(this,ue)),n(this,Mt)):f(this,Mt,null)}isUNC(){let t=n(this,q);return n(this,de)!==void 0?n(this,de):f(this,de,n(this,xe)==="win32"&&n(this,K)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=n(this,q);return n(this,ue)!==void 0?n(this,ue):f(this,ue,n(this,xe)==="win32"&&n(this,K)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=n(this,q);return n(this,pe)!==void 0?n(this,pe):f(this,pe,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=n(this,q)[0];return typeof t=="string"&&this.isAbsolute()&&n(this,K)===0?t:""}checkFollowGlobstar(){return !(n(this,K)===0||!this.isGlobstar()||!n(this,Xe))}markFollowGlobstar(){return n(this,K)===0||!this.isGlobstar()||!n(this,Xe)?false:(f(this,Xe,false),true)}},q=new WeakMap,ct=new WeakMap,K=new WeakMap,xe=new WeakMap,Mt=new WeakMap,Pi=new WeakMap,ue=new WeakMap,de=new WeakMap,pe=new WeakMap,Xe=new WeakMap,Qe),Da=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",fr=class{constructor(i,{nobrace:t,nocase:e,noext:s,noglobstar:r,platform:o=Da}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:true,nobrace:t,nocase:e,noext:s,noglobstar:r,optimizationLevel:2,platform:o,nocomment:true,nonegate:true};for(let a of i)this.add(a);}add(i){let t=new ge(i,this.mmopts);for(let e=0;e<t.set.length;e++){let s=t.set[e],r=t.globParts[e];if(!s||!r)throw new Error("invalid pattern object");for(;s[0]==="."&&r[0]===".";)s.shift(),r.shift();let o=new kn(s,r,0,this.platform),a=new ge(o.globString(),this.mmopts),h=r[r.length-1]==="**",l=o.isAbsolute();l?this.absolute.push(a):this.relative.push(a),h&&(l?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(i){let t=i.fullpath(),e=`${t}/`,s=i.relative()||".",r=`${s}/`;for(let o of this.relative)if(o.match(s)||o.match(r))return true;for(let o of this.absolute)if(o.match(t)||o.match(e))return true;return false}childrenIgnored(i){let t=i.fullpath()+"/",e=(i.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(e))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},Fa=class Ln{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new Ln(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),r=this.store.get(s);r?r.add(e.globString()):this.store.set(s,new Set([e.globString()]));}},Pa=class{constructor(){p(this,"store",new Map);}add(i,t,e){let s=(t?2:0)|(e?1:0),r=this.store.get(i);this.store.set(i,r===void 0?s:s&r);}entries(){return [...this.store.entries()].map(([i,t])=>[i,!!(t&2),!!(t&1)])}},Ma=class{constructor(){p(this,"store",new Map);}add(i,t){if(!i.canReaddir())return;let e=this.store.get(i);e?e.find(s=>s.globString()===t.globString())||e.push(t):this.store.set(i,[t]);}get(i){let t=this.store.get(i);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(i=>[i,this.store.get(i)])}keys(){return [...this.store.keys()].filter(i=>i.canReaddir())}},gr=class xn{constructor(t,e){p(this,"hasWalkedCache");p(this,"matches",new Pa);p(this,"subwalks",new Ma);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new Fa;}processPatterns(t,e){this.patterns=e;let s=e.map(r=>[t,r]);for(let[r,o]of s){this.hasWalkedCache.storeWalked(r,o);let a=o.root(),h=o.isAbsolute()&&this.opts.absolute!==false;if(a){r=r.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);let u=o.rest();if(u)o=u;else {this.matches.add(r,true,false);continue}}if(r.isENOENT())continue;let l,c,d=false;for(;typeof(l=o.pattern())=="string"&&(c=o.rest());)r=r.resolve(l),o=c,d=true;if(l=o.pattern(),c=o.rest(),d){if(this.hasWalkedCache.hasWalked(r,o))continue;this.hasWalkedCache.storeWalked(r,o);}if(typeof l=="string"){let u=l===".."||l===""||l===".";this.matches.add(r.resolve(l),h,u);continue}else if(l===at){(!r.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(r,o);let u=c?.pattern(),g=c?.rest();if(!c||(u===""||u===".")&&!g)this.matches.add(r,h,u===""||u===".");else if(u===".."){let y=r.parent||r;g?this.hasWalkedCache.hasWalked(y,g)||this.subwalks.add(y,g):this.matches.add(y,h,true);}}else l instanceof RegExp&&this.subwalks.add(r,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new xn(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),r=this.child();for(let o of e)for(let a of s){let h=a.isAbsolute(),l=a.pattern(),c=a.rest();l===at?r.testGlobstar(o,a,c,h):l instanceof RegExp?r.testRegExp(o,l,c,h):r.testString(o,l,c,h);}return r}testGlobstar(t,e,s,r){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,r,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let o=s.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(t,o,s.rest(),r);else if(o===".."){let a=t.parent||t;this.subwalks.add(a,s);}else o instanceof RegExp&&this.testRegExp(t,o,s.rest(),r);}}testRegExp(t,e,s,r){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,r,false));}testString(t,e,s,r){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,r,false));}},_a=(i,t)=>typeof i=="string"?new fr([i],t):Array.isArray(i)?new fr(i,t):i,Je,Zt,Oe,Nt,Se,js,Ur,On=(Ur=class{constructor(i,t,e){v(this,Nt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);v(this,Je,[]);v(this,Zt);v(this,Oe);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=i,this.path=t,this.opts=e,f(this,Oe,!e.posix&&e.platform==="win32"?"\\":"/"),this.includeChildMatches=e.includeChildMatches!==false,(e.ignore||!this.includeChildMatches)&&(f(this,Zt,_a(e.ignore??[],e)),!this.includeChildMatches&&typeof n(this,Zt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=e.maxDepth||1/0,e.signal&&(this.signal=e.signal,this.signal.addEventListener("abort",()=>{n(this,Je).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let i;for(;!this.paused&&(i=n(this,Je).shift());)i();}onResume(i){this.signal?.aborted||(this.paused?n(this,Je).push(i):i());}async matchCheck(i,t){if(t&&this.opts.nodir)return;let e;if(this.opts.realpath){if(e=i.realpathCached()||await i.realpath(),!e)return;i=e;}let s=i.isUnknown()||this.opts.stat?await i.lstat():i;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let r=await s.realpath();r&&(r.isUnknown()||this.opts.stat)&&await r.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(i,t){return i&&(this.maxDepth===1/0||i.depth()<=this.maxDepth)&&(!t||i.canReaddir())&&(!this.opts.nodir||!i.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!i.isSymbolicLink()||!i.realpathCached()?.isDirectory())&&!m(this,Nt,Se).call(this,i)?i:void 0}matchCheckSync(i,t){if(t&&this.opts.nodir)return;let e;if(this.opts.realpath){if(e=i.realpathCached()||i.realpathSync(),!e)return;i=e;}let s=i.isUnknown()||this.opts.stat?i.lstatSync():i;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let r=s.realpathSync();r&&(r?.isUnknown()||this.opts.stat)&&r.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(i,t){if(m(this,Nt,Se).call(this,i))return;if(!this.includeChildMatches&&n(this,Zt)?.add){let r=`${i.relativePosix()}/**`;n(this,Zt).add(r);}let e=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(i);let s=this.opts.mark&&i.isDirectory()?n(this,Oe):"";if(this.opts.withFileTypes)this.matchEmit(i);else if(e){let r=this.opts.posix?i.fullpathPosix():i.fullpath();this.matchEmit(r+s);}else {let r=this.opts.posix?i.relativePosix():i.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+n(this,Oe))?"."+n(this,Oe):"";this.matchEmit(r?o+r+s:"."+s);}}async match(i,t,e){let s=await this.matchCheck(i,e);s&&this.matchFinish(s,t);}matchSync(i,t,e){let s=this.matchCheckSync(i,e);s&&this.matchFinish(s,t);}walkCB(i,t,e){this.signal?.aborted&&e(),this.walkCB2(i,t,new gr(this.opts),e);}walkCB2(i,t,e,s){if(m(this,Nt,js).call(this,i))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(i,t,e,s));return}e.processPatterns(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,h,l]of e.matches.entries())m(this,Nt,Se).call(this,a)||(r++,this.match(a,h,l).then(()=>o()));for(let a of e.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;r++;let h=a.readdirCached();a.calledReaddir()?this.walkCB3(a,h,e,o):a.readdirCB((l,c)=>this.walkCB3(a,c,e,o),true);}o();}walkCB3(i,t,e,s){e=e.filterEntries(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,h,l]of e.matches.entries())m(this,Nt,Se).call(this,a)||(r++,this.match(a,h,l).then(()=>o()));for(let[a,h]of e.subwalks.entries())r++,this.walkCB2(a,h,e.child(),o);o();}walkCBSync(i,t,e){this.signal?.aborted&&e(),this.walkCB2Sync(i,t,new gr(this.opts),e);}walkCB2Sync(i,t,e,s){if(m(this,Nt,js).call(this,i))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(i,t,e,s));return}e.processPatterns(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,h,l]of e.matches.entries())m(this,Nt,Se).call(this,a)||this.matchSync(a,h,l);for(let a of e.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;r++;let h=a.readdirSync();this.walkCB3Sync(a,h,e,o);}o();}walkCB3Sync(i,t,e,s){e=e.filterEntries(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,h,l]of e.matches.entries())m(this,Nt,Se).call(this,a)||this.matchSync(a,h,l);for(let[a,h]of e.subwalks.entries())r++,this.walkCB2Sync(a,h,e.child(),o);o();}},Je=new WeakMap,Zt=new WeakMap,Oe=new WeakMap,Nt=new WeakSet,Se=function(i){return this.seen.has(i)||!!n(this,Zt)?.ignored?.(i)},js=function(i){return !!n(this,Zt)?.childrenIgnored?.(i)},Ur),mr=class extends On{constructor(t,e,s){super(t,e,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},yr=class extends On{constructor(t,e,s){super(t,e,s);p(this,"results");this.results=new os({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},za=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",De=class{constructor(i,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof i=="string"&&(i=[i]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(i=i.map(h=>h.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");i=i.map(h=>h.includes("/")?h:`./**/${h}`);}if(this.pattern=i,this.platform=t.platform||za,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 h=t.platform==="win32"?Gs:t.platform==="darwin"?In:t.platform?Hs:La;this.scurry=new h(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let e=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:e,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(h=>new ge(h,s)),[o,a]=r.reduce((h,l)=>(h[0].push(...l.set),h[1].push(...l.globParts),h),[[],[]]);this.patterns=o.map((h,l)=>{let c=a[l];if(!c)throw new Error("invalid pattern object");return new kn(h,c,0,this.platform)});}async walk(){return [...await new mr(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 mr(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 yr(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 yr(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()}},Wa=(i,t={})=>{Array.isArray(i)||(i=[i]);for(let e of i)if(new ge(e,t).hasMagic())return true;return false};function ls(i,t={}){return new De(i,t).streamSync()}function Cn(i,t={}){return new De(i,t).stream()}function Dn(i,t={}){return new De(i,t).walkSync()}async function br(i,t={}){return new De(i,t).walk()}function cs(i,t={}){return new De(i,t).iterateSync()}function Fn(i,t={}){return new De(i,t).iterate()}var ja=ls,Ba=Object.assign(Cn,{sync:ls}),Ua=cs,$a=Object.assign(Fn,{sync:cs}),Ga=Object.assign(Dn,{stream:ls,iterate:cs}),as=Object.assign(br,{glob:br,globSync:Dn,sync:Ga,globStream:Cn,stream:Ba,globStreamSync:ls,streamSync:ja,globIterate:Fn,iterate:$a,globIterateSync:cs,iterateSync:Ua,Glob:De,hasMagic:Wa,escape:Vr,unescape:ze});as.glob=as;var bt;(N=>{N.Level=qa.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},e="INFO";function s(T){return t[T]>=t[e]}function r(){return e}N.getLevel=r;let o=new Map;N.Default=I({service:"default"});let h="";function l(){return h}N.file=l;let c,d,u=false,g=()=>{},y=false;async function w(T){if(u)return;if(T.print){u=true;return}T.level&&(e=T.level);let L=T.logDir||ye__default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");T.logFile?h=ye__default.join(L,T.logFile??"note.log"):h=ye__default.join(L,"note.log");try{await Ve.mkdir(L,{recursive:!0}),c=await Ve.open(h,"a"),d=createWriteStream("",{fd:c.fd,autoClose:!1}),g=C=>{if(!(y||!d||d.destroyed))try{if(!d.writable)return;d.write(C,z=>{z&&!y&&(y=!0,setTimeout(()=>{y=!1;},1e3));});}catch(z){y||(y=!0,process.stderr.write(`[LOG ERROR] Write failed: ${z}
81
- `),setTimeout(()=>{y=!1;},1e3));}},u=!0;}catch(C){process.stderr.write(`[LOG ERROR] Failed to init log file: ${C}
82
- `),g=z=>{try{process.stderr.write(z);}catch{}},u=true;}}N.init=w;async function b(){u&&(d&&!d.destroyed&&(await new Promise((T,L)=>{d.end(C=>{C?L(C):T();});}).catch(T=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${T}
83
- `);}),d=void 0),c&&(await c.close().catch(T=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${T}
84
- `);}),c=void 0),g=T=>{try{process.stderr.write(T);}catch{}},u=false);}N.close=b;function E(T,L=0){let C=T.message;return T.cause instanceof Error&&L<10?C+" Caused by: "+E(T.cause,L+1):C}let A=Date.now();function I(T){T=T||{};let L=T.service;if(L&&typeof L=="string"){let F=o.get(L);if(F)return F}function C(F,W){let Fe=Object.entries({...T,...W}).filter(([Ys,ee])=>ee!=null).map(([Ys,ee])=>{let ys=`${Ys}=`;return ee instanceof Error?ys+E(ee):typeof ee=="object"?ys+JSON.stringify(ee):ys+ee}).join(" "),D=new Date,_i=D.getTime()-A;return A=D.getTime(),[D.getFullYear()+"-"+String(D.getMonth()+1).padStart(2,"0")+"-"+String(D.getDate()).padStart(2,"0")+"T"+String(D.getHours()).padStart(2,"0")+":"+String(D.getMinutes()).padStart(2,"0")+":"+String(D.getSeconds()).padStart(2,"0"),"+"+_i+"ms",Fe,F].filter(Boolean).join(" ")+`
85
- `}let z={debug(F,W){s("DEBUG")&&g("DEBUG "+C(F,W));},info(F,W){s("INFO")&&g("INFO "+C(F,W));},error(F,W){s("ERROR")&&g("ERROR "+C(F,W));},warn(F,W){s("WARN")&&g("WARN "+C(F,W));},tag(F,W){return T&&(T[F]=W),z},clone(){return N.create({...T})},time(F,W){let Fe=Date.now();z.info(F,{status:"started",...W});function D(){z.info(F,{status:"completed",duration:Date.now()-Fe,...W});}return {stop:D,[Symbol.dispose](){D();}}}};return L&&typeof L=="string"&&o.set(L,z),z}N.create=I;})(bt||(bt={}));var $t=bt.create({service:"note.tokenizer"}),me=false,Xa=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function vl(i){if(!me)try{$t.info("Initializing jieba tokenizer");let t=Xa();if(te.with_dict(t),$t.info("Built-in dictionary loaded"),i?.dictPath&&i.dictPath.length>0)for(let e of i.dictPath)await Qa(e);me=!0,$t.info("Jieba tokenizer initialized");}catch(t){throw $t.error("Failed to initialize jieba tokenizer",{error:String(t)}),t}}async function Qa(i){if(!me)throw new Error("Tokenizer not initialized");try{let t=await Filesystem.readText(i);te.with_dict(t),$t.info("Custom dictionary loaded",{dictPath:i});}catch(t){$t.warn("Failed to load custom dictionary",{dictPath:i,error:String(t)});}}function Ja(i){if(!me)return i.split(/\s+/).filter(Boolean);try{return te.cut(i)}catch(t){return $t.warn("Tokenization failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function Va(i){if(!me)return i.split(/\s+/).filter(Boolean);try{return te.cut_for_search(i)}catch(t){return $t.warn("Tokenization for search failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function Tl(i,t,e){if(me)try{te.add_word(i,t,e);}catch(s){$t.warn("Failed to add word",{word:i,error:String(s)});}}function Rl(){return me}async function Nl(){me=false,$t.info("Tokenizer closed");}function Pn(i){return Ja(i).join(" ")}function Mn(i){return Va(i).join(" ")}var ut;(y=>{let i=bt.create({service:"note-llm"}),t=null,e=()=>{if(!t)throw new Error("Llm is not initialized. Please call Llm.init() first.");return t};function s(w){r()||(t={models:w.models,options:{graph:w.options?.graph,rerankTopN:w.options?.rerankTopN}},i.debug("Llm initialized"));}y.init=s;function r(){return t!==null}y.isInitialized=r;function o(){return t?{embedding:!!t.models.embeddingLlm,graphLlm:!!t.models.graphLlm,rerankLlm:!!t.models.rerankLlm}:{embedding:false,graphLlm:false,rerankLlm:false}}y.capabilities=o;async function a(w){let S=e().models.embeddingLlm;if(!S)throw new Error("embeddingLlm model is not configured.");let E=await embed({model:S,value:w});return new Float32Array(E.embedding)}y.embedText=a;async function h(w){let S=e().models.embeddingLlm;if(!S)throw new Error("embeddingLlm model is not configured.");return (await embedMany({model:S,values:w})).embeddings.map(A=>new Float32Array(A))}y.embedTexts=h;async function l(w,b){let S=e(),E=S.models.graphLlm;if(!E)return "";let A=d(w);return streamText({model:E,prompt:A,maxOutputTokens:b?.maxOutputTokens??S.options.graph?.maxOutputTokens,temperature:b?.temperature??S.options.graph?.temperature}).text}y.generateGraph=l;async function c(w,b,S){let E=e();return E.models.rerankLlm?(await rerank({model:E.models.rerankLlm,query:w,documents:b,topN:S??E.options.rerankTopN??b.length})).ranking.map(I=>({index:I.originalIndex,score:I.score??0})):[]}y.rerank=c;function d(w){let b=GRAPH_ENTITY_TYPE_DEFINITIONS.map(I=>`- ${I.type}: ${I.rule}`).join(`
86
- `),S=GRAPH_RELATION_TYPE_DEFINITIONS.map(I=>`- ${I.type}: ${I.rule}`).join(`
87
- `),A=w.slice(0,5).join(`
81
+ `),e.pragma("foreign_keys = ON");}query(e,t){if(!this.db)throw new Error("Database not initialized");try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new R(`Query failed: ${r.message}`,"DATABASE_QUERY_FAILED",r)}}run(e,t){if(!this.db)throw new Error("Database not initialized");try{let r=this.db.prepare(e),n=t?r.run(...t):r.run();return {lastID:Number(n.lastInsertRowid),changes:n.changes}}catch(r){throw new R(`Execution failed: ${r.message}`,"DATABASE_QUERY_FAILED",r)}}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}async close(){this.db&&(this.db.close(),this.db=null);}getPath(){return this.storagePath}getDb(){if(!this.db)throw new Error("Database not initialized");return this.db}async getDocumentsCount(){return (await this.query("SELECT COUNT(*) as count FROM documents"))[0]?.count??0}async getChunksCount(){return (await this.query("SELECT COUNT(*) as count FROM chunks"))[0]?.count??0}async getNodesCount(){return (await this.query("SELECT COUNT(*) as count FROM nodes"))[0]?.count??0}async getEdgesCount(){return (await this.query("SELECT COUNT(*) as count FROM edges"))[0]?.count??0}async isVectorSearchAvailable(){try{return ((await this.query("SELECT COUNT(*) as count FROM vectors"))[0]?.count??0)>0}catch{return false}}async healthCheck(){try{return this.db?(await this.query("SELECT 1"),!0):!1}catch{return false}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}getAllDocumentPaths(){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT path FROM documents").all().map(t=>t.path)}getDocumentIdByPath(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT id FROM documents WHERE path = ?").get(e)?.id??null}getChunkIdsByDocumentId(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT id FROM chunks WHERE documentId = ?").all(e).map(r=>r.id)}cleanupDocumentData(e){if(!this.db)throw new Error("Database not initialized");this.transaction(()=>{let t=this.db.prepare("SELECT id, nodeIds, contentHash FROM chunks WHERE documentId = ?").all(e);if(t.length===0){this.run("DELETE FROM documents WHERE id = ?",[e]);return}let r=t.map(s=>s.id),n=t.map(s=>s.contentHash),o=new Set;for(let s of t)if(s.nodeIds)try{let i=JSON.parse(s.nodeIds);for(let c of i)o.add(c);}catch{}if(r.length>0){let s=r.map(()=>"?").join(",");try{this.run(`DELETE FROM chunks_fts WHERE chunkId IN (${s})`,r);}catch{for(let i of r)try{this.run("DELETE FROM chunks_fts WHERE chunkId = ?",[i]);}catch{}}}if(o.size>0){let s=Array.from(o),i=this.db.prepare(`
82
+ SELECT nodeIds FROM chunks
83
+ WHERE documentId != ?
84
+ `).all(e),c=new Set;for(let a of i)if(a.nodeIds)try{let d=JSON.parse(a.nodeIds);for(let l of d)c.add(l);}catch{}for(let a of s)c.has(a)||this.run("DELETE FROM nodes WHERE id = ?",[a]);}if(n.length>0)for(let s of n){let i=this.db.prepare("SELECT COUNT(*) as count FROM chunks WHERE contentHash = ? AND documentId != ?").get(s,e);(!i||i.count===0)&&this.run("DELETE FROM embedding_cache WHERE contentHash = ?",[s]);}this.run("DELETE FROM chunks WHERE documentId = ?",[e]),this.run("DELETE FROM documents WHERE id = ?",[e]);});}deleteDocumentByPath(e){let t=this.getDocumentIdByPath(e);return t===null?false:(this.cleanupDocumentData(t),true)}};var H=class{async parse(e){try{let t=await readFile(e,"utf-8"),r=extname(e).toLowerCase(),n=this.parseMarkdown(t);return {content:n.content,metadata:n.metadata}}catch(t){throw new R(`\u6587\u6863\u89E3\u6790\u5931\u8D25: ${t.message}`,"DOCUMENT_PARSE_FAILED",t)}}parseMarkdown(e){let{frontmatter:t,content:r}=Markdown.extractFrontmatter(e),n={};t.title!==void 0&&(n.title=String(t.title)),t.author!==void 0&&(n.author=String(t.author)),t.date!==void 0&&(n.date=String(t.date));for(let[s,i]of Object.entries(t))["title","author","date"].includes(s)||(n[s]=i);return {content:Markdown.format(r),metadata:n}}static computeHash(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t;}return Math.abs(t).toString(16)}};var P=b.create({service:"note.tokenizer"}),_=false,ye=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function nt(E){if(!_)try{P.info("Initializing jieba tokenizer");let e=ye();if(F.with_dict(e),P.info("Built-in dictionary loaded"),E?.dictPath&&E.dictPath.length>0)for(let t of E.dictPath)await be(t);_=!0,P.info("Jieba tokenizer initialized");}catch(e){throw P.error("Failed to initialize jieba tokenizer",{error:String(e)}),e}}async function be(E){if(!_)throw new Error("Tokenizer not initialized");try{let e=await Filesystem.readText(E);F.with_dict(e),P.info("Custom dictionary loaded",{dictPath:E});}catch(e){P.warn("Failed to load custom dictionary",{dictPath:E,error:String(e)});}}function Ie(E){if(!_)return E.split(/\s+/).filter(Boolean);try{return F.cut(E)}catch(e){return P.warn("Tokenization failed, using fallback",{error:String(e)}),E.split(/\s+/).filter(Boolean)}}function Ne(E){if(!_)return E.split(/\s+/).filter(Boolean);try{return F.cut_for_search(E)}catch(e){return P.warn("Tokenization for search failed, using fallback",{error:String(e)}),E.split(/\s+/).filter(Boolean)}}function st(E,e,t){if(_)try{F.add_word(E,e,t);}catch(r){P.warn("Failed to add word",{word:E,error:String(r)});}}function it(){return _}async function ot(){_=false,P.info("Tokenizer closed");}function ie(E){return Ie(E).join(" ")}function oe(E){return Ne(E).join(" ")}var L;(u=>{let E=b.create({service:"note-llm"}),e=null,t=()=>{if(!e)throw new Error("Llm is not initialized. Please call Llm.init() first.");return e};function r(m){n()||(e={models:m.models,options:{graph:m.options?.graph,rerankTopN:m.options?.rerankTopN}},E.debug("Llm initialized"));}u.init=r;function n(){return e!==null}u.isInitialized=n;function o(){return e?{embedding:!!e.models.embeddingLlm,graphLlm:!!e.models.graphLlm,rerankLlm:!!e.models.rerankLlm}:{embedding:false,graphLlm:false,rerankLlm:false}}u.capabilities=o;async function s(m){let f=t().models.embeddingLlm;if(!f)throw new Error("embeddingLlm model is not configured.");let y=await embed({model:f,value:m});return new Float32Array(y.embedding)}u.embedText=s;async function i(m){let f=t().models.embeddingLlm;if(!f)throw new Error("embeddingLlm model is not configured.");return (await embedMany({model:f,values:m})).embeddings.map(b=>new Float32Array(b))}u.embedTexts=i;async function c(m,h){let f=t(),y=f.models.graphLlm;if(!y)return "";let b=d(m);return (await streamText({model:y,prompt:b,maxOutputTokens:h?.maxOutputTokens??f.options.graph?.maxOutputTokens,temperature:h?.temperature??f.options.graph?.temperature})).text}u.generateGraph=c;async function a(m,h,f){let y=t();return y.models.rerankLlm?(await rerank({model:y.models.rerankLlm,query:m,documents:h,topN:f??y.options.rerankTopN??h.length})).ranking.map(S=>({index:S.originalIndex,score:S.score??0})):[]}u.rerank=a;function d(m){let h=GRAPH_ENTITY_TYPE_DEFINITIONS.map(S=>`- ${S.type}: ${S.rule}`).join(`
85
+ `),f=GRAPH_RELATION_TYPE_DEFINITIONS.map(S=>`- ${S.type}: ${S.rule}`).join(`
86
+ `),b=m.slice(0,5).join(`
88
87
 
89
88
  `).slice(0,2e3);return `You are an information extraction engine for a general-purpose memory graph.
90
89
 
91
90
  Extract entities and directed relations from the text.
92
91
 
93
92
  Entity type taxonomy:
94
- ${b}
93
+ ${h}
95
94
 
96
95
  Relation type taxonomy:
97
- ${S}
96
+ ${f}
98
97
 
99
98
  Extraction rules:
100
99
  - Output valid JSON only. Do not include markdown, prose, or code fences.
@@ -116,10 +115,12 @@ Return this exact JSON shape:
116
115
  }
117
116
 
118
117
  Input text:
119
- ${A}`}y.embed=a,y.embedMany=h;})(ut||(ut={}));var nh=bt.create({service:"note-ingestion"}),oh=new Set(GRAPH_ENTITY_TYPE_DEFINITIONS.map(i=>i.type)),ah=new Set(GRAPH_RELATION_TYPE_DEFINITIONS.map(i=>i.type)),us=class{constructor(t,e){p(this,"db");p(this,"config");p(this,"parser");this.db=t,this.config={...e,embeddingLlm:e.embeddingLlm},this.parser=new be,e.embeddingLlm&&ut.init({models:{embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm,rerankLlm:e.rerankLlm}});}async process(t){let e=Filesystem.toUnixPath(t),{content:s,metadata:r}=await this.parser.parse(t),o=be.computeHash(s),a=this.db.query("SELECT id, contentHash FROM documents WHERE path = ?",[e]);if(a.length>0&&a[0]?.contentHash===o)return {documentId:a[0].id,chunksCreated:0,vectorsCreated:0};let h=this.chunk(s),l=await this.embedWithCache(h);return this.db.transaction(()=>{a.length>0&&this.db.run("DELETE FROM documents WHERE id = ?",[a[0].id]);let d=this.db.run(`INSERT INTO documents (path, title, contentHash, summary, metadata, lastModified)
120
- VALUES (?, ?, ?, ?, ?, ?)`,[e,r.title||ye.basename(t)||"Untitled",o,null,r.title?JSON.stringify(r):null,Date.now()]).lastID,u=0,g=0,y=new Map,w,b;if(this.config.graphLlm){let S=this.extractEntitiesSync(h);w=S.entities.length,b=S.relations.length,this.mapChunksToNodes(h,S.entities,y),this.storeEntities(S.entities,S.relations);}for(let S=0;S<h.length;S++){let E=h[S],A=be.computeHash(E),I=y.get(S)||[],T=this.db.run(`INSERT INTO chunks (documentId, startLine, endLine, content, contentHash, nodeIds)
121
- VALUES (?, ?, ?, ?, ?, ?)`,[d,S*(this.config.chunkSize-this.config.chunkOverlap),S*(this.config.chunkSize-this.config.chunkOverlap)+E.length,E,A,JSON.stringify(I)]).lastID,L=l[S];L&&(this.db.run("INSERT INTO vectors (chunkId, embedding) VALUES (?, ?)",[T,this.float32ToBuffer(L)]),g++);let C=Pn(E);this.db.run("INSERT INTO chunks_fts (rowid, documentId, content) VALUES (?, ?, ?)",[T,d,C]),u++;}return {documentId:d,chunksCreated:u,vectorsCreated:g,entitiesExtracted:w,relationsExtracted:b}})}async processBatch(t,e){let s=[];for(let r=0;r<t.length;r++){let o=await this.process(t[r]);s.push(o),e?.(r+1,t.length,o);}return s}chunk(t){let{chunkSize:e}=this.config;return Markdown.chunk(t,e)}async embedWithCache(t){if(!this.config.embeddingLlm)return t.map(()=>new Float32Array(this.config.vectorDims));let e=[],s=[];for(let r=0;r<t.length;r++){let o=t[r],a=be.computeHash(o),h=this.db.query("SELECT embedding FROM embedding_cache WHERE contentHash = ?",[a]);h.length>0&&h[0]?.embedding?e[r]=new Float32Array(h[0].embedding.buffer,h[0].embedding.byteOffset,h[0].embedding.length/4):s.push({index:r,content:o,hash:a});}if(s.length>0)try{let r=s.map(a=>a.content),o=await ut.embedMany(r);for(let a=0;a<s.length;a++){let{index:h,hash:l}=s[a],c=o[a];if(c){let d=new Float32Array(c);e[h]=d,this.db.run("INSERT OR REPLACE INTO embedding_cache (contentHash, embedding) VALUES (?, ?)",[l,this.float32ToBuffer(d)]);}}}catch(r){throw new j(`\u5D4C\u5165\u751F\u6210\u5931\u8D25: ${r.message}`,"EMBEDDING_FAILED",r)}return e}async embed(t){if(!this.config.embeddingLlm)return t.map(()=>new Float32Array(this.config.vectorDims));try{return await ut.embedMany(t)}catch(e){throw new j(`\u5D4C\u5165\u751F\u6210\u5931\u8D25: ${e.message}`,"EMBEDDING_FAILED",e)}}async extractEntities(t){let e=t.slice(0,5).join(`
118
+ ${b}`}u.embed=s,u.embedMany=i;})(L||(L={}));var ee=b.create({service:"note-ingestion"}),De=new Set(GRAPH_ENTITY_TYPE_DEFINITIONS.map(E=>E.type)),Oe=new Set(GRAPH_RELATION_TYPE_DEFINITIONS.map(E=>E.type)),Y=class{constructor(e,t){a(this,"db");a(this,"config");a(this,"parser");this.db=e,this.config={...DEFAULT_NOTE_CHUNK_CONFIG,...t,embeddingLlm:t.embeddingLlm},this.parser=new H,t.embeddingLlm&&L.init({models:{embeddingLlm:t.embeddingLlm,graphLlm:t.graphLlm,rerankLlm:t.rerankLlm}});}async process(e){let t=Filesystem.toUnixPath(e),{content:r,metadata:n}=await this.parser.parse(e),o=H.computeHash(r),s=this.db.query("SELECT id, contentHash FROM documents WHERE path = ?",[t]);if(s.length>0&&s[0]?.contentHash===o){let m=this.db.query("SELECT id FROM chunks WHERE documentId = ?",[s[0].id]).flatMap(y=>{let b=this.db.query("SELECT nodeIds FROM chunks WHERE id = ?",[y.id]);return b[0]?.nodeIds?JSON.parse(b[0].nodeIds):[]}),h=new Set(m).size,f=this.db.query(`SELECT id FROM edges WHERE source IN (${Array.from({length:h},()=>"?").join(",")})`,[...new Set(m)]).length;return {documentId:s[0].id,chunksCreated:0,vectorsCreated:0,entitiesExtracted:h,relationsExtracted:f}}let i=this.chunk(r),c=await this.embedWithCache(i),a=new Map,d,l,g=this.extractEntitiesSync(i);if(d=g.entities.length,l=g.relations.length,this.mapChunksToNodes(i,g.entities,a),this.storeEntities(g.entities,g.relations),this.config.graphLlm){let u=t;this.extractEntities(i).then(m=>{(m.entities.length>g.entities.length||m.relations.length>g.relations.length)&&(this.mergeEntitiesAndRelations(u,m.entities,m.relations),ee.debug("LLM entity extraction completed in background",{path:u,entities:m.entities.length,relations:m.relations.length}));}).catch(m=>{ee.warn("Background graph extraction failed",{path:u,error:String(m)});});}return this.db.transaction(()=>{s.length>0&&this.db.cleanupDocumentData(s[0].id);let m=this.db.run(`INSERT INTO documents (path, title, contentHash, summary, metadata, lastModified, createdAt, updatedAt)
119
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[t,n.title||U.basename(e)||"Untitled",o,null,n.title?JSON.stringify(n):null,new Date().toISOString(),new Date().toISOString(),new Date().toISOString()]).lastID,h=0,f=0;r.split(`
120
+ `);let b=0,S=0,q=[];for(let O=0;O<i.length;O++){let k=i[O],p=k.split(`
121
+ `).length-1;q.push({startLine:S,endLine:S+p,startChar:b,endChar:b+k.length});let I=this.config.chunkOverlap;b=b+Math.max(1,k.length-I);let T=Math.floor(I/20);S=S+Math.max(1,p-T);}for(let O=0;O<i.length;O++){let k=i[O],p=H.computeHash(k),I=a.get(O)||[],T=q[O],x=this.db.run(`INSERT INTO chunks (documentId, startLine, endLine, startChar, endChar, content, contentHash, nodeIds, createdAt)
122
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[m,T.startLine,T.endLine,T.startChar,T.endChar,k,p,JSON.stringify(I),new Date().toISOString()]).lastID,K=c[O];K&&(this.db.run("INSERT INTO vectors (chunkId, embedding) VALUES (?, ?)",[x,this.float32ToBuffer(K)]),f++);let W=ie(k);this.db.run("INSERT INTO chunks_fts (chunkId, documentId, content) VALUES (?, ?, ?)",[x,m,W]),h++;}return {documentId:m,chunksCreated:h,vectorsCreated:f,entitiesExtracted:d,relationsExtracted:l}})}async processBatch(e,t){let r=[];for(let n=0;n<e.length;n++){let o=await this.process(e[n]);r.push(o),t?.(n+1,e.length,o);}return r}chunk(e){let{chunkSize:t,minChunkLength:r=100}=this.config;return Markdown.chunk(e,t,{minLength:r})}async embedWithCache(e){if(!this.config.embeddingLlm)return e.map(()=>new Float32Array(this.config.vectorDims));let t=[],r=[];for(let n=0;n<e.length;n++){let o=e[n],s=H.computeHash(o),i=this.db.query("SELECT embedding FROM embedding_cache WHERE contentHash = ?",[s]);i.length>0&&i[0]?.embedding?t[n]=new Float32Array(i[0].embedding.buffer,i[0].embedding.byteOffset,i[0].embedding.length/4):r.push({index:n,content:o,hash:s});}if(r.length>0)try{let n=r.map(s=>s.content),o=await L.embedMany(n);for(let s=0;s<r.length;s++){let{index:i,hash:c}=r[s],a=o[s];if(a){let d=new Float32Array(a);t[i]=d,this.ensureVectorDims(d.length),this.db.run("INSERT OR REPLACE INTO embedding_cache (contentHash, embedding, createdAt) VALUES (?, ?, ?)",[c,this.float32ToBuffer(d),new Date().toISOString()]);}}}catch(n){throw new R(`\u5D4C\u5165\u751F\u6210\u5931\u8D25: ${n.message}`,"EMBEDDING_FAILED",n)}return t}async embed(e){if(!this.config.embeddingLlm)return e.map(()=>new Float32Array(this.config.vectorDims));try{return await L.embedMany(e)}catch(t){throw new R(`\u5D4C\u5165\u751F\u6210\u5931\u8D25: ${t.message}`,"EMBEDDING_FAILED",t)}}async extractEntities(e){let t=e.slice(0,5).join(`
122
123
 
123
- `);if(!this.config.graphLlm)return this.extractEntitiesByRules(e);try{let s=await ut.generateGraph(t,{maxOutputTokens:2e3}),r=this.parseEntityExtractionResult(s);return r.entities.length===0&&r.relations.length===0?this.extractEntitiesByRules(e):r}catch(s){if(s instanceof Error)return this.extractEntitiesByRules(e);throw new j(`\u5B9E\u4F53\u63D0\u53D6\u5931\u8D25: ${String(s)}`,"ENTITY_EXTRACTION_FAILED")}}extractEntitiesSync(t){let e=t.slice(0,5).join(`
124
+ `);if(!this.config.graphLlm)return this.extractEntitiesByRules(t);try{let r=await L.generateGraph(e,{maxOutputTokens:2e3}),n=this.parseEntityExtractionResult(r);return n.entities.length===0&&n.relations.length===0?this.extractEntitiesByRules(t):n}catch(r){if(r instanceof Error)return this.extractEntitiesByRules(t);throw new R(`\u5B9E\u4F53\u63D0\u53D6\u5931\u8D25: ${String(r)}`,"ENTITY_EXTRACTION_FAILED")}}extractEntitiesSync(e){let t=e.slice(0,5).join(`
124
125
 
125
- `);return this.extractEntitiesByRules(e)}parseEntityExtractionResult(t){try{let e=t.match(/\{[\s\S]*\}/);if(e){let s=JSON.parse(e[0]);return this.normalizeExtractionResult(s)}}catch(e){nh.debug("Failed to parse entity extraction result",{error:String(e)});}return {entities:[],relations:[]}}normalizeExtractionResult(t){let e=t,s=Array.isArray(e.entities)?e.entities:[],r=Array.isArray(e.relations)?e.relations:[],o=[],a=new Set,h=new Map;for(let d of s){let u=typeof d?.name=="string"?d.name.trim():"";if(!u)continue;let g=u.toLowerCase();if(a.has(g))continue;a.add(g),h.set(g,u);let y=typeof d?.type=="string"?d.type.trim():"",w=oh.has(y)?y:"keyword",b=d?.properties&&typeof d.properties=="object"&&!Array.isArray(d.properties)?d.properties:{};o.push({name:u,type:w,properties:b});}let l=[],c=new Set;for(let d of r){let u=typeof d?.source=="string"?d.source.trim():"",g=typeof d?.target=="string"?d.target.trim():"";if(!u||!g)continue;let y=h.get(u.toLowerCase()),w=h.get(g.toLowerCase());if(!y||!w||y===w)continue;let b=typeof d?.relation=="string"?d.relation.trim():"",S=ah.has(b)?b:"related_to",E=`${y.toLowerCase()}|${w.toLowerCase()}|${S}`;c.has(E)||(c.add(E),l.push({source:y,target:w,relation:S}));}return {entities:o,relations:l}}extractEntitiesByRules(t){let e=[],s=[],r=new Set,o=new Set,a=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let l of t.matchAll(a)){let c=this.sanitizeEntityToken(l[1]??""),d=(l[2]??"related_to").trim(),u=this.sanitizeEntityToken(l[3]??"");if(!c||!u||c===u)continue;let g=c.toLowerCase();r.has(g)||(r.add(g),e.push({name:c,type:this.inferEntityType(c),properties:{source:"rule_extracted"}}));let y=u.toLowerCase();r.has(y)||(r.add(y),e.push({name:u,type:this.inferEntityType(u),properties:{source:"rule_extracted"}}));let w=`${g}|${y}|${d}`;o.has(w)||(o.add(w),s.push({source:c,target:u,relation:d}));}let h=t.match(/[A-Za-z][A-Za-z0-9_.-]{2,80}/g)??[];for(let l of h){let c=this.sanitizeEntityToken(l);if(!c)continue;let d=c.toLowerCase();r.has(d)||(r.add(d),e.push({name:c,type:this.inferEntityType(c),properties:{source:"keyword_extracted"}}));}return {entities:e,relations:s}}sanitizeEntityToken(t){return t.trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"").replace(/\s+/g," ").slice(0,120)}inferEntityType(t){return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(t)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(t)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(t)?"organization":/(deadline|date|day|week|month|year|q[1-4]|sprint)/i.test(t)?"time":/(score|rate|ratio|latency|accuracy|recall|precision|throughput|kpi)/i.test(t)?"metric":/(task|issue|ticket|todo|action)/i.test(t)?"task":/(event|incident|release|meeting|migration|launch)/i.test(t)?"event":/(process|workflow|procedure|flow|lifecycle)/i.test(t)?"process":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(t)?"object":/(concept|principle|policy|method|pattern|strategy)/i.test(t)?"concept":/[A-Z]/.test(t)?"object":"keyword"}storeEntities(t,e){if(t.length===0)return;let s=new Map;this.db.transaction(()=>{for(let r of t){let o=this.db.query("SELECT id FROM nodes WHERE name = ? AND type = ?",[r.name,r.type]);if(o.length>0&&o[0])s.set(r.name,o[0].id);else {let a=this.db.run("INSERT OR IGNORE INTO nodes (name, type, properties) VALUES (?, ?, ?)",[r.name,r.type,JSON.stringify(r.properties)]);a.lastID>0&&s.set(r.name,a.lastID);}}for(let r of e){let o=s.get(r.source),a=s.get(r.target);o&&a&&this.db.run("INSERT OR IGNORE INTO edges (source, target, relation) VALUES (?, ?, ?)",[o,a,r.relation]);}});}float32ToBuffer(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}mapChunksToNodes(t,e,s){let r=new Map;this.db.transaction(()=>{for(let o of e){let a=this.db.query("SELECT id FROM nodes WHERE name = ? AND type = ?",[o.name,o.type]);if(a.length>0&&a[0])r.set(o.name,a[0].id);else {let h=this.db.run("INSERT OR IGNORE INTO nodes (name, type, properties) VALUES (?, ?, ?)",[o.name,o.type,JSON.stringify(o.properties)]);h.lastID>0&&r.set(o.name,h.lastID);}}for(let o=0;o<t.length;o++){let a=t[o],h=[];for(let l of e)if(a.includes(l.name)){let c=r.get(l.name);c&&h.push(c);}s.set(o,h);}});}};var ds=class{constructor(t,e){p(this,"db");p(this,"config");this.db=t,this.config={...e,embeddingLlm:e.embeddingLlm},e.embeddingLlm&&ut.init({models:{embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm,rerankLlm:e.rerankLlm}});}async search(t,e){let s=e?.maxResults||3,r=e?.minScore||0,o=e?.vectorWeight??this.config.search.hybrid.vectorWeight,a=e?.textWeight??this.config.search.hybrid.textWeight,h=await this.hybridSearch(t,s*2,r,o,a,e);return h.length===0?[]:this.config.rerankLlm?this.rerank(t,h,s):h.slice(0,s)}async hybridSearch(t,e,s,r,o,a){let h=await this.embed(t),[l,c]=await Promise.all([this.vectorSearch(h,e,s,a),a?.enableFts===false?Promise.resolve([]):this.ftsSearch(t,e,s,a)]);return this.mergeResults(l,c,r,o)}async vectorSearch(t,e,s,r){if(!this.config.embeddingLlm)return [];try{let o;if(r?.candidateChunkIds&&r.candidateChunkIds.length>0){let l=r.candidateChunkIds.map(()=>"?").join(",");o=this.db.query(`SELECT chunkId, embedding FROM vectors WHERE chunkId IN (${l})`,r.candidateChunkIds);}else o=this.db.query("SELECT chunkId, embedding FROM vectors LIMIT ?",[Math.max(e*100,1e3)]);let a=[];for(let l of o){let c=new Float32Array(l.embedding.buffer,l.embedding.byteOffset,l.embedding.length/4),d=this.cosineSimilarity(t,c);d>=s&&a.push({chunkId:l.chunkId,score:d});}a.sort((l,c)=>c.score-l.score);let h=a.slice(0,e);return this.buildSearchResults(h,"vector",r)}catch(o){throw new j(`\u5411\u91CF\u641C\u7D22\u5931\u8D25: ${o.message}`,"SEARCH_FAILED",o)}}async ftsSearch(t,e,s,r){try{let o=Mn(t),a=this.db.query("SELECT rowid, rank FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?",[o,e]);if(a.length===0)return [];let h=a.map(l=>({chunkId:l.rowid,score:1/(1+l.rank)}));return this.buildSearchResults(h,"fts",r)}catch{return []}}mergeResults(t,e,s,r){let o=s+r,a=s/o,h=r/o,l=new Map;for(let d of t){let u=`${d.chunk.id}`,g=d.score*a;l.set(u,{...d,score:g,source:"hybrid"});}for(let d of e){let u=`${d.chunk.id}`,g=l.get(u);g?g.score+=d.score*h:l.set(u,{...d,score:d.score*h,source:"hybrid"});}let c=Array.from(l.values());return c.sort((d,u)=>u.score-d.score),c}async rerank(t,e,s){if(!this.config.rerankLlm)return e.slice(0,s);try{let r=e.map(c=>{let d=c.nodes&&c.nodes.length>0?c.nodes.map(u=>{let g=(u.edges??[]).map(y=>`${y.relation}:${y.source}->${y.target}`).join("|");return `${u.name}(${u.type})[edges=${g}]`}).join(", "):"";return `<doc filePath="${c.document.path}" lineStart="${c.chunk.startLine}" lineEnd="${c.chunk.endLine}" docUpdatedAt="${c.document.updatedAt}" docLastModified="${c.document.lastModified}"><snippet>${c.snippet}</snippet><nodes>${d}</nodes></doc>`}),o=await ut.rerank(t,r,e.length);if(o.length===0)return e;let a=o.map(c=>c.index).filter(c=>c>=0&&c<e.length),h=[],l=new Set;for(let c of a)if(!l.has(c)){l.add(c);let d=e[c];h.push({...d,originalScore:d.score,score:1-h.length/e.length,source:"reranked"});}for(let c=0;c<e.length;c++)l.has(c)||h.push(e[c]);return h.slice(0,s)}catch{return e.slice(0,s)}}async embed(t){try{return await ut.embed(t)}catch{return new Float32Array(this.config.vectorDims)}}cosineSimilarity(t,e){let s=0,r=0,o=0;for(let a=0;a<t.length;a++){let h=t[a],l=e[a];s+=h*l,r+=h*h,o+=l*l;}return r===0||o===0?0:s/(Math.sqrt(r)*Math.sqrt(o))}async buildSearchResults(t,e,s){let r=[],o=t.map(N=>N.chunkId);if(o.length===0)return r;let a=s?.includeEdges??true,h=Math.max(1,s?.edgesLimit??100),l=this.db.query("SELECT * FROM chunks WHERE id IN ("+o.map(()=>"?").join(",")+")",o),c=new Map(l.map(N=>[N.id,N])),d=Array.from(new Set(l.map(N=>N.documentId))),u=d.length>0?this.db.query("SELECT * FROM documents WHERE id IN ("+d.map(()=>"?").join(",")+")",d):[],g=new Map(u.map(N=>[N.id,N])),y=new Map,w=[];for(let N of l){let T=[];try{let L=N.nodeIds?JSON.parse(N.nodeIds):[];T=Array.isArray(L)?L.filter(C=>typeof C=="number"):[];}catch{T=[];}y.set(N.id,T),w.push(...T);}let b=Array.from(new Set(w)),S=b.length>0?this.db.query("SELECT * FROM nodes WHERE id IN ("+b.map(()=>"?").join(",")+")",b):[],E=new Map(S.map(N=>[N.id,{id:N.id,name:N.name,type:N.type,properties:N.properties?JSON.parse(N.properties):void 0,createdAt:N.createdAt,updatedAt:N.updatedAt}])),A=a&&b.length>0?this.db.query("SELECT * FROM edges WHERE source IN ("+b.map(()=>"?").join(",")+") OR target IN ("+b.map(()=>"?").join(",")+") ORDER BY id LIMIT ?",[...b,...b,b.length*h]):[],I=new Map;for(let N of A){let T={id:N.id,source:N.source,target:N.target,relation:N.relation,properties:N.properties?JSON.parse(N.properties):void 0,createdAt:N.createdAt},L=I.get(T.source)??[];L.length<h&&(L.push(T),I.set(T.source,L));let C=I.get(T.target)??[];C.length<h&&(C.push(T),I.set(T.target,C));}for(let N of t){let T=c.get(N.chunkId);if(!T)continue;let L=g.get(T.documentId);if(!L)continue;let C=y.get(T.id)??[],z=C.map(D=>E.get(D)).filter(D=>D!==void 0),F=a&&C.length>0?Array.from(new Map(C.flatMap(D=>I.get(D)??[]).map(D=>[D.id,D])).values()):[],W=new Map;for(let D of F){let _i=W.get(D.source)??[];_i.push(D),W.set(D.source,_i);}let Fe=z.length>0?z.map(D=>({...D,edges:a?W.get(D.id)??[]:void 0})):[];r.push({chunk:{id:T.id,documentId:T.documentId,startLine:T.startLine,endLine:T.endLine,content:T.content,contentHash:T.contentHash,nodeIds:C,path:L.path,createdAt:T.createdAt},document:{id:L.id,path:L.path,title:L.title,contentHash:L.contentHash,summary:L.summary,lastModified:L.lastModified,createdAt:L.createdAt,updatedAt:L.updatedAt},nodes:Fe.length>0?Fe:void 0,score:N.score,snippet:T.content.slice(0,200),source:e});}return r}};var ps=class{constructor(t){p(this,"db");this.db=t;}async queryNodes(t,e){try{if(typeof t=="string")return this.db.query(t,e).map(l=>this.mapNode(l));let s=[],r=[];t.ids&&t.ids.length>0&&(s.push(`id IN (${t.ids.map(()=>"?").join(",")})`),r.push(...t.ids)),t.name&&(s.push("name LIKE ?"),r.push(`%${t.name}%`)),t.type&&(s.push("type = ?"),r.push(t.type));let o="SELECT * FROM nodes";return s.length>0&&(o+=` WHERE ${s.join(" AND ")}`),o+=" ORDER BY id",t.limit&&t.limit>0&&(o+=" LIMIT ?",r.push(t.limit)),this.db.query(o,r).map(h=>this.mapNode(h))}catch(s){throw new j(`\u67E5\u8BE2\u8282\u70B9\u5931\u8D25: ${s.message}`,"SEARCH_FAILED",s)}}async queryEdges(t,e){try{if(typeof t=="string")return this.db.query(t,e).map(l=>this.mapEdge(l));let s=[],r=[];t.ids&&t.ids.length>0&&(s.push(`id IN (${t.ids.map(()=>"?").join(",")})`),r.push(...t.ids)),typeof t.source=="number"&&(s.push("source = ?"),r.push(t.source)),typeof t.target=="number"&&(s.push("target = ?"),r.push(t.target)),t.sourceOrTarget&&t.sourceOrTarget.length>0&&(s.push(`(source IN (${t.sourceOrTarget.map(()=>"?").join(",")}) OR target IN (${t.sourceOrTarget.map(()=>"?").join(",")}))`),r.push(...t.sourceOrTarget,...t.sourceOrTarget)),t.relation&&(s.push("relation = ?"),r.push(t.relation));let o="SELECT * FROM edges";return s.length>0&&(o+=` WHERE ${s.join(" AND ")}`),o+=" ORDER BY id",t.limit&&t.limit>0&&(o+=" LIMIT ?",r.push(t.limit)),this.db.query(o,r).map(h=>this.mapEdge(h))}catch(s){throw new j(`\u67E5\u8BE2\u8FB9\u5931\u8D25: ${s.message}`,"SEARCH_FAILED",s)}}async queryNeighbors(t,e){let s=e?.direction??"both",r=e?.relationTypes,o=e?.limit&&e.limit>0?e.limit:100,a=[],h=[];s==="incoming"?(a.push("target = ?"),h.push(t)):s==="outgoing"?(a.push("source = ?"),h.push(t)):(a.push("(source = ? OR target = ?)"),h.push(t,t)),r&&r.length>0&&(a.push(`relation IN (${r.map(()=>"?").join(",")})`),h.push(...r));let l=await this.queryEdges(`SELECT * FROM edges WHERE ${a.join(" AND ")} ORDER BY id LIMIT ?`,[...h,o]),c=Array.from(new Set(l.map(u=>u.source===t?u.target:u.source)));return c.length===0?{nodes:[],edges:l}:{nodes:await this.queryNodes({ids:c,limit:c.length}),edges:l}}async queryCallGraph(t,e=2){let s=Math.max(1,e),r=new Map,o=[{id:t,level:0}],a=new Set;for(;o.length>0;){let h=o.shift();if(a.has(h.id)||h.level>s)continue;a.add(h.id);let l=await this.queryEdges({source:h.id,relation:"CALLS",limit:100}),c=await this.queryEdges({target:h.id,relation:"CALLS",limit:100}),d=Array.from(new Set(l.map(g=>g.target))),u=Array.from(new Set(c.map(g=>g.source)));r.set(h.id,{callers:u,callees:d});for(let g of [...u,...d])a.has(g)||o.push({id:g,level:h.level+1});}return r}async queryInheritance(t){let e=["EXTENDS","INHERITS_FROM","IMPLEMENTS"],s=await this.collectInheritance(t,"ancestor",e),r=await this.collectInheritance(t,"descendant",e);return {ancestors:s,descendants:r}}async findPath(t,e,s=3){let r=[],o=new Set,a=this.db.query("SELECT * FROM nodes WHERE name = ?",[t]);if(a.length===0)return [];let h=a.map(l=>({nodeId:l.id,path:[l.id]}));for(;h.length>0;){let{nodeId:l,path:c}=h.shift();if(c.length>s)continue;let d=c.join(",");if(o.has(d))continue;if(o.add(d),c.length>1){let g=this.db.query("SELECT id, name FROM nodes WHERE id = ?",[l]);if(g.length>0&&g[0]?.name===e){let y=c.map(()=>"?").join(","),w=this.db.query(`SELECT * FROM nodes WHERE id IN (${y})`,c),b=new Map(w.map(E=>[E.id,E])),S=[];for(let E of c){let A=b.get(E);A&&S.push({id:A.id,name:A.name,type:A.type,properties:A.properties?JSON.parse(A.properties):void 0,createdAt:A.createdAt,updatedAt:A.updatedAt});}r.push(S);continue}}let u=this.db.query("SELECT source, target FROM edges WHERE source = ? OR target = ?",[l,l]);for(let g of u){let y=g.source===l?g.target:g.source;c.includes(y)||h.push({nodeId:y,path:[...c,y]});}}return r}async searchNodesByName(t){return this.queryNodes("SELECT * FROM nodes WHERE name LIKE ?",[t])}async searchNodesByType(t){return this.queryNodes("SELECT * FROM nodes WHERE type = ?",[t])}async searchRelations(t){return this.queryEdges("SELECT * FROM edges WHERE relation = ?",[t])}async createNode(t,e,s){let r=this.db.run("INSERT INTO nodes (name, type, properties) VALUES (?, ?, ?)",[t,e,s?JSON.stringify(s):null]),a=this.db.query("SELECT * FROM nodes WHERE id = ?",[r.lastID])[0];return {id:a.id,name:a.name,type:a.type,properties:a.properties?JSON.parse(a.properties):void 0,createdAt:a.createdAt,updatedAt:a.updatedAt}}async updateNode(t,e){this.db.run("UPDATE nodes SET properties = ?, updatedAt = unixepoch() WHERE id = ?",[JSON.stringify(e),t]);let s=this.db.query("SELECT * FROM nodes WHERE id = ?",[t]);if(s.length===0)throw new j(`\u8282\u70B9\u4E0D\u5B58\u5728: ${t}`,"NODE_NOT_FOUND");let r=s[0];return {id:r.id,name:r.name,type:r.type,properties:r.properties?JSON.parse(r.properties):void 0,createdAt:r.createdAt,updatedAt:r.updatedAt}}async deleteNode(t){this.db.run("DELETE FROM nodes WHERE id = ?",[t]);}async createEdge(t,e,s,r){let o=this.db.query("SELECT id FROM nodes WHERE id = ?",[t]),a=this.db.query("SELECT id FROM nodes WHERE id = ?",[e]);if(o.length===0||a.length===0)throw new j("\u8282\u70B9\u4E0D\u5B58\u5728","NODE_NOT_FOUND");let h=this.db.run("INSERT INTO edges (source, target, relation, properties) VALUES (?, ?, ?, ?)",[t,e,s,r?JSON.stringify(r):null]),c=this.db.query("SELECT * FROM edges WHERE id = ?",[h.lastID])[0];return {id:c.id,source:c.source,target:c.target,relation:c.relation,properties:c.properties?JSON.parse(c.properties):void 0,createdAt:c.createdAt}}async deleteEdge(t){this.db.run("DELETE FROM edges WHERE id = ?",[t]);}mapNode(t){return {id:t.id,name:t.name,type:t.type,properties:t.properties?JSON.parse(t.properties):void 0,createdAt:t.createdAt,updatedAt:t.updatedAt}}mapEdge(t){return {id:t.id,source:t.source,target:t.target,relation:t.relation,properties:t.properties?JSON.parse(t.properties):void 0,createdAt:t.createdAt}}async collectInheritance(t,e,s){let r=[t],o=new Set([t]),a=new Set;for(;r.length>0;){let h=r.shift(),l=e==="ancestor"?await this.queryEdges(`SELECT * FROM edges WHERE source = ? AND relation IN (${s.map(()=>"?").join(",")})`,[h,...s]):await this.queryEdges(`SELECT * FROM edges WHERE target = ? AND relation IN (${s.map(()=>"?").join(",")})`,[h,...s]);for(let c of l){let d=e==="ancestor"?c.target:c.source;o.has(d)||(o.add(d),a.add(d),r.push(d));}}return a.size===0?[]:this.queryNodes({ids:Array.from(a),limit:a.size})}};var fs=bt.create({service:"note-scanner"}),hh=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.md"],Mi=class{constructor(t){p(this,"workspaceDir");p(this,"extraPaths");p(this,"sources");p(this,"ignorePatterns");this.workspaceDir=t.workspaceDir,this.extraPaths=t.extraPaths??[],this.sources=new Set(t.sources??["docs"]),this.ignorePatterns=[...hh,...t.ignorePatterns??[]];}async scanAll(t){let e=[],s=[];if(this.sources.has("docs")){let a=ye__default.join(this.workspaceDir,"docs");s.push({source:"docs",dir:a});}if(this.sources.has("local"))for(let a of this.extraPaths){let h=ye__default.isAbsolute(a)?a:ye__default.join(this.workspaceDir,a);s.push({source:"local",dir:h});}let r=0,o=s.length;for(let a of s){let h=await this.scanDirectory(a.dir,a.source);e.push(...h),r++,t?.(r,o,h[0]||{absolutePath:a.dir,relativePath:a.dir,source:a.source,contentHash:"",lastModified:0,size:0});}return e}async scanDirectory(t,e){let s=[];try{await Ve.access(t);}catch{return fs.debug("Directory not found, skipping",{dir:t}),s}let r=async o=>{try{let a=await Ve.readdir(o,{withFileTypes:!0});for(let h of a){let l=ye__default.join(o,h.name);if(!this.shouldIgnore(h.name)){if(h.isDirectory())await r(l);else if(h.isFile()&&this.isMarkdownFile(h.name)){let c=await this.getFileInfo(l,e);c&&s.push(c);}}}}catch(a){fs.warn("Failed to scan directory",{dir:o,error:String(a)});}};return await r(t),s}async scanFile(t,e="upload"){try{let s=await Ve.stat(t);if(!s.isFile())return null;let r=await Ve.readFile(t,"utf-8"),o=createHash("sha256").update(r).digest("hex"),a=ye__default.isAbsolute(t)?Filesystem.toUnixPath(ye__default.relative(this.workspaceDir,t)):t;return {absolutePath:t,relativePath:a||ye__default.basename(t),source:e,contentHash:o,lastModified:s.mtimeMs,size:s.size}}catch(s){return fs.error("Failed to scan file",{filePath:t,error:String(s)}),null}}async getFileInfo(t,e){try{let s=await Ve.readFile(t,"utf-8"),r=await Ve.stat(t),o=createHash("sha256").update(s).digest("hex"),a=Filesystem.toUnixPath(ye__default.relative(this.workspaceDir,t));return {absolutePath:t,relativePath:a,source:e,contentHash:o,lastModified:r.mtimeMs,size:r.size}}catch(s){return fs.error("Failed to get file info",{filePath:t,error:String(s)}),null}}shouldIgnore(t){if(t.startsWith("."))return true;for(let e of this.ignorePatterns)if(new RegExp("^"+e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$").test(t))return true;return false}isMarkdownFile(t){return t.endsWith(".md")||t.endsWith(".markdown")}};var Gt=bt.create({service:"note"}),ms=class{constructor(t){p(this,"config");p(this,"db");p(this,"pipeline");p(this,"searchEngine");p(this,"graphInterface");p(this,"fileScanner");p(this,"initialized",false);p(this,"dirty",false);p(this,"syncTimer");p(this,"syncConfig");let e=t.workspaceDir||process.cwd(),s=t.embeddingLlm;if(!s)throw new Error("embeddingLlm is required");let r=t.database?.path||getDefaultDatabasePath(xdgData,"note.db");this.config={workspaceDir:e,database:{path:r,walMode:t.database?.walMode??true},vectorDims:t.vectorDims??768,chunkSize:t.chunkSize??1e3,chunkOverlap:t.chunkOverlap??200,extraPaths:t.extraPaths,sources:t.sources,search:{...DEFAULT_SEARCH_CONFIG,...t.search},indexer:{...DEFAULT_INDEXER_CONFIG,...t.indexer},sync:{...DEFAULT_SYNC_CONFIG,...t.sync},logDir:t.logDir,embeddingLlm:s,graphLlm:t.graphLlm,rerankLlm:t.rerankLlm},this.syncConfig=this.config.sync,this.db=new Bi(this.config.database.path),this.pipeline=new us(this.db,this.config),this.searchEngine=new ds(this.db,this.config),this.graphInterface=new ps(this.db),this.fileScanner=new Mi({workspaceDir:this.config.workspaceDir,extraPaths:this.config.extraPaths,sources:this.config.sources,ignorePatterns:this.config?.indexer?.ignorePatterns});}async initialize(){this.initialized||(await bt.init({logDir:this.config.logDir||ye__default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),ut.init({models:{embeddingLlm:this.config.embeddingLlm,graphLlm:this.config.graphLlm,rerankLlm:this.config.rerankLlm},options:{graph:{maxOutputTokens:2e3,temperature:.1}}}),await this.db.initialize(),this.initialized=true,this.syncConfig.onBoot&&this.startSyncTimer());}startSyncTimer(){this.syncTimer&&clearInterval(this.syncTimer),this.syncTimer=setInterval(async()=>{try{await this.syncAll();}catch(t){Gt.error("Sync failed",{error:String(t)});}},this.syncConfig.intervalMs);}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}async syncAll(){Gt.debug("Starting sync...");let t=await this.fileScanner.scanAll((e,s,r)=>{Gt.debug("Scanning file",{current:r.relativePath||ye__default.basename(r.absolutePath),total:s});});for(let e of t)try{await this.ingestDocument(e.absolutePath),Gt.debug("Ingested file",{path:e.relativePath||ye__default.basename(e.absolutePath)});}catch(s){Gt.error("Failed to ingest file",{path:e.relativePath||ye__default.basename(e.absolutePath),error:String(s)});}Gt.debug("Sync completed",{totalFiles:t.length});}async ingestDocument(t){return await this.ensureInitialized(),this.pipeline.process(t)}async ingestDocuments(t,e){await this.ensureInitialized();let s=[];for(let r=0;r<t.length;r++){let o=await this.pipeline.process(t[r]);s.push(o),e?.((r+1)/t.length);}return s}async scanAndIngest(t){await this.ensureInitialized();let e=await this.fileScanner.scanAll(t);if(e.length===0)return [];let s=e.map(r=>r.absolutePath);return this.ingestDocuments(s,r=>{t?.(Math.round(r*e.length),e.length,e[0]||{absolutePath:"ingesting...",relativePath:"ingesting...",source:"docs",contentHash:"",lastModified:0,size:0});})}async ingestUploadedFile(t){await this.ensureInitialized();let e=await this.fileScanner.scanFile(t,"upload");if(!e)throw new Error(`\u65E0\u6CD5\u626B\u63CF\u6587\u4EF6: ${t}`);return this.pipeline.process(e.absolutePath)}async removeDocument(t){await this.ensureInitialized();let e=Filesystem.toUnixPath(t),s=this.db.query("SELECT id FROM documents WHERE path = ?",[e]);if(s.length===0)return;let r=s[0].id,o=this.db.query("SELECT id FROM chunks WHERE documentId = ?",[r]);for(let a of o)try{this.db.run("INSERT INTO chunks_fts(chunks_fts, rowid) VALUES('delete', ?)",[a.id]);}catch{Gt.warn("Failed to delete FTS entry for chunk",{chunkId:a.id});}this.db.run("DELETE FROM documents WHERE path = ?",[e]);}async sync(t){await this.ensureInitialized();let e=await this.fileScanner.scanAll(t);for(let s of e){let r=Filesystem.toUnixPath(s.relativePath),o=this.db.query("SELECT contentHash FROM documents WHERE path = ?",[r]);(o.length===0||o[0]?.contentHash!==s.contentHash)&&await this.pipeline.process(s.absolutePath);}}async search(t,e){return await this.ensureInitialized(),this.searchEngine.search(t,e)}async queryNodes(t,e){return await this.ensureInitialized(),typeof t=="string"?this.graphInterface.queryNodes(t,e):this.graphInterface.queryNodes(t)}async queryEdges(t,e){return await this.ensureInitialized(),typeof t=="string"?this.graphInterface.queryEdges(t,e):this.graphInterface.queryEdges(t)}async findPath(t,e,s){return await this.ensureInitialized(),this.graphInterface.findPath(t,e,s)}async queryNeighbors(t,e){return await this.ensureInitialized(),this.graphInterface.queryNeighbors(t,e)}async queryCallGraph(t,e){return await this.ensureInitialized(),this.graphInterface.queryCallGraph(t,e)}async queryInheritance(t){return await this.ensureInitialized(),this.graphInterface.queryInheritance(t)}async createNode(t,e,s){return await this.ensureInitialized(),this.graphInterface.createNode(t,e,s)}async updateNode(t,e){return await this.ensureInitialized(),this.graphInterface.updateNode(t,e)}async deleteNode(t){return await this.ensureInitialized(),this.graphInterface.deleteNode(t)}async createEdge(t,e,s,r){return await this.ensureInitialized(),this.graphInterface.createEdge(t,e,s,r)}async deleteEdge(t){return await this.ensureInitialized(),this.graphInterface.deleteEdge(t)}getStatus(){let t=this.db.getPath(),e=0,s=0,r=0,o=0;try{e=this.db.getDb().prepare("SELECT COUNT(*) as count FROM documents").get()?.count||0,s=this.db.getDb().prepare("SELECT COUNT(*) as count FROM chunks").get()?.count||0,r=this.db.getDb().prepare("SELECT COUNT(*) as count FROM nodes").get()?.count||0,o=this.db.getDb().prepare("SELECT COUNT(*) as count FROM edges").get()?.count||0;}catch{}return {dbPath:t,documentsCount:e,chunksCount:s,nodesCount:r,edgesCount:o,vectorDims:this.config.vectorDims,vectorSearchAvailable:!!this.config.embeddingLlm,llmAvailable:!!this.config.graphLlm,healthy:this.initialized}}async healthCheck(){try{return this.db.query("SELECT 1"),!0}catch{return false}}async clear(){this.db.transaction(()=>{this.db.run("DELETE FROM chunks"),this.db.run("DELETE FROM documents"),this.db.run("DELETE FROM vectors"),this.db.run("DELETE FROM nodes"),this.db.run("DELETE FROM edges"),this.db.run("DELETE FROM embedding_cache"),this.db.run("DELETE FROM sqlite_sequence WHERE name IN ('chunks', 'documents', 'nodes', 'edges')");});try{this.db.run("INSERT INTO chunks_fts(chunks_fts) VALUES('delete-all')");}catch(t){Gt.warn("Failed to clear FTS index",{error:String(t)});}Gt.info("Note knowledge base cleared");}async ensureInitialized(){this.initialized||await this.initialize();}async close(){this.initialized&&(this.stopSyncTimer(),await this.db.close(),this.initialized=false,Gt.info("NoteKnowledge closed"));}};async function fh(i){let t=new ms(i);return await t.initialize(),t}export{Mi as FileScanner,j as KnowledgeBaseError,Pe as KnowledgeBaseErrorCode,ut as Llm,ms as NoteKnowledge,Tl as addWord,Nl as closeTokenizer,fh as createNoteKnowledge,vl as initTokenizer,Rl as isInitialized,Qa as loadCustomDict,Pn as toFtsTokens,Mn as toFtsTokensForSearch,Ja as tokenize,Va as tokenizeForSearch};
126
+ `);return this.extractEntitiesByRules(t)}parseEntityExtractionResult(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let r=JSON.parse(t[0]);return this.normalizeExtractionResult(r)}}catch(t){ee.debug("Failed to parse entity extraction result",{error:String(t)});}return {entities:[],relations:[]}}normalizeExtractionResult(e){let t=e,r=Array.isArray(t.entities)?t.entities:[],n=Array.isArray(t.relations)?t.relations:[],o=[],s=new Set,i=new Map;for(let d of r){let l=typeof d?.name=="string"?d.name.trim():"";if(!l)continue;let g=l.toLowerCase();if(s.has(g))continue;s.add(g),i.set(g,l);let u=typeof d?.type=="string"?d.type.trim():"",m=De.has(u)?u:"keyword",h=d?.properties&&typeof d.properties=="object"&&!Array.isArray(d.properties)?d.properties:{};o.push({name:l,type:m,properties:h});}let c=[],a=new Set;for(let d of n){let l=typeof d?.source=="string"?d.source.trim():"",g=typeof d?.target=="string"?d.target.trim():"";if(!l||!g)continue;let u=i.get(l.toLowerCase()),m=i.get(g.toLowerCase());if(!u||!m||u===m)continue;let h=typeof d?.relation=="string"?d.relation.trim():"",f=Oe.has(h)?h:"related_to",y=`${u.toLowerCase()}|${m.toLowerCase()}|${f}`;a.has(y)||(a.add(y),c.push({source:u,target:m,relation:f}));}return {entities:o,relations:c}}extractEntitiesByRules(e){let t=[],r=[],n=new Set,o=new Set,s=new Map,i=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let d of e.matchAll(i)){let l=this.sanitizeEntityToken(d[1]??""),g=(d[2]??"related_to").trim(),u=this.sanitizeEntityToken(d[3]??"");if(!l||!u||l===u)continue;let m=l.toLowerCase(),h=u.toLowerCase();n.has(m)||(n.add(m),s.set(m,l),t.push({name:l,type:this.inferEntityType(l),properties:{source:"rule_extracted"}})),n.has(h)||(n.add(h),s.set(h,u),t.push({name:u,type:this.inferEntityType(u),properties:{source:"rule_extracted"}}));let f=`${m}|${h}|${g}`;o.has(f)||(o.add(f),r.push({source:l,target:u,relation:g}));}let c=e.match(/[\p{L}\p{N}][\p{L}\p{N}_.-]{1,80}/gu)??[],a=e.split(/\n\s*\n/);for(let d of c){let l=this.sanitizeEntityToken(d);if(!l)continue;let g=l.toLowerCase();n.has(g)||(n.add(g),s.set(g,l),t.push({name:l,type:this.inferEntityType(l),properties:{source:"keyword_extracted"}}));}for(let d of a){if(d.trim().length<20)continue;let l=[];for(let g of d.match(/[\p{L}\p{N}][\p{L}\p{N}_.-]{2,80}/gu)??[]){let u=this.sanitizeEntityToken(g);if(!u)continue;let m=u.toLowerCase();n.has(m)&&!l.some(h=>h.key===m)&&l.push({key:m,name:u});}for(let g=0;g<l.length;g++)for(let u=g+1;u<l.length;u++){let m=l[g],h=l[u];if(m.key===h.key)continue;let f="related_to",y=this.inferEntityType(m.name),b=this.inferEntityType(h.name);y==="document"&&b==="object"?f="defines":y==="object"&&b==="document"?f="referenced_in":y==="process"&&b==="object"?f="uses":y==="object"&&b==="process"?f="used_by":y==="concept"&&(f="relates_to");let S=`${m.key}|${h.key}|${f}`;o.has(S)||(o.add(S),r.push({source:m.name,target:h.name,relation:f}));}}return {entities:t,relations:r}}sanitizeEntityToken(e){return e.trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"").replace(/\s+/g," ").slice(0,120)}inferEntityType(e){return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(e)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(e)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(e)?"organization":/(deadline|date|day|week|month|year|q[1-4]|sprint)/i.test(e)?"time":/(score|rate|ratio|latency|accuracy|recall|precision|throughput|kpi)/i.test(e)?"metric":/(task|issue|ticket|todo|action)/i.test(e)?"task":/(event|incident|release|meeting|migration|launch)/i.test(e)?"event":/(process|workflow|procedure|flow|lifecycle)/i.test(e)?"process":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(e)?"object":/(concept|principle|policy|method|pattern|strategy)/i.test(e)?"concept":/[A-Z]/.test(e)?"object":"keyword"}storeEntities(e,t){if(e.length===0)return;let r=new Map,n=new Date().toISOString();for(let o of e){let s=this.db.query("SELECT id FROM nodes WHERE name = ? AND type = ?",[o.name,o.type]);s.length>0&&s[0]&&r.set(o.name,s[0].id);}this.db.transaction(()=>{for(let o of e){if(r.has(o.name))continue;let s=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[o.name,o.type,JSON.stringify(o.properties),n,n]);s.lastID>0&&r.set(o.name,s.lastID);}for(let o of t){let s=r.get(o.source),i=r.get(o.target);if(s&&i){let c=this.db.query("SELECT id FROM nodes WHERE id = ?",[s]),a=this.db.query("SELECT id FROM nodes WHERE id = ?",[i]);c.length>0&&a.length>0&&this.db.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[s,i,o.relation,"{}",n]);}}});}mergeEntitiesAndRelations(e,t,r){if(t.length===0&&r.length===0)return;let n=new Map,o=new Date().toISOString(),s=t.map(()=>"?").join(","),i=this.db.query(`SELECT id, name, type FROM nodes WHERE name IN (${s})`,t.map(c=>c.name));for(let c of i)n.set(c.name,c.id);this.db.transaction(()=>{for(let c of t)if(n.get(c.name)===void 0){let d=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[c.name,c.type,JSON.stringify(c.properties),o,o]);d.lastID>0&&n.set(c.name,d.lastID);}for(let c of r){let a=n.get(c.source),d=n.get(c.target);if(a&&d){let l=this.db.query("SELECT id FROM nodes WHERE id = ?",[a]),g=this.db.query("SELECT id FROM nodes WHERE id = ?",[d]);l.length>0&&g.length>0&&this.db.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[a,d,c.relation,"{}",o]);}}});}float32ToBuffer(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}ensureVectorDims(e){this.db.query("SELECT value FROM meta WHERE key = ?",["vectorDims"]).length===0&&this.db.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(e)]);}mapChunksToNodes(e,t,r){let n=new Map,o=new Date().toISOString();this.db.transaction(()=>{for(let s of t){let i=this.db.query("SELECT id FROM nodes WHERE name = ? AND type = ?",[s.name,s.type]);if(i.length>0&&i[0])n.set(s.name,i[0].id);else {let c=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[s.name,s.type,JSON.stringify(s.properties),o,o]);c.lastID>0&&n.set(s.name,c.lastID);}}for(let s=0;s<e.length;s++){let i=e[s],c=[];for(let a of t)if(i.includes(a.name)){let d=n.get(a.name);d&&c.push(d);}r.set(s,c);}});}};b.create({service:"note-search"});var Q=class{constructor(e,t){a(this,"db");a(this,"config");this.db=e,this.config={...DEFAULT_NOTE_CHUNK_CONFIG,...t,embeddingLlm:t.embeddingLlm},t.embeddingLlm&&L.init({models:{embeddingLlm:t.embeddingLlm,graphLlm:t.graphLlm,rerankLlm:t.rerankLlm}});}async search(e,t){if(!e.trim())return [];let r=t?.maxResults||3,n=t?.minScore??this.config.search.minScore,o=await this.hybridSearch(e,{...t,maxResults:r*2});return o.length===0?[]:this.config.rerankLlm?(await this.rerank(e,o,r)).filter(i=>i.score>=n):o.filter(s=>s.score>=n).slice(0,r)}async hybridSearch(e,t){let{maxResults:r=this.config.search.maxResults,minScore:n=this.config.search.minScore,vectorWeight:o=this.config.search.hybrid.vectorWeight,textWeight:s=this.config.search.hybrid.textWeight,enableEmbedding:i=true,enableFts:c=true}=t??{},a=i?await this.embed(e):new Float32Array(0),[d,l]=await Promise.all([i&&this.config.embeddingLlm?this.vectorSearch(a,r,n,t):Promise.resolve([]),c===false?Promise.resolve([]):this.ftsSearch(e,r,n,t)]);return this.mergeResults(d,l,o,s,n)}async vectorSearch(e,t,r,n){if(!this.config.embeddingLlm)return [];try{let o;if(n?.candidateChunkIds&&n.candidateChunkIds.length>0){let c=n.candidateChunkIds.map(()=>"?").join(",");o=this.db.query(`SELECT chunkId, embedding FROM vectors WHERE chunkId IN (${c})`,n.candidateChunkIds);}else o=this.db.query("SELECT chunkId, embedding FROM vectors LIMIT ?",[Math.max(t*100,1e3)]);let s=[];for(let c of o){let a=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),d=this.cosineSimilarity(e,a);s.push({chunkId:c.chunkId,score:d});}s.sort((c,a)=>a.score-c.score);let i=s.slice(0,t);return this.buildSearchResults(i,"vector",n)}catch(o){throw new R(`\u5411\u91CF\u641C\u7D22\u5931\u8D25: ${o.message}`,"SEARCH_FAILED",o)}}async ftsSearch(e,t,r,n){let o=async()=>[];try{let s=oe(e),i=this.db.query("SELECT chunkId, rank FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?",[s,t]);if(i.length===0)return o();let c=i.map(a=>({chunkId:a.chunkId,score:1/(1+a.rank)}));return this.buildSearchResults(c,"fts",n)}catch{return o()}}mergeResults(e,t,r,n,o){let s=r+n,i=r/s,c=n/s,a=new Map;for(let g of e){let u=`${g.chunk.id}`,m=g.score*i;a.set(u,{...g,score:m,source:"hybrid"});}for(let g of t){let u=`${g.chunk.id}`,m=a.get(u);if(m)m.score+=g.score*c;else {let h=g.score*c;a.set(u,{...g,score:h,source:"hybrid"});}}return Array.from(a.values()).map(g=>{let u=g.score,m=new Date(g.document.updatedAt),h=(Date.now()-m.getTime())/864e5,f=Math.exp(-0.01*h),y=.6*u+.4*f;return {...g,score:y}}).sort((g,u)=>u.score-g.score)}async rerank(e,t,r){if(!this.config.rerankLlm)return t.slice(0,r);try{let n=t.map(a=>{let d=a.nodes&&a.nodes.length>0?a.nodes.map(l=>{let g=(l.edges??[]).map(u=>{let m=u.source===l.id?"\u2192":"\u2190",h=u.targetNode?`${u.targetNode.type}:${u.targetNode.name}`:`id=${u.target}`;return `${m} [${u.relation}] ${h}`}).join(" | ");return `node: id=${l.id} name=${l.name} type=${l.type}${g?` edges: ${g}`:""}`}).join(" | "):"";return `<doc filePath="${a.document.path}" lineStart="${a.chunk.startLine}" lineEnd="${a.chunk.endLine}"><snippet>${a.snippet}</snippet>${d?`<nodes>${d}</nodes>`:""}</doc>`}),o=await L.rerank(e,n,t.length);if(o.length===0)return t.slice(0,r);let s=new Map;for(let a of o)a.index>=0&&a.index<t.length&&s.set(a.index,a.score);let i=.5,c=t.map((a,d)=>{let l=s.get(d)??a.score,g=i*a.score+(1-i)*l;return {...a,originalScore:a.score,score:g,source:"reranked"}});return c.sort((a,d)=>d.score-a.score),c.slice(0,r)}catch{return t.slice(0,r)}}async embed(e){try{return await L.embed(e)}catch{return new Float32Array(this.config.vectorDims)}}cosineSimilarity(e,t){let r=0,n=0,o=0;for(let s=0;s<e.length;s++){let i=e[s],c=t[s];r+=i*c,n+=i*i,o+=c*c;}return n===0||o===0?0:r/(Math.sqrt(n)*Math.sqrt(o))}async buildSearchResults(e,t,r){let n=[],o=e.map(p=>p.chunkId);if(o.length===0)return n;let s=r?.includeEdges??true,i=Math.max(1,r?.edgesLimit??100),c=this.db.query("SELECT * FROM chunks WHERE id IN ("+o.map(()=>"?").join(", ")+")",o),a=new Map(c.map(p=>[p.id,p])),d=Array.from(new Set(c.map(p=>p.documentId))),l=d.length>0?this.db.query("SELECT * FROM documents WHERE id IN ("+d.map(()=>"?").join(", ")+")",d):[],g=new Map(l.map(p=>[p.id,p])),u=new Map,m=[];for(let p of c){let I=[];try{let T=p.nodeIds?JSON.parse(p.nodeIds):[];I=Array.isArray(T)?T.filter(C=>typeof C=="number"):[];}catch{I=[];}u.set(p.id,I),m.push(...I);}let h=Array.from(new Set(m)),f=h.length>0?this.db.query("SELECT * FROM nodes WHERE id IN ("+h.map(()=>"?").join(", ")+")",h):[],y=new Map(f.map(p=>[p.id,{id:p.id,name:p.name,type:p.type,properties:p.properties?JSON.parse(p.properties):void 0,createdAt:p.createdAt,updatedAt:p.updatedAt}])),b=s&&h.length>0?this.db.query("SELECT * FROM edges WHERE source IN ("+h.map(()=>"?").join(", ")+") OR target IN ("+h.map(()=>"?").join(", ")+") ORDER BY id LIMIT ?",[...h,...h,h.length*i]):[],S=[...new Set([...h,...b.map(p=>p.target)])],q=S.length>0?this.db.query("SELECT * FROM nodes WHERE id IN ("+S.map(()=>"?").join(", ")+")",S):[],O=new Map(q.map(p=>[p.id,{id:p.id,name:p.name,type:p.type,properties:p.properties?JSON.parse(p.properties):void 0,createdAt:p.createdAt,updatedAt:p.updatedAt}])),k=new Map;for(let p of b){let I={id:p.id,source:p.source,target:p.target,relation:p.relation,properties:p.properties?JSON.parse(p.properties):void 0,createdAt:p.createdAt},T=O.get(p.target);T&&(I.targetNode=T);let C=k.get(I.source)??[];C.length<i&&(C.push(I),k.set(I.source,C));let x=k.get(I.target)??[];x.length<i&&(x.push(I),k.set(I.target,x));}for(let p of e){let I=a.get(p.chunkId);if(!I)continue;let T=g.get(I.documentId);if(!T)continue;let C=u.get(I.id)??[],x=C.map(w=>y.get(w)).filter(w=>w!==void 0),K=s&&C.length>0?Array.from(new Map(C.flatMap(w=>k.get(w)??[]).map(w=>[w.id,w])).values()):[],W=new Map;for(let w of K){let ne=W.get(w.source)??[];ne.push(w),W.set(w.source,ne);}let re=x.length>0?x.map(w=>({...w,edges:s?W.get(w.id)??[]:void 0})):[];n.push({chunk:{id:I.id,documentId:I.documentId,startLine:I.startLine,endLine:I.endLine,startChar:I.startChar,endChar:I.endChar,content:I.content,contentHash:I.contentHash,nodeIds:C,path:T.path,createdAt:I.createdAt},document:{id:T.id,path:T.path,title:T.title,contentHash:T.contentHash,summary:T.summary,lastModified:T.lastModified,createdAt:T.createdAt,updatedAt:T.updatedAt},nodes:re.length>0?re:void 0,score:p.score,snippet:I.content.slice(0,200),source:t});}return n}};var V=class{constructor(e){a(this,"db");this.db=e;}async queryNodes(e,t){try{if(typeof e=="string")return this.db.query(e,t).map(c=>this.mapNode(c));let r=[],n=[];e.ids&&e.ids.length>0&&(r.push(`id IN (${e.ids.map(()=>"?").join(",")})`),n.push(...e.ids)),e.name&&(r.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(r.push("type = ?"),n.push(e.type));let o="SELECT * FROM nodes";return r.length>0&&(o+=` WHERE ${r.join(" AND ")}`),o+=" ORDER BY id",e.limit&&e.limit>0&&(o+=" LIMIT ?",n.push(e.limit)),this.db.query(o,n).map(i=>this.mapNode(i))}catch(r){throw new R(`\u67E5\u8BE2\u8282\u70B9\u5931\u8D25: ${r.message}`,"SEARCH_FAILED",r)}}async queryEdges(e,t){try{if(typeof e=="string")return this.db.query(e,t).map(c=>this.mapEdge(c));let r=[],n=[];e.ids&&e.ids.length>0&&(r.push(`id IN (${e.ids.map(()=>"?").join(",")})`),n.push(...e.ids)),typeof e.source=="number"&&(r.push("source = ?"),n.push(e.source)),typeof e.target=="number"&&(r.push("target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0&&(r.push(`(source IN (${e.sourceOrTarget.map(()=>"?").join(", ")}) OR target IN (${e.sourceOrTarget.map(()=>"?").join(", ")}))`),n.push(...e.sourceOrTarget,...e.sourceOrTarget)),e.relation&&(r.push("relation = ?"),n.push(e.relation));let o="SELECT * FROM edges";return r.length>0&&(o+=` WHERE ${r.join(" AND ")}`),o+=" ORDER BY id",e.limit&&e.limit>0&&(o+=" LIMIT ?",n.push(e.limit)),this.db.query(o,n).map(i=>this.mapEdge(i))}catch(r){throw new R(`\u67E5\u8BE2\u8FB9\u5931\u8D25: ${r.message}`,"SEARCH_FAILED",r)}}async queryNeighbors(e,t){let r=t?.direction??"both",n=t?.relationTypes,o=t?.limit&&t.limit>0?t.limit:100,s=[],i=[];r==="incoming"?(s.push("target = ?"),i.push(e)):r==="outgoing"?(s.push("source = ?"),i.push(e)):(s.push("(source = ? OR target = ?)"),i.push(e,e)),n&&n.length>0&&(s.push(`relation IN (${n.map(()=>"?").join(",")})`),i.push(...n));let c=await this.queryEdges(`SELECT * FROM edges WHERE ${s.join(" AND ")} ORDER BY id LIMIT ?`,[...i,o]),a=Array.from(new Set(c.map(u=>u.source===e?u.target:u.source)));if(a.length===0)return {nodes:await this.queryNodes({ids:[e],limit:1}),edges:c};let d=[...new Set([e,...a])],l=await this.queryNodes({ids:d,limit:d.length}),g=new Map(l.map(u=>[u.id,u]));for(let u of c){let m=g.get(u.target);m&&(u.targetNode=m);}return {nodes:l,edges:c}}async queryCallGraph(e,t=2){let r=Math.max(1,t),n=new Map,o=[{id:e,level:0}],s=new Set;for(;o.length>0;){let i=o.shift();if(s.has(i.id)||i.level>r)continue;s.add(i.id);let c=await this.queryEdges({source:i.id,relation:"CALLS",limit:100}),a=await this.queryEdges({target:i.id,relation:"CALLS",limit:100}),d=Array.from(new Set(c.map(g=>g.target))),l=Array.from(new Set(a.map(g=>g.source)));n.set(i.id,{callers:l,callees:d});for(let g of [...l,...d])s.has(g)||o.push({id:g,level:i.level+1});}return n}async queryInheritance(e){let t=["EXTENDS","INHERITS_FROM","IMPLEMENTS"],r=await this.collectInheritance(e,"ancestor",t),n=await this.collectInheritance(e,"descendant",t);return {ancestors:r,descendants:n}}async findPath(e,t,r=3){let n=[],o=new Set,s=this.db.query("SELECT * FROM nodes WHERE name = ?",[e]);if(s.length===0)return [];let i=s.map(c=>({nodeId:c.id,path:[c.id]}));for(;i.length>0;){let{nodeId:c,path:a}=i.shift();if(a.length>r)continue;let d=a.join(",");if(o.has(d))continue;if(o.add(d),a.length>1){let g=this.db.query("SELECT id, name FROM nodes WHERE id = ?",[c]);if(g.length>0&&g[0]?.name===t){let u=a.map(()=>"?").join(","),m=this.db.query(`SELECT * FROM nodes WHERE id IN (${u})`,a),h=new Map(m.map(y=>[y.id,y])),f=[];for(let y of a){let b=h.get(y);b&&f.push({id:b.id,name:b.name,type:b.type,properties:b.properties?JSON.parse(b.properties):void 0,createdAt:b.createdAt,updatedAt:b.updatedAt});}n.push(f);continue}}let l=this.db.query("SELECT source, target FROM edges WHERE source = ? OR target = ?",[c,c]);for(let g of l){let u=g.source===c?g.target:g.source;a.includes(u)||i.push({nodeId:u,path:[...a,u]});}}return n}async searchNodesByName(e){return this.queryNodes("SELECT * FROM nodes WHERE name LIKE ?",[e])}async searchNodesByType(e){return this.queryNodes("SELECT * FROM nodes WHERE type = ?",[e])}async searchRelations(e){return this.queryEdges("SELECT * FROM edges WHERE relation = ?",[e])}async createNode(e,t,r){let n=new Date().toISOString(),o=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[e,t,r?JSON.stringify(r):null,n,n]),i=this.db.query("SELECT * FROM nodes WHERE id = ?",[o.lastID])[0];return {id:i.id,name:i.name,type:i.type,properties:i.properties?JSON.parse(i.properties):void 0,createdAt:i.createdAt,updatedAt:i.updatedAt}}async updateNode(e,t){let r=new Date().toISOString();this.db.run("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?",[JSON.stringify(t),r,e]);let n=this.db.query("SELECT * FROM nodes WHERE id = ?",[e]);if(n.length===0)throw new R(`\u8282\u70B9\u4E0D\u5B58\u5728: ${e}`,"NODE_NOT_FOUND");let o=n[0];return {id:o.id,name:o.name,type:o.type,properties:o.properties?JSON.parse(o.properties):void 0,createdAt:o.createdAt,updatedAt:o.updatedAt}}async deleteNode(e){this.db.run("DELETE FROM nodes WHERE id = ?",[e]);}async createEdge(e,t,r,n){let o=this.db.query("SELECT id FROM nodes WHERE id = ?",[e]),s=this.db.query("SELECT id FROM nodes WHERE id = ?",[t]);if(o.length===0||s.length===0)throw new R("\u8282\u70B9\u4E0D\u5B58\u5728","NODE_NOT_FOUND");let i=new Date().toISOString(),c=this.db.run("INSERT INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[e,t,r,n?JSON.stringify(n):null,i]),d=this.db.query("SELECT * FROM edges WHERE id = ?",[c.lastID])[0];return {id:d.id,source:d.source,target:d.target,relation:d.relation,properties:d.properties?JSON.parse(d.properties):void 0,createdAt:d.createdAt}}async deleteEdge(e){this.db.run("DELETE FROM edges WHERE id = ?",[e]);}mapNode(e){return {id:e.id,name:e.name,type:e.type,properties:e.properties?JSON.parse(e.properties):void 0,createdAt:e.createdAt,updatedAt:e.updatedAt}}mapEdge(e){return {id:e.id,source:e.source,target:e.target,relation:e.relation,properties:e.properties?JSON.parse(e.properties):void 0,createdAt:e.createdAt}}async collectInheritance(e,t,r){let n=[e],o=new Set([e]),s=new Set;for(;n.length>0;){let i=n.shift(),c=t==="ancestor"?await this.queryEdges(`SELECT * FROM edges WHERE source = ? AND relation IN (${r.map(()=>"?").join(",")})`,[i,...r]):await this.queryEdges(`SELECT * FROM edges WHERE target = ? AND relation IN (${r.map(()=>"?").join(",")})`,[i,...r]);for(let a of c){let d=t==="ancestor"?a.target:a.source;o.has(d)||(o.add(d),s.add(d),n.push(d));}}return s.size===0?[]:this.queryNodes({ids:Array.from(s),limit:s.size})}};var J=b.create({service:"note-scanner"}),Me=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.md"],$=class{constructor(e){a(this,"workspaceDir");a(this,"extraPaths");a(this,"sources");a(this,"ignorePatterns");this.workspaceDir=e.workspaceDir,this.extraPaths=e.extraPaths??[],this.sources=new Set(e.sources??["docs"]),this.ignorePatterns=[...Me,...e.ignorePatterns??[]];}async scanAll(e){let t=[],r=[];for(let s of this.sources){let i=U__default.join(this.workspaceDir,s);r.push({source:s,dir:i});}for(let s of this.extraPaths){let i=U__default.isAbsolute(s)?s:U__default.join(this.workspaceDir,s);r.push({source:"local",dir:i});}let n=0,o=r.length;for(let s of r){let i=await this.scanDirectory(s.dir,s.source);t.push(...i),n++,e?.(n,o,i[0]||{absolutePath:s.dir,relativePath:s.dir,source:s.source,contentHash:"",lastModified:0,size:0});}return t}async scanDirectory(e,t){let r=[];try{await B.access(e);}catch{return J.debug("Directory not found, skipping",{dir:e}),r}let n=async o=>{try{let s=await B.readdir(o,{withFileTypes:!0});for(let i of s){let c=U__default.join(o,i.name);if(!this.shouldIgnore(i.name)){if(i.isDirectory())await n(c);else if(i.isFile()&&this.isMarkdownFile(i.name)){let a=await this.getFileInfo(c,t);a&&r.push(a);}}}}catch(s){J.warn("Failed to scan directory",{dir:o,error:String(s)});}};return await n(e),r}async scanFile(e,t="upload"){try{let r=await B.stat(e);if(!r.isFile())return null;let n=await B.readFile(e,"utf-8"),o=createHash("sha256").update(n).digest("hex"),s=U__default.isAbsolute(e)?Filesystem.toUnixPath(U__default.relative(this.workspaceDir,e)):e;return {absolutePath:e,relativePath:s||U__default.basename(e),source:t,contentHash:o,lastModified:r.mtimeMs,size:r.size}}catch(r){return J.error("Failed to scan file",{filePath:e,error:String(r)}),null}}async getFileInfo(e,t){try{let r=await B.readFile(e,"utf-8"),n=await B.stat(e),o=createHash("sha256").update(r).digest("hex"),s=Filesystem.toUnixPath(U__default.relative(this.workspaceDir,e));return {absolutePath:e,relativePath:s,source:t,contentHash:o,lastModified:n.mtimeMs,size:n.size}}catch(r){return J.error("Failed to get file info",{filePath:e,error:String(r)}),null}}shouldIgnore(e){if(e.startsWith("."))return true;for(let t of this.ignorePatterns)if(new RegExp("^"+t.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$").test(e))return true;return false}isMarkdownFile(e){return e.endsWith(".md")||e.endsWith(".markdown")}};var A=b.create({service:"note"}),Z=class{constructor(e){a(this,"config");a(this,"db");a(this,"pipeline");a(this,"searchEngine");a(this,"graphInterface");a(this,"fileScanner");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncConfig");a(this,"syncingInProgress",false);let t=e.workspaceDir||process.cwd(),r=e.embeddingLlm;if(!r)throw new Error("embeddingLlm is required");let n=e.database?.path||getDefaultDatabasePath(xdgData,"note.db");this.config={workspaceDir:t,database:{path:n,walMode:e.database?.walMode??true},vectorDims:e.vectorDims??768,...DEFAULT_NOTE_CHUNK_CONFIG,extraPaths:e.extraPaths,sources:e.sources,search:{...DEFAULT_SEARCH_CONFIG,...e.search},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},sync:{...DEFAULT_SYNC_CONFIG,...e.sync},logDir:e.logDir,embeddingLlm:r,graphLlm:e.graphLlm,rerankLlm:e.rerankLlm},this.syncConfig=this.config.sync,this.db=new X(this.config.database.path),this.pipeline=new Y(this.db,this.config),this.searchEngine=new Q(this.db,this.config),this.graphInterface=new V(this.db),this.fileScanner=new $({workspaceDir:this.config.workspaceDir,extraPaths:this.config.extraPaths,sources:this.config.sources,ignorePatterns:this.config?.indexer?.ignorePatterns});}async initialize(){if(this.initialized)return;await b.init({logDir:this.config.logDir||U__default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),L.init({models:{embeddingLlm:this.config.embeddingLlm,graphLlm:this.config.graphLlm,rerankLlm:this.config.rerankLlm},options:{graph:{maxOutputTokens:2e3,temperature:.1}}}),await this.db.initialize();let e=[["version","1.0.0"],["chunkSize",String(this.config.chunkSize)],["chunkOverlap",String(this.config.chunkOverlap)],["createdAt",new Date().toISOString()]];for(let[t,r]of e)this.db.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[t,r]);this.initialized=true,this.syncConfig.onBoot&&(this.syncAll().catch(t=>A.warn("onBoot sync failed",{error:String(t)})),this.startSyncTimer());}startSyncTimer(){this.syncTimer&&clearInterval(this.syncTimer),this.syncConfig.intervalMs>0&&(this.syncTimer=setInterval(async()=>{try{await this.syncAll();}catch(e){A.error("Interval sync failed",{error:String(e)});}},this.syncConfig.intervalMs));}ensureSynced(){this.dirty&&this.syncConfig.onSearch&&this.syncAll().catch(e=>{A.warn("Background sync failed",{error:String(e)});});}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}async syncAll(){if(this.syncingInProgress){A.debug("Sync already in progress, skipping...");return}this.syncingInProgress=true,A.debug("Starting sync...");try{let e=await this.sync((t,r,n)=>{A.debug("Syncing file",{current:t,total:r,path:n.relativePath||U__default.basename(n.absolutePath)});});this.dirty=!1,A.debug("Sync completed",{totalFiles:e.filesAdded+e.filesUpdated+e.filesSkipped,added:e.filesAdded,updated:e.filesUpdated,deleted:e.filesDeleted,skipped:e.filesSkipped,errors:e.errors.length});}finally{this.syncingInProgress=false;}}async ingestDocument(e){return await this.ensureInitialized(),this.pipeline.process(e)}async ingestDocuments(e,t){await this.ensureInitialized();let r=[];for(let n=0;n<e.length;n++){let o=await this.pipeline.process(e[n]);r.push(o),t?.((n+1)/e.length);}return r}async scanAndIngest(e){for(await this.ensureInitialized();this.syncingInProgress;)await new Promise(n=>setTimeout(n,100));let t=await this.fileScanner.scanAll(e);if(t.length===0)return [];let r=t.map(n=>n.absolutePath);return this.ingestDocuments(r,n=>{e?.(Math.round(n*t.length),t.length,t[0]||{absolutePath:"ingesting...",relativePath:"ingesting...",source:"docs",contentHash:"",lastModified:0,size:0});})}async ingestUploadedFile(e){await this.ensureInitialized();let t=await this.fileScanner.scanFile(e,"upload");if(!t)throw new Error(`\u65E0\u6CD5\u626B\u63CF\u6587\u4EF6: ${e}`);return this.pipeline.process(t.absolutePath)}async removeDocument(e){await this.ensureInitialized();let t=Filesystem.toUnixPath(e);try{this.db.deleteDocumentByPath(t)&&A.debug("Removed document",{path:t});}catch(r){throw A.error("Failed to remove document",{path:t,error:String(r)}),r}}markDirty(){this.dirty=true,A.debug("Marked as dirty, will sync before next search");}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return A.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,chunksCreated:0,vectorsCreated:0,entitiesExtracted:0,relationsExtracted:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=Date.now(),r={success:!0,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,chunksCreated:0,vectorsCreated:0,entitiesExtracted:0,relationsExtracted:0,errors:[],duration:0},n=await this.fileScanner.scanAll(e),o=new Set(n.map(a=>Filesystem.toUnixPath(a.relativePath))),s=this.db.query("SELECT path, contentHash FROM documents"),i=new Map;for(let a of s)i.set(a.path,a.contentHash);for(let[a]of i)if(!o.has(a))try{this.db.deleteDocumentByPath(a)&&(r.filesDeleted++,A.debug("Deleted document from index",{path:a}));}catch(d){let l=d instanceof Error?d.message:String(d);r.errors.push({filePath:a,error:`Failed to delete document: ${l}`}),A.error("Failed to delete document",{path:a,error:l});}for(let a=0;a<n.length;a++){let d=n[a],l=Filesystem.toUnixPath(d.relativePath);e?.(a+1,n.length,d);try{let g=i.get(l);if(g===void 0){let u=await this.pipeline.process(d.absolutePath);r.filesAdded++,r.chunksCreated+=u.chunksCreated,r.vectorsCreated+=u.vectorsCreated,r.entitiesExtracted+=u.entitiesExtracted||0,r.relationsExtracted+=u.relationsExtracted||0,A.debug("Added new document",{path:l});}else if(g!==d.contentHash){let u=await this.pipeline.process(d.absolutePath);r.filesUpdated++,r.chunksCreated+=u.chunksCreated,r.vectorsCreated+=u.vectorsCreated,r.entitiesExtracted+=u.entitiesExtracted||0,r.relationsExtracted+=u.relationsExtracted||0,A.debug("Updated document",{path:l});}else r.filesSkipped++;}catch(g){let u=g instanceof Error?g.message:String(g);r.errors.push({filePath:l,error:u}),A.error("Failed to process document",{path:l,error:u});}}r.duration=Date.now()-t,r.success=r.errors.length===0;let c={timestamp:new Date().toISOString(),success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,vectorsCreated:r.vectorsCreated,entitiesExtracted:r.entitiesExtracted,relationsExtracted:r.relationsExtracted,errorCount:r.errors.length,duration:r.duration};return this.db.setMeta("lastSync",c.timestamp),this.db.setMeta("lastSyncResult",JSON.stringify(c)),A.info("Sync completed",{added:r.filesAdded,updated:r.filesUpdated,deleted:r.filesDeleted,skipped:r.filesSkipped,errors:r.errors.length,duration:r.duration}),r}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.searchEngine.search(e,t)}async queryNodes(e,t){return await this.ensureInitialized(),typeof e=="string"?this.graphInterface.queryNodes(e,t):this.graphInterface.queryNodes(e)}async queryEdges(e,t){return await this.ensureInitialized(),typeof e=="string"?this.graphInterface.queryEdges(e,t):this.graphInterface.queryEdges(e)}async findPath(e,t,r){return await this.ensureInitialized(),this.graphInterface.findPath(e,t,r)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.graphInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.graphInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.graphInterface.queryInheritance(e)}async createNode(e,t,r){return await this.ensureInitialized(),this.graphInterface.createNode(e,t,r)}async updateNode(e,t){return await this.ensureInitialized(),this.graphInterface.updateNode(e,t)}async deleteNode(e){return await this.ensureInitialized(),this.graphInterface.deleteNode(e)}async createEdge(e,t,r,n){return await this.ensureInitialized(),this.graphInterface.createEdge(e,t,r,n)}async deleteEdge(e){return await this.ensureInitialized(),this.graphInterface.deleteEdge(e)}getStatus(){let e=this.db.getPath(),t=0,r=0,n=0,o=0;try{t=this.db.getDb().prepare("SELECT COUNT(*) as count FROM documents").get()?.count||0,r=this.db.getDb().prepare("SELECT COUNT(*) as count FROM chunks").get()?.count||0,n=this.db.getDb().prepare("SELECT COUNT(*) as count FROM nodes").get()?.count||0,o=this.db.getDb().prepare("SELECT COUNT(*) as count FROM edges").get()?.count||0;}catch{}return {dbPath:e,workspaceDir:this.config.workspaceDir,documentsCount:t,chunksCount:r,nodesCount:n,edgesCount:o,embeddingLlmAvailable:!!this.config.embeddingLlm,graphLlmAvailable:!!this.config.graphLlm,rerankLlmAvailable:!!this.config.rerankLlm,healthy:this.initialized,meta:this.getMetaMap()}}getMetaMap(){let e={};try{let t=this.db.query("SELECT key, value FROM meta");for(let r of t)e[r.key]=r.value;}catch{}return e}async healthCheck(){try{return this.db.query("SELECT 1"),!0}catch{return false}}async clear(){this.db.transaction(()=>{this.db.run("DELETE FROM chunks"),this.db.run("DELETE FROM documents"),this.db.run("DELETE FROM vectors"),this.db.run("DELETE FROM nodes"),this.db.run("DELETE FROM edges"),this.db.run("DELETE FROM embedding_cache"),this.db.run("DELETE FROM sqlite_sequence WHERE name IN ('chunks', 'documents', 'nodes', 'edges')");});try{this.db.run("INSERT INTO chunks_fts(chunks_fts) VALUES('delete-all')");}catch(e){A.warn("Failed to clear FTS index",{error:String(e)});}A.info("Note knowledge base cleared");}async ensureInitialized(){this.initialized||await this.initialize();}async close(){this.initialized&&(this.stopSyncTimer(),await this.db.close(),this.initialized=false,A.info("NoteKnowledge closed"));}};async function He(E){let e=new Z(E);return await e.initialize(),e}async function cr(E){let{Log:e}=await import('./chunks/log-EPJXYODF.mjs'),t=false;await e.init({logDir:E.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:E.print??false,dev:E.dev??t,level:E.level??("INFO")});}export{$ as FileScanner,R as KnowledgeBaseError,z as KnowledgeBaseErrorCode,L as Llm,Z as NoteKnowledge,st as addWord,ot as closeTokenizer,He as createNoteKnowledge,cr as initLog,nt as initTokenizer,it as isInitialized,be as loadCustomDict,ie as toFtsTokens,oe as toFtsTokensForSearch,Ie as tokenize,Ne as tokenizeForSearch};