@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.cjs CHANGED
@@ -1,29 +1,31 @@
1
- 'use strict';var Gn=require('better-sqlite3'),utils=require('@easbot/utils'),types=require('@easbot/types'),Je=require('fs/promises'),me=require('path'),Zt=require('jieba-wasm'),ha=require('fs'),qa=require('zod'),url=require('url'),events=require('events'),an=require('stream'),string_decoder=require('string_decoder'),ai$1=require('ai'),crypto=require('crypto'),xdgBasedir=require('xdg-basedir');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Gn__default=/*#__PURE__*/_interopDefault(Gn);var Je__default=/*#__PURE__*/_interopDefault(Je);var me__namespace=/*#__PURE__*/_interopNamespace(me);var Zt__namespace=/*#__PURE__*/_interopNamespace(Zt);var ha__namespace=/*#__PURE__*/_interopNamespace(ha);var qa__default=/*#__PURE__*/_interopDefault(qa);var an__default=/*#__PURE__*/_interopDefault(an);var Bn=Object.defineProperty;var Ys=i=>{throw TypeError(i)};var Un=(i,t,e)=>t in i?Bn(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var p=(i,t,e)=>Un(i,typeof t!="symbol"?t+"":t,e),ys=(i,t,e)=>t.has(i)||Ys("Cannot "+e);var n=(i,t,e)=>(ys(i,t,"read from private field"),e?e.call(i):t.get(i)),v=(i,t,e)=>t.has(i)?Ys("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),f=(i,t,e,s)=>(ys(i,t,"write to private field"),t.set(i,e),e),m=(i,t,e)=>(ys(i,t,"access private method"),e);var _i=(i,t,e,s)=>({set _(r){f(i,t,r);},get _(){return n(i,t,s)}});var $n=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,lt=$n();var Fe=(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))(Fe||{}),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 ji=class{constructor(t){p(this,"db",null);p(this,"storagePath");p(this,"initialized",false);p(this,"initPromise",null);this.storagePath=utils.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__default.default(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
+ 'use strict';var chunkF2MSBWJN_cjs=require('./chunks/chunk-F2MSBWJN.cjs'),le=require('better-sqlite3'),utils=require('@easbot/utils'),types=require('@easbot/types'),z=require('fs/promises'),_=require('path'),x=require('jieba-wasm'),ai=require('ai'),crypto=require('crypto'),xdgBasedir=require('xdg-basedir');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var le__default=/*#__PURE__*/_interopDefault(le);var z__default=/*#__PURE__*/_interopDefault(z);var ___namespace=/*#__PURE__*/_interopNamespace(_);var x__namespace=/*#__PURE__*/_interopNamespace(x);var H=(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))(H||{}),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 G=class{constructor(e){chunkF2MSBWJN_cjs.a(this,"db",null);chunkF2MSBWJN_cjs.a(this,"storagePath");chunkF2MSBWJN_cjs.a(this,"initialized",false);chunkF2MSBWJN_cjs.a(this,"initPromise",null);this.storagePath=utils.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 le__default.default(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 @@
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 ye=class{async parse(t){try{let e=await Je.readFile(t,"utf-8"),s=me.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}=utils.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:utils.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 Ur=(i,t,e)=>{let s=i instanceof RegExp?Qs(i,e):i,r=t instanceof RegExp?Qs(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)}},Qs=(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},$r="\0SLASH"+Math.random()+"\0",Gr="\0OPEN"+Math.random()+"\0",js="\0CLOSE"+Math.random()+"\0",Hr="\0COMMA"+Math.random()+"\0",qr="\0PERIOD"+Math.random()+"\0",Xn=new RegExp($r,"g"),Qn=new RegExp(Gr,"g"),Jn=new RegExp(js,"g"),Vn=new RegExp(Hr,"g"),Zn=new RegExp(qr,"g"),to=/\\\\/g,eo=/\\{/g,io=/\\}/g,so=/\\,/g,ro=/\\./g,no=1e5;function bs(i){return isNaN(i)?i.charCodeAt(0):parseInt(i,10)}function oo(i){return i.replace(to,$r).replace(eo,Gr).replace(io,js).replace(so,Hr).replace(ro,qr)}function ao(i){return i.replace(Xn,"\\").replace(Qn,"{").replace(Jn,"}").replace(Vn,",").replace(Zn,".")}function Kr(i){if(!i)return [""];let t=[],e=Ur("{","}",i);if(!e)return i.split(",");let{pre:s,body:r,post:o}=e,a=s.split(",");a[a.length-1]+="{"+r+"}";let h=Kr(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)),ri(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 ri(i,t,e){let s=[],r=Ur("{","}",i);if(!r)return [i];let o=r.pre,a=r.post.length?ri(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+js+r.post,ri(i,t,true)):[i];let u;if(c)u=r.body.split(/\.\./);else if(u=Kr(r.body),u.length===1&&u[0]!==void 0&&(u=ri(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=bs(u[0]),w=bs(u[1]),b=Math.max(u[0].length,u[1].length),S=u.length===3&&u[2]!==void 0?Math.abs(bs(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,ri(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 ss=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]},Ve=i=>i.replace(/[[\]\\-]/g,"\\$&"),go=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Js=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(Ve(u)+"-"+Ve(w)):w===u&&s.push(Ve(w)),u="",o++;continue}if(i.startsWith("-]",o+1)){s.push(Ve(w+"-")),o+=2;continue}if(i.startsWith("-",o+1)){u=w,o+=2;continue}s.push(Ve(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?"^":"")+Js(s)+"]",y="["+(c?"":"^")+Js(r)+"]";return [s.length&&r.length?"("+g+"|"+y+")":s.length?g:y,h,d-e,true]},_e=(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(["!","?","+","*","@"]),Vs=i=>yo.has(i),bo="(?!(?:^|/)\\.\\.?(?:$|/))",Bi="(?!\\.)",wo=new Set(["[","."]),Eo=new Set(["..","."]),So=new Set("().*{}+?[]^$\\!"),vo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Bs="[^/]",Zs=Bs+"*?",tr=Bs+"+?",G,J,qt,M,U,oe,Se,ae,zt,ve,ui,Oe,Xr,pe,tt,Xi,As,Qr,Yr=(tt=class{constructor(t,e,s={}){v(this,Oe);p(this,"type");v(this,G);v(this,J);v(this,qt,false);v(this,M,[]);v(this,U);v(this,oe);v(this,Se);v(this,ae,false);v(this,zt);v(this,ve);v(this,ui,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,zt,n(this,G)===this?s:n(n(this,G),zt)),f(this,Se,n(this,G)===this?[]:n(n(this,G),Se)),t==="!"&&!n(n(this,G),ae)&&n(this,Se).push(this),f(this,oe,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,ve)!==void 0?n(this,ve):this.type?f(this,ve,this.type+"("+n(this,M).map(t=>String(t)).join("|")+")"):f(this,ve,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),ae)&&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,oe)===0)return true;let t=n(this,U);for(let e=0;e<n(this,oe);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,oe)===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,pe,Xi).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,zt).nocase&&!n(this,zt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let a=(n(this,zt).nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${e}$`,a),{_src:e,_glob:t})}get options(){return n(this,zt)}toRegExpSource(t){let e=t??!!n(this,zt).dot;if(n(this,G)===this&&m(this,Oe,Xr).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,pe,Qr).call(E,g,n(this,J),l):g.toRegExpSource(t);return f(this,J,n(this,J)||b),f(this,qt,n(this,qt)||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?Bi:"";}let u="";return this.isEnd()&&n(n(this,G),ae)&&n(this,U)?.type==="!"&&(u="(?:$|\\/)"),[d+c+u,_e(c),f(this,J,!!n(this,J)),n(this,qt)]}let s=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",o=m(this,Oe,As).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,_e(this.toString()),false,false]}let a=!s||t||e||!Bi?"":m(this,Oe,As).call(this,true);a===o&&(a=""),a&&(o=`(?:${o})(?:${a})*?`);let h="";if(this.type==="!"&&n(this,ui))h=(this.isStart()&&!e?Bi:"")+tr;else {let l=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Bi:"")+Zs+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;h=r+o+l;}return [h,_e(o),f(this,J,!!n(this,J)),n(this,qt)]}},G=new WeakMap,J=new WeakMap,qt=new WeakMap,M=new WeakMap,U=new WeakMap,oe=new WeakMap,Se=new WeakMap,ae=new WeakMap,zt=new WeakMap,ve=new WeakMap,ui=new WeakMap,Oe=new WeakSet,Xr=function(){if(this!==n(this,G))throw new Error("should only call on root");if(n(this,ae))return this;this.toString(),f(this,ae,true);let t;for(;t=n(this,Se).pop();){if(t.type!=="!")continue;let e=t,s=n(e,U);for(;s;){for(let r=n(e,oe)+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},pe=new WeakSet,Xi=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&&Vs(E)&&t.charAt(b)==="("){e.push(S),S="";let A=new tt(E,e);b=m(y=tt,pe,Xi).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(Vs(b)&&t.charAt(c)==="("){d.push(g),g="";let S=new tt(b,d);d.push(S),c=m(w=tt,pe,Xi).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,ui,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},As=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,qt,n(this,qt)||a),s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")},Qr=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)?tr:Zs,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+=Bs,e=true;continue}o+=vo(c);}return [o,_e(t),!!e,a]},v(tt,pe),tt),Jr=(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={})=>(ss(t),!e.nocomment&&t.charAt(0)==="#"?false:new fe(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=Vr([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},zo=([i,t=""])=>{let e=Zr([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Wo=([i,t=""])=>{let e=Zr([i]);return t?s=>e(s)&&s.endsWith(t):e},jo=([i,t=""])=>{let e=Vr([i]);return t?s=>e(s)&&s.endsWith(t):e},Vr=([i])=>{let t=i.length;return e=>e.length===t&&!e.startsWith(".")},Zr=([i])=>{let t=i.length;return e=>e.length===t&&e!=="."&&e!==".."},tn=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",er={win32:{sep:"\\"},posix:{sep:"/"}},Bo=tn==="win32"?er.win32.sep:er.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 Et=(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,Et(i,r)),{Minimatch:class extends t.Minimatch{constructor(e,s={}){super(e,Et(i,s));}static defaults(e){return t.defaults(Et(i,e)).Minimatch}},AST:class extends t.AST{constructor(e,s,r={}){super(e,s,Et(i,r));}static fromGlob(e,s={}){return t.AST.fromGlob(e,Et(i,s))}},unescape:(e,s={})=>t.unescape(e,Et(i,s)),escape:(e,s={})=>t.escape(e,Et(i,s)),filter:(e,s={})=>t.filter(e,Et(i,s)),defaults:e=>t.defaults(Et(i,e)),makeRe:(e,s={})=>t.makeRe(e,Et(i,s)),braceExpand:(e,s={})=>t.braceExpand(e,Et(i,s)),match:(e,s,r={})=>t.match(e,s,Et(i,r)),sep:t.sep,GLOBSTAR:at})};ht.defaults=Ko;var en=(i,t={})=>(ss(i),t.nobrace||!/\{(?:(?!\{).)*\}/.test(i)?[i]:ho(i,{max:t.braceExpandMax}));ht.braceExpand=en;var Yo=(i,t={})=>new fe(i,t).makeRe();ht.makeRe=Yo;var Xo=(i,t,e={})=>{let s=new fe(t,e);return i=i.filter(r=>s.match(r)),s.options.nonull&&!i.length&&i.push(t),i};ht.match=Xo;var ir=/[?*]|[+@!]\(.*?\)|\[|\]/,Qo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),fe=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");ss(i),t=t||{},this.options=t,this.pattern=i,this.platform=t.platform||tn,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]==="?"||!ir.test(r[2]))&&!ir.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 en(this.pattern,this.options)}parse(i){ss(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=Yr.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=Yr;ht.Minimatch=fe;ht.escape=Jr;ht.unescape=_e;var Vo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,sn=new Set,Is=typeof process=="object"&&process?process:{},rn=(i,t,e,s)=>{typeof Is.emitWarning=="function"?Is.emitWarning(i,t,e,s):console.error(`[${e}] ${t}: ${i}`);},rs=globalThis.AbortController,sr=globalThis.AbortSignal;if(typeof rs>"u"){sr=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(e,s){this._onabort.push(s);}},rs=class{constructor(){p(this,"signal",new sr);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=Is.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{i&&(i=false,rn("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=>!sn.has(i),ie=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),nn=i=>ie(i)?i<=Math.pow(2,8)?Uint8Array:i<=Math.pow(2,16)?Uint16Array:i<=Math.pow(2,32)?Uint32Array:i<=Number.MAX_SAFE_INTEGER?Qi:null:null,Qi=class extends Array{constructor(i){super(i),this.fill(0);}},Bt,ze,ta=(Bt=class{constructor(t,e){p(this,"heap");p(this,"length");if(!n(Bt,ze))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}static create(t){let e=nn(t);if(!e)return [];f(Bt,ze,true);let s=new Bt(t,e);return f(Bt,ze,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},ze=new WeakMap,v(Bt,ze,false),Bt),br,wr,vt,ft,It,Te,kt,We,je,Lt,H,xt,$,_,O,rt,gt,it,V,Ot,Z,Ct,Dt,mt,yt,Ft,he,nt,Be,R,ks,Re,Kt,di,bt,on,Ne,Ue,pi,se,re,Ls,Ji,Vi,P,xs,ni,ne,Os,$e,as=($e=class{constructor(t){v(this,R);v(this,vt);v(this,ft);v(this,It);v(this,Te);v(this,kt);v(this,We);v(this,je);v(this,Lt);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,xt);v(this,$);v(this,_);v(this,O);v(this,rt);v(this,gt);v(this,it);v(this,V);v(this,Ot);v(this,Z);v(this,Ct);v(this,Dt);v(this,mt);v(this,yt);v(this,Ft);v(this,he);v(this,nt);v(this,Be);v(this,Re,()=>{});v(this,Kt,()=>{});v(this,di,()=>{});v(this,bt,()=>false);v(this,Ne,t=>{});v(this,Ue,(t,e,s)=>{});v(this,pi,(t,e,s,r)=>{if(s||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,br,"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,Lt,z??Vo),e!==0&&!ie(e))throw new TypeError("max option must be a nonnegative integer");let F=e?nn(e):Array;if(!F)throw new Error("invalid max value: "+e);if(f(this,vt,e),f(this,ft,w),this.maxEntrySize=b||n(this,ft),this.sizeCalculation=S,this.sizeCalculation){if(!n(this,ft)&&!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,je,A),E!==void 0&&typeof E!="function")throw new TypeError("fetchMethod must be a function if specified");if(f(this,We,E),f(this,he,!!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,gt,new F(e)),f(this,it,0),f(this,V,0),f(this,Ot,ta.create(e)),f(this,H,0),f(this,xt,0),typeof c=="function"&&f(this,It,c),typeof d=="function"&&f(this,Te,d),typeof u=="function"?(f(this,kt,u),f(this,Z,[])):(f(this,kt,void 0),f(this,Z,void 0)),f(this,Ft,!!n(this,It)),f(this,Be,!!n(this,Te)),f(this,nt,!!n(this,kt)),this.noDisposeOnSet=!!g,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!I,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(n(this,ft)!==0&&!ie(n(this,ft)))throw new TypeError("maxSize must be a positive integer if specified");if(!ie(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");m(this,R,on).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!N,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!h,this.ttlResolution=ie(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!ie(this.ttl))throw new TypeError("ttl must be a positive integer if specified");m(this,R,ks).call(this);}if(n(this,vt)===0&&this.ttl===0&&n(this,ft)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,vt)&&!n(this,ft)){let W="LRU_CACHE_UNBOUNDED";Zo(W)&&(sn.add(W),rn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",W,$e));}}get perf(){return n(this,Lt)}static unsafeExposeInternals(t){return {starts:n(t,Dt),ttls:n(t,mt),autopurgeTimers:n(t,yt),sizes:n(t,Ct),keyMap:n(t,$),keyList:n(t,_),valList:n(t,O),next:n(t,rt),prev:n(t,gt),get head(){return n(t,it)},get tail(){return n(t,V)},free:n(t,Ot),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,Vi).call(a,e,s,r,o)},moveToTail:e=>{var s;return m(s=t,R,ni).call(s,e)},indexes:e=>{var s;return m(s=t,R,se).call(s,e)},rindexes:e=>{var s;return m(s=t,R,re).call(s,e)},isStale:e=>{var s;return n(s=t,bt).call(s,e)}}}get max(){return n(this,vt)}get maxSize(){return n(this,ft)}get calculatedSize(){return n(this,xt)}get size(){return n(this,H)}get fetchMethod(){return n(this,We)}get memoMethod(){return n(this,je)}get dispose(){return n(this,It)}get onInsert(){return n(this,Te)}get disposeAfter(){return n(this,kt)}getRemainingTTL(t){return n(this,$).has(t)?1/0:0}*entries(){for(let t of m(this,R,se).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,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]]);}*keys(){for(let t of m(this,R,se).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,re).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,se).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,re).call(this))n(this,O)[t]!==void 0&&!m(this,R,P).call(this,n(this,O)[t])&&(yield n(this,O)[t]);}[(wr=Symbol.iterator,br=Symbol.toStringTag,wr)](){return this.entries()}find(t,e={}){for(let s of m(this,R,se).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,se).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,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);}}purgeStale(){let t=false;for(let e of m(this,R,re).call(this,{allowStale:true}))n(this,bt).call(this,e)&&(m(this,R,ne).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,mt)&&n(this,Dt)){let a=n(this,mt)[e],h=n(this,Dt)[e];if(a&&h){let l=a-(n(this,Lt).now()-h);o.ttl=l,o.start=Date.now();}}return n(this,Ct)&&(o.size=n(this,Ct)[e]),o}dump(){let t=[];for(let e of m(this,R,se).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,mt)&&n(this,Dt)){a.ttl=n(this,mt)[e];let h=n(this,Lt).now()-n(this,Dt)[e];a.start=Math.floor(Date.now()-h);}n(this,Ct)&&(a.size=n(this,Ct)[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,Lt).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,pi).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,ne).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,Ot).length!==0?n(this,Ot).pop():n(this,H)===n(this,vt)?m(this,R,Ji).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,gt)[u]=n(this,V),f(this,V,u),_i(this,H)._++,n(this,Ue).call(this,u,d,l),l&&(l.set="add"),c=false,n(this,Be)&&((g=n(this,Te))==null||g.call(this,e,t,"add"));else {m(this,R,ni).call(this,u);let S=n(this,O)[u];if(e!==S){if(n(this,he)&&m(this,R,P).call(this,S)){S.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:E}=S;E!==void 0&&!a&&(n(this,Ft)&&((y=n(this,It))==null||y.call(this,E,t,"set")),n(this,nt)&&n(this,Z)?.push([E,t,"set"]));}else a||(n(this,Ft)&&((w=n(this,It))==null||w.call(this,S,t,"set")),n(this,nt)&&n(this,Z)?.push([S,t,"set"]));if(n(this,Ne).call(this,u),n(this,Ue).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,Be)&&this.onInsert?.(e,t,e===S?"update":"replace");}if(r!==0&&!n(this,mt)&&m(this,R,ks).call(this),n(this,mt)&&(c||n(this,di).call(this,u,r,o),l&&n(this,Kt).call(this,l,u)),!a&&n(this,nt)&&n(this,Z)){let S=n(this,Z),E;for(;E=S?.shift();)(b=n(this,kt))==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,Ji).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,kt))==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,bt).call(this,o))r&&(r.has="stale",n(this,Kt).call(this,r,o));else return s&&n(this,Re).call(this,o),r&&(r.has="hit",n(this,Kt).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,bt).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,he))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,Vi).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,bt).call(this,N);if(!S&&!L)return E&&(E.fetch="hit"),m(this,R,ni).call(this,N),r&&n(this,Re).call(this,N),E&&n(this,Kt).call(this,E,N),T;let C=m(this,R,Vi).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,je);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,Kt).call(this,a,h),n(this,bt).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,ne).call(this,t,"expire"),a&&s&&(a.returnedStale=true),s?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(m(this,R,ni).call(this,h),r&&n(this,Re).call(this,h),l))}else a&&(a.get="miss");}delete(t){return m(this,R,ne).call(this,t,"delete")}clear(){return m(this,R,Os).call(this,"delete")}},vt=new WeakMap,ft=new WeakMap,It=new WeakMap,Te=new WeakMap,kt=new WeakMap,We=new WeakMap,je=new WeakMap,Lt=new WeakMap,H=new WeakMap,xt=new WeakMap,$=new WeakMap,_=new WeakMap,O=new WeakMap,rt=new WeakMap,gt=new WeakMap,it=new WeakMap,V=new WeakMap,Ot=new WeakMap,Z=new WeakMap,Ct=new WeakMap,Dt=new WeakMap,mt=new WeakMap,yt=new WeakMap,Ft=new WeakMap,he=new WeakMap,nt=new WeakMap,Be=new WeakMap,R=new WeakSet,ks=function(){let t=new Qi(n(this,vt)),e=new Qi(n(this,vt));f(this,mt,t),f(this,Dt,e);let s=this.ttlAutopurge?new Array(n(this,vt)):void 0;f(this,yt,s),f(this,di,(a,h,l=n(this,Lt).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,bt).call(this,a)&&m(this,R,ne).call(this,n(this,_)[a],"expire");},h+1);c.unref&&c.unref(),s[a]=c;}}),f(this,Re,a=>{e[a]=t[a]!==0?n(this,Lt).now():0;}),f(this,Kt,(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,Lt).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,bt,a=>{let h=e[a],l=t[a];return !!l&&!!h&&(r||o())-h>l});},Re=new WeakMap,Kt=new WeakMap,di=new WeakMap,bt=new WeakMap,on=function(){let t=new Qi(n(this,vt));f(this,xt,0),f(this,Ct,t),f(this,Ne,e=>{f(this,xt,n(this,xt)-t[e]),t[e]=0;}),f(this,pi,(e,s,r,o)=>{if(m(this,R,P).call(this,s))return 0;if(!ie(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(s,e),!ie(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,Ue,(e,s,r)=>{if(t[e]=s,n(this,ft)){let o=n(this,ft)-t[e];for(;n(this,xt)>o;)m(this,R,Ji).call(this,true);}f(this,xt,n(this,xt)+t[e]),r&&(r.entrySize=s,r.totalCalculatedSize=n(this,xt));});},Ne=new WeakMap,Ue=new WeakMap,pi=new WeakMap,se=function*({allowStale:t=this.allowStale}={}){if(n(this,H))for(let e=n(this,V);!(!m(this,R,Ls).call(this,e)||((t||!n(this,bt).call(this,e))&&(yield e),e===n(this,it)));)e=n(this,gt)[e];},re=function*({allowStale:t=this.allowStale}={}){if(n(this,H))for(let e=n(this,it);!(!m(this,R,Ls).call(this,e)||((t||!n(this,bt).call(this,e))&&(yield e),e===n(this,V)));)e=n(this,rt)[e];},Ls=function(t){return t!==void 0&&n(this,$).get(n(this,_)[t])===t},Ji=function(t){var o;let e=n(this,it),s=n(this,_)[e],r=n(this,O)[e];return n(this,he)&&m(this,R,P).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Ft)||n(this,nt))&&(n(this,Ft)&&((o=n(this,It))==null||o.call(this,r,s,"evict")),n(this,nt)&&n(this,Z)?.push([r,s,"evict"])),n(this,Ne).call(this,e),n(this,yt)?.[e]&&(clearTimeout(n(this,yt)[e]),n(this,yt)[e]=void 0),t&&(n(this,_)[e]=void 0,n(this,O)[e]=void 0,n(this,Ot).push(e)),n(this,H)===1?(f(this,it,f(this,V,0)),n(this,Ot).length=0):f(this,it,n(this,rt)[e]),n(this,$).delete(s),_i(this,H)._--,e},Vi=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 rs,{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,ne).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,ne).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,We))==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,he))return false;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof rs},xs=function(t,e){n(this,gt)[e]=t,n(this,rt)[t]=e;},ni=function(t){t!==n(this,V)&&(t===n(this,it)?f(this,it,n(this,rt)[t]):m(this,R,xs).call(this,n(this,gt)[t],n(this,rt)[t]),m(this,R,xs).call(this,n(this,V),t),f(this,V,t));},ne=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,yt)?.[a]&&(clearTimeout(n(this,yt)?.[a]),n(this,yt)[a]=void 0),s=true,n(this,H)===1)m(this,R,Os).call(this,e);else {n(this,Ne).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,Ft)||n(this,nt))&&(n(this,Ft)&&((r=n(this,It))==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,gt)[a]);else if(a===n(this,it))f(this,it,n(this,rt)[a]);else {let l=n(this,gt)[a];n(this,rt)[l]=n(this,rt)[a];let c=n(this,rt)[a];n(this,gt)[c]=n(this,gt)[a];}_i(this,H)._--,n(this,Ot).push(a);}}if(n(this,nt)&&n(this,Z)?.length){let a=n(this,Z),h;for(;h=a?.shift();)(o=n(this,kt))==null||o.call(this,...h);}return s},Os=function(t){var e,s;for(let r of m(this,R,re).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,Ft)&&((e=n(this,It))==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,mt)&&n(this,Dt)){n(this,mt).fill(0),n(this,Dt).fill(0);for(let r of n(this,yt)??[])r!==void 0&&clearTimeout(r);n(this,yt)?.fill(void 0);}if(n(this,Ct)&&n(this,Ct).fill(0),f(this,it,0),f(this,V,0),n(this,Ot).length=0,f(this,xt,0),f(this,H,0),n(this,nt)&&n(this,Z)){let r=n(this,Z),o;for(;o=r?.shift();)(s=n(this,kt))==null||s.call(this,...o);}},$e),rr=typeof process=="object"&&process?process:{stdout:null,stderr:null},fa=i=>!!i&&typeof i=="object"&&(i instanceof ns||i instanceof an__default.default||ga(i)||ma(i)),ga=i=>!!i&&typeof i=="object"&&i instanceof events.EventEmitter&&typeof i.pipe=="function"&&i.pipe!==an__default.default.Writable.prototype.pipe,ma=i=>!!i&&typeof i=="object"&&i instanceof events.EventEmitter&&typeof i.write=="function"&&typeof i.end=="function",Gt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),ee=Symbol("emittedEnd"),Ui=Symbol("emittingEnd"),Ze=Symbol("emittedError"),$i=Symbol("closed"),nr=Symbol("read"),Gi=Symbol("flush"),or=Symbol("flushChunk"),Nt=Symbol("encoding"),Pe=Symbol("decoder"),Y=Symbol("flowing"),ti=Symbol("paused"),Me=Symbol("resume"),X=Symbol("buffer"),st=Symbol("pipes"),Q=Symbol("bufferLength"),ws=Symbol("bufferPush"),Hi=Symbol("bufferShift"),et=Symbol("objectMode"),B=Symbol("destroyed"),Es=Symbol("error"),Ss=Symbol("emitData"),ar=Symbol("emitEnd"),vs=Symbol("emitEnd2"),Mt=Symbol("async"),Ts=Symbol("abort"),qi=Symbol("aborted"),ei=Symbol("signal"),be=Symbol("dataListeners"),pt=Symbol("discarded"),ii=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),hn=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[Me](),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 hn{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",Er,Sr,vr,Tr,Rr,Nr,Ar,Ir,kr,Lr,xr,Or,Cr,Dr,Fr,Pr,Mr,_r,zr,ns=class extends events.EventEmitter{constructor(...t){let e=t[0]||{};super();p(this,zr,false);p(this,_r,false);p(this,Mr,[]);p(this,Pr,[]);p(this,Fr);p(this,Dr);p(this,Cr);p(this,Or);p(this,xr,false);p(this,Lr,false);p(this,kr,false);p(this,Ir,false);p(this,Ar,null);p(this,Nr,0);p(this,Rr,false);p(this,Tr);p(this,vr,false);p(this,Sr,0);p(this,Er,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[Nt]=null):Ta(e)?(this[Nt]=e.encoding,this[et]=false):(this[et]=false,this[Nt]=null),this[Mt]=!!e.async,this[Pe]=this[Nt]?new string_decoder.StringDecoder(this[Nt]):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[ei]=s,s.aborted?this[Ts]():s.addEventListener("abort",()=>this[Ts]()));}get bufferLength(){return this[Q]}get encoding(){return this[Nt]}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[Mt]}set async(t){this[Mt]=this[Mt]||!!t;}[(zr=Y,_r=ti,Mr=st,Pr=X,Fr=et,Dr=Nt,Cr=Mt,Or=Pe,xr=Gt,Lr=ee,kr=Ui,Ir=$i,Ar=Ze,Nr=Q,Rr=B,Tr=ei,vr=qi,Sr=be,Er=pt,Ts)](){this[qi]=true,this.emit("abort",this[ei]?.reason),this.destroy(this[ei]?.reason);}get aborted(){return this[qi]}set aborted(t){}write(t,e,s){if(this[qi])return false;if(this[Gt])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[Mt]?ii: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[Gi](true),this[Y]?this.emit("data",t):this[ws](t),this[Q]!==0&&this.emit("readable"),s&&r(s),this[Y]):t.length?(typeof t=="string"&&!(e===this[Nt]&&!this[Pe]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Nt]&&(t=this[Pe].write(t)),this[Y]&&this[Q]!==0&&this[Gi](true),this[Y]?this.emit("data",t):this[ws](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[pt]=false,this[Q]===0||t===0||t&&t>this[Q])return this[Ht](),null;this[et]&&(t=null),this[X].length>1&&!this[et]&&(this[X]=[this[Nt]?this[X].join(""):Buffer.concat(this[X],this[Q])]);let e=this[nr](t||null,this[X][0]);return this[Ht](),e}[nr](t,e){if(this[et])this[Hi]();else {let s=e;t===s.length||t===null?this[Hi]():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[Gt]&&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[Gt]=true,this.writable=false,(this[Y]||!this[ti])&&this[Ht](),this}[Me](){this[B]||(!this[be]&&!this[st].length&&(this[pt]=true),this[ti]=false,this[Y]=true,this.emit("resume"),this[X].length?this[Gi]():this[Gt]?this[Ht]():this.emit("drain"));}resume(){return this[Me]()}pause(){this[Y]=false,this[ti]=true,this[pt]=false;}get destroyed(){return this[B]}get flowing(){return this[Y]}get paused(){return this[ti]}[ws](t){this[et]?this[Q]+=1:this[Q]+=t.length,this[X].push(t);}[Hi](){return this[et]?this[Q]-=1:this[Q]-=this[X][0].length,this[X].shift()}[Gi](t=false){do;while(this[or](this[Hi]())&&this[X].length);!t&&!this[X].length&&!this[Gt]&&this.emit("drain");}[or](t){return this.emit("data",t),this[Y]}pipe(t,e){if(this[B])return t;this[pt]=false;let s=this[ee];return e=e||{},t===rr.stdout||t===rr.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 hn(this,t,e)),this[Mt]?ii(()=>this[Me]()):this[Me]()),t}unpipe(t){let e=this[st].find(s=>s.dest===t);e&&(this[st].length===1?(this[Y]&&this[be]===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[pt]=false,this[be]++,!this[st].length&&!this[Y]&&this[Me]();else if(t==="readable"&&this[Q]!==0)super.emit("readable");else if(ba(t)&&this[ee])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ze]){let r=e;this[Mt]?ii(()=>r.call(this,this[Ze])):r.call(this,this[Ze]);}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[be]=this.listeners("data").length,this[be]===0&&!this[pt]&&!this[st].length&&(this[Y]=false)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[be]=0,!this[pt]&&!this[st].length&&(this[Y]=false)),e}get emittedEnd(){return this[ee]}[Ht](){!this[Ui]&&!this[ee]&&!this[B]&&this[X].length===0&&this[Gt]&&(this[Ui]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$i]&&this.emit("close"),this[Ui]=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[Mt]?(ii(()=>this[Ss](s)),true):this[Ss](s);if(t==="end")return this[ar]();if(t==="close"){if(this[$i]=true,!this[ee]&&!this[B])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[Ze]=s,super.emit(Es,s);let o=!this[ei]||this.listeners("error").length?super.emit("error",s):false;return this[Ht](),o}else if(t==="resume"){let o=super.emit("resume");return this[Ht](),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[Ht](),r}[Ss](t){for(let s of this[st])s.dest.write(t)===false&&this.pause();let e=this[pt]?false:super.emit("data",t);return this[Ht](),e}[ar](){return this[ee]?false:(this[ee]=true,this.readable=false,this[Mt]?(ii(()=>this[vs]()),true):this[vs]())}[vs](){if(this[Pe]){let e=this[Pe].end();if(e){for(let s of this[st])s.dest.write(e);this[pt]||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[Nt]?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[pt]=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[Gt])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[Gt]});},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[pt]=false;let t=false,e=()=>(this.pause(),this.off(Es,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(Es,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[pt]=true,this[X].length=0,this[Q]=0;let e=this;return typeof e.close=="function"&&!this[$i]&&e.close(),t?this.emit("error",t):this.emit(B),this}static get isStream(){return fa}},Ra=ha.realpathSync.native,oi={lstatSync:ha.lstatSync,readdir:ha.readdir,readdirSync:ha.readdirSync,readlinkSync:ha.readlinkSync,realpathSync:Ra,promises:{lstat:Je.lstat,readdir:Je.readdir,readlink:Je.readlink,realpath:Je.realpath}},ln=i=>!i||i===oi||i===ha__namespace?oi:{...oi,...i,promises:{...oi.promises,...i.promises||{}}},cn=/^\\\\\?\\([a-z]:)\\?$/i,Na=i=>i.replace(/\//g,"\\").replace(cn,"$1\\"),Aa=/[\\\/]/,Tt=0,un=1,dn=2,_t=4,pn=6,fn=8,we=10,gn=12,St=15,si=~St,Rs=16,hr=32,ai=64,At=128,Ki=256,Zi=512,lr=ai|At|Zi,Ia=1023,Ns=i=>i.isFile()?fn:i.isDirectory()?_t:i.isSymbolicLink()?we:i.isCharacterDevice()?dn:i.isBlockDevice()?pn:i.isSocket()?gn:i.isFIFO()?un:Tt,cr=new as({max:2**12}),hi=i=>{let t=cr.get(i);if(t)return t;let e=i.normalize("NFKD");return cr.set(i,e),e},ur=new as({max:2**12}),Yi=i=>{let t=ur.get(i);if(t)return t;let e=hi(i.toLowerCase());return ur.set(i,e),e},dr=class extends as{constructor(){super({max:256});}},ka=class extends as{constructor(i=16*1024){super({maxSize:i,sizeCalculation:t=>t.length+1});}},mn=Symbol("PathScurry setAsCwd"),ot,fi,gi,mi,yi,bi,wi,Ei,Si,vi,Ti,Ri,Ni,Ai,Ii,ki,Li,xi,Oi,le,Ae,Wt,Yt,Xt,Qt,x,Ie,Jt,jt,k,Ds,ts,li,Fs,Ps,ci,es,Ms,_s,is,yn,bn,wn,zs,Ge,He,En,ke,Wr,ct=(Wr=class{constructor(i,t=Tt,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,fi);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,le);v(this,Ae);v(this,Wt);v(this,Yt);v(this,Xt);v(this,Qt);v(this,x);v(this,Ie);v(this,Jt);v(this,jt);v(this,Ge,[]);v(this,He,false);v(this,ke);this.name=i,f(this,le,r?Yi(i):hi(i)),f(this,x,t&Ia),this.nocase=r,this.roots=s,this.root=e||this,f(this,Ie,o),f(this,Wt,a.fullpath),f(this,Xt,a.relative),f(this,Qt,a.relativePosix),this.parent=a.parent,this.parent?f(this,ot,n(this.parent,ot)):f(this,ot,ln(a.fs));}get dev(){return n(this,fi)}get mode(){return n(this,gi)}get nlink(){return n(this,mi)}get uid(){return n(this,yi)}get gid(){return n(this,bi)}get rdev(){return n(this,wi)}get blksize(){return n(this,Ei)}get ino(){return n(this,Si)}get size(){return n(this,vi)}get blocks(){return n(this,Ti)}get atimeMs(){return n(this,Ri)}get mtimeMs(){return n(this,Ni)}get ctimeMs(){return n(this,Ai)}get birthtimeMs(){return n(this,Ii)}get atime(){return n(this,ki)}get mtime(){return n(this,Li)}get ctime(){return n(this,xi)}get birthtime(){return n(this,Oi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,Ae)!==void 0?n(this,Ae):this.parent?f(this,Ae,this.parent.depth()+1):f(this,Ae,0)}childrenCache(){return n(this,Ie)}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,Ds).call(s,e):m(this,k,Ds).call(this,e)}children(){let i=n(this,Ie).get(this);if(i)return i;let t=Object.assign([],{provisional:0});return n(this,Ie).set(this,t),f(this,x,n(this,x)&~Rs),t}child(i,t){if(i===""||i===".")return this;if(i==="..")return this.parent||this;let e=this.children(),s=this.nocase?Yi(i):hi(i);for(let h of e)if(n(h,le)===s)return h;let r=this.parent?this.sep:"",o=n(this,Wt)?n(this,Wt)+r+i:void 0,a=this.newChild(i,Tt,{...t,parent:this,fullpath:o});return this.canReaddir()||f(a,x,n(a,x)|At),e.push(a),a}relative(){if(this.isCWD)return "";if(n(this,Xt)!==void 0)return n(this,Xt);let i=this.name,t=this.parent;if(!t)return f(this,Xt,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,Qt)!==void 0)return n(this,Qt);let i=this.name,t=this.parent;if(!t)return f(this,Qt,this.fullpathPosix());let e=t.relativePosix();return e+(!e||!t.parent?"":"/")+i}fullpath(){if(n(this,Wt)!==void 0)return n(this,Wt);let i=this.name,t=this.parent;if(!t)return f(this,Wt,this.name);let e=t.fullpath()+(t.parent?this.sep:"")+i;return f(this,Wt,e)}fullpathPosix(){if(n(this,Yt)!==void 0)return n(this,Yt);if(this.sep==="/")return f(this,Yt,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?f(this,Yt,`//?/${s}`):f(this,Yt,s)}let i=this.parent,t=i.fullpathPosix(),e=t+(!t||!i.parent?"":"/")+this.name;return f(this,Yt,e)}isUnknown(){return (n(this,x)&St)===Tt}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)&St)===fn}isDirectory(){return (n(this,x)&St)===_t}isCharacterDevice(){return (n(this,x)&St)===dn}isBlockDevice(){return (n(this,x)&St)===pn}isFIFO(){return (n(this,x)&St)===un}isSocket(){return (n(this,x)&St)===gn}isSymbolicLink(){return (n(this,x)&we)===we}lstatCached(){return n(this,x)&hr?this:void 0}readlinkCached(){return n(this,Jt)}realpathCached(){return n(this,jt)}readdirCached(){let i=this.children();return i.slice(0,i.provisional)}canReadlink(){if(n(this,Jt))return true;if(!this.parent)return false;let i=n(this,x)&St;return !(i!==Tt&&i!==we||n(this,x)&Ki||n(this,x)&At)}calledReaddir(){return !!(n(this,x)&Rs)}isENOENT(){return !!(n(this,x)&At)}isNamed(i){return this.nocase?n(this,le)===Yi(i):n(this,le)===hi(i)}async readlink(){let i=n(this,Jt);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,Jt,e)}catch(t){m(this,k,_s).call(this,t.code);return}}readlinkSync(){let i=n(this,Jt);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,Jt,e)}catch(t){m(this,k,_s).call(this,t.code);return}}async lstat(){if((n(this,x)&At)===0)try{return m(this,k,zs).call(this,await n(this,ot).promises.lstat(this.fullpath())),this}catch(i){m(this,k,Ms).call(this,i.code);}}lstatSync(){if((n(this,x)&At)===0)try{return m(this,k,zs).call(this,n(this,ot).lstatSync(this.fullpath())),this}catch(i){m(this,k,Ms).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,Ge).push(i),n(this,He))return;f(this,He,true);let s=this.fullpath();n(this,ot).readdir(s,{withFileTypes:true},(r,o)=>{if(r)m(this,k,es).call(this,r.code),e.provisional=0;else {for(let a of o)m(this,k,is).call(this,a,e);m(this,k,ts).call(this,e);}m(this,k,En).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,ke))await n(this,ke);else {let e=()=>{};f(this,ke,new Promise(s=>e=s));try{for(let s of await n(this,ot).promises.readdir(t,{withFileTypes:!0}))m(this,k,is).call(this,s,i);m(this,k,ts).call(this,i);}catch(s){m(this,k,es).call(this,s.code),i.provisional=0;}f(this,ke,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,is).call(this,e,i);m(this,k,ts).call(this,i);}catch(e){m(this,k,es).call(this,e.code),i.provisional=0;}return i.slice(0,i.provisional)}canReaddir(){if(n(this,x)&lr)return false;let i=St&n(this,x);return i===Tt||i===_t||i===we}shouldWalk(i,t){return (n(this,x)&_t)===_t&&!(n(this,x)&lr)&&!i.has(this)&&(!t||t(this))}async realpath(){if(n(this,jt))return n(this,jt);if(!((Zi|Ki|At)&n(this,x)))try{let i=await n(this,ot).promises.realpath(this.fullpath());return f(this,jt,this.resolve(i))}catch{m(this,k,Ps).call(this);}}realpathSync(){if(n(this,jt))return n(this,jt);if(!((Zi|Ki|At)&n(this,x)))try{let i=n(this,ot).realpathSync(this.fullpath());return f(this,jt,this.resolve(i))}catch{m(this,k,Ps).call(this);}}[mn](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,Xt,e.join(this.sep)),f(s,Qt,e.join("/")),s=s.parent,e.push("..");for(s=i;s&&s.parent&&!t.has(s);)f(s,Xt,void 0),f(s,Qt,void 0),s=s.parent;}},ot=new WeakMap,fi=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,le=new WeakMap,Ae=new WeakMap,Wt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Qt=new WeakMap,x=new WeakMap,Ie=new WeakMap,Jt=new WeakMap,jt=new WeakMap,k=new WeakSet,Ds=function(i){let t=this;for(let e of i)t=t.child(e);return t},ts=function(i){var t;f(this,x,n(this,x)|Rs);for(let e=i.provisional;e<i.length;e++){let s=i[e];s&&m(t=s,k,li).call(t);}},li=function(){n(this,x)&At||(f(this,x,(n(this,x)|At)&si),m(this,k,Fs).call(this));},Fs=function(){var t;let i=this.children();i.provisional=0;for(let e of i)m(t=e,k,li).call(t);},Ps=function(){f(this,x,n(this,x)|Zi),m(this,k,ci).call(this);},ci=function(){if(n(this,x)&ai)return;let i=n(this,x);(i&St)===_t&&(i&=si),f(this,x,i|ai),m(this,k,Fs).call(this);},es=function(i=""){i==="ENOTDIR"||i==="EPERM"?m(this,k,ci).call(this):i==="ENOENT"?m(this,k,li).call(this):this.children().provisional=0;},Ms=function(i=""){var t;i==="ENOTDIR"?m(t=this.parent,k,ci).call(t):i==="ENOENT"&&m(this,k,li).call(this);},_s=function(i=""){var e;let t=n(this,x);t|=Ki,i==="ENOENT"&&(t|=At),(i==="EINVAL"||i==="UNKNOWN")&&(t&=si),f(this,x,t),i==="ENOTDIR"&&this.parent&&m(e=this.parent,k,ci).call(e);},is=function(i,t){return m(this,k,bn).call(this,i,t)||m(this,k,yn).call(this,i,t)},yn=function(i,t){let e=Ns(i),s=this.newChild(i.name,e,{parent:this}),r=n(s,x)&St;return r!==_t&&r!==we&&r!==Tt&&f(s,x,n(s,x)|ai),t.unshift(s),t.provisional++,s},bn=function(i,t){for(let e=t.provisional;e<t.length;e++){let s=t[e];if((this.nocase?Yi(i.name):hi(i.name))===n(s,le))return m(this,k,wn).call(this,i,s,e,t)}},wn=function(i,t,e,s){let r=t.name;return f(t,x,n(t,x)&si|Ns(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},zs=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,ki,t),f(this,Ri,e),f(this,Oi,s),f(this,Ii,r),f(this,Ei,o),f(this,Ti,a),f(this,xi,h),f(this,Ai,l),f(this,fi,c),f(this,bi,d),f(this,Si,u),f(this,gi,g),f(this,Li,y),f(this,Ni,w),f(this,mi,b),f(this,wi,S),f(this,vi,E),f(this,yi,A);let I=Ns(i);f(this,x,n(this,x)&si|I|hr),I!==Tt&&I!==_t&&I!==we&&f(this,x,n(this,x)|ai);},Ge=new WeakMap,He=new WeakMap,En=function(i){f(this,He,false);let t=n(this,Ge).slice();n(this,Ge).length=0,t.forEach(e=>e(null,i));},ke=new WeakMap,Wr),Sn=class vn extends ct{constructor(e,s=Tt,r,o,a,h,l){super(e,s,r,o,a,h,l);p(this,"sep","\\");p(this,"splitSep",Aa);}newChild(e,s=Tt,r={}){return new vn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return me.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 $s(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(cn,"$1\\"),e===s}},Tn=class Rn extends ct{constructor(e,s=Tt,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=Tt,r={}){return new Rn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}},qe,Ke,Ci,Di,jr,Nn=(jr=class{constructor(i=process.cwd(),t,e,{nocase:s,childrenCacheSize:r=16*1024,fs:o=oi}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");v(this,qe);v(this,Ke);v(this,Ci);p(this,"nocase");v(this,Di);f(this,Di,ln(o)),(i instanceof URL||i.startsWith("file://"))&&(i=url.fileURLToPath(i));let a=t.resolve(i);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),f(this,qe,new dr),f(this,Ke,new dr),f(this,Ci,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,Di)),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,Ci)}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,qe).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpath();return n(this,qe).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,Ke).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpathPosix();return n(this,Ke).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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new ns({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 ct||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new ns({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[mn](t);}},qe=new WeakMap,Ke=new WeakMap,Ci=new WeakMap,Di=new WeakMap,jr),$s=class extends Nn{constructor(t=process.cwd(),e={}){let{nocase:s=true}=e;super(t,me.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 me.win32.parse(t).root.toUpperCase()}newRoot(t){return new Sn(this.rootPath,_t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Gs=class extends Nn{constructor(t=process.cwd(),e={}){let{nocase:s=false}=e;super(t,me.posix,"/",{...e,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Tn(this.rootPath,_t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},An=class extends Gs{constructor(i=process.cwd(),t={}){let{nocase:e=true}=t;super(i,{...t,nocase:e});}};process.platform==="win32"?Sn:Tn;var La=process.platform==="win32"?$s:process.platform==="darwin"?An:Gs,xa=i=>i.length>=1,Oa=i=>i.length>=1,Ca=Symbol.for("nodejs.util.inspect.custom"),q,ut,K,Le,Pt,Fi,ce,ue,de,Ye,Xe,In=(Xe=class{constructor(t,e,s,r){v(this,q);v(this,ut);v(this,K);p(this,"length");v(this,Le);v(this,Pt);v(this,Fi);v(this,ce);v(this,ue);v(this,de);v(this,Ye,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,ut,e),f(this,K,s),f(this,Le,r),n(this,K)===0){if(this.isUNC()){let[o,a,h,l,...c]=n(this,q),[d,u,g,y,...w]=n(this,ut);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,ut,[S,...w]),this.length=n(this,q).length;}else if(this.isDrive()||this.isAbsolute()){let[o,...a]=n(this,q),[h,...l]=n(this,ut);a[0]===""&&(a.shift(),l.shift());let c=o+"/",d=h+"/";f(this,q,[c,...a]),f(this,ut,[d,...l]),this.length=n(this,q).length;}}}[Ca](){return "Pattern <"+n(this,ut).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,Fi,n(this,Fi)||(n(this,K)===0?this.isAbsolute()?n(this,ut)[0]+n(this,ut).slice(1).join("/"):n(this,ut).join("/"):n(this,ut).slice(n(this,K)).join("/")))}hasMore(){return this.length>n(this,K)+1}rest(){return n(this,Pt)!==void 0?n(this,Pt):this.hasMore()?(f(this,Pt,new Xe(n(this,q),n(this,ut),n(this,K)+1,n(this,Le))),f(n(this,Pt),de,n(this,de)),f(n(this,Pt),ue,n(this,ue)),f(n(this,Pt),ce,n(this,ce)),n(this,Pt)):f(this,Pt,null)}isUNC(){let t=n(this,q);return n(this,ue)!==void 0?n(this,ue):f(this,ue,n(this,Le)==="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,ce)!==void 0?n(this,ce):f(this,ce,n(this,Le)==="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,de)!==void 0?n(this,de):f(this,de,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,Ye))}markFollowGlobstar(){return n(this,K)===0||!this.isGlobstar()||!n(this,Ye)?false:(f(this,Ye,false),true)}},q=new WeakMap,ut=new WeakMap,K=new WeakMap,Le=new WeakMap,Pt=new WeakMap,Fi=new WeakMap,ce=new WeakMap,ue=new WeakMap,de=new WeakMap,Ye=new WeakMap,Xe),Da=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",pr=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 fe(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 In(s,r,0,this.platform),a=new fe(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 kn{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new kn(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())}},fr=class Ln{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 Ln(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 pr([i],t):Array.isArray(i)?new pr(i,t):i,Qe,Vt,xe,Rt,Ee,Ws,Br,xn=(Br=class{constructor(i,t,e){v(this,Rt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);v(this,Qe,[]);v(this,Vt);v(this,xe);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=i,this.path=t,this.opts=e,f(this,xe,!e.posix&&e.platform==="win32"?"\\":"/"),this.includeChildMatches=e.includeChildMatches!==false,(e.ignore||!this.includeChildMatches)&&(f(this,Vt,_a(e.ignore??[],e)),!this.includeChildMatches&&typeof n(this,Vt).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,Qe).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let i;for(;!this.paused&&(i=n(this,Qe).shift());)i();}onResume(i){this.signal?.aborted||(this.paused?n(this,Qe).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,Rt,Ee).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,Rt,Ee).call(this,i))return;if(!this.includeChildMatches&&n(this,Vt)?.add){let r=`${i.relativePosix()}/**`;n(this,Vt).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,xe):"";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,xe))?"."+n(this,xe):"";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 fr(this.opts),e);}walkCB2(i,t,e,s){if(m(this,Rt,Ws).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,Rt,Ee).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,Rt,Ee).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 fr(this.opts),e);}walkCB2Sync(i,t,e,s){if(m(this,Rt,Ws).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,Rt,Ee).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,Rt,Ee).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();}},Qe=new WeakMap,Vt=new WeakMap,xe=new WeakMap,Rt=new WeakSet,Ee=function(i){return this.seen.has(i)||!!n(this,Vt)?.ignored?.(i)},Ws=function(i){return !!n(this,Vt)?.childrenIgnored?.(i)},Br),gr=class extends xn{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}},mr=class extends xn{constructor(t,e,s){super(t,e,s);p(this,"results");this.results=new ns({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",Ce=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=url.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"?$s:t.platform==="darwin"?An:t.platform?Gs: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 fe(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 In(h,c,0,this.platform)});}async walk(){return [...await new gr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new gr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new 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}).stream()}streamSync(){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}).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 fe(e,t).hasMagic())return true;return false};function hs(i,t={}){return new Ce(i,t).streamSync()}function On(i,t={}){return new Ce(i,t).stream()}function Cn(i,t={}){return new Ce(i,t).walkSync()}async function yr(i,t={}){return new Ce(i,t).walk()}function ls(i,t={}){return new Ce(i,t).iterateSync()}function Dn(i,t={}){return new Ce(i,t).iterate()}var ja=hs,Ba=Object.assign(On,{sync:hs}),Ua=ls,$a=Object.assign(Dn,{sync:ls}),Ga=Object.assign(Cn,{stream:hs,iterate:ls}),os=Object.assign(yr,{glob:yr,globSync:Cn,sync:Ga,globStream:On,stream:Ba,globStreamSync:hs,streamSync:ja,globIterate:Dn,iterate:$a,globIterateSync:ls,iterateSync:Ua,Glob:Ce,hasMagic:Wa,escape:Jr,unescape:_e});os.glob=os;var wt;(N=>{N.Level=qa__default.default.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||me__namespace.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");T.logFile?h=me__namespace.default.join(L,T.logFile??"note.log"):h=me__namespace.default.join(L,"note.log");try{await Je__default.default.mkdir(L,{recursive:!0}),c=await Je__default.default.open(h,"a"),d=ha.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 De=Object.entries({...T,...W}).filter(([Ks,te])=>te!=null).map(([Ks,te])=>{let ms=`${Ks}=`;return te instanceof Error?ms+E(te):typeof te=="object"?ms+JSON.stringify(te):ms+te}).join(" "),D=new Date,Mi=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"),"+"+Mi+"ms",De,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 De=Date.now();z.info(F,{status:"started",...W});function D(){z.info(F,{status:"completed",duration:Date.now()-De,...W});}return {stop:D,[Symbol.dispose](){D();}}}};return L&&typeof L=="string"&&o.set(L,z),z}N.create=I;})(wt||(wt={}));var Ut=wt.create({service:"note.tokenizer"}),ge=false,Xa=utils.loadTextFile("./assets/jieba_dict.txt",lt);async function Tl(i){if(!ge)try{Ut.info("Initializing jieba tokenizer");let t=Xa();if(Zt__namespace.with_dict(t),Ut.info("Built-in dictionary loaded"),i?.dictPath&&i.dictPath.length>0)for(let e of i.dictPath)await Qa(e);ge=!0,Ut.info("Jieba tokenizer initialized");}catch(t){throw Ut.error("Failed to initialize jieba tokenizer",{error:String(t)}),t}}async function Qa(i){if(!ge)throw new Error("Tokenizer not initialized");try{let t=await utils.Filesystem.readText(i);Zt__namespace.with_dict(t),Ut.info("Custom dictionary loaded",{dictPath:i});}catch(t){Ut.warn("Failed to load custom dictionary",{dictPath:i,error:String(t)});}}function Ja(i){if(!ge)return i.split(/\s+/).filter(Boolean);try{return Zt__namespace.cut(i)}catch(t){return Ut.warn("Tokenization failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function Va(i){if(!ge)return i.split(/\s+/).filter(Boolean);try{return Zt__namespace.cut_for_search(i)}catch(t){return Ut.warn("Tokenization for search failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function Rl(i,t,e){if(ge)try{Zt__namespace.add_word(i,t,e);}catch(s){Ut.warn("Failed to add word",{word:i,error:String(s)});}}function Nl(){return ge}async function Al(){ge=false,Ut.info("Tokenizer closed");}function Fn(i){return Ja(i).join(" ")}function Pn(i){return Va(i).join(" ")}exports.Llm=void 0;(y=>{let i=wt.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 ai$1.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 ai$1.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 ai$1.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 ai$1.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=types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(I=>`- ${I.type}: ${I.rule}`).join(`
86
- `),S=types.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 U=class{async parse(e){try{let t=await z.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}=utils.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:utils.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 v=chunkF2MSBWJN_cjs.c.create({service:"note.tokenizer"}),F=false,fe=utils.loadTextFile("./assets/jieba_dict.txt",chunkF2MSBWJN_cjs.b);async function rt(E){if(!F)try{v.info("Initializing jieba tokenizer");let e=fe();if(x__namespace.with_dict(e),v.info("Built-in dictionary loaded"),E?.dictPath&&E.dictPath.length>0)for(let t of E.dictPath)await ye(t);F=!0,v.info("Jieba tokenizer initialized");}catch(e){throw v.error("Failed to initialize jieba tokenizer",{error:String(e)}),e}}async function ye(E){if(!F)throw new Error("Tokenizer not initialized");try{let e=await utils.Filesystem.readText(E);x__namespace.with_dict(e),v.info("Custom dictionary loaded",{dictPath:E});}catch(e){v.warn("Failed to load custom dictionary",{dictPath:E,error:String(e)});}}function be(E){if(!F)return E.split(/\s+/).filter(Boolean);try{return x__namespace.cut(E)}catch(e){return v.warn("Tokenization failed, using fallback",{error:String(e)}),E.split(/\s+/).filter(Boolean)}}function Ie(E){if(!F)return E.split(/\s+/).filter(Boolean);try{return x__namespace.cut_for_search(E)}catch(e){return v.warn("Tokenization for search failed, using fallback",{error:String(e)}),E.split(/\s+/).filter(Boolean)}}function nt(E,e,t){if(F)try{x__namespace.add_word(E,e,t);}catch(r){v.warn("Failed to add word",{word:E,error:String(r)});}}function st(){return F}async function it(){F=false,v.info("Tokenizer closed");}function se(E){return be(E).join(" ")}function ie(E){return Ie(E).join(" ")}exports.Llm=void 0;(u=>{let E=chunkF2MSBWJN_cjs.c.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 ai.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 ai.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 ai.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 ai.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=types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(S=>`- ${S.type}: ${S.rule}`).join(`
85
+ `),f=types.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;})(exports.Llm||(exports.Llm={}));var nh=wt.create({service:"note-ingestion"}),oh=new Set(types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(i=>i.type)),ah=new Set(types.GRAPH_RELATION_TYPE_DEFINITIONS.map(i=>i.type)),cs=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 ye,e.embeddingLlm&&exports.Llm.init({models:{embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm,rerankLlm:e.rerankLlm}});}async process(t){let e=utils.Filesystem.toUnixPath(t),{content:s,metadata:r}=await this.parser.parse(t),o=ye.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||me__namespace.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=ye.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=Fn(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 utils.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=ye.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 exports.Llm.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 exports.Llm.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;})(exports.Llm||(exports.Llm={}));var Z=chunkF2MSBWJN_cjs.c.create({service:"note-ingestion"}),ke=new Set(types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(E=>E.type)),De=new Set(types.GRAPH_RELATION_TYPE_DEFINITIONS.map(E=>E.type)),X=class{constructor(e,t){chunkF2MSBWJN_cjs.a(this,"db");chunkF2MSBWJN_cjs.a(this,"config");chunkF2MSBWJN_cjs.a(this,"parser");this.db=e,this.config={...types.DEFAULT_NOTE_CHUNK_CONFIG,...t,embeddingLlm:t.embeddingLlm},this.parser=new U,t.embeddingLlm&&exports.Llm.init({models:{embeddingLlm:t.embeddingLlm,graphLlm:t.graphLlm,rerankLlm:t.rerankLlm}});}async process(e){let t=utils.Filesystem.toUnixPath(e),{content:r,metadata:n}=await this.parser.parse(e),o=U.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),Z.debug("LLM entity extraction completed in background",{path:u,entities:m.entities.length,relations:m.relations.length}));}).catch(m=>{Z.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||___namespace.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,$=[];for(let O=0;O<i.length;O++){let k=i[O],p=k.split(`
121
+ `).length-1;$.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=U.computeHash(k),I=a.get(O)||[],T=$[O],P=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,q=c[O];q&&(this.db.run("INSERT INTO vectors (chunkId, embedding) VALUES (?, ?)",[P,this.float32ToBuffer(q)]),f++);let B=se(k);this.db.run("INSERT INTO chunks_fts (chunkId, documentId, content) VALUES (?, ?, ?)",[P,m,B]),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 utils.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=U.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 exports.Llm.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 exports.Llm.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 exports.Llm.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 exports.Llm.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 us=class{constructor(t,e){p(this,"db");p(this,"config");this.db=t,this.config={...e,embeddingLlm:e.embeddingLlm},e.embeddingLlm&&exports.Llm.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=Pn(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 exports.Llm.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 exports.Llm.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 Mi=W.get(D.source)??[];Mi.push(D),W.set(D.source,Mi);}let De=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:De.length>0?De:void 0,score:N.score,snippet:T.content.slice(0,200),source:e});}return r}};var ds=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 ps=wt.create({service:"note-scanner"}),hh=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.md"],Pi=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=me__namespace.default.join(this.workspaceDir,"docs");s.push({source:"docs",dir:a});}if(this.sources.has("local"))for(let a of this.extraPaths){let h=me__namespace.default.isAbsolute(a)?a:me__namespace.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 Je__default.default.access(t);}catch{return ps.debug("Directory not found, skipping",{dir:t}),s}let r=async o=>{try{let a=await Je__default.default.readdir(o,{withFileTypes:!0});for(let h of a){let l=me__namespace.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){ps.warn("Failed to scan directory",{dir:o,error:String(a)});}};return await r(t),s}async scanFile(t,e="upload"){try{let s=await Je__default.default.stat(t);if(!s.isFile())return null;let r=await Je__default.default.readFile(t,"utf-8"),o=crypto.createHash("sha256").update(r).digest("hex"),a=me__namespace.default.isAbsolute(t)?utils.Filesystem.toUnixPath(me__namespace.default.relative(this.workspaceDir,t)):t;return {absolutePath:t,relativePath:a||me__namespace.default.basename(t),source:e,contentHash:o,lastModified:s.mtimeMs,size:s.size}}catch(s){return ps.error("Failed to scan file",{filePath:t,error:String(s)}),null}}async getFileInfo(t,e){try{let s=await Je__default.default.readFile(t,"utf-8"),r=await Je__default.default.stat(t),o=crypto.createHash("sha256").update(s).digest("hex"),a=utils.Filesystem.toUnixPath(me__namespace.default.relative(this.workspaceDir,t));return {absolutePath:t,relativePath:a,source:e,contentHash:o,lastModified:r.mtimeMs,size:r.size}}catch(s){return ps.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 $t=wt.create({service:"note"}),gs=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||types.getDefaultDatabasePath(xdgBasedir.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:{...types.DEFAULT_SEARCH_CONFIG,...t.search},indexer:{...types.DEFAULT_INDEXER_CONFIG,...t.indexer},sync:{...types.DEFAULT_SYNC_CONFIG,...t.sync},logDir:t.logDir,embeddingLlm:s,graphLlm:t.graphLlm,rerankLlm:t.rerankLlm},this.syncConfig=this.config.sync,this.db=new ji(this.config.database.path),this.pipeline=new cs(this.db,this.config),this.searchEngine=new us(this.db,this.config),this.graphInterface=new ds(this.db),this.fileScanner=new Pi({workspaceDir:this.config.workspaceDir,extraPaths:this.config.extraPaths,sources:this.config.sources,ignorePatterns:this.config?.indexer?.ignorePatterns});}async initialize(){this.initialized||(await wt.init({logDir:this.config.logDir||me__namespace.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),exports.Llm.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){$t.error("Sync failed",{error:String(t)});}},this.syncConfig.intervalMs);}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}async syncAll(){$t.debug("Starting sync...");let t=await this.fileScanner.scanAll((e,s,r)=>{$t.debug("Scanning file",{current:r.relativePath||me__namespace.default.basename(r.absolutePath),total:s});});for(let e of t)try{await this.ingestDocument(e.absolutePath),$t.debug("Ingested file",{path:e.relativePath||me__namespace.default.basename(e.absolutePath)});}catch(s){$t.error("Failed to ingest file",{path:e.relativePath||me__namespace.default.basename(e.absolutePath),error:String(s)});}$t.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=utils.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{$t.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=utils.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){$t.warn("Failed to clear FTS index",{error:String(t)});}$t.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,$t.info("NoteKnowledge closed"));}};async function fh(i){let t=new gs(i);return await t.initialize(),t}Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.FileScanner=Pi;exports.KnowledgeBaseError=j;exports.KnowledgeBaseErrorCode=Fe;exports.NoteKnowledge=gs;exports.addWord=Rl;exports.closeTokenizer=Al;exports.createNoteKnowledge=fh;exports.initTokenizer=Tl;exports.isInitialized=Nl;exports.loadCustomDict=Qa;exports.toFtsTokens=Fn;exports.toFtsTokensForSearch=Pn;exports.tokenize=Ja;exports.tokenizeForSearch=Va;
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){Z.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=ke.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=De.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);}});}};chunkF2MSBWJN_cjs.c.create({service:"note-search"});var Y=class{constructor(e,t){chunkF2MSBWJN_cjs.a(this,"db");chunkF2MSBWJN_cjs.a(this,"config");this.db=e,this.config={...types.DEFAULT_NOTE_CHUNK_CONFIG,...t,embeddingLlm:t.embeddingLlm},t.embeddingLlm&&exports.Llm.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=ie(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 exports.Llm.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 exports.Llm.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(M=>typeof M=="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)])],$=S.length>0?this.db.query("SELECT * FROM nodes WHERE id IN ("+S.map(()=>"?").join(", ")+")",S):[],O=new Map($.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 M=k.get(I.source)??[];M.length<i&&(M.push(I),k.set(I.source,M));let P=k.get(I.target)??[];P.length<i&&(P.push(I),k.set(I.target,P));}for(let p of e){let I=a.get(p.chunkId);if(!I)continue;let T=g.get(I.documentId);if(!T)continue;let M=u.get(I.id)??[],P=M.map(w=>y.get(w)).filter(w=>w!==void 0),q=s&&M.length>0?Array.from(new Map(M.flatMap(w=>k.get(w)??[]).map(w=>[w.id,w])).values()):[],B=new Map;for(let w of q){let re=B.get(w.source)??[];re.push(w),B.set(w.source,re);}let te=P.length>0?P.map(w=>({...w,edges:s?B.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:M,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:te.length>0?te:void 0,score:p.score,snippet:I.content.slice(0,200),source:t});}return n}};var Q=class{constructor(e){chunkF2MSBWJN_cjs.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 V=chunkF2MSBWJN_cjs.c.create({service:"note-scanner"}),Ce=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.md"],W=class{constructor(e){chunkF2MSBWJN_cjs.a(this,"workspaceDir");chunkF2MSBWJN_cjs.a(this,"extraPaths");chunkF2MSBWJN_cjs.a(this,"sources");chunkF2MSBWJN_cjs.a(this,"ignorePatterns");this.workspaceDir=e.workspaceDir,this.extraPaths=e.extraPaths??[],this.sources=new Set(e.sources??["docs"]),this.ignorePatterns=[...Ce,...e.ignorePatterns??[]];}async scanAll(e){let t=[],r=[];for(let s of this.sources){let i=___namespace.default.join(this.workspaceDir,s);r.push({source:s,dir:i});}for(let s of this.extraPaths){let i=___namespace.default.isAbsolute(s)?s:___namespace.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 z__default.default.access(e);}catch{return V.debug("Directory not found, skipping",{dir:e}),r}let n=async o=>{try{let s=await z__default.default.readdir(o,{withFileTypes:!0});for(let i of s){let c=___namespace.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){V.warn("Failed to scan directory",{dir:o,error:String(s)});}};return await n(e),r}async scanFile(e,t="upload"){try{let r=await z__default.default.stat(e);if(!r.isFile())return null;let n=await z__default.default.readFile(e,"utf-8"),o=crypto.createHash("sha256").update(n).digest("hex"),s=___namespace.default.isAbsolute(e)?utils.Filesystem.toUnixPath(___namespace.default.relative(this.workspaceDir,e)):e;return {absolutePath:e,relativePath:s||___namespace.default.basename(e),source:t,contentHash:o,lastModified:r.mtimeMs,size:r.size}}catch(r){return V.error("Failed to scan file",{filePath:e,error:String(r)}),null}}async getFileInfo(e,t){try{let r=await z__default.default.readFile(e,"utf-8"),n=await z__default.default.stat(e),o=crypto.createHash("sha256").update(r).digest("hex"),s=utils.Filesystem.toUnixPath(___namespace.default.relative(this.workspaceDir,e));return {absolutePath:e,relativePath:s,source:t,contentHash:o,lastModified:n.mtimeMs,size:n.size}}catch(r){return V.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=chunkF2MSBWJN_cjs.c.create({service:"note"}),J=class{constructor(e){chunkF2MSBWJN_cjs.a(this,"config");chunkF2MSBWJN_cjs.a(this,"db");chunkF2MSBWJN_cjs.a(this,"pipeline");chunkF2MSBWJN_cjs.a(this,"searchEngine");chunkF2MSBWJN_cjs.a(this,"graphInterface");chunkF2MSBWJN_cjs.a(this,"fileScanner");chunkF2MSBWJN_cjs.a(this,"initialized",false);chunkF2MSBWJN_cjs.a(this,"dirty",false);chunkF2MSBWJN_cjs.a(this,"syncTimer");chunkF2MSBWJN_cjs.a(this,"syncConfig");chunkF2MSBWJN_cjs.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||types.getDefaultDatabasePath(xdgBasedir.xdgData,"note.db");this.config={workspaceDir:t,database:{path:n,walMode:e.database?.walMode??true},vectorDims:e.vectorDims??768,...types.DEFAULT_NOTE_CHUNK_CONFIG,extraPaths:e.extraPaths,sources:e.sources,search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},sync:{...types.DEFAULT_SYNC_CONFIG,...e.sync},logDir:e.logDir,embeddingLlm:r,graphLlm:e.graphLlm,rerankLlm:e.rerankLlm},this.syncConfig=this.config.sync,this.db=new G(this.config.database.path),this.pipeline=new X(this.db,this.config),this.searchEngine=new Y(this.db,this.config),this.graphInterface=new Q(this.db),this.fileScanner=new W({workspaceDir:this.config.workspaceDir,extraPaths:this.config.extraPaths,sources:this.config.sources,ignorePatterns:this.config?.indexer?.ignorePatterns});}async initialize(){if(this.initialized)return;await chunkF2MSBWJN_cjs.c.init({logDir:this.config.logDir||___namespace.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),exports.Llm.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||___namespace.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=utils.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=>utils.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=utils.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 Ue(E){let e=new J(E);return await e.initialize(),e}async function ar(E){let{Log:e}=await import('./chunks/log-LGRFSTIM.cjs'),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")});}Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.FileScanner=W;exports.KnowledgeBaseError=R;exports.KnowledgeBaseErrorCode=H;exports.NoteKnowledge=J;exports.addWord=nt;exports.closeTokenizer=it;exports.createNoteKnowledge=Ue;exports.initLog=ar;exports.initTokenizer=rt;exports.isInitialized=st;exports.loadCustomDict=ye;exports.toFtsTokens=se;exports.toFtsTokensForSearch=ie;exports.tokenize=be;exports.tokenizeForSearch=Ie;