@easbot/codebase 0.3.23 → 0.3.24

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.
Files changed (42) hide show
  1. package/dist/chunks/chunk-4HJ7RFP7.cjs +1 -0
  2. package/dist/chunks/{chunk-UAWXUGY5.cjs → chunk-5E5YY2J3.cjs} +22 -22
  3. package/dist/chunks/{chunk-XXH7ZLAJ.mjs → chunk-AIUVBWJX.mjs} +22 -22
  4. package/dist/chunks/{chunk-GWR5LCUV.mjs → chunk-EWVG3S6R.mjs} +22 -22
  5. package/dist/chunks/chunk-NF6CVHEK.cjs +203 -0
  6. package/dist/chunks/{chunk-3NTIN3AN.cjs → chunk-PLI6SXTS.cjs} +22 -22
  7. package/dist/chunks/chunk-SQJ64NFE.mjs +58 -0
  8. package/dist/chunks/chunk-STDI2Q67.mjs +203 -0
  9. package/dist/chunks/chunk-WC5CUSXD.cjs +58 -0
  10. package/dist/chunks/chunk-ZPEE2LSX.mjs +1 -0
  11. package/dist/chunks/cli-handler-SF3CJR3N.mjs +1 -0
  12. package/dist/chunks/cli-handler-WMBILZ4H.cjs +1 -0
  13. package/dist/chunks/code-base-DJZICYWH.cjs +1 -0
  14. package/dist/chunks/{code-base-HAX5SGRL.mjs → code-base-Y6HLPDF3.mjs} +1 -1
  15. package/dist/chunks/database-manager-MOJW62MZ.cjs +1 -0
  16. package/dist/chunks/database-manager-X7H4U45I.mjs +1 -0
  17. package/dist/chunks/file-watcher-QS442D52.cjs +1 -0
  18. package/dist/chunks/file-watcher-X56TEWNY.mjs +1 -0
  19. package/dist/chunks/stdio-server-OHQSGNMK.cjs +47 -0
  20. package/dist/chunks/stdio-server-OJGV4CSS.mjs +47 -0
  21. package/dist/cli.cjs +1 -1
  22. package/dist/cli.mjs +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +13 -1
  25. package/dist/index.d.ts +13 -1
  26. package/dist/index.mjs +1 -1
  27. package/package.json +8 -8
  28. package/dist/chunks/chunk-A4EAKE3M.mjs +0 -49
  29. package/dist/chunks/chunk-DHH2XXGJ.mjs +0 -203
  30. package/dist/chunks/chunk-HRFLFP6O.cjs +0 -1
  31. package/dist/chunks/chunk-KU6UZET2.cjs +0 -49
  32. package/dist/chunks/chunk-QQXDOGRV.mjs +0 -1
  33. package/dist/chunks/chunk-YY3Z7NGV.cjs +0 -203
  34. package/dist/chunks/cli-handler-7XFZK7GK.cjs +0 -1
  35. package/dist/chunks/cli-handler-H6VHMEHB.mjs +0 -1
  36. package/dist/chunks/code-base-E5TX7O7M.cjs +0 -1
  37. package/dist/chunks/database-manager-WTV3TBJS.cjs +0 -1
  38. package/dist/chunks/database-manager-YGQQHLYR.mjs +0 -1
  39. package/dist/chunks/file-watcher-HVST5PAC.cjs +0 -1
  40. package/dist/chunks/file-watcher-LCQ55MPE.mjs +0 -1
  41. package/dist/chunks/stdio-server-2QHQ7ESX.cjs +0 -47
  42. package/dist/chunks/stdio-server-5YSJE5E5.mjs +0 -47
@@ -0,0 +1,203 @@
1
+ import {l}from'./chunk-34CU2EU4.mjs';import {a as a$1,h,f,c,g,n,e,m}from'./chunk-EWVG3S6R.mjs';import {a as a$2}from'./chunk-GWCRGM4D.mjs';import {a,b}from'./chunk-2YMB6W5S.mjs';import K from'path';import {existsSync,mkdirSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,Shell,Glob,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import Je from'fs/promises';import {createHash}from'crypto';var Oe={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var j=Filesystem.toUnixPath,at=`
2
+ INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4
+ `,ot=`
5
+ INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
6
+ VALUES (?, ?, ?, ?, ?)
7
+ `,ct="DELETE FROM nodes_fts WHERE rowid = (SELECT rowid FROM nodes_fts WHERE id = ?)",dt="INSERT INTO nodes_fts (id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)";var lt=`
8
+ INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
9
+ VALUES (?, ?, ?)
10
+ `,pt=`
11
+ INSERT OR IGNORE INTO embedding_cache (content_hash, embedding)
12
+ VALUES (?, ?)
13
+ `,ut=`
14
+ INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
15
+ VALUES (?, ?, ?)
16
+ `;var We=`
17
+ INSERT INTO unresolved_refs
18
+ (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
20
+ `,ft="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",mt="DELETE FROM nodes WHERE file_path = ?";var gt="DELETE FROM file_hashes WHERE file_path = ?",G="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",yt="DELETE FROM meta WHERE key = ?",le=class{constructor(e,r,t={}){a(this,"db",e);a(this,"writeBackend",r);a(this,"options",t);}insertNodes(e){if(e.length===0)return;let r=[];for(let t of e){let i=j(t.file_path);r.push({sql:at,params:[t.id,t.name,t.ast_type,t.language,i,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at]}),this.options.ftsAvailable&&(r.push({sql:ct,params:[t.id]}),r.push({sql:dt,params:[t.id,t.name,t.ast_type,t.language,i,t.text]}));}this.writeBackend.enqueue(r);}insertEdges(e){if(e.length===0)return;let r=[];for(let t of e)r.push({sql:ot,params:[t.id,t.source,t.target,t.relation,t.created_at]});this.writeBackend.enqueue(r);}insertUnresolvedRef(e){this.writeBackend.enqueue([{sql:We,params:[e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,j(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null]}]);}insertUnresolvedRefsBatch(e){if(e.length===0)return;let r=e.map(t=>({sql:We,params:[t.fromNodeId??null,t.referenceName,t.referenceKind,t.line??null,t.col??null,j(t.filePath),t.language,t.candidates?JSON.stringify(t.candidates):null]}));this.writeBackend.enqueue(r);}setFileHash(e,r){this.writeBackend.enqueue([{sql:lt,params:[j(e),r,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,r){this.writeBackend.enqueue([{sql:pt,params:[e,Buffer.from(r.buffer,r.byteOffset,r.byteLength)]}]);}storeNodeEmbeddings(e){if(e.length===0)return;let r=[];for(let t of e)r.push({sql:ut,params:[t.nodeId,t.embeddingText,Buffer.from(t.embedding.buffer,t.embedding.byteOffset,t.embedding.byteLength)]});this.writeBackend.enqueue(r);}deleteEdgesByFile(e){let r=j(e);return this.writeBackend.enqueue([{sql:ft,params:[r,r]}]),-1}deleteNodesByFile(e){let r=j(e);return this.writeBackend.enqueue([{sql:mt,params:[r]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:gt,params:[j(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,r){this.writeBackend.enqueue([{sql:G,params:[e,r]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:yt,params:[e]}]);}markIndexed(e,r,t){let i=[{sql:G,params:["indexed_with_version",e]},{sql:G,params:["indexed_with_extraction_version",String(r)]},{sql:G,params:["index_state","complete"]},{sql:G,params:["last_index_state_change",t]}];this.writeBackend.enqueue(i);}setIndexState(e){let r=new Date().toISOString(),t=[{sql:G,params:["index_state",e]},{sql:G,params:["last_index_state_change",r]}];this.writeBackend.enqueue(t);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function ht(){return `
21
+ const { parentPort } = require('node:worker_threads');
22
+
23
+ if (parentPort !== null) {
24
+ const port = parentPort;
25
+ let queueDepth = 0;
26
+
27
+ port.on('message', (msg) => {
28
+ if (msg.type === 'shutdown') {
29
+ const reqId = msg.requestId;
30
+ // \u7B49\u961F\u5217 drain \u518D exit\uFF08\u4EFF Real worker drainInterval \u6A21\u5F0F\uFF09
31
+ const drainInterval = setInterval(() => {
32
+ if (queueDepth === 0) {
33
+ clearInterval(drainInterval);
34
+ port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
35
+ process.exit(0);
36
+ }
37
+ }, 5);
38
+ return;
39
+ }
40
+ if (msg.type === 'ping') {
41
+ port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
42
+ return;
43
+ }
44
+ if (msg.type === 'open') {
45
+ port.postMessage({ type: 'open_ack', requestId: msg.requestId });
46
+ return;
47
+ }
48
+ if (msg.type === 'flush') {
49
+ port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
50
+ return;
51
+ }
52
+ if (msg.type === 'write_batch') {
53
+ const reqId = msg.requestId;
54
+ queueDepth++;
55
+ const affected = (msg.statements || []).reduce((sum, s) => sum + (s.affectedRows || 0), 0);
56
+ setTimeout(() => {
57
+ queueDepth--;
58
+ port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
59
+ }, 10);
60
+ }
61
+ });
62
+
63
+ port.postMessage({ type: 'ready' });
64
+ }
65
+ `}function Be(){return new Worker(ht(),{eval:true})}function _t(y){return `
66
+ const { parentPort } = require('node:worker_threads');
67
+
68
+ if (parentPort !== null) {
69
+ const port = parentPort;
70
+ let Database;
71
+ try {
72
+ Database = require(${JSON.stringify(y)});
73
+ } catch (err) {
74
+ port.postMessage({ type: 'error', requestId: -1, error: 'better-sqlite3 not loadable at ${y}: ' + err.message });
75
+ process.exit(1);
76
+ }
77
+
78
+ let db = null;
79
+ let queueDepth = 0;
80
+ const queueMax = 1000;
81
+ // Wave 5 \u5927\u4ED3 sync \u4F18\u5316\uFF1A\u5355 batch timeout \u52A0\u5927\u5230 5min\uFF08100 \u6761 SQL + WAL fsync \u5927\u6587\u4EF6\u53EF\u80FD\u8D85 30s\uFF09
82
+ // \u4E4B\u524D 30s \u5728 30K files \u5927\u4ED3\u4E0A\u4F1A\u5047\u9633\u6027 timeout \u2014\u2014 \u5B9E\u9645\u662F WAL fsync \u7B49 IO \u800C\u4E0D\u662F\u5361\u6B7B
83
+ const txTimeoutMs = 300000;
84
+ // Wave 5 \u5927\u4ED3 sync \u4F18\u5316\uFF1Astatement cache \u2014\u2014 30K files \xD7 11 stmts = 330K \u6B21 prepare \u592A\u6162
85
+ // \u5B9E\u6D4B 1407 files sync \u8DD1\u5230 53% \u65F6 5min flush timeout \u2014\u2014 \u6839\u56E0\u662F\u91CD\u590D prepare
86
+ // \u4FEE\uFF1AMap<sql, prepared statement> \u7F13\u5B58\uFF0C\u540C SQL \u6A21\u677F\u590D\u7528 prepared \u5BF9\u8C61
87
+ const stmtCache = new Map();
88
+
89
+ function getPrepared(sql) {
90
+ let prepared = stmtCache.get(sql);
91
+ if (!prepared) {
92
+ prepared = db.prepare(sql);
93
+ stmtCache.set(sql, prepared);
94
+ }
95
+ return prepared;
96
+ }
97
+
98
+ function runStatement(stmt) {
99
+ try {
100
+ const prepared = getPrepared(stmt.sql);
101
+ const info = prepared.run(...(stmt.params || []));
102
+ return info.changes || 0;
103
+ } catch (err) {
104
+ // Wave 4 R3-2\uFF1Aworker \u7AEF debug \u65E5\u5FD7 \u2014\u2014 \u771F\u51F6\u96BE\u8FFD\uFF0C\u52A0\u8BE6\u7EC6 error \u4FE1\u606F
105
+ // \u8F93\u51FA SQL + params + error \u8BE6\u60C5\uFF08\u901A\u8FC7 stderr \u2192 \u4E3B\u8FDB\u7A0B\uFF09
106
+ port.postMessage({
107
+ type: 'debug_error',
108
+ requestId: -1,
109
+ sql: stmt.sql,
110
+ paramsCount: (stmt.params || []).length,
111
+ paramsJson: JSON.stringify(stmt.params || []).slice(0, 500),
112
+ error: err.message,
113
+ });
114
+ throw err;
115
+ }
116
+ }
117
+
118
+ port.on('message', (msg) => {
119
+ if (msg.type === 'shutdown') {
120
+ const reqId = msg.requestId;
121
+ const drainInterval = setInterval(() => {
122
+ if (queueDepth === 0) {
123
+ clearInterval(drainInterval);
124
+ try { if (db) db.close(); } catch (e) {}
125
+ port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
126
+ process.exit(0);
127
+ }
128
+ }, 5);
129
+ return;
130
+ }
131
+ if (msg.type === 'ping') {
132
+ port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
133
+ return;
134
+ }
135
+ if (msg.type === 'open') {
136
+ const reqId = msg.requestId;
137
+ try {
138
+ if (db) db.close();
139
+ db = new Database(msg.dbPath, { timeout: txTimeoutMs });
140
+ db.pragma('journal_mode = WAL');
141
+ db.pragma('synchronous = NORMAL');
142
+ // Wave 3 \u8BC4\u5BA1 R3\uFF1Aworker \u4E5F\u8981\u5F00 FK \u7EA7\u8054 \u2014\u2014 \u5220 nodes \u81EA\u52A8\u7EA7\u8054\u6E05 node_embeddings / edges
143
+ db.pragma('foreign_keys = ON');
144
+ port.postMessage({ type: 'open_ack', requestId: reqId });
145
+ } catch (err) {
146
+ port.postMessage({ type: 'error', requestId: reqId, error: err.message });
147
+ }
148
+ return;
149
+ }
150
+ if (msg.type === 'flush') {
151
+ port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
152
+ return;
153
+ }
154
+ if (msg.type === 'write_batch') {
155
+ const reqId = msg.requestId;
156
+ if (!db) {
157
+ port.postMessage({ type: 'error', requestId: reqId, error: 'db not open' });
158
+ return;
159
+ }
160
+ if (queueDepth >= queueMax) {
161
+ port.postMessage({ type: 'error', requestId: reqId, error: 'queue overflow (' + queueDepth + '/' + queueMax + ')' });
162
+ return;
163
+ }
164
+ queueDepth++;
165
+ try {
166
+ // ADR 0080 (FK + wildcard target fix): CALLS / IMPORTS edge targets are wildcards
167
+ // ('ts:*:*:calleeName', resolved in resolution stage) \u2014 by design NOT in nodes table.
168
+ // edges FK (source/target) \u2192 nodes(id) makes every CALLS / IMPORTS INSERT FK-fail,
169
+ // rolling back the whole transaction \u2192 caller sees success:true but db is empty.
170
+ // Fix: disable FK at write_batch start (connection-level PRAGMA, before transaction),
171
+ // restore at end. Preserves ON DELETE CASCADE behavior (still active outside worker
172
+ // write_batch, via main db.pragma('foreign_keys=ON') + worker open).
173
+ // NOTE: PRAGMA inside db.transaction() callback is unreliable in better-sqlite3
174
+ // (pragma may be buffered until tx commit), so set PRAGMA outside tx wrapper.
175
+ db.pragma('foreign_keys = OFF');
176
+ let affected = 0;
177
+ try {
178
+ const tx = db.transaction((statements) => {
179
+ let totalChanges = 0;
180
+ for (const stmt of statements) {
181
+ totalChanges += runStatement(stmt);
182
+ }
183
+ return totalChanges;
184
+ });
185
+ affected = tx(msg.statements || []);
186
+ } finally {
187
+ db.pragma('foreign_keys = ON');
188
+ }
189
+ port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
190
+ } catch (err) {
191
+ port.postMessage({ type: 'error', requestId: reqId, error: err.message });
192
+ } finally {
193
+ queueDepth--;
194
+ }
195
+ }
196
+ });
197
+
198
+ port.postMessage({ type: 'ready' });
199
+ }
200
+ `}function Se(y,e){return new Worker(_t(e.betterSqlite3Path),{eval:true})}var ue=Log.create({service:"codebase.better-sqlite3-resolver"}),He=createRequire(import.meta.url);async function $e(y={}){try{let a=He.resolve("better-sqlite3");if(a)return ue.debug("better-sqlite3 resolved from monorepo",{resolved:a}),{absolutePath:Filesystem.normalize(a),source:"monorepo"}}catch(a){ue.debug("better-sqlite3 not in current resolve paths",{error:a instanceof Error?a.message:String(a)});}let e=process.env.EASBOT_CACHE_PATH,r=y.installPath??e??`${process.cwd()}/.easbot/cache`,t=Filesystem.normalize(r),i=y.version??"latest";ue.info("better-sqlite3 not found locally, installing to cache",{installPath:t,version:i,envCache:e});let n;try{n=await Shell.install("better-sqlite3",i,t);}catch(a){throw new fe(`Failed to install better-sqlite3@${i} into ${t}: ${a instanceof Error?a.message:String(a)}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,t)}try{let a=He.resolve("better-sqlite3",{paths:[n]}),o=Filesystem.normalize(a),d=t===Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return ue.info("better-sqlite3 installed and resolved",{resolved:o,installPath:t}),{absolutePath:o,source:d}}catch(a){throw new fe(`Installed better-sqlite3 to ${n} but cannot resolve entry from there: ${a instanceof Error?a.message:String(a)}`,n)}}var fe=class extends Error{constructor(r,t){super(r);a(this,"installPath");this.name="BetterSqlite3ResolveError",this.installPath=t;}};var ie=Log.create({service:"database.async-write"}),Ne,re,me=class{constructor(e){a(this,"worker");a(this,"mock");a(this,"dbPath");a(this,"batchSize");a(this,"batchIntervalMs");a(this,"queueMax");a(this,"bufferedStatements",[]);a(this,"pendingRequests",new Map);a(this,"nextRequestId",1);a(this,"flushTimer",null);a(this,"ready");a(this,"disposed",false);a(this,"lastBatchError",null);if(this.dbPath=e.dbPath,this.mock=e.mock??false,this.batchSize=e.batchSize??100,this.batchIntervalMs=e.batchIntervalMs??50,this.queueMax=e.queueMax??1e3,this.mock)this.worker=Be(),this.ready=this.waitForReady();else {let r=e.betterSqlite3Path;r?(this.worker=Se(this.dbPath,{betterSqlite3Path:r}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await Et();this.worker=Se(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",r=>{let t=r;if(t.type==="debug_error"){ie.error("AsyncWriteBackend statement failed (debug)",{sql:t.sql?.slice(0,200),paramsCount:t.paramsCount,params:t.paramsJson,error:t.error});return}if(typeof t.requestId!="number"||t.requestId<1)return;let i=this.pendingRequests.get(t.requestId);if(i){if(this.pendingRequests.delete(t.requestId),clearTimeout(i.timer),t.type==="write_batch_ack")i.resolve();else if(t.type==="error"){let n=new Error(t.error??"worker write error");this.lastBatchError={error:n,timestamp:Date.now()},i.reject(n);}}});}requireWorker(){if(!this.worker)throw new Error("AsyncWriteBackend worker not initialized yet (call installAckHandler / waitForReady only after spawn)");return this.worker}waitForReady(){let e=this.requireWorker();return new Promise((r,t)=>{let i=setTimeout(()=>t(new Error("worker init timeout")),1e4),n=a=>{if(a.type==="ready"){clearTimeout(i),e.off("message",n);let o=setTimeout(()=>t(new Error("worker open timeout")),1e4),d=c=>{c.type==="open_ack"&&c.requestId===0?(clearTimeout(o),e.off("message",d),r()):c.type==="error"&&c.requestId===0&&(clearTimeout(o),e.off("message",d),t(new Error(c.error??"worker open error")));};e.on("message",d),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else a.type==="error"&&a.requestId===-1&&(clearTimeout(i),e.off("message",n),t(new Error(a.error??"unknown init error")));};e.on("message",n);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new Error("AsyncWriteBackend \u5DF2 dispose");if(!this.worker)throw new Error("AsyncWriteBackend worker not ready yet (await backend.ready before enqueue)");let r=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+r>=this.queueMax)throw new Error(`AsyncWriteBackend queue overflow (pending=${this.pendingRequests.size}, buffered=${this.bufferedStatements.length}, max=${this.queueMax})`);this.bufferedStatements.push(...e),this.bufferedStatements.length>=this.batchSize?this.flushBuffer():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flushBuffer(),this.batchIntervalMs));}flushBuffer(){if(!this.worker||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.bufferedStatements.length===0))return;let e=this.bufferedStatements;this.bufferedStatements=[];let r=this.nextRequestId++,t={resolve:()=>{},reject:i=>{ie.error("AsyncWriteBackend write failed",{error:i.message,requestId:r});},timer:setTimeout(()=>{this.pendingRequests.delete(r),t.reject(new Error(`AsyncWriteBackend write timeout (${r})`));},3e4)};this.pendingRequests.set(r,t),this.worker.postMessage({type:"write_batch",statements:e,requestId:r});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT??"3600000",10)||36e5){let r=this.lastBatchError;if(this.lastBatchError=null,this.flushBuffer(),this.pendingRequests.size===0){if(r)throw new Error(`AsyncWriteBackend flush failed (deferred from previous batch): ${r.error.message}`);return}let t=this.pendingRequests.size,i=Date.now();await new Promise((a,o)=>{let d=setTimeout(()=>o(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),c=setInterval(()=>{let p=this.pendingRequests.size,u=Math.floor((Date.now()-i)/1e3);p>0&&u>0&&u%5===0&&ie.info("flush in progress",{pending:p,initial:t,elapsedSec:u});},1e3),l=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(d),clearInterval(l),clearInterval(c),a());},5);});let n=this.lastBatchError;if(n!==null)throw this.lastBatchError=null,new Error(`AsyncWriteBackend flush failed: ${n.error.message}`)}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){ie.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:e instanceof Error?e.message:String(e)});}this.worker&&(this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate());}pendingCount(){return this.pendingRequests.size}getLastBatchError(){return this.lastBatchError}clearLastBatchError(){this.lastBatchError=null;}};async function Et(){return Ne||(re||(re=$e().then(y=>(Ne=y.absolutePath,re=void 0,ie.info("better-sqlite3 resolved for AsyncWriteBackend",{path:y.absolutePath,source:y.source}),y.absolutePath)).catch(y=>{throw re=void 0,y})),re)}var je=Log.create({service:"codebase-parser"}),It={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"},zig:{package:"@tree-sitter-grammars/tree-sitter-zig",wasmFile:"tree-sitter-zig.wasm"}};function Pt(){return typeof import.meta<"u"&&import.meta.url?K.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function Ct(y,e){let r=Pt(),t=r;for(let i=0;i<10;i++){let n=K.join(t,"node_modules",y,e);if(Filesystem.stat(n)!==void 0)return n;let a=K.dirname(t);if(a===t)break;t=a;}return K.join(r,"node_modules",y,e)}var V=class{constructor(){a(this,"parsers",new Map);a(this,"initialized",false);a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),r=e.default?.default||e.default?.Parser||e.default||e.Parser,t=r?.Language||e.Language||e.default?.Language;if(typeof r?.init=="function"&&await r.init(),typeof r!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof r}`);if(typeof t!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof t}`);let i=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],n=await Promise.allSettled(i.map(async a=>{try{let o=It[a];if(!o)return je.warn("No WASM config for language",{lang:a}),null;let d=Ct(o.package,o.wasmFile),c=await t.load(d),l=new r;return l.setLanguage(c),{lang:a,parser:l,language:c}}catch(o){return je.warn("Failed to load parser",{lang:a,error:String(o)}),null}}));for(let a of n)if(a.status==="fulfilled"&&a.value){let{lang:o,parser:d,language:c}=a.value;this.parsers.set(o,{parser:d,language:c});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let r=K.extname(e).toLowerCase();return Oe[r]??null}parse(e,r){if(!this.initialized)throw new a$1("Parser not initialized","");let t=this.parsers.get(r);if(!t)throw new a$1(`No parser available for language: ${r}`,"");try{return t.parser.parse(e)}catch(i){throw new a$1("Failed to parse code","",i instanceof Error?i:new Error(String(i)))}}parseFile(e,r){let t=this.detectLanguage(e);if(!t)throw new h(K.extname(e),e);return this.parse(r,t)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},r=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let t of r)e[t]=this.parsers.has(t);return e}dispose(){this.parsers.clear(),this.initialized=false;}},Q=null;async function kt(){return Q||(Q=new V,await Q.initialize()),Q}function Rt(){Q&&(Q.dispose(),Q=null);}var q={class_declaration:"class_declaration",class_item:"class_declaration",class_definition:"class_declaration",abstract_class_declaration:"class_declaration",class_specifier:"class_declaration",record_declaration:"class_declaration",interface_declaration:"interface_declaration",protocol_declaration:"interface_declaration",function_declaration:"function_definition",function_definition:"function_definition",function_item:"function_definition",function_expression:"function_definition",arrow_function:"function_definition",method_definition:"method_definition",method_declaration:"method_definition",method:"method_definition",method_invocation:"method_definition",public_field_definition:"property_declaration",field_definition:"property_declaration",property_signature:"property_declaration",field_declaration:"field_declaration",property_declaration:"property_declaration",val_definition:"property_declaration",var_definition:"property_declaration",variable_declaration:"variable_declaration",lexical_declaration:"variable_declaration",variable_declarator:"variable_declaration",assignment:"variable_declaration",module:"module_declaration",internal_module:"module_declaration",ambient_declaration:"module_declaration",namespace_declaration:"module_declaration",namespace_definition:"module_declaration",mod_item:"module_declaration",import_declaration:"import_declaration",import_statement:"import_declaration",import_from_statement:"import_declaration",use_declaration:"import_declaration",use_list:"import_declaration",using_directive:"import_declaration",require:"import_declaration",require_relative:"import_declaration",preproc_include:"import_declaration",include_directive:"import_declaration",struct_declaration:"struct_declaration",struct_definition:"struct_declaration",struct_item:"struct_declaration",struct_specifier:"struct_declaration",trait_item:"trait_declaration",trait_definition:"trait_declaration",impl_item:"impl_item",enum_declaration:"enum_declaration",enum_item:"enum_declaration",enum_specifier:"enum_declaration",type_alias_declaration:"type_alias_declaration",type_declaration:"type_declaration",class:"class_declaration",decorator:"decorator",annotation:"annotation",marker_annotation:"annotation",attribute:"attribute",attribute_item:"attribute",modifiers:"modifiers",decorated_expression:"decorator",attribute_decorator:"decorator",export_statement:"export_statement",const_item:"constant_declaration",constant_declaration:"constant_declaration",function:"function_definition"},ve={language:"ts",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["module","internal_module","ambient_declaration"],methodTypes:["method_definition","function_declaration"],propertyTypes:["public_field_definition","property_signature"],functionTypes:["function_declaration"],typeAliasTypes:["type_alias_declaration"],enumTypes:["enum_declaration"],importTypes:["import_statement"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["member_expression"],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","type_identifier","property_identifier"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:["export_statement"],ambientDeclarationTypes:["ambient_declaration"]},normalizeMap:q,inheritance:{extendsClauseTypes:["extends_clause","extends_type_clause"],implementsClauseTypes:["implements_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","abstract_class_declaration","function_declaration","method_definition","export_statement"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},At={...ve,language:"tsx"},Ft={language:"js",rawTypes:{classTypes:["class_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_definition"],propertyTypes:["public_field_definition","field_definition"],functionTypes:["function_declaration","function_expression","arrow_function"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["member_expression"],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","property_identifier"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},Mt={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],callExpressionTypes:["call"],memberAccessTypes:["attribute"],contextualKeywordTypes:[],identifierTypes:["identifier"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["argument_list","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["function_definition","class_definition","decorated_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["identifier","typed_parameter","default_parameter","list_splat_pattern","dictionary_splat_pattern"],typeInWrapper:["type","identifier"],declaratorStyle:"wrapper"}},Lt={language:"java",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["import_declaration"],callExpressionTypes:["method_invocation","object_creation_expression"],memberAccessTypes:[],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","type_identifier"],annotationTypes:["annotation","marker_annotation","modifiers"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["superclass","extends_clause"],implementsClauseTypes:["super_interfaces","implements_clause","interface_list"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration","interface_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["formal_parameter"],typeInWrapper:["type_identifier","generic_type","array_type","integral_type","floating_point_type","boolean_type"],declaratorStyle:"wrapper"}},qt={language:"csharp",rawTypes:{classTypes:["class_declaration","record_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration","property_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["using_directive"],callExpressionTypes:["invocation_expression","new_expression","object_creation_expression"],memberAccessTypes:["member_access_expression"],contextualKeywordTypes:["this","base"],identifierTypes:["identifier","type_identifier"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["base_list","super"],implementsClauseTypes:["base_list"],fallbackToFirstIdentifier:true,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["parameter"],typeInWrapper:["predefined_type","identifier","generic_name","array_type","nullable_type"],declaratorStyle:"wrapper"}},Dt={language:"c",rawTypes:{classTypes:["struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],callExpressionTypes:["call_expression"],memberAccessTypes:["field_expression"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier","field_identifier"],annotationTypes:[],variableTypes:["declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","union_specifier","enum_specifier"],declaratorStyle:"declarator"}},Ot={language:"cpp",rawTypes:{classTypes:["class_specifier","struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["field_expression"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier","field_identifier","pointer_type","reference_type","qualified_identifier"],annotationTypes:["attribute"],variableTypes:["declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["base_class_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_specifier","function_definition"]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","class_specifier","enum_specifier","scoped_identifier","template_type","auto"],declaratorStyle:"declarator"}},Wt={language:"rs",rawTypes:{classTypes:["struct_item","enum_item","impl_item"],interfaceTypes:["trait_item"],moduleTypes:["mod_item"],methodTypes:["function_item"],propertyTypes:["field_declaration"],functionTypes:["function_item"],typeAliasTypes:["type_declaration"],enumTypes:["enum_item"],importTypes:["use_declaration"],callExpressionTypes:["call_expression"],memberAccessTypes:["field_expression","scoped_identifier"],contextualKeywordTypes:["Self"],identifierTypes:["identifier","type_identifier"],annotationTypes:["attribute_item"],variableTypes:["const_item"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_item","struct_item","trait_item"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","reference_type","slice_type","array_type","generic_type","scoped_identifier","pointer_type","unit_type","never_type"],declaratorStyle:"wrapper"}},zt={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],callExpressionTypes:["call_expression"],memberAccessTypes:["selector_expression"],contextualKeywordTypes:[],identifierTypes:["identifier","type_identifier","field_identifier"],annotationTypes:[],variableTypes:[],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","variadic_parameter"],typeInWrapper:["type_identifier","pointer_type","slice_type","map_type","channel_type","array_type","function_type","qualified_type","generic_type"],declaratorStyle:"wrapper"}},Bt={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],callExpressionTypes:["call"],memberAccessTypes:["constant"],contextualKeywordTypes:["self"],identifierTypes:["identifier","constant"],annotationTypes:[],variableTypes:["assignment"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"method_parameters",paramTypes:["identifier","required_parameter","optional_parameter","splat_parameter","hash_splat_parameter","block_parameter","keyword_rest_parameter"],typeInWrapper:[],declaratorStyle:"wrapper"}},Ht={language:"php",rawTypes:{classTypes:["class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["namespace_definition"],methodTypes:["method_declaration"],propertyTypes:["property_declaration"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["namespace_use_declaration"],callExpressionTypes:["function_call_expression","member_call_expression","scoped_call_expression","object_creation_expression"],memberAccessTypes:["member_call_expression"],contextualKeywordTypes:[],identifierTypes:["name","variable_name"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["base_clause"],implementsClauseTypes:["class_interface_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","method_declaration","function_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["simple_parameter","variadic_parameter","property_promotion_parameter"],typeInWrapper:["named_type","primitive_type","optional_type"],declaratorStyle:"wrapper"}},$t={language:"scala",rawTypes:{classTypes:["class_definition"],interfaceTypes:["trait_definition"],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["val_definition","var_definition"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_declaration"],callExpressionTypes:["call_expression","call","instance_expression"],memberAccessTypes:["field_expression","select","stable_identifier","field_access"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier"],annotationTypes:["annotation"],variableTypes:["val_definition","var_definition"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:["extends_clause"],implementsClauseTypes:["with_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_definition","class_definition","trait_definition"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","generic_type","scoped_type_identifier","function_type","tuple_type","refined_type"],declaratorStyle:"wrapper"}},jt={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],callExpressionTypes:["call_expression","builtin_call_expression"],memberAccessTypes:["field_access","field_expression"],contextualKeywordTypes:[],identifierTypes:["identifier","type_identifier"],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:q,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["identifier","optional_type","array_type","pointer_type","slice_type"],declaratorStyle:"wrapper"}},Ge=new Map([["ts",ve],["tsx",At],["js",Ft],["py",Mt],["java",Lt],["csharp",qt],["c",Dt],["cpp",Ot],["rs",Wt],["go",zt],["php",Ht],["scala",$t],["zig",jt],["ruby",Bt]]);function R(y){return Ge.get(y)??ve}Array.from(Ge.keys());function Qe(y){let e=R(y),r=new Set;for(let t of [e.rawTypes.classTypes,e.rawTypes.interfaceTypes,e.rawTypes.moduleTypes,e.rawTypes.methodTypes,e.rawTypes.propertyTypes,e.rawTypes.functionTypes,e.rawTypes.typeAliasTypes,e.rawTypes.enumTypes,e.rawTypes.importTypes,e.rawTypes.annotationTypes,e.rawTypes.variableTypes,e.rawTypes.exportTypes,e.rawTypes.ambientDeclarationTypes])for(let i of t)r.add(i);return r}function Ue(y){let e=R(y),r=new Set;for(let t of e.rawTypes.methodTypes)r.add(t);for(let t of e.rawTypes.propertyTypes)r.add(t);return r}function Ke(y){let e=R(y);return new Set(e.rawTypes.identifierTypes)}function P(y,e){return R(y).normalizeMap[e]??e}var Y=class{extractNodes(e,r,t,i){let n=[],a=r.split(`
201
+ `),o=Qe(t),d=Ue(t),c=Ke(t);return this.walkTree(e.rootNode,n,t,i,a,o,d,c),n}walkTree(e,r,t,i,n,a,o,d,c,l){if(a.has(e.type)){let p=this.extractNode(e,t,i,n,c,l,o,d);p&&(r.push(p),p.name&&(c=this.generateNodeId(p)),o.has(e.type)||(l=p.name??l));}for(let p=0;p<e.childCount;p++){let u=e.children[p];u&&this.walkTree(u,r,t,i,n,a,o,d,c,l);}}extractNode(e,r,t,i,n,a,o,d){let c=this.getNodeName(e,r,d);if(!c)return null;let l=e.startPosition,p=e.endPosition,u=this.getNodeText(e,i),f=o.has(e.type),m=f&&a?`${a}.${c}@${l.row+1}`:c,x=f?this.extractParameterTypes(e,r):[];return {name:m,ast_type:P(r,e.type),language:r,file_path:t,start_line:l.row+1,start_col:l.column,end_line:p.row+1,end_col:p.column,text:u,parent_id:n,metadata:f?{originalName:c,parameterTypes:x}:void 0}}extractParameterTypes(e,r){let i=R(r).parameters;if(!i)return [];let n=new Set(i.typeInWrapper),a=[],o=d=>{for(let c of d.children)if(c.type===i.wrapperType)return c;return null};if(i.declaratorStyle==="declarator"){for(let d of e.children)if(d.type==="function_declarator"||d.type==="pointer_declarator"){let c=o(d);if(c){for(let l of c.children)if(i.paramTypes.includes(l.type)){let p=this.findTypeInNode(l,n);p&&a.push(p);}return a}}}else {let d=o(e);if(d){for(let c of d.children)if(i.paramTypes.includes(c.type)){let l=this.findTypeInNode(c,n);l&&a.push(l);}}}return a}findTypeInNode(e,r){for(let t of e.children)if(r.has(t.type))return t.text;return null}getNodeName(e,r,t){switch(e.type){case "class_declaration":case "class_definition":case "abstract_class_declaration":case "class":case "interface_declaration":case "protocol_declaration":case "trait_item":case "trait_definition":case "struct_item":case "struct_declaration":case "struct_definition":case "struct_specifier":case "enum_item":case "enum_declaration":case "enum_specifier":case "type_alias_declaration":case "record_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"],t);case "function_declaration":case "function_definition":case "function_item":case "function_expression":case "arrow_function":case "function":case "method_definition":case "method_declaration":case "method":case "method_invocation":case "singleton_method":return this.findNameInChildren(e,["name","property_identifier","function_name"],t)??this.findNameInGrandchildren(e,["function_declarator","declarator","name"],["identifier","property_identifier","field_identifier","name"],t);case "public_field_definition":case "field_definition":case "field_declaration":case "property_signature":case "property_declaration":case "val_definition":case "var_definition":return this.findNameInGrandchildren(e,["variable_declarator","declarator","property_element"],["identifier","name"],t)??this.findNameInChildren(e,["name","property_identifier","field_identifier"],t);case "module":case "internal_module":case "ambient_declaration":case "namespace_declaration":case "namespace_definition":case "mod_item":case "type_declaration":if(e.type==="namespace_definition"){for(let n of e.children)if(n.type==="namespace_name")return n.text}return this.findNameInChildren(e,["name","identifier"],t)??this.findNameInGrandchildren(e,["type_spec","type_alias","namespace_name"],["type_identifier","identifier","name"],t);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"],t)??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"],t);case "import_declaration":case "import_statement":case "import_from_statement":case "use_declaration":case "use_list":case "namespace_use_declaration":case "namespace_use_clause":case "using_directive":case "require":case "require_relative":case "preproc_include":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"],t);case "attribute_item":case "attribute":case "annotation":case "marker_annotation":case "decorator":return this.findNameInChildren(e,["name","identifier"],t)??this.findNameInGrandchildren(e,["attribute","decorator"],["identifier","name","token_tree"],t);default:return this.findNameInChildren(e,["name","identifier"],t)}}findNameInChildren(e,r,t){for(let i of r){let n=e.childForFieldName?.(i);if(n?.text)return n.text}for(let i of e.children)if(t.has(i.type))return i.text;return null}findNameInGrandchildren(e,r,t,i){for(let n of e.children)if(r.includes(n.type)){let a=this.findNameInChildren(n,t,i);if(a)return a}return null}extractImportName(e){for(let r of e.children)if(r.type==="string"||r.type==="string_literal"||r.type==="module_name"||r.type==="identifier"||r.type==="dotted_name"){let t=r.text;return (t.startsWith('"')||t.startsWith("'"))&&(t=t.slice(1,-1)),t}return e.text.slice(0,100)}getNodeText(e,r){let t=e.startPosition.row,i=e.endPosition.row;return t===i?r[t]?.trim()??"":r.slice(t,i+1).join(`
202
+ `)}generateNodeId(e){let r=Filesystem.toUnixPath(e.file_path);return `${e.language}:${r}:${e.ast_type}:${e.name}`}};function Qt(){return new Y}var s={class_declaration:"class_declaration",class_definition:"class_definition",class_specifier:"class_specifier",interface_declaration:"interface_declaration",struct_item:"struct_item",struct_declaration:"struct_declaration",struct_specifier:"struct_specifier",type_declaration:"type_declaration",type_alias_declaration:"type_alias_declaration",enum_declaration:"enum_declaration",record_declaration:"record_declaration",function_declaration:"function_declaration",function_definition:"function_definition",function_item:"function_item",method_declaration:"method_declaration",method_definition:"method_definition",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",variable_declarator:"variable_declarator",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_parameters",parameter_list:"parameter_list",parameters:"parameters",simple_parameter:"simple_parameter",typed_param:"typed_param",argument:"argument",field_declaration:"field_declaration",property_declaration:"property_declaration",public_field_definition:"public_field_definition",field_definition:"field_definition",property_signature:"property_signature",type_identifier:"type_identifier",type_annotation:"type_annotation",generic_type:"generic_type",named_type:"named_type",primitive_type:"primitive_type",return_type:"return_type",pointer_type:"pointer_type",reference_type:"reference_type",array_type:"array_type",sized_type_specifier:"sized_type_specifier",void_type:"void_type",predefined_type:"predefined_type",this:"this",function_declarator:"function_declarator",pointer_declarator:"pointer_declarator",declarator:"declarator",identifier:"identifier",property_identifier:"property_identifier",field_identifier:"field_identifier",name:"name",type_spec:"type_spec",super:"super",self:"self",required_parameter:"required_parameter",optional_parameter:"optional_parameter",aliased_import:"aliased_import",relative_import:"relative_import",import_prefix:"import_prefix",import_statement:"import_statement",import_from_statement:"import_from_statement",namespace_use_declaration:"namespace_use_declaration",scoped_identifier:"scoped_identifier",qualified_name:"qualified_name",dotted_name:"dotted_name",dotted_identifier:"dotted_identifier",module_name:"module_name",namespace_name:"namespace_name",system_lib_string:"system_lib_string",string_literal:"string_literal",string:"string",string_content:"string_content",interpreted_string_literal:"interpreted_string_literal",interpreted_string_literal_content:"interpreted_string_literal_content",annotation:"annotation",attribute:"attribute",member_call_expression:"member_call_expression",scoped_call_expression:"scoped_call_expression",relative_scope:"relative_scope",scoped_type_identifier:"scoped_type_identifier",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Ie={extends:"extends",implements:"implements"},Ve="new",ne={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function ge(y,e){e(y);for(let r of y.children)ge(r,e);}function F(y){for(let e of y.children)if(e.type===s.identifier||e.type===s.type_identifier||e.type===s.property_identifier||e.type===s.field_identifier||e.type===s.name)return e.text;return null}function ye(y){for(let e=y.children.length-1;e>=0;e--){let r=y.children[e];if(r&&(r.type===s.identifier||r.type===s.property_identifier||r.type===s.name))return r.text}return null}function he(y,e){for(let r of y.children)if(e.includes(r.type))return r;return null}function W(y,e){for(let r of y.children){if(e.includes(r.type))return r;let t=W(r,e);if(t)return t}return null}function z(y,e){for(let r of y.children)if(e.includes(r.type)){let t=F(r);if(t)return t;for(let i of r.children){let n=F(i);if(n)return n}}for(let r of y.children){let t=z(r,e);if(t)return t}return null}function se(y){let e=y.indexOf("<");if(e<0)return y;let r=0,t=null;for(let i=e;i<y.length;i++){let n=y[i];if(t){n===t&&(t=null);continue}if(n==='"'||n==="'"||n==="`"){t=n;continue}if(n==="<")r++;else if(n===">"&&(r--,r===0))return y.slice(0,e).trim()}return y}function Ye(y){let e=R(y),r=new Set;for(let t of e.rawTypes.classTypes)r.add(P(y,t));for(let t of e.rawTypes.interfaceTypes)r.add(P(y,t));for(let t of e.rawTypes.moduleTypes)r.add(P(y,t));return r}function Ut(y){let e=R(y),r=new Set;for(let t of e.rawTypes.methodTypes)r.add(P(y,t));return r}function Kt(y){let e=R(y),r=new Set;for(let t of e.rawTypes.propertyTypes)r.add(P(y,t));return r}var J=class{extractEdges(e,r,t,i){let n=[],a=new Map;for(let d of r){let c=a.get(d.name);c||(c=[],a.set(d.name,c)),c.push(d);}let o=new Map;for(let[d,c]of a){let l=c[0];l&&o.set(d,l);}return this.extractContainsEdges(r,n),this.extractCallEdges(e.rootNode,r,n,t,i,o),this.extractInheritanceEdges(e.rootNode,r,n,t,i,o),this.extractImportEdges(e.rootNode,r,n,t,i),this.extractTypeReferences(e.rootNode,r,n,t,i,o),this.extractAnnotationEdges(e.rootNode,r,n,t,i),this.extractHasMethodEdges(r,n,t),this.extractHasPropertyEdges(r,n,t),this.extractOverrideEdges(r,n,t,i),n}extractContainsEdges(e,r){for(let t of e)t.parent_id&&r.push({source:t.parent_id,target:this.generateNodeId(t),relation:"CONTAINS"});}extractCallEdges(e,r,t,i,n,a){let o=R(i),d=new Set(o.rawTypes.callExpressionTypes),c=new Set,l=Filesystem.toUnixPath(n),p=`${i}:${l}:module:file`;this.walkTree(e,u=>{if(d.has(u.type)){let f=this.findEnclosingFunction(u,r,a,i,n,p),m=this.extractCalleeName(u,i);if(f&&m){let x=`${i}:*:*:${m}`,g=`${f.id}|${x}|CALLS`;if(c.has(g))return;c.add(g),t.push({source:f.id,target:x,relation:"CALLS",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}});}extractInheritanceEdges(e,r,t,i,n,a){let o=R(i),d=new Set(o.rawTypes.classTypes),c=new Set(o.rawTypes.interfaceTypes),l=this.buildImportAliasMap(e,i);this.walkTree(e,p=>{if(d.has(p.type)){let u=F(p);if(!u)return;let f=Filesystem.toUnixPath(n),m=`${i}:${f}:${P(i,p.type)}:${u}`,x=he(p,[...o.inheritance.extendsClauseTypes]);x||(x=W(p,[...o.inheritance.extendsClauseTypes]));let g=[];x?(g=this.extractClauseNames(x,i),o.inheritance.stripTemplateArgs&&(g=g.map(_=>se(_)))):o.inheritance.fallbackToFirstIdentifier&&(g=this.collectNamedIdentifiers(p).filter(_=>_!==u).slice(0,1));for(let _ of g){if(!_||_===u)continue;let h=P(i,o.rawTypes.classTypes[0]??"class_declaration"),E=l.get(_)??_,b=Filesystem.toUnixPath(n),T=`${i}:${b}:${h}:${E}`;t.push({source:m,target:T,relation:"EXTENDS",line:(x?.startPosition?.row??p.startPosition?.row??-1)+1,col:(x?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}for(let _ of o.inheritance.implementsClauseTypes){let h=he(p,[_]);if(h||(h=W(p,[_])),h){let E=this.extractClauseNames(h,i);o.inheritance.stripTemplateArgs&&(E=E.map(b=>se(b)));for(let b of E){if(!b)continue;let T=o.rawTypes.interfaceTypes[0]??o.rawTypes.classTypes[0]??s.interface_declaration,N=l.get(b)??b,C=Filesystem.toUnixPath(n),B=`${i}:${C}:${T}:${N}`;t.push({source:m,target:B,relation:"IMPLEMENTS",line:(h?.startPosition?.row??p.startPosition?.row??-1)+1,col:(h?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}}}return}if(c.has(p.type)){let u=F(p);if(!u)return;let f=Filesystem.toUnixPath(n),m=`${i}:${f}:${P(i,p.type)}:${u}`;for(let x of o.inheritance.extendsClauseTypes){let g=W(p,[x]);if(g){let _=this.extractClauseNames(g,i);o.inheritance.stripTemplateArgs&&(_=_.map(h=>se(h)));for(let h of _){if(h===u)continue;let E=P(i,o.rawTypes.interfaceTypes[0]??"interface_declaration"),b=l.get(h)??h,T=`${i}:${f}:${E}:${b}`;t.push({source:m,target:T,relation:"EXTENDS",line:(g?.startPosition?.row??p.startPosition?.row??-1)+1,col:(g?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}break}}}});}collectTypeAnnotations(e){let r=[],t=new Set([s.type_annotation,"type",s.reference_type,s.pointer_type,s.generic_type,s.array_type,s.named_type,s.primitive_type]),i=n=>{if(t.has(n.type)){r.push(n);return}for(let a of n.children)i(a);};return i(e),r}collectNamedIdentifiers(e){let r=[],t=new Set,i=n=>{if(n.type===s.identifier||n.type===s.type_identifier||n.type===s.attribute){let a=n.text;t.has(a)||(t.add(a),r.push(a));return}for(let a of n.namedChildren)a&&i(a);};return i(e),r}extractClauseNames(e,r){let t=[],i=new Set,n=c=>{!c||i.has(c)||(i.add(c),t.push(c));},a=new Set([s.scoped_identifier,s.scoped_type_identifier,s.qualified_name,s.dotted_name,s.dotted_identifier]),o=new Set([s.identifier,s.type_identifier,s.name,s.attribute]),d=c=>{if(a.has(c.type)){n(c.text);return}if(o.has(c.type)){if(c.type===s.name&&(c.text===Ie.extends||c.text===Ie.implements))return;n(c.text);return}if(c.type===s.generic_type){let l=c.childForFieldName?.("name")?.text??c.namedChildren[0]?.text;l&&n(l);return}for(let l of c.namedChildren)l&&d(l);};return d(e),t}extractImportEdges(e,r,t,i,n){let a=R(i),o=new Set(a.rawTypes.importTypes),d=new Set;this.walkTree(e,c=>{if(o.has(c.type)){let l,p=this.extractImportWholePath(c);p?l=[p]:l=this.extractImportPaths(c);for(let u of l){if(!u||d.has(u))continue;d.add(u);let f=Filesystem.toUnixPath(n),m=`${i}:${f}:module:file`;t.push({source:m,target:u,relation:"IMPORTS",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:n});}}});}walkTree(e,r){ge(e,r);}findEnclosingFunction(e,r,t,i,n,a){let o=e,d=R(i),c=new Set([...d.rawTypes.methodTypes,...d.rawTypes.functionTypes]),l=new Set([s.lexical_declaration,s.variable_declaration,s.variable_declarator,s.export_statement]),p=new Set([s.public_field_definition,s.property_declaration,s.field_declaration]),u=new Map;for(let f of r){let m=u.get(f.ast_type);m?m.push(f):u.set(f.ast_type,[f]);}for(;o;){if(c.has(o.type)){let f=null,m=new Set([d.parameters?.wrapperType??s.parameter_list,s.parameter_list]);if(o.type===s.method_declaration||o.type===s.method_definition){let x=-1;for(let g=0;g<o.childCount;g++){let _=o.children[g];if(_&&m.has(_.type)){x=g;break}}if(x>0)for(let g=x-1;g>=0;g--){let _=o.children[g];if(_&&(_.type===s.identifier||_.type===s.type_identifier||_.type===s.property_identifier)){f=_.text;break}}}if(f||(f=F(o)??z(o,[s.function_declarator,s.declarator])),f){let x=P(i,o.type),_=u.get(x)?.find(h=>{let E=h.name.split("@")[0]??h.name;return E===f||E.endsWith(`.${f}`)});if(_){let h=Filesystem.toUnixPath(_.file_path);return {id:`${_.language}:${h}:${_.ast_type}:${_.name}`,name:_.name}}return null}}if(l.has(o.type)){let f=F(o);if(f){let m=P(i,s.variable_declaration),g=u.get(m)?.find(_=>(_.name.split("@")[0]??_.name)===f);if(g){let _=Filesystem.toUnixPath(g.file_path);return {id:`${g.language}:${_}:${g.ast_type}:${g.name}`,name:g.name}}}}if(p.has(o.type)){let f=F(o);if(f){let m=P(i,s.property_declaration),g=(u.get(m)??u.get(P(i,s.public_field_definition)))?.find(_=>{let h=_.name.split("@")[0]??_.name;return h===f||h.endsWith(`.${f}`)});if(g){let _=Filesystem.toUnixPath(g.file_path);return {id:`${g.language}:${_}:${g.ast_type}:${g.name}`,name:g.name}}}}o=o.parent;}return a?{id:a,name:"file"}:null}extractCalleeName(e,r){let t=e.firstChild;if(!t)return null;if(t.type===s.constant){for(let a of e.namedChildren)if(a!==t&&(a.type===s.identifier||a.type===s.property_identifier))return `${t.text}.${a.text}`}let i=R(r),n=new Set(i.rawTypes.memberAccessTypes);if(t.type===s.variable_name&&e.type===s.member_call_expression){let a=t.text,o=e.childForFieldName?.("name");if(o)return `${a}.${o.text}`;let d=e.children.find(c=>c.type===s.name);if(d)return `${a}.${d.text}`}if(e.type===s.member_call_expression){let a=e.childForFieldName?.("name");if(a){let d=e.childForFieldName?.("object")?.text??"";return /[()]/.test(d)?a.text:`${d}.${a.text}`}}if(n.has(t.type)){let a=t.childForFieldName?.("property")?.text,o=t.childForFieldName?.("field")?.text,d=t.childForFieldName?.("name")?.text,c;for(let p=t.children.length-1;p>=0;p--){let u=t.children[p];if(u&&(u.type===s.identifier||u.type===s.property_identifier||u.type===s.name||u.type===s.field_identifier||u.type===s.constant)){c=u.text;break}}let l=a??o??d??c;if(l){let p=t.childForFieldName?.("object")??t.children[0],u=p?.text,f=new Set(i.rawTypes.contextualKeywordTypes),m=!u||u===l||(p?f.has(p.type):false)||/[()]/.test(u);return u&&!m?`${u}.${l}`:l}}if(t.type===s.relative_scope&&e.type===s.scoped_call_expression){for(let a of e.children)if(a.type===s.name)return a.text}if(t.type===s.identifier||t.type===s.property_identifier||t.type===s.name)return t.text;if(t.type===s.this){for(let a of e.children)if(a.type===s.identifier||a.type===s.property_identifier)return a.text}if(t.type===s.identifier&&t.text.includes("."))return t.text;if(t.type===s.super){for(let a of e.children)if(a.type===s.identifier||a.type===s.property_identifier)return a.text}if(t.type===s.self){for(let a of e.children)if(a.type===s.identifier||a.type===s.property_identifier)return a.text}if(t.type===Ve){for(let a of e.children)if(a.type===s.identifier||a.type===s.type_identifier||a.type===s.name||a.type===s.scoped_identifier)return a.text}return null}extractImportPaths(e){let r=this.extractPythonImportPaths(e);if(r.length>0)return r;let t=new Set([s.string,s.string_literal,s.string_content,s.interpreted_string_literal,s.interpreted_string_literal_content,s.system_lib_string]),i=new Set([s.dotted_name,s.dotted_identifier,s.scoped_identifier,s.qualified_name,s.module_name,s.namespace_name,s.name,s.identifier]),n=[],a=d=>{if(t.has(d.type)){let c=d.text;(c.startsWith('"')||c.startsWith("'")||c.startsWith("<"))&&(c=c.slice(1,-1)),n.push(c);return}for(let c of d.children)a(c);};if(a(e),n.length>0)return n;let o=d=>{if(i.has(d.type)){let c=d.text;(c.startsWith('"')||c.startsWith("'")||c.startsWith("<"))&&(c=c.slice(1,-1)),n.push(c);return}for(let c of d.children)o(c);};return o(e),n}extractPythonImportPaths(e){let r=e.type;if(r!==s.import_statement&&r!==s.import_from_statement)return [];let t=[];if(r===s.import_statement){for(let i of e.children)if(i.type===s.dotted_name)t.push(i.text);else if(i.type===s.aliased_import){let n=i.childForFieldName?.("name");if(n)t.push(n.text);else for(let a of i.children)if(a.type===s.dotted_name||a.type===s.identifier){t.push(a.text);break}}}else for(let i of e.children){if(i.type===s.dotted_name){t.push(i.text);break}if(i.type===s.relative_import){let n=i.childForFieldName?.(s.import_prefix),a=i.childForFieldName?.(s.module_name),o="";n&&(o+=n.text),a&&(o+=a.text),o?t.push(o):t.push(i.text);break}}return t}extractImportWholePath(e){let r=new Set([s.qualified_name,s.scoped_identifier,s.dotted_name,s.dotted_identifier,s.module_name,s.namespace_name,s.namespace_use_clause,s.name,s.identifier,s.string,s.string_literal,s.interpreted_string_literal,s.system_lib_string]);return (i=>{if(r.has(i.type)){let n=i.text;return (n.startsWith('"')||n.startsWith("'")||n.startsWith("<"))&&(n=n.slice(1,-1)),i.type===s.namespace_use_clause&&n.includes(" as ")&&(n=n.split(" as ")[0]??n),n}if(i.type===s.namespace_use_declaration||i.type===s.namespace_use_clause){for(let n of i.children)if(r.has(n.type)){let a=n.text;return (a.startsWith('"')||a.startsWith("'")||a.startsWith("<"))&&(a=a.slice(1,-1)),n.type===s.namespace_use_clause&&a.includes(" as ")&&(a=a.split(" as ")[0]??a),a}}return null})(e)}generateNodeId(e){let r=Filesystem.toUnixPath(e.file_path);return `${e.language}:${r}:${e.ast_type}:${e.name}`}extractTypeReferences(e,r,t,i,n,a){let o=new Set([s.function_declaration,s.function_definition,s.function_item,s.method_declaration,s.method_definition,s.variable_declaration,s.lexical_declaration,s.property_declaration,s.field_declaration,s.typed_param,s.identifier]),d=new Set([s.field_declaration,s.parameter_declaration,s.parameter]),c=new Set([s.formal_parameters,s.parameter,s.parameter_declaration,s.formal_parameter,s.simple_parameter,s.typed_param,s.argument,s.required_parameter,s.optional_parameter,s.parameter,s.parameters]);this.walkTree(e,l=>{if(o.has(l.type)&&l.type!==s.lexical_declaration&&l.type!==s.variable_declaration){let f=l.childForFieldName?.("name")?.text??ye(l)??F(l)??z(l,[s.function_declarator,s.pointer_declarator,s.declarator]);if(!f)return;let m=null,x=[s.return_type,s.type_annotation,"type",s.pointer_type,s.array_type,s.void_type];for(let b of x){for(let T of l.children)if(T.type===b){m=T;break}if(m)break}let g=new Set([s.type_identifier,s.generic_type,s.array_type,s.identifier,s.struct_specifier,s.class_specifier,s.named_type,s.primitive_type]),_=new Set([s.function_declarator,s.pointer_declarator,s.declarator]);if(!m){for(let b of l.children)if(g.has(b.type)){if(b.type===s.void_type)continue;let T=ye(l);if(T&&b.text===T||_.has(b.type))continue;m=b;break}}let h=new Set([s.type_identifier,s.pointer_type,s.array_type]);if(!m){let b=false;for(let T of l.children){if(T.type==="->"||T.text==="->"){b=true;continue}if(b&&h.has(T.type)){m=T;break}}}if(m){let b=this.extractTypeName(m);if(b&&!ne.void_any_null.has(b)){let T=this.resolveTypeNodeId(b,i,n);T&&t.push({source:this.generateNodeIdFromName(f,l.type,i,n),target:T,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:n});}}let E=W(l,["type_parameter","generic_type"]);if(E){let b=this.extractTypeName(E);if(b){let T=this.resolveTypeNodeId(b,i,n);T&&t.push({source:this.generateNodeIdFromName(f,l.type,i,n),target:T,relation:"TYPE_REFERENCES",line:(E.startPosition?.row??-1)+1,col:(E.startPosition?.column??-1)+1,filePath:n});}}}if(d.has(l.type)){let f=this.findEnclosingClass(l,r);if(f){for(let m of l.children)if(m.type===s.type_identifier){let x=m.text,g=this.resolveTypeNodeId(x,i,n);g&&t.push({source:f.id,target:g,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:n});}}}let p=new Set([s.type_annotation,s.annotation,"type",s.reference_type,s.pointer_type,s.type_identifier,s.struct_specifier,s.class_specifier,s.array_type,s.sized_type_specifier,s.named_type,s.primitive_type,s.slice_type,s.array_type,s.map_type,s.channel_type]);if(c.has(l.type)){for(let f of l.children)if(p.has(f.type)){let m=this.extractTypeName(f);if(m&&!ne.string_number_boolean.has(m)){let x=this.resolveTypeNodeId(m,i,n);if(x){let g=this.findEnclosingFunction(l,r,a,i,n);g&&t.push({source:g.id,target:x,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:n});}}}if((i==="zig"||i==="csharp")&&l.type===s.parameter&&l.children.length>=2){let f=i==="zig"?2:0,m=l.children[f];if(m&&m.type===s.identifier){let x=m.text;if(x&&!ne.string_number_boolean.has(x)){let g=this.resolveTypeNodeId(x,i,n);if(g){let _=this.findEnclosingFunction(l,r,a,i,n);_&&t.push({source:_.id,target:g,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:n});}}}}}if(new Set([s.variable_declaration,s.lexical_declaration,s.public_field_definition,s.field_definition,s.field_declaration,s.property_declaration,s.property_signature,s.assignment]).has(l.type)){let f=this.collectTypeAnnotations(l);for(let m of f){let x=this.extractTypeName(m);if(x&&!ne.string_number_boolean.has(x)&&x!=="any"){let g=this.resolveTypeNodeId(x,i,n);if(g){let _=F(l)??z(l,["variable_declarator"])??F(l);_&&t.push({source:this.generateNodeIdFromName(_,"variable_declaration",i,n),target:g,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:n});}}}}});}extractHasMethodEdges(e,r,t){let i=Ye(t),n=Ut(t);this.emitContainerToMemberEdges(e,r,i,n,"HAS_METHOD");}extractHasPropertyEdges(e,r,t){let i=Ye(t),n=Kt(t);this.emitContainerToMemberEdges(e,r,i,n,"HAS_PROPERTY");}emitContainerToMemberEdges(e,r,t,i,n){let a=new Map;for(let o of e){let d=a.get(o.file_path);d||(d=[],a.set(o.file_path,d)),d.push(o);}for(let o of a.values()){o.sort((c,l)=>c.start_line-l.start_line);let d=[];for(let c of o){for(;d.length>0&&(d[d.length-1]?.end_line??1/0)<c.start_line;)d.pop();if(t.has(c.ast_type))d.push(c);else if(i.has(c.ast_type)){let l=d[d.length-1];if(l){let p=this.generateNodeId(l),u=this.generateNodeId(c);r.push({source:p,target:u,relation:n});}}}}}extractOverrideEdges(e,r,t,i){let n=R(t),a=new Set;for(let l of n.rawTypes.classTypes)a.add(P(t,l));for(let l of n.rawTypes.interfaceTypes)a.add(P(t,l));let o=e.filter(l=>a.has(l.ast_type));if(o.length===0)return;let d=new Map;for(let l of e){let p=d.get(l.file_path);p||(p=[],d.set(l.file_path,p)),p.push(l);}let c=new Map;for(let l of r)if(l.relation==="EXTENDS"){let p;for(let f of d.values())if(p=f.find(m=>this.generateNodeId(m)===l.target),p)break;if(!p)continue;let u=c.get(l.source);u||(u=[],c.set(l.source,u)),u.push(p);}for(let l of o){let p=c.get(this.generateNodeId(l))??[];if(p.length===0)continue;let u=this.collectMemberIdsByName(l,d,"HAS_METHOD",t);if(u.size===0)continue;let f=new Set,m=[],x=[...p];for(;x.length>0;){let g=x.shift();if(f.has(this.generateNodeId(g)))continue;f.add(this.generateNodeId(g)),m.push(g);let _=c.get(this.generateNodeId(g))??[];x.push(..._);}for(let[g,_]of u){let h=_[0];if(!h)continue;let E=null;for(let b of m){let N=this.collectMemberIdsByName(b,d,"HAS_METHOD",t).get(g);if(!(!N||N.length===0)){E=N[0]??null;break}}if(E&&E!==h){let b=this.generateNodeId(l);if(r.some(C=>C.relation==="METHOD_OVERRIDES"&&C.source===b&&C.target===E))continue;r.push({source:b,target:E,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,r,t,i){let n=new Map,a=r.get(e.file_path);if(!a)return n;let o=new Set([s.method_definition,s.method_declaration,s.function_definition]);for(let d of a)if(o.has(d.ast_type)&&d.start_line>=e.start_line&&d.end_line<=e.end_line){let c=d.metadata?.originalName??d.name,l=d.metadata?.parameterTypes??[],p=l.length>0?`${c}|${l.join(",")}`:c,u=n.get(p);u||(u=[],n.set(p,u));let f=this.generateNodeId(d);u.push(f);}return n}buildImportAliasMap(e,r){let t=new Map;return this.walkTree(e,i=>{if(i.type===s.namespace_use_clause){let n=i.children,a=n.findIndex(o=>o.type==="as");if(a>=0){let o=n.slice(0,a).find(c=>c.type===s.qualified_name),d=n[a+1];o&&d&&d.type===s.name&&d.text&&t.set(d.text,o.text);}}}),t}findEnclosingClass(e,r){let t=e.parent,i=new Set([s.class_declaration,s.class_definition,s.struct_specifier,s.struct_declaration,s.struct_item,s.type_declaration,s.record_declaration,s.class_specifier,s.enum_declaration]);for(;t;){if(i.has(t.type)){let n=F(t)??z(t,[s.type_spec,s.name]);if(n){let a=r.find(l=>l.name===n);if(a)return {id:this.generateNodeId(a),name:n};let o=r[0],d=o?.language??"ts",c=o?.file_path??"";return {id:`${d}:${c}:${t.type}:${n}`,name:n}}}t=t.parent;}return null}extractAnnotationEdges(e,r,t,i,n){let a=R(i),o=new Set(a.rawTypes.annotationTypes),d=new Set(a.annotation.annotatableTypes);this.walkTree(e,c=>{if(o.has(c.type)){let l=this.extractTypeName(c)||F(c);if(!l)return;let p=c.parent;for(;p;){if(d.has(p.type)){let u=F(p),f=p.type;if(!u&&(p.type===s.decorated_definition||p.type===s.export_statement)){let m=z(p,[s.function_definition,s.class_definition,s.method_definition,s.function_declaration,s.method_declaration]),x=W(p,[s.function_definition,s.class_definition,s.method_definition,s.function_declaration,s.method_declaration]);m&&(u=m,f=x?.type??"function_definition");}if(u){let m=this.generateNodeIdFromName(u,f,i,n),x=Filesystem.toUnixPath(n),g=`${i}:${x}:annotation:${l}`;t.push({source:g,target:m,relation:"ANNOTATES",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:n});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===s.type_identifier||e.type===s.identifier||e.type===s.predefined_type||e.type===s.name)return e.text;let r=new Set([s.type_identifier,s.identifier,s.name]);for(let i of e.children)if(r.has(i.type))return i.text;for(let i of e.children)if(i.type===s.predefined_type)return i.text;let t=new Set([s.pointer_type,s.reference_type,s.array_type,s.generic_type,s.slice_type,s.map_type,s.channel_type,s.parenthesized_type]);for(let i of e.children)if(t.has(i.type)){let n=this.extractTypeName(i);if(n)return n}return null}resolveTypeNodeId(e,r,t){let i=[s.class_declaration,s.interface_declaration,s.type_alias_declaration,s.type_declaration,s.enum_declaration,s.struct_declaration];for(let n of i)return `${r}:${Filesystem.toUnixPath(t)}:${n}:${e}`;return null}generateNodeIdFromName(e,r,t,i){return `${t}:${Filesystem.toUnixPath(i)}:${P(t,r)}:${e}`}};function Vt(){return new J}var Z=Log.create({service:"codebase-indexer"}),X=class{constructor(e,r,t,i){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");a(this,"writeProxy",null);this.db=e,this.parserManager=r,this.nodeExtractor=new Y,this.edgeExtractor=new J,this.config=t,this.writeProxy=i??null;}async flushPendingWrites(){this.writeProxy&&await this.writeProxy.flush();}get dbWriter(){return this.writeProxy?this.writeProxy:this.db}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let r=this.computeHash(e),t=this.db.getCachedEmbedding?.(r);if(t)return new Float32Array(t.buffer,t.byteOffset,t.length/4);let n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let a=new Float32Array(n);return this.dbWriter.cacheEmbedding?.(r,a),a}return null}catch{return null}}async indexFile(e,r){let t=Date.now(),i=[],n=0,a=0,o=null;try{let d=this.parserManager.detectLanguage(e);if(!d)throw new f("Unsupported file type",e);r?.({currentFile:e,processed:0,total:1,stage:"parsing"});let c=await this.readFile(e),l=this.computeHash(c);if(this.config.incremental&&this.db.getFileHash(e)===l)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-t};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),r?.({currentFile:e,processed:0,total:1,stage:"extracting"}),o=this.parserManager.parse(c,d);let p=this.nodeExtractor.extractNodes(o,c,d,e);n=p.length;let u=this.edgeExtractor.extractEdges(o,p,d,e);r?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let f$1=this.getValidEdgeCount(u,p);this.storeEdges(u,p),a=f$1,this.config.embedding&&p.length>0&&(r?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(p)),this.dbWriter.setFileHash(e,l),this.writeProxy&&this.writeProxy.flush();}catch(d){let c=d instanceof Error?d.message:String(d);i.push({filePath:e,error:c});}finally{if(o)try{o.delete();}catch(d){Z.warn("tree.delete failed",{filePath:e,error:String(d)});}}return {success:i.length===0,filesProcessed:1,nodesCreated:n,edgesCreated:a,errors:i,duration:Date.now()-t}}async indexDirectory(e,r){let t=Date.now(),i=e??this.config.workspaceDir,n=[],a=0,o=0,d=0;try{let c=await this.scanFiles(i);for(let m of c.readErrors)n.push(m);let l=c.results,p=l.length,u=0,f=m=>{r&&r({currentFile:m.currentFile,processed:u,total:l.length,stage:m.stage});};for(let m=0;m<l.length;m+=this.config.batchSize){let x=l.slice(m,m+this.config.batchSize),g=await Promise.all(x.map(_=>this.indexFile(_.filePath,f)));for(let _ of g)a++,u++,o+=_.nodesCreated,d+=_.edgesCreated,!_.success&&_.errors.length>0&&n.push(..._.errors);}if(r&&l.length>0){let m=l[l.length-1]?.filePath??"";r({currentFile:m,processed:l.length,total:l.length,stage:"storing"});}}catch(c){let l=c instanceof Error?c.message:String(c);n.push({filePath:i,error:l});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:n.length===0,filesProcessed:a,nodesCreated:o,edgesCreated:d,errors:n,duration:Date.now()-t}}async sync(e){let r=Date.now(),t=[],i=0,n=0,a=0,o=0,d=0,c=0;try{let f=await this.scanFiles(this.config.workspaceDir),m=f.results;for(let w of f.readErrors)t.push(w);let x=new Set(m.map(w=>w.filePath)),g=this.db.getAllFileHashes(),_=new Set(g.map(w=>w.file_path));for(let w of g)x.has(w.file_path)||(this.dbWriter.deleteFtsByFile?.(w.file_path),this.dbWriter.deleteNodesByFile(w.file_path),this.dbWriter.deleteEdgesByFile(w.file_path),this.dbWriter.deleteFileHash(w.file_path),a++);let h=m.length,E=0,b=w=>{e&&e({currentFile:w.currentFile,processed:E,total:h,stage:w.stage});},T=Math.max(1,this.config.batchSize),N=new Map;for(let w of g)N.set(w.file_path,w.content_hash);for(let w=0;w<m.length;w+=T){let H=m.slice(w,w+T),U=await Promise.all(H.map(M=>{let L=N.get(M.filePath);return L?L!==M.contentHash?this.indexFile(M.filePath,b).then($=>({file:M,kind:"updated",r:$})):Promise.resolve({file:M,kind:"skipped",r:null}):this.indexFile(M.filePath,b).then($=>({file:M,kind:"added",r:$}))}));for(let{kind:M,r:L}of U)M==="skipped"?o++:L&&(L.success?L.nodesCreated===0?o++:(M==="added"?i++:n++,d+=L.nodesCreated,c+=L.edgesCreated):t.push(...L.errors));E+=H.length;}if(e&&h>0){let w=m[m.length-1]?.filePath??"";e({currentFile:w,processed:h,total:h,stage:"storing"});}this.writeProxy&&await this.writeProxy.flush();let C=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(w=>w.file_path)),B=this.db.getAllFileHashes().filter(w=>!C.has(w.file_path)).map(w=>w.file_path);for(let w of B)this.dbWriter.deleteFileHash(w);}catch(f){let m=f instanceof Error?f.message:String(f);t.push({filePath:this.config.workspaceDir,error:m});}this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush();let l=new Date().toISOString(),p=Date.now()-r,u={timestamp:l,success:t.length===0,filesAdded:i,filesUpdated:n,filesDeleted:a,filesSkipped:o,nodesCreated:d,edgesCreated:c,errorCount:t.length,errors:t,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(u)),{success:t.length===0,filesAdded:i,filesUpdated:n,filesDeleted:a,filesSkipped:o,nodesCreated:d,edgesCreated:c,errors:t,duration:p}}async scanFiles(e){let r=[],t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),a=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],o=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),d=[...a,...o],c=await this.loadGitignore(e),l=new Set;for(let g of n){let _=await Glob.scan(g,{cwd:e,absolute:true,include:"file",dot:false,symlink:false,ignore:d});for(let h of _)l.has(h)||l.add(h);}let p=Array.from(l),u=Filesystem.toUnixPath(e),f=c?p.filter(g=>!c.ignores(this.toRelativePosix(g,u),false)):p,m=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),x=[];for(let g of f){let _=Filesystem.normalize(g);this.parserManager.detectLanguage(_)&&x.push(_);}for(let g=0;g<x.length;g+=m){let _=x.slice(g,g+m),h=await Promise.all(_.map(async E=>{try{let b=await this.readFile(E),T=this.computeHash(b),N=this.parserManager.detectLanguage(E);return N?{filePath:E,language:N,contentHash:T,content:b}:null}catch(b){let T=b instanceof Error?b.message:String(b);return t.push({filePath:E,error:T}),Z.warn("scanFiles read failed",{filePath:E,error:T}),null}}));for(let E of h)E&&r.push(E);}return {results:r,readErrors:t}}async loadGitignore(e){try{let r=`${Filesystem.toUnixPath(e)}/.gitignore`,t=await Je.readFile(r,"utf-8"),i=Ignore.create();return i.add(t),Z.debug("Loaded .gitignore",{path:r,lines:t.split(`
203
+ `).length}),i}catch(r){return r.code!=="ENOENT"&&Z.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:String(r)}),null}}toRelativePosix(e,r){let t=Filesystem.toUnixPath(e),i=Filesystem.toUnixPath(r),n=t;return i&&n.startsWith(i)&&(n=n.slice(i.length)),(i.endsWith("/")&&n.startsWith("/")||n.startsWith("/"))&&(n=n.slice(1)),n}async readFile(e){try{return await Je.readFile(e,"utf-8")}catch(r){throw new c("Failed to read file",e,r instanceof Error?r:new Error(String(r)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let r=e.map(t=>({id:this.nodeExtractor.generateNodeId(t),name:t.name,ast_type:t.ast_type,language:t.language,file_path:t.file_path,start_line:t.start_line,start_col:t.start_col,end_line:t.end_line,end_col:t.end_col,text:t.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(r),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let r=[];for(let t of e){let i=this.splitIdentifier(t.name);for(let n of i)n.length>0&&r.push({segment:n,name:t.name});}if(r.length!==0)try{this.db.insertNameSegmentsBatch(r);}catch(t){Z.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:r.length,error:String(t)});for(let{segment:i,name:n}of r)try{this.db.insertNameSegment(i,n);}catch(a){Z.warn("insertNameSegment failed",{nodeName:n,segment:i,error:String(a)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let r=[],n=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let a of n.split(/\s+/)){let o=a.toLowerCase();o.length>0&&r.push(o);}return r}storeEdges(e,r){let t=new Set(r.map(o=>this.nodeExtractor.generateNodeId(o))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]),a=e.filter(o=>o.source===o.target?false:n.has(o.relation)||t.has(o.source)?i.has(o.relation)?true:t.has(o.target):false).map((o,d)=>({id:`${o.source}:${o.relation}:${o.target}:${d}`,source:o.source,target:o.target,relation:o.relation,created_at:new Date().toISOString()}));a.length>0&&this.dbWriter.insertEdges(a),this.storeUnresolvedRefs(e,r,t);}storeUnresolvedRefs(e,r,t){let i=new Map,n=(l,p)=>{let u=i.get(l);u||(u=[],i.set(l,u)),u.includes(p)||u.push(p);};for(let l of r){let p=this.nodeExtractor.generateNodeId(l);n(l.name,p);let u=l.metadata?.originalName;typeof u=="string"&&u.length>0&&n(u,p);let f=l.name.lastIndexOf("@");if(f>0){let m=l.name.slice(0,f),x=m.lastIndexOf(".");x>0&&n(m.slice(x+1),p);}}let a=r[0]?.file_path??"",o=r[0]?.language??"unknown",d=new Set(["CALLS","IMPORTS"]),c=[];for(let l of e){if(d.has(l.relation))continue;let p=t.has(l.source),u=t.has(l.target);if(p&&u)continue;let f=p?l.target:l.source,m=p?l.source:t.has(l.target)?l.target:void 0,x=f.includes(":")?f.split(":").pop()??f:f,g=i.get(x)??[];c.push({fromNodeId:m,referenceName:f,referenceKind:l.relation,line:l.line,col:l.col,filePath:l.filePath??a,language:o,candidates:g.length>0?g:void 0});}c.length!==0&&this.dbWriter.insertUnresolvedRefsBatch(c);}getValidEdgeCount(e,r){let t=new Set(r.map(a=>this.nodeExtractor.generateNodeId(a))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]);return e.filter(a=>n.has(a.relation)||t.has(a.source)?i.has(a.relation)?true:t.has(a.target):false).length}async embedNodes(e){if(!this.config.embedding)return;let r=this.config.embedding.maxEmbeddingsPerCall||10,t=this.chunkArray(e,r),i=[],n=4,a=t.map((d,c)=>({index:c,batch:d})),o=[];for(let d=0;d<a.length;d+=n){let c=a.slice(d,d+n),l=await Promise.all(c.map(async({index:p,batch:u})=>{let f=[],m=u.map(x=>this.generateNodeEmbeddingText(x));try{let x=await this.config.embedding.doEmbed({values:m});for(let g=0;g<u.length;g++){let _=u[g];if(!_)continue;let h=x.embeddings[g];if(h){let E=new Float32Array(h),b=this.computeHash(this.generateNodeEmbeddingText(_));this.dbWriter.cacheEmbedding?.(b,E),f.push({nodeId:this.nodeExtractor.generateNodeId(_),embeddingText:m[g]||"",embedding:E});}}}catch{for(let g of u){if(!g)continue;let _=this.generateNodeEmbeddingText(g),h=await this.embedText(_);h&&f.push({nodeId:this.nodeExtractor.generateNodeId(g),embeddingText:_,embedding:h});}}return {index:p,embeddings:f}}));o.push(...l);}o.sort((d,c)=>d.index-c.index);for(let d of o)i.push(...d.embeddings);i.length>0&&this.dbWriter.storeNodeEmbeddings?.(i);}chunkArray(e,r){let t=[];for(let i=0;i<e.length;i+=r)t.push(e.slice(i,i+r));return t}};function er(y,e,r){return new X(y,e,r)}function Pe(y){if(!y)return [];let e=y.split(/[^a-zA-Z0-9]+/),r=[];for(let t of e){if(!t)continue;let i=t.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);i&&r.push(...i);}return r.map(t=>t.toLowerCase()).filter(t=>t.length>0)}function Ze(y,e){if(y.length===0||e.length===0)return 0;let r=0;for(let t of y)e.includes(t)&&r++;return r/y.length}function Xe(y,e,r={}){let t=r.limit??20,i=r.minScore??.2;if(!y)return [];let n=Pe(y),a=[];for(let o of e){let d=o.id.split(":").pop()??"";if(d===y||o.name===y){a.push({nodeId:o.id,score:1,matchedPart:"full"});continue}let c=Pe(d),l=Pe(o.name),p=Ze(n,c),u=Ze(n,l),f=Math.max(p,u);f>=i&&a.push({nodeId:o.id,score:f,matchedPart:f>=.99?"full":"segment"});}return a.sort((o,d)=>d.score-o.score),a.slice(0,t)}var Ce=Filesystem.toUnixPath,I=Log.create({service:"codebase.query"}),ir=new Set(["AND","OR","NOT","NEAR"]);function nr(y){return y?y.split(/\s+/).flatMap(r=>r.split(/[^\p{L}\p{N}_]+/u)).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!ir.has(r.toUpperCase())).join(" "):""}var ee=class{constructor(e,r,t={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(this,"config");this.db=e,this.embedding=r,this.config=t;}async search(e,r={}){let{maxResults:t=this.config.maxResults,minScore:i=this.config.minScore,language:n,filePath:a,astType:o,enableFts:d=true,includeEdges:c=true,edgesLimit:l=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:u=this.config.hybrid.textWeight,enableEmbedding:f=true}=r;I.debug("search() called",{query:e,astType:o,language:n,enableEmbedding:f,enableFts:d,minScore:i});let m=[],x=new Map;if(f&&this.embedding){let h=await this.vectorSearchNodes(e,t*2,i);I.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let E of h){if(n&&E.language!==n||o&&E.astType!==o)continue;let b={...E,source:"vector",vectorScore:E.score,hybridScore:E.score*p};m.push(b),x.set(b.id,b);}I.debug("after vector filter",{resultsCount:m.length});}if(d&&this.db.isFtsAvailable()){let h=nr(e);h||I.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let E=h?this.db.searchNodesFts(h,t*2):[];I.debug("FTS results before filter",{count:E.length});for(let b of E){if(n&&b.language!==n||a&&!b.file_path.includes(Ce(a))||o&&b.ast_type!==o)continue;let T=this.normalizeScore(b.score),N=x.get(b.id);if(N)N.ftsScore=T,N.hybridScore=N.vectorScore*p+T*u;else {let C={id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:T,source:"fts",ftsScore:T,hybridScore:T*u};m.push(C),x.set(C.id,C);}}I.debug("after FTS filter",{resultsCount:m.length});}if(!d||!this.db.isFtsAvailable()||m.length===0){try{let h=this.db.queryNodes({limit:t*2,astType:o,language:n,filePath:a}),E=new Set(m.map(w=>w.id)),b=e.toLowerCase(),T=b.split(/\s+/).filter(w=>w.length>0),N=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),C=T.map(w=>({term:w,regex:new RegExp(N(w),"gi")})),B=[];for(let w of h){if(a&&!w.file_path.includes(Ce(a)))continue;let H=w.name.toLowerCase(),U=w.text.toLowerCase(),M=0;if(C.some(({term:O})=>H.includes(O))){let O=0;for(let{regex:oe}of C){let ce=H.match(oe);O+=ce?ce.length:0;}M=.8*Math.min(O/C.length,1);}let L=0;if(C.some(({term:O})=>U.includes(O))){let O=0;for(let{regex:nt}of C){let Fe=U.match(nt);O+=Fe?Fe.length:0;}L=.5*Math.min(O/C.length,1);let oe=U.indexOf(b),ce=oe===-1?0:Math.max(0,1-oe/U.length)*.2;L+=ce;}let $=Math.max(M,L);$>0&&B.push({id:w.id,name:w.name,astType:w.ast_type,language:w.language,filePath:w.file_path,text:w.text,snippet:w.text.slice(0,200),startLine:w.start_line,startCol:w.start_col,endLine:w.end_line,endCol:w.end_col,score:$,source:"basic",hybridScore:$});}B.sort((w,H)=>H.score-w.score),m.push(...B.slice(0,t));}catch{}if(m.length===0)try{let h=this.db.queryNodes({limit:1e3}),E=Xe(e,h,{limit:t,minScore:.5});I.debug("name-segment matches",{count:E.length,query:e});for(let b of E){let T=this.db.getNodeById(b.nodeId);if(!T||n&&T.language!==n||o&&T.ast_type!==o||a&&!T.file_path.includes(Ce(a)))continue;let N={id:T.id,name:T.name,astType:T.ast_type,language:T.language,filePath:T.file_path,text:T.text??"",snippet:(T.text??"").slice(0,200),startLine:T.start_line??0,startCol:T.start_col??0,endLine:T.end_line??0,endCol:T.end_col??0,score:b.score,source:"structural",hybridScore:b.score};m.push(N),x.set(N.id,N);}}catch(h){I.debug("name-segment channel error",{error:h instanceof Error?h.message:String(h)});}}let g=m.filter(h=>h.hybridScore>=i).sort((h,E)=>E.hybridScore-h.hybridScore).slice(0,t);g.length===0&&d&&this.db.isFtsAvailable()&&(!f||!this.embedding)&&(g=m.sort((h,E)=>E.hybridScore-h.hybridScore).slice(0,t),I.warn("q.search: FTS-only \u901A\u9053 minScore threshold \u8FC7\u4E25\uFF0C\u964D\u7EA7\u4E3A minScore=0",{originalMinScore:i,ftsRawCount:m.filter(h=>h.source==="fts").length,preservedHits:g.length}));let _=g.map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(c&&_.length>0){let h=_.map(T=>T.id),E=this.db.queryEdges({sourceOrTarget:h}),b=new Map;for(let T of E)T.source!==T.target&&(b.has(T.source)||b.set(T.source,[]),b.get(T.source).push(T));return _.map(T=>{let N=b.get(T.id)||[];return {...T,edges:N.slice(0,l)}})}return _.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,r,t,i){if(I.debug("vectorSearchNodes start",{query:e,limit:r,minScore:t,hasEmbedding:!!this.embedding,candidateCount:i?.length}),!this.embedding)return I.debug("vectorSearchNodes skip - no embedding model"),[];let n=await this.embedText(e);if(!n)return I.debug("vectorSearchNodes skip - no embedding result"),[];let a=new Float32Array(n),o,d=5e3;if(i&&i.length>0){let f=i.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${f})`,i);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[d]);I.debug("vectorSearchNodes vectors loaded",{count:o.length});let c=[];for(let f of o){let m=new Float32Array(f.embedding.buffer,f.embedding.byteOffset,f.embedding.length/4),x=this.cosineSimilarity(a,m);x<t||(c.push({nodeId:f.node_id,score:x}),c.length>r&&(c.sort((g,_)=>_.score-g.score),c.splice(r)));}if(c.length===0)return I.debug("vectorSearchNodes done - no results above minScore"),[];c.sort((f,m)=>m.score-f.score);let l=c.map(f=>f.nodeId);I.debug("vectorSearchNodes query nodes",{nodeIdsCount:l.length});let p=this.db.queryNodes({ids:l}),u=new Map(c.map(f=>[f.nodeId,f.score]));return I.debug("vectorSearchNodes done",{nodesFound:p.length}),p.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text??"",snippet:(f.text??"").slice(0,200),startLine:f.start_line??0,startCol:f.start_col??0,endLine:f.end_line??0,endCol:f.end_col??0,score:u.get(f.id)||0,source:"vector"}))}async getEdgesForNode(e,r=100){let t=this.db.queryEdges({sourceOrTarget:[e.id],limit:r});return {...e,edges:t}}async embedText(e){if(!this.embedding)return null;try{let t=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return t?new Float32Array(t):null}catch{return null}}cosineSimilarity(e,r){let t=0,i=0,n=0;for(let a=0;a<e.length;a++){let o=e[a],d=r[a];t+=o*d,i+=o*o,n+=d*d;}return i===0||n===0?0:t/(Math.sqrt(i)*Math.sqrt(n))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){I.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(r){throw new g("Failed to query nodes",{filter:e},r instanceof Error?r:new Error(String(r)))}}queryEdges(e){I.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(r=>r.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(r){throw new g("Failed to query edges",{filter:e},r instanceof Error?r:new Error(String(r)))}}queryEdgesWithNodes(e){let r=this.db.queryEdges(e),t=[];for(let i of r){let n=this.db.getNodeById(i.source),a=this.db.getNodeById(i.target);n&&a&&t.push({edge:i,sourceNode:n,targetNode:a});}return t}queryNeighbors(e,r={}){let{relationTypes:t,direction:i="both",limit:n=100}=r;I.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:t,direction:i,limit:n});let a=[],o=[],d=new Set,c=new Set,l=t&&t.length>0?t:[void 0],p=u=>{for(let f of l){let m=f===void 0?{}:{relation:f},x=u==="outgoing"?this.db.queryEdges({source:e,...m,limit:n}):this.db.queryEdges({target:e,...m,limit:n});for(let g of x){if(c.has(g.id))continue;c.add(g.id),a.push(g);let _=u==="outgoing"?g.target:g.source,h=this.db.getNodeById(_);h&&!d.has(h.id)&&(o.push(h),d.add(h.id));}}};return (i==="outgoing"||i==="both")&&p("outgoing"),(i==="incoming"||i==="both")&&p("incoming"),{nodes:o.slice(0,n),edges:a.slice(0,n)}}queryCallGraph(e,r=2){let t=new Map,i=new Set,n=(a,o)=>{if(o>r||i.has(a))return;i.add(a);let d=[],c=[],l=this.db.queryEdges({target:a,relation:"CALLS"});for(let u of l)d.push(u.source),n(u.source,o+1);let p=this.db.queryEdges({source:a,relation:"CALLS"});for(let u of p)c.push(u.target),n(u.target,o+1);t.set(a,{callers:d,callees:c});};return n(e,0),t}queryInheritance(e){I.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let r=[],t=[],i=new Set,n=new Set,a=d=>{if(i.has(d))return;i.add(d);let c=this.db.queryEdges({source:d,relation:"EXTENDS"}),l=this.db.queryEdges({source:d,relation:"IMPLEMENTS"});for(let p of [...c,...l]){let u=this.db.getNodeById(p.target);u&&(r.push(u),a(p.target));}},o=d=>{if(n.has(d))return;n.add(d);let c=this.db.queryEdges({target:d,relation:"EXTENDS"}),l=this.db.queryEdges({target:d,relation:"IMPLEMENTS"});for(let p of [...c,...l]){let u=this.db.getNodeById(p.source);u&&(t.push(u),o(p.source));}};return a(e),o(e),{ancestors:r,descendants:t}}queryMembers(e,r){let t=r?Array.isArray(r)?r:[r]:["HAS_METHOD","HAS_PROPERTY"],i=[],n=new Set;for(let a of t){let o=this.db.queryEdges({source:e,relation:a});for(let d of o){if(n.has(d.target))continue;n.add(d.target);let c=this.db.getNodeById(d.target);c&&i.push(c);}}return i}queryOverrides(e){let r=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),t=[],i=new Set;for(let n of r){if(i.has(n.target))continue;i.add(n.target);let a=this.db.getNodeById(n.target);a&&t.push(a);}return t}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}getDatabase(){return this.db}};function sr(y){return new ee(y)}function rt(y){return Filesystem.join(y,".easbot")}function Wi(y){return Filesystem.join(rt(y),"codebase.json")}function ke(y){return Filesystem.join(rt(y),"db","codebase.db")}function zi(y){let e=Filesystem.dirname(ke(y));existsSync(e)||mkdirSync(e,{recursive:true});}function it(y){existsSync(y)||mkdirSync(y,{recursive:true});}function Bi(y){let e=y?.dir;return e&&Filesystem.isAbsolute(e)?e:e?Filesystem.join(l(),e):l()}var v=Log.create({service:"codebase"}),mr={database:{path:Filesystem.resolve(".easbot/db/codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},Ae=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"writeBackend",null);a(this,"writeProxy",null);a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);a(this,"codebasePackageVersion");a(this,"fileWatcher",null);this.config={...mr,...e};let r=e.workspaceDir??process.cwd(),t=e.database?.path||ke(r);this.config={workspaceDir:r,database:{path:t,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},a$2.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let i=this.resolveDbPath();it(Filesystem.dirname(i)),this.db=new n(i),this.parserManager=new V,this.queryInterface=new ee(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=gr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(this.initialized)return;this.db.initialize(),await this.parserManager.initialize();let e=null,r=null;try{e=new me({dbPath:this.db.getDbPath()}),await e.ready,r=new le(this.db,e,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new X(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??!0,embedding:this.config.embeddingLlm},r),this.writeBackend=e,this.writeProxy=r,e=null,r=null;}catch(t){if(v.error("Codebase.initialize failed; rolling back resources",{error:t instanceof Error?t.message:String(t)}),r)try{await r.dispose();}catch(i){v.warn("writeProxy.dispose failed during rollback",{error:String(i)});}if(e)try{await e.dispose();}catch(i){v.warn("writeBackend.dispose failed during rollback",{error:String(i)});}throw t}try{let t=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",t),this.db.setProjectMetadata("project",t),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(t){v.warn("setProjectMetadata failed",{error:String(t)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(t=>v.warn("codebase sync on boot failed",{error:String(t)})),this.initialized=true,v.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){v.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(r=>{v.error("Interval sync failed",{error:String(r)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{v.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Filesystem.isAbsolute(e)?e:Filesystem.join(this.config.workspaceDir,e)}async indexFile(e,r){return await this.ensureInitialized(),this.indexer.indexFile(e,r)}async indexDirectory(e,r){return await this.ensureInitialized(),this.indexer.indexDirectory(e,r)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return v.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let r=await this.indexer.sync(e),t=new Date().toISOString();return r.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,m,t):r.nodesCreated>0||r.filesAdded>0||r.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,m,t),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),v.debug("Codebase sync completed",{success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,nodesCreated:r.nodesCreated,edgesCreated:r.edgesCreated,errors:r.errors.length,duration:r.duration}),this.writeProxy&&await this.writeProxy.flush(),r}catch(r){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),r}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return v.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:r}=await import('./file-watcher-X56TEWNY.mjs'),t=this.config.workspaceDir,i=e?.debounceMs??200,n=e?.initialSync??true,a=new r({workspaceDir:t,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=a;try{await a.start();}catch(p){throw this.fileWatcher=null,p}let o=null,d=new Set,c=()=>{o=null;let p=d.size;d.clear(),p!==0&&(v.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(u=>{v.error("auto-sync after file change failed",{error:u instanceof Error?u.message:String(u)});}));},l=()=>{o&&clearTimeout(o),o=setTimeout(c,i);};return a.on((p,u)=>{v.debug("file change",{event:p,relPath:u}),d.add(u),l();}),n&&this.sync().catch(p=>{v.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),v.info("file watcher started",{workspaceDir:t,debounceMs:i}),{stop:async()=>{o&&(clearTimeout(o),o=null),await a.stop(),this.fileWatcher=null,v.info("file watcher stopped");}}}async search(e,r){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,r)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,r){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,r)}async queryCallGraph(e,r){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,r)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,r){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,r)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let r=this.db.getNodeCount();return r===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:r,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){v.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){v.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){v.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,v.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function on(y){let e=new Ae(y);return await e.initialize(),e}function gr(){try{let e=K.dirname(fileURLToPath(import.meta.url));for(let r=0;r<8;r++){let t=K.join(e,"package.json");try{let n=JSON.parse(readFileSync(t,"utf-8"));if(n&&n.name==="@easbot/codebase"&&typeof n.version=="string")return n.version}catch{}let i=K.dirname(e);if(i===e)break;e=i;}}catch{}return "0.0.0"}export{rt as a,Wi as b,ke as c,zi as d,Bi as e,$e as f,Oe as g,V as h,kt as i,Rt as j,Y as k,Qt as l,J as m,Vt as n,X as o,er as p,ee as q,sr as r,Ae as s,on as t};
@@ -0,0 +1,58 @@
1
+ 'use strict';var chunkNF6CVHEK_cjs=require('./chunk-NF6CVHEK.cjs'),chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var T=class extends Error{constructor(n,c,a){super(n);chunkM2YU5LAI_cjs.a(this,"code",c);chunkM2YU5LAI_cjs.a(this,"details",a);this.name="ServiceError";}},w=class extends T{constructor(e,n=[]){super(`Node not found: ${e}`,"NOT_FOUND",{name:e,candidates:n});}},k=class extends T{constructor(e,n){super(`Ambiguous name "${e}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:e,candidates:n});}};var re=utils.Log.create({service:"codebase-service"}),R=utils.Filesystem.toUnixPath;function Pe(t,e){let n={exact:1,qualified:.85,substring:.5}[t];return e?Math.min(1,n+.2):n}function Se(t,e){if(!e)return false;if(t===e)return true;let n=t.split(/[/\\]/).pop()??"",c=e.split(/[/\\]/).pop()??"";return !!(n&&c&&n===c||e.includes("/")&&t.endsWith("/"+e))}async function M(t,e,n){if(n.nodeId){let o=t.getNode(n.nodeId);if(!o)throw new w(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new T("Either name or nodeId is required","NOT_FOUND",n);let a=t.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(a.length===0)throw new w(n.name);let i=!!n.file,d=n.file?R(n.file):null,s=a.map(o=>{let p=d?Se(R(o.node.file_path),d):false;return {node:o.node,score:Pe(o.matchKind,p),matchKind:o.matchKind,inFile:p}});if(s.sort((o,p)=>p.score-o.score),s.length===1)return {node:s[0].node,candidates:s.map(o=>({node:o.node,score:o.score}))};let l=s[0].score,r=s.filter(o=>o.score===l);if(r.length===1)return {node:r[0].node,candidates:s.slice(0,10).map(o=>({node:o.node,score:o.score}))};if(i&&r.length>1){let o=r.filter(p=>p.inFile);if(o.length===1)return {node:o[0].node,candidates:s.slice(0,10).map(p=>({node:p.node,score:p.score}))}}throw new k(n.name,s.slice(0,10).map(o=>({node:o.node,score:o.score})))}async function P(t){let e=chunkNF6CVHEK_cjs.c(t.rootDir),n=new chunkNF6CVHEK_cjs.s({workspaceDir:t.workspaceDir,database:{path:e,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function oe(t,e,n,c){let a=n.map(()=>"?").join(","),i=e.name.split("@")[0]??e.name,d=i.includes(".")?i.split(".").pop()??i:i,s=new Set([`${e.language}:*:*:${i}`]);d!==i&&s.add(`${e.language}:*:*:${d}`);let l=[];d!==i&&l.push(`${e.language}:*:*:%${d}`);let r=Array.from(s),o=r.map(()=>"?").join(","),u=l.length>0?"OR LOWER(target) LIKE LOWER(?)":"";r.length>1&&re.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:e.name,wildcards:r,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let g=`
2
+ SELECT id, source, target, relation, created_at FROM edges
3
+ WHERE relation IN (${a})
4
+ AND source != target
5
+ AND (
6
+ target = ?
7
+ OR target IN (${o})
8
+ ${u}
9
+ )
10
+ GROUP BY id
11
+ LIMIT ?
12
+ `;return t.queryAll(g,[...n,e.id,...r,...l,c])}function Ie(t){return t==="class_declaration"||t==="class_definition"||t==="interface_declaration"||t==="struct_declaration"||t==="struct_specifier"||t==="record_declaration"}function Te(t,e,n,c,a){let d=t.queryAll("SELECT id FROM nodes WHERE file_path = ? AND start_line >= ? AND end_line <= ? AND ast_type IN ('method_definition', 'method_declaration') LIMIT 1000",[e.file_path,e.start_line,e.end_line]).map(r=>r.id),s=new Set,l=[];for(let r of n)r.id&&!s.has(r.id)&&(s.add(r.id),l.push(r));if(d.length>0){let r=c.map(()=>"?").join(","),o=d.map(()=>"?").join(","),p=`
13
+ SELECT id, source, target, relation, created_at FROM edges
14
+ WHERE relation IN (${r})
15
+ AND source != target
16
+ AND source IN (${o})
17
+ GROUP BY id
18
+ LIMIT ?
19
+ `,u=t.queryAll(p,[...c,...d,a]);for(let g of u)g.id&&!s.has(g.id)&&(s.add(g.id),l.push(g));}return l.slice(0,a)}function se(t,e,n,c){let i=`
20
+ SELECT id, source, target, relation, created_at FROM edges
21
+ WHERE relation IN (${n.map(()=>"?").join(",")})
22
+ AND source != target
23
+ AND source = ?
24
+ LIMIT ?
25
+ `;return t.queryAll(i,[...n,e.id,c])}function ie(t,e,n,c){let a=c==="in"?t.source:t.target;e.id;let d=n.getNodeById(a);if(!d&&a.includes(":*:")){let s=a.split(":").pop()??a,l=s.split("@")[0]??s;if(l&&l!==a){let r=n.findNodesByName({name:l}),o=e.file_path??"",p=o.split(/[/\\]/).pop()??"",u=r.find(g=>!g.node.file_path||!o?false:g.node.file_path===o||p&&g.node.file_path.split(/[/\\]/).pop()===p)??null;u&&(d=u.node);}}if(!d){let s=a.split(":").pop()??a;return {id:a,name:s,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:t.relation}}return {id:d.id,name:d.name,astType:d.ast_type,filePath:R(d.file_path),startLine:d.start_line??0,relation:t.relation}}async function ae(t,e){let n=Date.now(),d=await(await P(t)).getQuery().search(e.query??"",{maxResults:e.maxResults??10,language:e.language,filePath:e.file,astType:e.astType,includeEdges:true,enableFts:e.enableFts!==false,enableEmbedding:e.enableEmbedding!==false});if(e.kind){let r=e.kind.toLowerCase();d=d.filter(o=>o.ast_type.includes(r)||o.name.toLowerCase().includes(r));}if(e.file){let r=R(e.file);d=d.filter(o=>R(o.file_path).endsWith(r)||R(o.file_path).includes(r));}let s=e.maxEdgesPerNode??10,l=d.map(r=>({nodeId:r.id,name:r.name,kind:r.ast_type??"unknown",filePath:R(r.file_path),startLine:r.start_line,endLine:r.end_line,edges:(r.edges??[]).slice(0,s),source:"basic",score:0,snippet:(r.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:l.length,hits:l,durationMs:Date.now()-n,truncated:false}}async function Ce(t,e){let n=await P(t),c=n.getQuery(),a=n.getDatabase(),{node:i}=await M(c,t,e),d=[];if(e.includeEdges){let s=e.maxEdgesPerNode??10,l=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],r=oe(a,i,l,s+1),o=se(a,i,l,s+1),p=new Set,u=[];for(let g of [...r,...o])g.id&&!p.has(g.id)&&(p.add(g.id),u.push(g));d=u.slice(0,s);}return {node:i,edges:d}}var Le=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function $e(t,e){let n=await P(t),c=n.getQuery(),a=n.getDatabase(),{node:i}=await M(c,t,e);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=e.depth??2,s=e.maxNodes??100,l=e.direction??"both";e.maxEdgesPerNode??10;let o=new Map,p=[{nodeId:i.id,depth:0}];o.set(i.id,0);let u=[],g=false;for(;p.length>0;){let m=p.shift();if(m.depth>=d)continue;if(o.size>=s){g=true;break}let $=c.queryNeighbors(m.nodeId,{direction:l,relationTypes:e.relationTypes??Le,limit:s-o.size+1});for(let b of $.edges){u.push(b);let F=b.source===m.nodeId?b.target:b.source;if(!o.has(F)&&(o.set(F,m.depth+1),p.push({nodeId:F,depth:m.depth+1}),o.size>=s)){g=true;break}}if(g)break}let f=new Set,N=[];for(let m of u)!m.id||f.has(m.id)||(f.add(m.id),N.push(m));let h=Array.from(o.keys()),I=h.length>0?a.queryNodes({ids:h}):[],C=new Map(I.map(m=>[m.id,m])),E=[];for(let[m,$]of o.entries()){let b=C.get(m);b&&E.push({node:b,depth:$});}return {root:i,nodes:E,edges:N,truncated:g,totalNodes:E.length,totalEdges:u.length}}var Fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function _e(t,e){let n=await P(t),c=n.getQuery(),a=n.getDatabase(),{node:i}=await M(c,t,e);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=e.depth??2,s=e.maxResults??10,l=e.relationTypes??Fe,r=e.maxEdgesPerNode??10,o=new Set([i.id]),p=[],u=[i.id],g=new Map([[i.id,i.name]]);for(let f=1;f<=d&&!(u.length===0||o.size-1>=s);f++){u.map(()=>"?").join(",");let h=l.map(()=>"?").join(","),I=i,C=u.flatMap(x=>{let D=g.get(x)??"",_=D.split("@")[0]??D,A=new Set([`${I.language}:*:*:${_}`]);if(_.includes(".")){let Q=_.split(".").pop()??_;A.add(`${I.language}:*:*:${Q}`);}return Array.from(A)}),E=[...u,...C],m=E.map(()=>"?").join(","),$=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${h}) LIMIT ?`,[...E,...l,r+1]),b=[],F=new Set;for(let x of $)if(!o.has(x.source)&&!F.has(x.source)&&(F.add(x.source),o.add(x.source),b.push(x.source),o.size-1>=s))break;if(b.length>0){let x=b.slice(0,10),D=a.queryNodes({ids:x}),_=new Map(D.map(y=>[y.id,y]));for(let y of D)y?.name&&!g.has(y.id)&&g.set(y.id,y.name);let A=new Map;for(let y of $)A.has(y.source)||A.set(y.source,y.relation);let Q=x.map(y=>{let Y=_.get(y);return {id:y,name:Y?.name??"(unknown)",filePath:Y?R(Y.file_path):"(unknown)",relation:A.get(y)??"CALLS"}});p.push({depth:f,count:b.length,sample:Q});}u=b;}return p.length===0&&re.warn("impact: no incoming edges found",{root:i.name,depth:d,relationTypes:l}),{root:i,totalImpacted:o.size-1,buckets:p}}var le=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function Ae(t,e){return ce(t,e)}async function we(t,e){return de(t,e)}async function ce(t,e){let n=await P(t),c=n.getQuery(),a=n.getDatabase(),{node:i}=await M(c,t,e);if(!i)return {root:null,callers:[],truncated:false};let d=e.maxResults??10,s=e.maxEdgesPerNode??d,l=e.relationTypes??le,r=oe(a,i,l,s+1),o=[];for(let u of r){let g=ie(u,i,a,"in");g&&o.push(g);}let p=o.length>d;return {root:i,callers:p?o.slice(0,d):o,truncated:p}}async function de(t,e){let n=await P(t),c=n.getQuery(),a=n.getDatabase(),{node:i}=await M(c,t,e);if(!i)return {root:null,callees:[],truncated:false};let d=e.maxResults??10,s=e.maxEdgesPerNode??d,l=e.relationTypes??le,r=se(a,i,l,s+1),o=Ie(i.ast_type)?Te(a,i,r,l,s+1):r,p=[];for(let g of o){let f=ie(g,i,a,"out");f&&p.push(f);}let u=p.length>d;return {root:i,callees:u?p.slice(0,d):p,truncated:u}}async function Oe(t,e){if(!e.query)throw new T("explore requires a non-empty query","NOT_FOUND",{query:e.query});let c=await P(t);c.getQuery();let i=c.getDatabase(),s=(await ae(t,{query:e.query,file:e.file,kind:e.kind,intent:e.intent,maxResults:e.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,l=new Map;for(let u of s){let g=R(u.filePath),f=l.get(g);f?f.push(u):l.set(g,[u]);}let r=e.maxSymbols??3,o=e.maxEdgesPerNode??10,p=[];for(let[u,g]of l){let f=g.slice(0,r),N=[];for(let h of f){let I=await ce(t,{name:h.name,file:u,kind:e.kind,maxResults:o,maxEdgesPerNode:o}),C=await de(t,{name:h.name,file:u,kind:e.kind,maxResults:o,maxEdgesPerNode:o});N.push({node:(()=>{let E={id:h.nodeId,name:h.name,ast_type:h.kind,language:"ts",file_path:h.filePath,start_line:h.startLine??0,end_line:h.endLine??0};try{let m=i.getNodeById(h.nodeId);return {...E,text:m?.text??""}}catch{return {...E,text:""}}})(),callers:I.callers,callees:C.callees});}p.push({file:u,symbols:N});}return {query:e.query,entryPoints:p,totalHits:s.length}}async function De(t,e){return await(await P(t)).getStatus()}async function ke(t,e){return await(await P(t)).healthCheck()}var ue=utils.Filesystem.toUnixPath;function ve(t){let e=t.text??"";if(!e)return false;let n=e.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function He(t){let e=t.text??"";if(!e)return [];let n=e.slice(0,80),c=[];return /\basync\s/.test(n)&&c.push("async"),/\bstatic\s/.test(n)&&c.push("static"),/\babstract\s/.test(n)&&c.push("abstract"),/\breadonly\s/.test(n)&&c.push("readonly"),/\bconst\s/.test(n)&&c.push("const"),/\blet\s/.test(n)&&c.push("let"),c}function S(t){return {id:t.id,name:t.name,astType:t.ast_type,language:t.language,filePath:ue(t.file_path),startLine:t.start_line??0,endLine:t.end_line??0,isExported:ve(t),modifiers:He(t)}}function O(t,e){return {id:t.id,source:t.source,target:t.target,relation:t.relation,direction:e}}function X(t){return t.map(e=>({node:{id:e.nodeId,name:e.name,astType:e.kind,language:"typescript",filePath:ue(e.filePath),startLine:e.startLine??0,endLine:e.endLine??0,isExported:false,modifiers:[]},source:e.source,score:e.score,snippet:(e.snippet??"").slice(0,200),edges:(e.edges??[]).slice(0,10).map(n=>O({...n}))}))}function V(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Be=utils.Log.create({service:"codebase-format-truncate"}),J="**`",Ue="**",pe=24e3,me=25e3;async function B(t,e={}){let n=e.softLimit??pe,c=e.hardCeiling??me,a=e.toolName??"codebase",i=e.writeToDisk!==false;if(t.length<=n)return {content:t,truncated:false};let d=t.slice(0,c),s=d.lastIndexOf(`
26
+ ${J}`),l=d.lastIndexOf(`
27
+ `),r;s>c*.5?r=s:l>0?r=l:r=-1;let o=r>0?d.slice(0,r):d,u=o+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${t.length-o.length}/${t.length} characters truncated ...`};try{let g=await utils.TruncateContent.truncate(t,{maxChars:o.length,direction:"head",label:`${a}-output`});return g.truncated?{content:u,truncated:!0,outputPath:g.outputPath,hint:utils.TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${t.length-o.length}/${t.length} characters truncated ...`}}catch(g){return Be.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${t.length-o.length}/${t.length} characters truncated ...`}}}function U(t,e={}){let n=e.softLimit??pe,c=e.hardCeiling??me;if(t.length<=n)return {content:t,truncated:false};let a=t.slice(0,c),i=a.lastIndexOf(`
28
+ ${J}`),d=a.lastIndexOf(`
29
+ `),s;i>c*.5?s=i:d>0?s=d:s=-1;let l=s>0?a.slice(0,s):a;return {content:l+`
30
+
31
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${t.length-l.length}/${t.length} characters truncated ...`}}function We(t,e=Date.now()){let n=Math.max(0,Math.floor((e-t)/1e3));return n>60?">60s ago":`${n}s ago`}function W(t,e){if(!t||t.length===0)return null;let n=t.filter(a=>e.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${We(a.lastEventAt)})`).join(", ")}
32
+
33
+ `}function v(t,e,n={}){return (fe[t]??fe.default).replace(/<(\w+)>/g,(a,i)=>i==="tool"?e:n[i]??`<${i}>`)}var fe={search:`---
34
+
35
+ > **Complete source for N files is included above \u2014 do NOT re-read them.**
36
+ > If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
37
+
38
+ > **Output truncated to budget; the content above is the source of truth.**
39
+ > For more detail, call \`<tool>\` with refined parameters.`};async function j(t,e){let{pendingFiles:n,toolName:c,sync:a=false}=e;if(t.length===0)return H(c,"No matches found.","Try broader search terms, or use `explore` to read source.");let i=Ge(t),d=new Set(i.keys()),s=[];s.push(W(n,d)??"");let l="[[codebase-search-summary]]";s.push(l+`
40
+ `);let r=t.length;s.push(`**Files with matches:** ${i.size}
41
+ `);for(let[g,f]of i){let N=f.map(E=>E.node.name),h=N.slice(0,5).join(", "),I=N.length>5?`, +${N.length-5} more`:"";s.push(`**\`${g}\`** \u2014 ${h}${I}
42
+ `);let C=f[0]?.node.language??"";s.push("```"+C);for(let E of f)s.push(`L${E.node.startLine} ${E.snippet}`);s.push("```\n");}s.push(v("search",c,{}));let o=s.join(`
43
+ `),p=`Found ${r} symbol${r===1?"":"s"} across ${i.size} file${i.size===1?"":"s"}.`,u=o.replace(l,p);return q(u,e,a)}async function G(t,e,n){let{pendingFiles:c,toolName:a,sync:i=false}=n;if(e.length===0||e.every(r=>r.count===0))return H(a,`No incoming edges for \`${t.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=e.reduce((r,o)=>r+o.count,0),s=je(d),l=[];l.push(W(c,new Set([t.filePath]))??""),l.push(`**Impact for \`${t.name}\`** (root: ${t.filePath}:${t.startLine}, total impacted: ${d})
44
+ `);for(let r of e){l.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let o of r.samples.slice(0,5))l.push(` - \`${o.name}\` ${o.file}:${o.line} [${o.relation}]`);r.samples.length>5&&l.push(` - ... and ${r.samples.length-5} more`);}return l.push(v("impact",a,{root:t.name,riskLevel:s})),q(l.join(`
45
+ `),n,i)}function je(t){return t>=100?"CRITICAL":t>=50?"HIGH":t>=10?"MEDIUM":"LOW"}function Z(t){return t===1?"WILL BREAK (direct callers)":t===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function ee(t,e){let{root:n,incoming:c,outgoing:a,neighbors:i}=t,{pendingFiles:d,toolName:s,sync:l=false}=e;if(c.length===0&&a.length===0&&i.length===0)return H(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(W(d,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
46
+ `),r.push(`**Incoming** (${c.length}):`);for(let o of c.slice(0,10))r.push(`- ${o.source} \u2192 [${o.relation}] \u2192 \`${n.name}\``);c.length>10&&r.push(`- ... and ${c.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let o of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${o.relation}] \u2192 ${o.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),i.length>0){r.push(`**Neighbors** (${i.length}):`);for(let o of i.slice(0,20))r.push(`- [d=${o.depth}] \`${o.node.name}\` (${o.node.astType}) ${o.node.filePath}:${o.node.startLine}`);i.length>20&&r.push(`- ... and ${i.length-20} more`),r.push("");}return r.push(v("context",s,{})),q(r.join(`
47
+ `),e,l)}async function K(t,e,n){let{pendingFiles:c,toolName:a,sync:i=false}=n;if(!t.id)return H(a,"Node not found.","Check the node ID or use `search` to find it.");let d=e.filter(r=>r.direction==="in"),s=e.filter(r=>r.direction==="out"),l=[];l.push(W(c,new Set([t.filePath]))??""),l.push(`**Node: \`${t.name}\`**
48
+ `),l.push(`- ID: \`${t.id}\``),l.push(`- Kind: ${t.astType}`),l.push(`- Language: ${t.language}`),l.push(`- Location: ${t.filePath}:${t.startLine}-${t.endLine}`),l.push(`- Exported: ${t.isExported}`),t.modifiers.length>0&&l.push(`- Modifiers: ${t.modifiers.join(", ")}`),l.push(""),l.push(`**Edges** (incoming: ${d.length} / outgoing: ${s.length}):`);for(let r of d.slice(0,5))l.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))l.push(`- \u2192 [${r.relation}] ${r.target}`);return e.length>10&&l.push(`- ... and ${e.length-10} more`),l.push(v("default",a,{})),q(l.join(`
49
+ `),n,i)}async function he(t,e){let{entryPoints:n,totalHits:c,query:a}=t,{toolName:i,sync:d=false}=e;if(n.length===0)return H(i,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
50
+ `),s.push(`**Query:** ${a} `),s.push(`**Total hits:** ${c} `),s.push(`**Entry points:** ${n.length}
51
+ `);for(let l of n){s.push(`**\`${l.file}\`** \u2014 ${l.symbols.length} symbol${l.symbols.length===1?"":"s"}
52
+ `);for(let r of l.symbols){let o=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(o),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
53
+ `),s.push(v("context",i,{})),q(s.join(`
54
+ `),e,d)}function Ge(t){let e=new Map;for(let n of t){let c=n.node.filePath,a=e.get(c);a?a.push(n):e.set(c,[n]);}return e}function H(t,e,n){return `**${t}**
55
+
56
+ ${e}
57
+
58
+ > **Tip:** ${n}`}async function q(t,e,n){let c={softLimit:e.softLimit,hardCeiling:e.hardCeiling,toolName:e.toolName,writeToDisk:n?false:e.writeToDisk};return (n?U(t,c):await B(t,c)).content}var Qe=utils.Log.create({service:"codebase-format-render"});async function Ye(t,e){if(t.length===0)return j([],e);let n=X(t);return j(n,e)}async function ze(t,e,n){if(e.length===0)return G(S(t),[],n);let c=[{depth:1,count:e.length,riskLabel:Z(1),samples:e.slice(0,10).map(a=>({name:a.source.name,file:S(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return G(S(t),c,n)}async function Xe(t,e,n,c,a){let i=S(t),d=e.map(r=>O(r,"in")),s=n.map(r=>O(r,"out")),l=c.map(r=>({node:S(r),depth:1}));return ee({root:i,incoming:d,outgoing:s,neighbors:l},a)}async function Ve(t,e,n){if(!t)return K(V(),[],n);let c=S(t),a=e.map(i=>{let d=i.target===t.id?"in":"out";return O(i,d)});return K(c,a,n)}async function Je(t,e){let n={query:t.query,totalHits:t.totalHits,entryPoints:t.entryPoints.map(c=>({file:c.file,symbols:c.symbols.map(a=>({node:S(a.node),source:a.node.text??"",callers:a.callers.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation})),callees:a.callees.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation}))}))}))};return he(n,e)}Qe.debug("format/render.ts loaded");exports.A=ze;exports.B=Xe;exports.C=Ve;exports.D=Je;exports.a=T;exports.b=w;exports.c=k;exports.d=ae;exports.e=Ce;exports.f=$e;exports.g=_e;exports.h=Ae;exports.i=we;exports.j=Oe;exports.k=De;exports.l=ke;exports.m=S;exports.n=O;exports.o=X;exports.p=V;exports.q=J;exports.r=Ue;exports.s=B;exports.t=U;exports.u=j;exports.v=G;exports.w=Z;exports.x=ee;exports.y=K;exports.z=Ye;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-2YMB6W5S.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join}from'path';import {createRequire}from'module';import {Log,Ignore,PKG,Shell}from'@easbot/utils';var o=Log.create({service:"codebase-file-watcher"});function O(){return process.env.EASBOT_CACHE_PATH||join(process.cwd(),".easbot","cache")}var S=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],s=class s{constructor(){a(this,"wrapper",null);a(this,"error",null);}static get(){return s.instance||(s.instance=new s),s.instance}static clearCache(){s.instance&&(s.instance.wrapper=null,s.instance.error=null);}};a(s,"instance",null);var f=s;function A(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function C(){let r=f.get();if(r.wrapper)return r.wrapper;if(r.error)throw new Error(r.error);let e=A(),t=O(),i;try{await R(e,t)?i=join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await T(e,t));}catch(l){let p=l instanceof Error?l.message:String(l),g=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=g,o.error("failed to install parcel watcher binding",{error:l,binding:e}),new Error(g)}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:h}=await import('@parcel/watcher/wrapper.js'),u=createRequire(join(i,"package.json"))(e),c=h(u);return r.wrapper=c,c}async function R(r,e){try{return !!await PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function T(r,e){return o.info("Installing Parcel watcher binding",{binding:r,cachePath:e}),await Shell.install(r,"latest",e),join(e,"node_modules",r)}function w(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var m=class{constructor(e){a(this,"workspaceDir");a(this,"backendOpt");a(this,"ignorePatterns");a(this,"onLoadFailure");a(this,"ignoreInstance");a(this,"listeners",new Set);a(this,"unsubscribe",null);a(this,"disposed",false);a(this,"running",false);this.workspaceDir=isAbsolute(e.workspaceDir)?e.workspaceDir:normalize(e.workspaceDir),this.backendOpt=e.backend??"auto",this.ignorePatterns=e.ignorePatterns??[...S],this.onLoadFailure=e.onLoadFailure??"throw",this.ignoreInstance=Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?w():this.backendOpt}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){if(this.running)return;this.running=true;let e=this.backendOpt==="auto"?w():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await C();}catch(i){if(this.running=false,this.onLoadFailure==="warn")return;throw i}await this.subscribeWithParcel(t,e);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(e){o.warn("parcel unsubscribe error",{error:e});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}static clearParcelWrapperCache(){f.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let i=(a,u)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),l=u.replace(/\\/g,"/"),p=u;if(l.startsWith(c+"/")&&(p=l.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let g=a==="create"?"add":a==="delete"?"unlink":"change";for(let v of this.listeners)try{v(g,p);}catch(k){o.warn("listener threw",{error:k});}},h=await e.subscribe(this.workspaceDir,(a,u)=>{if(a){o.error("parcel subscribe callback error",{error:a});return}for(let c of u)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await h.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await h.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:a});});};}};function b(r){return join(r,".watcher.pid")}function M(r){let e=b(r);if(!existsSync(e))return null;try{let t=readFileSync(e,"utf-8").trim(),i=parseInt(t,10);return Number.isFinite(i)?i:null}catch{return null}}async function N(r,e){let t=b(r);await promises.writeFile(t,String(e),"utf-8");}async function z(r){let e=b(r);try{await promises.unlink(e);}catch{}}export{m as a,b,M as c,N as d,z as e};
@@ -0,0 +1 @@
1
+ export{c as COMMANDS_HELP,d as handleCodebaseCli,e as mapCodebaseDoctor,a as renderBanner,b as renderHelp}from'./chunk-AIUVBWJX.mjs';import'./chunk-ZPEE2LSX.mjs';import'./chunk-SQJ64NFE.mjs';import'./chunk-STDI2Q67.mjs';import'./chunk-34CU2EU4.mjs';import'./chunk-EWVG3S6R.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk5E5YY2J3_cjs=require('./chunk-5E5YY2J3.cjs');require('./chunk-4HJ7RFP7.cjs'),require('./chunk-WC5CUSXD.cjs'),require('./chunk-NF6CVHEK.cjs'),require('./chunk-JVX6PHPN.cjs'),require('./chunk-PLI6SXTS.cjs'),require('./chunk-VPWALTY7.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk5E5YY2J3_cjs.c}});Object.defineProperty(exports,"handleCodebaseCli",{enumerable:true,get:function(){return chunk5E5YY2J3_cjs.d}});Object.defineProperty(exports,"mapCodebaseDoctor",{enumerable:true,get:function(){return chunk5E5YY2J3_cjs.e}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk5E5YY2J3_cjs.a}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk5E5YY2J3_cjs.b}});
@@ -0,0 +1 @@
1
+ 'use strict';var chunkNF6CVHEK_cjs=require('./chunk-NF6CVHEK.cjs');require('./chunk-JVX6PHPN.cjs');var chunkPLI6SXTS_cjs=require('./chunk-PLI6SXTS.cjs');require('./chunk-VPWALTY7.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.s}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.m}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.g}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.o}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.k}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.h}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.q}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.t}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.n}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.p}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.l}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.r}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.i}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunkNF6CVHEK_cjs.j}});Object.defineProperty(exports,"ConfigError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.e}});Object.defineProperty(exports,"DatabaseError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.b}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.n}});Object.defineProperty(exports,"FileSystemError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.c}});Object.defineProperty(exports,"IndexError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.f}});Object.defineProperty(exports,"ParserError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.a}});Object.defineProperty(exports,"QueryError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.g}});Object.defineProperty(exports,"SchemaError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.d}});Object.defineProperty(exports,"UnsupportedLanguageError",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.h}});
@@ -1 +1 @@
1
- export{s as CodeBase,m as EdgeExtractor,g as FILE_EXTENSION_MAP,o as Indexer,k as NodeExtractor,h as ParserManager,q as QueryInterface,t as createCodebase,n as createEdgeExtractor,p as createIndexer,l as createNodeExtractor,r as createQueryInterface,i as getParserManager,j as resetParserManager}from'./chunk-DHH2XXGJ.mjs';import'./chunk-34CU2EU4.mjs';export{e as ConfigError,b as DatabaseError,n as DatabaseManager,c as FileSystemError,f as IndexError,a as ParserError,g as QueryError,d as SchemaError,h as UnsupportedLanguageError}from'./chunk-GWR5LCUV.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';
1
+ export{s as CodeBase,m as EdgeExtractor,g as FILE_EXTENSION_MAP,o as Indexer,k as NodeExtractor,h as ParserManager,q as QueryInterface,t as createCodebase,n as createEdgeExtractor,p as createIndexer,l as createNodeExtractor,r as createQueryInterface,i as getParserManager,j as resetParserManager}from'./chunk-STDI2Q67.mjs';import'./chunk-34CU2EU4.mjs';export{e as ConfigError,b as DatabaseError,n as DatabaseManager,c as FileSystemError,f as IndexError,a as ParserError,g as QueryError,d as SchemaError,h as UnsupportedLanguageError}from'./chunk-EWVG3S6R.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunkPLI6SXTS_cjs=require('./chunk-PLI6SXTS.cjs');require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.n}});Object.defineProperty(exports,"EXTRACTION_VERSION",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.m}});Object.defineProperty(exports,"getDbPath",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.p}});Object.defineProperty(exports,"isClosed",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.o}});Object.defineProperty(exports,"transaction",{enumerable:true,get:function(){return chunkPLI6SXTS_cjs.q}});
@@ -0,0 +1 @@
1
+ export{n as DatabaseManager,m as EXTRACTION_VERSION,p as getDbPath,o as isClosed,q as transaction}from'./chunk-EWVG3S6R.mjs';import'./chunk-2YMB6W5S.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk4HJ7RFP7_cjs=require('./chunk-4HJ7RFP7.cjs');require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"FileWatcher",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.a}});Object.defineProperty(exports,"clearWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.e}});Object.defineProperty(exports,"getWatcherPidPath",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.b}});Object.defineProperty(exports,"readWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.c}});Object.defineProperty(exports,"writeWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.d}});
@@ -0,0 +1 @@
1
+ export{a as FileWatcher,e as clearWatcherPid,b as getWatcherPidPath,c as readWatcherPid,d as writeWatcherPid}from'./chunk-ZPEE2LSX.mjs';import'./chunk-2YMB6W5S.mjs';