@easbot/codebase 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{chunk-O3Z5ORQ3.mjs → chunk-3ZA3AOKC.mjs} +52 -37
- package/dist/chunks/{chunk-BL4XMOO2.cjs → chunk-AUNBGHMC.cjs} +52 -37
- package/dist/chunks/{chunk-SV4WN2DV.mjs → chunk-CJSKATXN.mjs} +1 -1
- package/dist/chunks/{chunk-YOFBT3V6.cjs → chunk-IXERCMYQ.cjs} +1 -1
- package/dist/chunks/chunk-JDULI4R5.cjs +234 -0
- package/dist/chunks/{chunk-PSPE6FME.mjs → chunk-TGMIUXU3.mjs} +1 -1
- package/dist/chunks/chunk-VBIXWHTD.mjs +234 -0
- package/dist/chunks/{chunk-B35QBUQP.cjs → chunk-XAODNPHT.cjs} +1 -1
- package/dist/chunks/{code-base-ONPUU5A3.cjs → code-base-HCFLEKJN.cjs} +1 -1
- package/dist/chunks/code-base-N3PTDWLC.mjs +1 -0
- package/dist/chunks/{stdio-server-3HFZJ5G2.mjs → stdio-server-DIGUR2PS.mjs} +1 -1
- package/dist/chunks/{stdio-server-3DPRM3WQ.cjs → stdio-server-LJGVWMB7.cjs} +6 -6
- package/dist/chunks/sync-52O2GQKE.cjs +1 -0
- package/dist/chunks/sync-JNCNYSWI.mjs +1 -0
- package/dist/cli.cjs +1 -2
- package/dist/cli.mjs +1 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.mjs +1 -1
- package/package.json +6 -6
- package/dist/chunks/chunk-ABKFCPSL.cjs +0 -234
- package/dist/chunks/chunk-LBEWQNER.mjs +0 -234
- package/dist/chunks/code-base-XJXVJ35Z.mjs +0 -1
- package/dist/chunks/sync-D5GNVNM2.mjs +0 -1
- package/dist/chunks/sync-IYOM3Y62.cjs +0 -1
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import {a as a$2,h,f,c,g,n,e,m}from'./chunk-Z4Y3VCYS.mjs';import {d}from'./chunk-UTKA3WG3.mjs';import {a as a$1,b}from'./chunk-G3IYU6TZ.mjs';import U from'path';import {readFileSync}from'fs';import {fileURLToPath}from'url';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,Shell,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import je from'fs/promises';import {createHash}from'crypto';import Bt from'fast-glob';import {streamText}from'ai';var Me={".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 oe=Filesystem.toUnixPath,Je=`
|
|
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
|
+
`,Xe=`
|
|
5
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
6
|
+
VALUES (?, ?, ?, ?, ?)
|
|
7
|
+
`,Ze="DELETE FROM nodes_fts WHERE rowid = (SELECT rowid FROM nodes_fts WHERE id = ?)",et="INSERT INTO nodes_fts (id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)";var tt=`
|
|
8
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
9
|
+
VALUES (?, ?, ?)
|
|
10
|
+
`,rt=`
|
|
11
|
+
INSERT OR IGNORE INTO embedding_cache (content_hash, embedding)
|
|
12
|
+
VALUES (?, ?)
|
|
13
|
+
`,it=`
|
|
14
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
15
|
+
VALUES (?, ?, ?)
|
|
16
|
+
`;var nt="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",at="DELETE FROM nodes WHERE file_path = ?";var st="DELETE FROM file_hashes WHERE file_path = ?",j="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",ot="DELETE FROM meta WHERE key = ?",ce=class{constructor(e,t,r={}){a$1(this,"db",e);a$1(this,"writeBackend",t);a$1(this,"options",r);}insertNodes(e){if(e.length===0)return;let t=[];for(let r of e){let i=r.file_path.replace(/\\/g,"/");t.push({sql:Je,params:[r.id,r.name,r.ast_type,r.language,i,r.start_line,r.start_col,r.end_line,r.end_col,r.text,r.created_at]}),this.options.ftsAvailable&&(t.push({sql:Ze,params:[r.id]}),t.push({sql:et,params:[r.id,r.name,r.ast_type,r.language,i,r.text]}));}this.writeBackend.enqueue(t);}insertEdges(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:Xe,params:[r.id,r.source,r.target,r.relation,r.created_at]});this.writeBackend.enqueue(t);}setFileHash(e,t){this.writeBackend.enqueue([{sql:tt,params:[oe(e),t,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,t){this.writeBackend.enqueue([{sql:rt,params:[e,Buffer.from(t.buffer,t.byteOffset,t.byteLength)]}]);}storeNodeEmbeddings(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:it,params:[r.nodeId,r.embeddingText,Buffer.from(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength)]});this.writeBackend.enqueue(t);}deleteEdgesByFile(e){let t=oe(e);return this.writeBackend.enqueue([{sql:nt,params:[t,t]}]),-1}deleteNodesByFile(e){let t=oe(e);return this.writeBackend.enqueue([{sql:at,params:[t]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:st,params:[oe(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,t){this.writeBackend.enqueue([{sql:j,params:[e,t]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:ot,params:[e]}]);}markIndexed(e,t,r){let i=[{sql:j,params:["indexed_with_version",e]},{sql:j,params:["indexed_with_extraction_version",String(t)]},{sql:j,params:["index_state","complete"]},{sql:j,params:["last_index_state_change",r]}];this.writeBackend.enqueue(i);}setIndexState(e){let t=new Date().toISOString(),r=[{sql:j,params:["index_state",e]},{sql:j,params:["last_index_state_change",t]}];this.writeBackend.enqueue(r);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function ct(){return `
|
|
17
|
+
const { parentPort } = require('node:worker_threads');
|
|
18
|
+
|
|
19
|
+
if (parentPort !== null) {
|
|
20
|
+
const port = parentPort;
|
|
21
|
+
let queueDepth = 0;
|
|
22
|
+
|
|
23
|
+
port.on('message', (msg) => {
|
|
24
|
+
if (msg.type === 'shutdown') {
|
|
25
|
+
const reqId = msg.requestId;
|
|
26
|
+
// \u7B49\u961F\u5217 drain \u518D exit\uFF08\u4EFF Real worker drainInterval \u6A21\u5F0F\uFF09
|
|
27
|
+
const drainInterval = setInterval(() => {
|
|
28
|
+
if (queueDepth === 0) {
|
|
29
|
+
clearInterval(drainInterval);
|
|
30
|
+
port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
|
|
31
|
+
process.exit(0);
|
|
32
|
+
}
|
|
33
|
+
}, 5);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (msg.type === 'ping') {
|
|
37
|
+
port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (msg.type === 'open') {
|
|
41
|
+
port.postMessage({ type: 'open_ack', requestId: msg.requestId });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (msg.type === 'flush') {
|
|
45
|
+
port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (msg.type === 'write_batch') {
|
|
49
|
+
const reqId = msg.requestId;
|
|
50
|
+
queueDepth++;
|
|
51
|
+
const affected = (msg.statements || []).reduce((sum, s) => sum + (s.affectedRows || 0), 0);
|
|
52
|
+
setTimeout(() => {
|
|
53
|
+
queueDepth--;
|
|
54
|
+
port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
|
|
55
|
+
}, 10);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
port.postMessage({ type: 'ready' });
|
|
60
|
+
}
|
|
61
|
+
`}function qe(){return new Worker(ct(),{eval:true})}function dt(y){return `
|
|
62
|
+
const { parentPort } = require('node:worker_threads');
|
|
63
|
+
|
|
64
|
+
if (parentPort !== null) {
|
|
65
|
+
const port = parentPort;
|
|
66
|
+
let Database;
|
|
67
|
+
try {
|
|
68
|
+
Database = require(${JSON.stringify(y)});
|
|
69
|
+
} catch (err) {
|
|
70
|
+
port.postMessage({ type: 'error', requestId: -1, error: 'better-sqlite3 not loadable at ${y}: ' + err.message });
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let db = null;
|
|
75
|
+
let queueDepth = 0;
|
|
76
|
+
const queueMax = 1000;
|
|
77
|
+
// 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
|
|
78
|
+
// \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
|
|
79
|
+
const txTimeoutMs = 300000;
|
|
80
|
+
// Wave 5 \u5927\u4ED3 sync \u4F18\u5316\uFF1Astatement cache \u2014\u2014 30K files \xD7 11 stmts = 330K \u6B21 prepare \u592A\u6162
|
|
81
|
+
// \u5B9E\u6D4B 1407 files sync \u8DD1\u5230 53% \u65F6 5min flush timeout \u2014\u2014 \u6839\u56E0\u662F\u91CD\u590D prepare
|
|
82
|
+
// \u4FEE\uFF1AMap<sql, prepared statement> \u7F13\u5B58\uFF0C\u540C SQL \u6A21\u677F\u590D\u7528 prepared \u5BF9\u8C61
|
|
83
|
+
const stmtCache = new Map();
|
|
84
|
+
|
|
85
|
+
function getPrepared(sql) {
|
|
86
|
+
let prepared = stmtCache.get(sql);
|
|
87
|
+
if (!prepared) {
|
|
88
|
+
prepared = db.prepare(sql);
|
|
89
|
+
stmtCache.set(sql, prepared);
|
|
90
|
+
}
|
|
91
|
+
return prepared;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function runStatement(stmt) {
|
|
95
|
+
try {
|
|
96
|
+
const prepared = getPrepared(stmt.sql);
|
|
97
|
+
const info = prepared.run(...(stmt.params || []));
|
|
98
|
+
return info.changes || 0;
|
|
99
|
+
} catch (err) {
|
|
100
|
+
// Wave 4 R3-2\uFF1Aworker \u7AEF debug \u65E5\u5FD7 \u2014\u2014 \u771F\u51F6\u96BE\u8FFD\uFF0C\u52A0\u8BE6\u7EC6 error \u4FE1\u606F
|
|
101
|
+
// \u8F93\u51FA SQL + params + error \u8BE6\u60C5\uFF08\u901A\u8FC7 stderr \u2192 \u4E3B\u8FDB\u7A0B\uFF09
|
|
102
|
+
port.postMessage({
|
|
103
|
+
type: 'debug_error',
|
|
104
|
+
requestId: -1,
|
|
105
|
+
sql: stmt.sql,
|
|
106
|
+
paramsCount: (stmt.params || []).length,
|
|
107
|
+
paramsJson: JSON.stringify(stmt.params || []).slice(0, 500),
|
|
108
|
+
error: err.message,
|
|
109
|
+
});
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
port.on('message', (msg) => {
|
|
115
|
+
if (msg.type === 'shutdown') {
|
|
116
|
+
const reqId = msg.requestId;
|
|
117
|
+
const drainInterval = setInterval(() => {
|
|
118
|
+
if (queueDepth === 0) {
|
|
119
|
+
clearInterval(drainInterval);
|
|
120
|
+
try { if (db) db.close(); } catch (e) {}
|
|
121
|
+
port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
|
|
122
|
+
process.exit(0);
|
|
123
|
+
}
|
|
124
|
+
}, 5);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (msg.type === 'ping') {
|
|
128
|
+
port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (msg.type === 'open') {
|
|
132
|
+
const reqId = msg.requestId;
|
|
133
|
+
try {
|
|
134
|
+
if (db) db.close();
|
|
135
|
+
db = new Database(msg.dbPath, { timeout: txTimeoutMs });
|
|
136
|
+
db.pragma('journal_mode = WAL');
|
|
137
|
+
db.pragma('synchronous = NORMAL');
|
|
138
|
+
// Wave 3 \u8BC4\u5BA1 R3\uFF1Aworker \u4E5F\u8981\u5F00 FK \u7EA7\u8054 \u2014\u2014 \u5220 nodes \u81EA\u52A8\u7EA7\u8054\u6E05 node_embeddings / edges
|
|
139
|
+
db.pragma('foreign_keys = ON');
|
|
140
|
+
port.postMessage({ type: 'open_ack', requestId: reqId });
|
|
141
|
+
} catch (err) {
|
|
142
|
+
port.postMessage({ type: 'error', requestId: reqId, error: err.message });
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (msg.type === 'flush') {
|
|
147
|
+
port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (msg.type === 'write_batch') {
|
|
151
|
+
const reqId = msg.requestId;
|
|
152
|
+
if (!db) {
|
|
153
|
+
port.postMessage({ type: 'error', requestId: reqId, error: 'db not open' });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (queueDepth >= queueMax) {
|
|
157
|
+
port.postMessage({ type: 'error', requestId: reqId, error: 'queue overflow (' + queueDepth + '/' + queueMax + ')' });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
queueDepth++;
|
|
161
|
+
try {
|
|
162
|
+
const tx = db.transaction((statements) => {
|
|
163
|
+
let totalChanges = 0;
|
|
164
|
+
for (const stmt of statements) {
|
|
165
|
+
totalChanges += runStatement(stmt);
|
|
166
|
+
}
|
|
167
|
+
return totalChanges;
|
|
168
|
+
});
|
|
169
|
+
const affected = tx(msg.statements || []);
|
|
170
|
+
port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
|
|
171
|
+
} catch (err) {
|
|
172
|
+
port.postMessage({ type: 'error', requestId: reqId, error: err.message });
|
|
173
|
+
} finally {
|
|
174
|
+
queueDepth--;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
port.postMessage({ type: 'ready' });
|
|
180
|
+
}
|
|
181
|
+
`}function Te(y,e){return new Worker(dt(e.betterSqlite3Path),{eval:true})}var le=Log.create({service:"codebase.better-sqlite3-resolver"}),Ae=createRequire(import.meta.url);async function Oe(y={}){try{let s=Ae.resolve("better-sqlite3");if(s)return le.debug("better-sqlite3 resolved from monorepo",{resolved:s}),{absolutePath:Filesystem.normalize(s),source:"monorepo"}}catch(s){le.debug("better-sqlite3 not in current resolve paths",{error:s instanceof Error?s.message:String(s)});}let e=process.env.EASBOT_CACHE_PATH,t=y.installPath??e??`${process.cwd()}/.easbot/cache`,r=Filesystem.normalize(t),i=y.version??"latest";le.info("better-sqlite3 not found locally, installing to cache",{installPath:r,version:i,envCache:e});let n;try{n=await Shell.install("better-sqlite3",i,r);}catch(s){throw new pe(`Failed to install better-sqlite3@${i} into ${r}: ${s instanceof Error?s.message:String(s)}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,r)}try{let s=Ae.resolve("better-sqlite3",{paths:[n]}),l=Filesystem.normalize(s),c=r===Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return le.info("better-sqlite3 installed and resolved",{resolved:l,installPath:r}),{absolutePath:l,source:c}}catch(s){throw new pe(`Installed better-sqlite3 to ${n} but cannot resolve entry from there: ${s instanceof Error?s.message:String(s)}`,n)}}var pe=class extends Error{constructor(t,r){super(t);a$1(this,"installPath");this.name="BetterSqlite3ResolveError",this.installPath=r;}};var te=Log.create({service:"database.async-write"}),we,ee,ue=class{constructor(e){a$1(this,"worker");a$1(this,"mock");a$1(this,"dbPath");a$1(this,"batchSize");a$1(this,"batchIntervalMs");a$1(this,"queueMax");a$1(this,"bufferedStatements",[]);a$1(this,"pendingRequests",new Map);a$1(this,"nextRequestId",1);a$1(this,"flushTimer",null);a$1(this,"ready");a$1(this,"disposed",false);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=qe(),this.ready=this.waitForReady();else {let t=e.betterSqlite3Path;t?(this.worker=Te(this.dbPath,{betterSqlite3Path:t}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await gt();this.worker=Te(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",t=>{let r=t;if(r.type==="debug_error"){te.error("AsyncWriteBackend statement failed (debug)",{sql:r.sql?.slice(0,200),paramsCount:r.paramsCount,params:r.paramsJson,error:r.error});return}if(typeof r.requestId!="number"||r.requestId<1)return;let i=this.pendingRequests.get(r.requestId);i&&(this.pendingRequests.delete(r.requestId),clearTimeout(i.timer),r.type==="write_batch_ack"?i.resolve():r.type==="error"&&i.reject(new Error(r.error??"worker write error")));});}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((t,r)=>{let i=setTimeout(()=>r(new Error("worker init timeout")),1e4),n=s=>{if(s.type==="ready"){clearTimeout(i),e.off("message",n);let l=setTimeout(()=>r(new Error("worker open timeout")),1e4),c=o=>{o.type==="open_ack"&&o.requestId===0?(clearTimeout(l),e.off("message",c),t()):o.type==="error"&&o.requestId===0&&(clearTimeout(l),e.off("message",c),r(new Error(o.error??"worker open error")));};e.on("message",c),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else s.type==="error"&&s.requestId===-1&&(clearTimeout(i),e.off("message",n),r(new Error(s.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 t=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+t>=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 t=this.nextRequestId++,r={resolve:()=>{},reject:i=>{te.error("AsyncWriteBackend write failed",{error:i.message,requestId:t});},timer:setTimeout(()=>{this.pendingRequests.delete(t),r.reject(new Error(`AsyncWriteBackend write timeout (${t})`));},3e4)};this.pendingRequests.set(t,r),this.worker.postMessage({type:"write_batch",statements:e,requestId:t});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT_MS??"3600000",10)||36e5){if(this.flushBuffer(),this.pendingRequests.size===0)return;let t=this.pendingRequests.size,r=Date.now();await new Promise((i,n)=>{let s=setTimeout(()=>n(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),l=setInterval(()=>{let o=this.pendingRequests.size,d=Math.floor((Date.now()-r)/1e3);o>0&&d>0&&d%5===0&&te.info("flush in progress",{pending:o,initial:t,elapsedSec:d});},1e3),c=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(s),clearInterval(c),clearInterval(l),i());},5);});}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){te.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}};async function gt(){return we||(ee||(ee=Oe().then(y=>(we=y.absolutePath,ee=void 0,te.info("better-sqlite3 resolved for AsyncWriteBackend",{path:y.absolutePath,source:y.source}),y.absolutePath)).catch(y=>{throw ee=void 0,y})),ee)}var De=Log.create({service:"codebase-parser"}),_t={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 bt(){return typeof import.meta<"u"&&import.meta.url?U.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function xt(y,e){let t=bt(),r=t;for(let i=0;i<10;i++){let n=U.join(r,"node_modules",y,e);if(Filesystem.stat(n)!==void 0)return n;let s=U.dirname(r);if(s===r)break;r=s;}return U.join(t,"node_modules",y,e)}var V=class{constructor(){a$1(this,"parsers",new Map);a$1(this,"initialized",false);a$1(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'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let i=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],n=await Promise.allSettled(i.map(async s=>{try{let l=_t[s];if(!l)return De.warn("No WASM config for language",{lang:s}),null;let c=xt(l.package,l.wasmFile),o=await r.load(c),d=new t;return d.setLanguage(o),{lang:s,parser:d,language:o}}catch(l){return De.warn("Failed to load parser",{lang:s,error:String(l)}),null}}));for(let s of n)if(s.status==="fulfilled"&&s.value){let{lang:l,parser:c,language:o}=s.value;this.parsers.set(l,{parser:c,language:o});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=U.extname(e).toLowerCase();return Me[t]??null}parse(e,t){if(!this.initialized)throw new a$2("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new a$2(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(i){throw new a$2("Failed to parse code","",i instanceof Error?i:new Error(String(i)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new h(U.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},G=null;async function Tt(){return G||(G=new V,await G.initialize()),G}function wt(){G&&(G.dispose(),G=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"},Ee={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"],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"}},Et={...Ee,language:"tsx"},St={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"],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"}},Nt={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],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"}},vt={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"],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"}},It={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"],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"}},Pt={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"],annotationTypes:[],variableTypes:["variable_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"}},Ct={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"],annotationTypes:["attribute"],variableTypes:["variable_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"}},Lt={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"],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"}},Rt={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],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"}},kt={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],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"}},Mt={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"],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"}},Ft={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"],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"}},qt={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],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"}},We=new Map([["ts",Ee],["tsx",Et],["js",St],["py",Nt],["java",vt],["csharp",It],["c",Pt],["cpp",Ct],["rs",Lt],["go",Rt],["php",Mt],["scala",Ft],["zig",qt],["ruby",kt]]);function A(y){return We.get(y)??Ee}Array.from(We.keys());function ze(y){let e=A(y),t=new Set;for(let r 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 r)t.add(i);return t}function Be(y){let e=A(y),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(r);for(let r of e.rawTypes.propertyTypes)t.add(r);return t}function R(y,e){return A(y).normalizeMap[e]??e}var Y=class{extractNodes(e,t,r,i){let n=[],s=t.split(`
|
|
182
|
+
`),l=ze(r),c=Be(r);return this.walkTree(e.rootNode,n,r,i,s,l,c),n}walkTree(e,t,r,i,n,s,l,c,o){if(s.has(e.type)){let d=this.extractNode(e,r,i,n,c,o,l);d&&(t.push(d),d.name&&(c=this.generateNodeId(d)),l.has(e.type)||(o=d.name??o));}for(let d=0;d<e.childCount;d++){let p=e.children[d];p&&this.walkTree(p,t,r,i,n,s,l,c,o);}}extractNode(e,t,r,i,n,s,l){let c=this.getNodeName(e,t);if(!c)return null;let o=e.startPosition,d=e.endPosition,p=this.getNodeText(e,i),f=l.has(e.type),g=f&&s?`${s}.${c}@${o.row+1}`:c,u=f?this.extractParameterTypes(e,t):[];return {name:g,ast_type:R(t,e.type),language:t,file_path:r,start_line:o.row+1,start_col:o.column,end_line:d.row+1,end_col:d.column,text:p,parent_id:n,metadata:f?{originalName:c,parameterTypes:u}:void 0}}extractParameterTypes(e,t){let i=A(t).parameters;if(!i)return [];let n=new Set(i.typeInWrapper),s=[],l=c=>{for(let o of c.children)if(o.type===i.wrapperType)return o;return null};if(i.declaratorStyle==="declarator"){for(let c of e.children)if(c.type==="function_declarator"||c.type==="pointer_declarator"){let o=l(c);if(o){for(let d of o.children)if(i.paramTypes.includes(d.type)){let p=this.findTypeInNode(d,n);p&&s.push(p);}return s}}}else {let c=l(e);if(c){for(let o of c.children)if(i.paramTypes.includes(o.type)){let d=this.findTypeInNode(o,n);d&&s.push(d);}}}return s}findTypeInNode(e,t){for(let r of e.children)if(t.has(r.type))return r.text;return null}getNodeName(e,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"]);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"])??this.findNameInGrandchildren(e,["function_declarator","declarator","name"],["identifier","property_identifier","field_identifier","name"]);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"])??this.findNameInChildren(e,["name","property_identifier","field_identifier"]);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 i of e.children)if(i.type==="namespace_name")return i.text}return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["type_spec","type_alias","namespace_name"],["type_identifier","identifier","name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);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"]);case "attribute_item":case "attribute":case "annotation":case "marker_annotation":case "decorator":return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["attribute","decorator"],["identifier","name","token_tree"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let i=e.childForFieldName?.(r);if(i?.text)return i.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let i of e.children)if(t.includes(i.type)){let n=this.findNameInChildren(i,r);if(n)return n}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"||t.type==="dotted_name"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}getNodeText(e,t){let r=e.startPosition.row,i=e.endPosition.row;return r===i?t[r]?.trim()??"":t.slice(r,i+1).join(`
|
|
183
|
+
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function At(){return new Y}var a={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",method_invocation:"method_invocation",invocation_expression:"invocation_expression",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_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",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",call:"call",call_expression:"call_expression",method_call_expression:"method_call_expression",function_call:"function_call",function_call_expression:"function_call_expression",member_call_expression:"member_call_expression",builtin_call_expression:"builtin_call_expression",member_expression:"member_expression",member_access:"member_access",member_access_expression:"member_access_expression",field_access:"field_access",field_expression:"field_expression",new_expression:"new_expression",object_creation_expression:"object_creation_expression",instance_expression:"instance_expression",scoped_type_identifier:"scoped_type_identifier",selector_expression:"selector_expression",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",parameters:"parameters",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Se={extends:"extends",implements:"implements"},He="new",re={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function me(y,e){e(y);for(let t of y.children)me(t,e);}function O(y){for(let e of y.children)if(e.type===a.identifier||e.type===a.type_identifier||e.type===a.property_identifier||e.type===a.field_identifier||e.type===a.name)return e.text;return null}function ge(y){for(let e=y.children.length-1;e>=0;e--){let t=y.children[e];if(t&&(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name))return t.text}return null}function fe(y,e){for(let t of y.children)if(e.includes(t.type))return t;return null}function W(y,e){for(let t of y.children){if(e.includes(t.type))return t;let r=W(t,e);if(r)return r}return null}function z(y,e){for(let t of y.children)if(e.includes(t.type)){let r=O(t);if(r)return r;for(let i of t.children){let n=O(i);if(n)return n}}for(let t of y.children){let r=z(t,e);if(r)return r}return null}function ie(y){let e=y.indexOf("<");if(e<0)return y;let t=0,r=null;for(let i=e;i<y.length;i++){let n=y[i];if(r){n===r&&(r=null);continue}if(n==='"'||n==="'"||n==="`"){r=n;continue}if(n==="<")t++;else if(n===">"&&(t--,t===0))return y.slice(0,e).trim()}return y}function $e(y){let e=A(y),t=new Set;for(let r of e.rawTypes.classTypes)t.add(R(y,r));for(let r of e.rawTypes.interfaceTypes)t.add(R(y,r));for(let r of e.rawTypes.moduleTypes)t.add(R(y,r));return t}function Ot(y){let e=A(y),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(R(y,r));return t}function Dt(y){let e=A(y),t=new Set;for(let r of e.rawTypes.propertyTypes)t.add(R(y,r));return t}var K=class{extractEdges(e,t,r,i){let n=[],s=new Map;for(let c of t){let o=s.get(c.name);o||(o=[],s.set(c.name,o)),o.push(c);}let l=new Map;for(let[c,o]of s){let d=o[0];d&&l.set(c,d);}return this.extractContainsEdges(t,n),this.extractCallEdges(e.rootNode,t,n,r,i,l),this.extractInheritanceEdges(e.rootNode,t,n,r,i,l),this.extractImportEdges(e.rootNode,t,n,r,i),this.extractTypeReferences(e.rootNode,t,n,r,i,l),this.extractAnnotationEdges(e.rootNode,t,n,r,i),this.extractHasMethodEdges(t,n,r),this.extractHasPropertyEdges(t,n,r),this.extractOverrideEdges(t,n,r,i),n}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,i,n,s){let l=new Set([a.call_expression,a.call,a.method_call_expression,a.function_call,a.function_call_expression,a.member_call_expression,a.method_invocation,a.invocation_expression,a.builtin_call_expression,a.new_expression,a.object_creation_expression,a.instance_expression]);this.walkTree(e,c=>{if(l.has(c.type)){let o=this.findEnclosingFunction(c,t,s),d=this.extractCalleeName(c);if(o&&d){let p=`${i}:*:*:${d}`;r.push({source:o.id,target:p,relation:"CALLS",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:n});}}});}extractInheritanceEdges(e,t,r,i,n,s){let l=A(i),c=new Set(l.rawTypes.classTypes),o=new Set(l.rawTypes.interfaceTypes),d=this.buildImportAliasMap(e,i);this.walkTree(e,p=>{if(c.has(p.type)){let f=O(p);if(!f)return;let g=`${i}:${n}:${R(i,p.type)}:${f}`,u=fe(p,[...l.inheritance.extendsClauseTypes]);u||(u=W(p,[...l.inheritance.extendsClauseTypes]));let m=[];u?(m=this.extractClauseNames(u,i),l.inheritance.stripTemplateArgs&&(m=m.map(h=>ie(h)))):l.inheritance.fallbackToFirstIdentifier&&(m=this.collectNamedIdentifiers(p).filter(h=>h!==f).slice(0,1));for(let h of m){if(!h||h===f)continue;let b=R(i,l.rawTypes.classTypes[0]??"class_declaration"),_=d.get(h)??h,E=`${i}:${n}:${b}:${_}`;r.push({source:g,target:E,relation:"EXTENDS",line:(u?.startPosition?.row??p.startPosition?.row??-1)+1,col:(u?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}for(let h of l.inheritance.implementsClauseTypes){let b=fe(p,[h]);if(b||(b=W(p,[h])),b){let _=this.extractClauseNames(b,i);l.inheritance.stripTemplateArgs&&(_=_.map(E=>ie(E)));for(let E of _){if(!E)continue;let x=l.rawTypes.interfaceTypes[0]??l.rawTypes.classTypes[0]??a.interface_declaration,T=d.get(E)??E,N=`${i}:${n}:${x}:${T}`;r.push({source:g,target:N,relation:"IMPLEMENTS",line:(b?.startPosition?.row??p.startPosition?.row??-1)+1,col:(b?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}}}return}if(o.has(p.type)){let f=O(p);if(!f)return;let g=`${i}:${n}:${R(i,p.type)}:${f}`;for(let u of l.inheritance.extendsClauseTypes){let m=W(p,[u]);if(m){let h=this.extractClauseNames(m,i);l.inheritance.stripTemplateArgs&&(h=h.map(b=>ie(b)));for(let b of h){if(b===f)continue;let _=R(i,l.rawTypes.interfaceTypes[0]??"interface_declaration"),E=d.get(b)??b,x=`${i}:${n}:${_}:${E}`;r.push({source:g,target:x,relation:"EXTENDS",line:(m?.startPosition?.row??p.startPosition?.row??-1)+1,col:(m?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}break}}}});}collectTypeAnnotations(e){let t=[],r=new Set([a.type_annotation,"type",a.reference_type,a.pointer_type,a.generic_type,a.array_type,a.named_type,a.primitive_type]),i=n=>{if(r.has(n.type)){t.push(n);return}for(let s of n.children)i(s);};return i(e),t}collectNamedIdentifiers(e){let t=[],r=new Set,i=n=>{if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.attribute){let s=n.text;r.has(s)||(r.add(s),t.push(s));return}for(let s of n.namedChildren)s&&i(s);};return i(e),t}extractClauseNames(e,t){let r=[],i=new Set,n=o=>{!o||i.has(o)||(i.add(o),r.push(o));},s=new Set([a.scoped_identifier,a.scoped_type_identifier,a.qualified_name,a.dotted_name,a.dotted_identifier]),l=new Set([a.identifier,a.type_identifier,a.name,a.attribute]),c=o=>{if(s.has(o.type)){n(o.text);return}if(l.has(o.type)){if(o.type===a.name&&(o.text===Se.extends||o.text===Se.implements))return;n(o.text);return}if(o.type===a.generic_type){let d=o.childForFieldName?.("name")?.text??o.namedChildren[0]?.text;d&&n(d);return}for(let d of o.namedChildren)d&&c(d);};return c(e),r}extractImportEdges(e,t,r,i,n){let s=A(i),l=new Set(s.rawTypes.importTypes),c=new Set;this.walkTree(e,o=>{if(l.has(o.type)){let d,p=this.extractImportWholePath(o);p?d=[p]:d=this.extractImportPaths(o);for(let f of d){if(!f||c.has(f))continue;c.add(f);let g=`${i}:${n}:module:file`;r.push({source:g,target:f,relation:"IMPORTS",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:n});}}});}walkTree(e,t){me(e,t);}findEnclosingFunction(e,t,r){let i=e,n=new Set([a.function_declaration,a.function_definition,a.method_definition,a.method_declaration,a.function_item]);for(;i;){if(n.has(i.type)){let s=O(i)??z(i,[a.function_declarator,a.declarator]);if(s){let l=r.get(s);if(l)return {id:this.generateNodeId(l),name:s};let c=t[0],o=c?.language??"ts",d=c?.file_path??"";return {id:`${o}:${d}:function_definition:${s}`,name:s}}}i=i.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;let r=new Set([a.member_expression,a.field_access,a.attribute,a.member_access,a.member_access_expression,a.member_call_expression,a.field_expression,a.selector_expression,a.constant]);if(t.type===a.variable_name&&e.type===a.member_call_expression){let i=e.childForFieldName?.("name");if(i)return i.text;let n=e.children.find(s=>s.type===a.name);if(n)return n.text}if(r.has(t.type)){let i=t.childForFieldName?.("property");if(i)return i.text;let n=t.childForFieldName?.("field");if(n)return n.text;let s=t.childForFieldName?.("name");if(s)return s.text;for(let l=t.children.length-1;l>=0;l--){let c=t.children[l];if(c&&(c.type===a.identifier||c.type===a.property_identifier||c.type===a.name||c.type===a.field_identifier||c.type===a.constant))return c.text}}if(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name||t.type===a.constant)return t.text;if(t.type===a.this){for(let i of e.children)if(i.type===a.identifier||i.type===a.property_identifier)return i.text}if(t.type===a.identifier&&t.text.includes(".")){let i=t.text.split(".");return i[i.length-1]??t.text}if(t.type===a.super){for(let i of e.children)if(i.type===a.identifier||i.type===a.property_identifier)return i.text}if(t.type===He){for(let i of e.children)if(i.type===a.identifier||i.type===a.type_identifier||i.type===a.name||i.type===a.scoped_identifier)return i.text}return null}extractImportPaths(e){let t=this.extractPythonImportPaths(e);if(t.length>0)return t;let r=new Set([a.string,a.string_literal,a.string_content,a.interpreted_string_literal,a.interpreted_string_literal_content,a.system_lib_string]),i=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),n=[],s=c=>{if(r.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),n.push(o);return}for(let o of c.children)s(o);};if(s(e),n.length>0)return n;let l=c=>{if(i.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),n.push(o);return}for(let o of c.children)l(o);};return l(e),n}extractPythonImportPaths(e){let t=e.type;if(t!==a.import_statement&&t!==a.import_from_statement)return [];let r=[];if(t===a.import_statement){for(let i of e.children)if(i.type===a.dotted_name)r.push(i.text);else if(i.type===a.aliased_import){let n=i.childForFieldName?.("name");if(n)r.push(n.text);else for(let s of i.children)if(s.type===a.dotted_name||s.type===a.identifier){r.push(s.text);break}}}else for(let i of e.children){if(i.type===a.dotted_name){r.push(i.text);break}if(i.type===a.relative_import){let n=i.childForFieldName?.(a.import_prefix),s=i.childForFieldName?.(a.module_name),l="";n&&(l+=n.text),s&&(l+=s.text),l?r.push(l):r.push(i.text);break}}return r}extractImportWholePath(e){let t=new Set([a.qualified_name,a.scoped_identifier,a.dotted_name,a.dotted_identifier,a.module_name,a.namespace_name,a.namespace_use_clause,a.name,a.identifier,a.string,a.string_literal,a.interpreted_string_literal,a.system_lib_string]);return (i=>{if(t.has(i.type)){let n=i.text;return (n.startsWith('"')||n.startsWith("'")||n.startsWith("<"))&&(n=n.slice(1,-1)),i.type===a.namespace_use_clause&&n.includes(" as ")&&(n=n.split(" as ")[0]??n),n}if(i.type===a.namespace_use_declaration||i.type===a.namespace_use_clause){for(let n of i.children)if(t.has(n.type)){let s=n.text;return (s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),n.type===a.namespace_use_clause&&s.includes(" as ")&&(s=s.split(" as ")[0]??s),s}}return null})(e)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,i,n,s){let l=new Set([a.function_declaration,a.function_definition,a.function_item,a.method_declaration,a.method_definition,a.variable_declaration,a.lexical_declaration,a.property_declaration,a.field_declaration,a.typed_param,a.identifier]),c=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),o=new Set([a.formal_parameters,a.parameter,a.parameter_declaration,a.formal_parameter,a.simple_parameter,a.typed_param,a.argument,a.required_parameter,a.optional_parameter,a.parameter,a.parameters]);this.walkTree(e,d=>{if(l.has(d.type)&&d.type!==a.lexical_declaration&&d.type!==a.variable_declaration){let g=d.childForFieldName?.("name")?.text??ge(d)??O(d)??z(d,[a.function_declarator,a.pointer_declarator,a.declarator]);if(!g)return;let u=null,m=[a.return_type,a.type_annotation,"type",a.pointer_type,a.array_type,a.void_type];for(let x of m){for(let T of d.children)if(T.type===x){u=T;break}if(u)break}let h=new Set([a.type_identifier,a.generic_type,a.array_type,a.identifier,a.struct_specifier,a.class_specifier,a.named_type,a.primitive_type]),b=new Set([a.function_declarator,a.pointer_declarator,a.declarator]);if(!u){for(let x of d.children)if(h.has(x.type)){if(x.type===a.void_type)continue;let T=ge(d);if(T&&x.text===T||b.has(x.type))continue;u=x;break}}let _=new Set([a.type_identifier,a.pointer_type,a.array_type]);if(!u){let x=false;for(let T of d.children){if(T.type==="->"||T.text==="->"){x=true;continue}if(x&&_.has(T.type)){u=T;break}}}if(u){let x=this.extractTypeName(u);if(x&&!re.void_any_null.has(x)){let T=this.resolveTypeNodeId(x,i,n);T&&r.push({source:this.generateNodeIdFromName(g,d.type,i,n),target:T,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}let E=W(d,["type_parameter","generic_type"]);if(E){let x=this.extractTypeName(E);if(x){let T=this.resolveTypeNodeId(x,i,n);T&&r.push({source:this.generateNodeIdFromName(g,d.type,i,n),target:T,relation:"TYPE_REFERENCES",line:(E.startPosition?.row??-1)+1,col:(E.startPosition?.column??-1)+1,filePath:n});}}}if(c.has(d.type)){let g=this.findEnclosingClass(d,t);if(g){for(let u of d.children)if(u.type===a.type_identifier){let m=u.text,h=this.resolveTypeNodeId(m,i,n);h&&r.push({source:g.id,target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}}let p=new Set([a.type_annotation,a.annotation,"type",a.reference_type,a.pointer_type,a.type_identifier,a.struct_specifier,a.class_specifier,a.array_type,a.sized_type_specifier,a.named_type,a.primitive_type,a.slice_type,a.array_type,a.map_type,a.channel_type]);if(o.has(d.type)){for(let g of d.children)if(p.has(g.type)){let u=this.extractTypeName(g);if(u&&!re.string_number_boolean.has(u)){let m=this.resolveTypeNodeId(u,i,n);if(m){let h=this.findEnclosingFunction(d,t,s);h&&r.push({source:h.id,target:m,relation:"TYPE_REFERENCES",line:(g.startPosition?.row??-1)+1,col:(g.startPosition?.column??-1)+1,filePath:n});}}}if((i==="zig"||i==="csharp")&&d.type===a.parameter&&d.children.length>=2){let g=i==="zig"?2:0,u=d.children[g];if(u&&u.type===a.identifier){let m=u.text;if(m&&!re.string_number_boolean.has(m)){let h=this.resolveTypeNodeId(m,i,n);if(h){let b=this.findEnclosingFunction(d,t,s);b&&r.push({source:b.id,target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}}}}if(new Set([a.variable_declaration,a.lexical_declaration,a.public_field_definition,a.field_definition,a.field_declaration,a.property_declaration,a.property_signature,a.assignment]).has(d.type)){let g=this.collectTypeAnnotations(d);for(let u of g){let m=this.extractTypeName(u);if(m&&!re.string_number_boolean.has(m)&&m!=="any"){let h=this.resolveTypeNodeId(m,i,n);if(h){let b=O(d)??z(d,["variable_declarator"])??O(d);b&&r.push({source:this.generateNodeIdFromName(b,"variable_declaration",i,n),target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}}}});}extractHasMethodEdges(e,t,r){let i=$e(r),n=Ot(r);this.emitContainerToMemberEdges(e,t,i,n,"HAS_METHOD");}extractHasPropertyEdges(e,t,r){let i=$e(r),n=Dt(r);this.emitContainerToMemberEdges(e,t,i,n,"HAS_PROPERTY");}emitContainerToMemberEdges(e,t,r,i,n){let s=new Map;for(let l of e){let c=s.get(l.file_path);c||(c=[],s.set(l.file_path,c)),c.push(l);}for(let l of s.values()){l.sort((o,d)=>o.start_line-d.start_line);let c=[];for(let o of l){for(;c.length>0&&(c[c.length-1]?.end_line??1/0)<o.start_line;)c.pop();if(r.has(o.ast_type))c.push(o);else if(i.has(o.ast_type)){let d=c[c.length-1];if(d){let p=this.generateNodeId(d),f=this.generateNodeId(o);t.push({source:p,target:f,relation:n});}}}}}extractOverrideEdges(e,t,r,i){let n=A(r),s=new Set;for(let d of n.rawTypes.classTypes)s.add(R(r,d));for(let d of n.rawTypes.interfaceTypes)s.add(R(r,d));let l=e.filter(d=>s.has(d.ast_type));if(l.length===0)return;let c=new Map;for(let d of e){let p=c.get(d.file_path);p||(p=[],c.set(d.file_path,p)),p.push(d);}let o=new Map;for(let d of t)if(d.relation==="EXTENDS"){let p;for(let g of c.values())if(p=g.find(u=>this.generateNodeId(u)===d.target),p)break;if(!p)continue;let f=o.get(d.source);f||(f=[],o.set(d.source,f)),f.push(p);}for(let d of l){let p=o.get(this.generateNodeId(d))??[];if(p.length===0)continue;let f=this.collectMemberIdsByName(d,c,"HAS_METHOD",r);if(f.size===0)continue;let g=new Set,u=[],m=[...p];for(;m.length>0;){let h=m.shift();if(g.has(this.generateNodeId(h)))continue;g.add(this.generateNodeId(h)),u.push(h);let b=o.get(this.generateNodeId(h))??[];m.push(...b);}for(let[h,b]of f){let _=b[0];if(!_)continue;let E=null;for(let x of u){let N=this.collectMemberIdsByName(x,c,"HAS_METHOD",r).get(h);if(!(!N||N.length===0)){E=N[0]??null;break}}if(E&&E!==_){let x=this.generateNodeId(d);if(t.some(v=>v.relation==="METHOD_OVERRIDES"&&v.source===x&&v.target===E))continue;t.push({source:x,target:E,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,t,r,i){let n=new Map,s=t.get(e.file_path);if(!s)return n;let l=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let c of s)if(l.has(c.ast_type)&&c.start_line>=e.start_line&&c.end_line<=e.end_line){let o=c.metadata?.originalName??c.name,d=c.metadata?.parameterTypes??[],p=d.length>0?`${o}|${d.join(",")}`:o,f=n.get(p);f||(f=[],n.set(p,f));let g=this.generateNodeId(c);f.push(g);}return n}buildImportAliasMap(e,t){let r=new Map;return this.walkTree(e,i=>{if(i.type===a.namespace_use_clause){let n=i.children,s=n.findIndex(l=>l.type==="as");if(s>=0){let l=n.slice(0,s).find(o=>o.type===a.qualified_name),c=n[s+1];l&&c&&c.type===a.name&&c.text&&r.set(c.text,l.text);}}}),r}findEnclosingClass(e,t){let r=e.parent,i=new Set([a.class_declaration,a.class_definition,a.struct_specifier,a.struct_declaration,a.struct_item,a.type_declaration,a.record_declaration,a.class_specifier,a.enum_declaration]);for(;r;){if(i.has(r.type)){let n=O(r)??z(r,[a.type_spec,a.name]);if(n){let s=t.find(d=>d.name===n);if(s)return {id:this.generateNodeId(s),name:n};let l=t[0],c=l?.language??"ts",o=l?.file_path??"";return {id:`${c}:${o}:${r.type}:${n}`,name:n}}}r=r.parent;}return null}extractAnnotationEdges(e,t,r,i,n){let s=A(i),l=new Set(s.rawTypes.annotationTypes),c=new Set(s.annotation.annotatableTypes);this.walkTree(e,o=>{if(l.has(o.type)){let d=this.extractTypeName(o)||O(o);if(!d)return;let p=o.parent;for(;p;){if(c.has(p.type)){let f=O(p),g=p.type;if(!f&&(p.type===a.decorated_definition||p.type===a.export_statement)){let u=z(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),m=W(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]);u&&(f=u,g=m?.type??"function_definition");}if(f){let u=this.generateNodeIdFromName(f,g,i,n),m=`${i}:${n}:annotation:${d}`;r.push({source:m,target:u,relation:"ANNOTATES",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:n});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===a.type_identifier||e.type===a.identifier||e.type===a.predefined_type||e.type===a.name)return e.text;let t=new Set([a.type_identifier,a.identifier,a.name]);for(let i of e.children)if(t.has(i.type))return i.text;for(let i of e.children)if(i.type===a.predefined_type)return i.text;let r=new Set([a.pointer_type,a.reference_type,a.array_type,a.generic_type,a.slice_type,a.map_type,a.channel_type,a.parenthesized_type]);for(let i of e.children)if(r.has(i.type)){let n=this.extractTypeName(i);if(n)return n}return null}resolveTypeNodeId(e,t,r){let i=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let n of i)return `${t}:${r}:${n}:${e}`;return null}generateNodeIdFromName(e,t,r,i){return `${r}:${i}:${R(r,t)}:${e}`}};function Wt(){return new K}var B=Log.create({service:"codebase-indexer"}),J=class{constructor(e,t,r,i){a$1(this,"db");a$1(this,"parserManager");a$1(this,"nodeExtractor");a$1(this,"edgeExtractor");a$1(this,"config");a$1(this,"writeProxy",null);this.db=e,this.parserManager=t,this.nodeExtractor=new Y,this.edgeExtractor=new K,this.config=r,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 t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let s=new Float32Array(n);return this.dbWriter.cacheEmbedding?.(t,s),s}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),i=[],n=0,s=0,l=null;try{let c=this.parserManager.detectLanguage(e);if(!c)throw new f("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let o=await this.readFile(e),d=this.computeHash(o);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),t?.({currentFile:e,processed:0,total:1,stage:"extracting"}),l=this.parserManager.parse(o,c);let p=this.nodeExtractor.extractNodes(l,o,c,e);n=p.length;let f$1=this.edgeExtractor.extractEdges(l,p,c,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let g=this.getValidEdgeCount(f$1,p);this.storeEdges(f$1,p),s=g,this.config.embedding&&p.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(p)),this.dbWriter.setFileHash(e,d),this.writeProxy&&this.writeProxy.flush();}catch(c){let o=c instanceof Error?c.message:String(c);i.push({filePath:e,error:o});}finally{if(l)try{l.delete();}catch(c){B.warn("tree.delete failed",{filePath:e,error:String(c)});}}return {success:i.length===0,filesProcessed:1,nodesCreated:n,edgesCreated:s,errors:i,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),i=e??this.config.workspaceDir,n=[],s=0,l=0,c=0;try{let o=await this.scanFiles(i);for(let u of o.readErrors)n.push(u);let d=o.results,p=d.length,f=0,g=u=>{t&&t({currentFile:u.currentFile,processed:f,total:d.length,stage:u.stage});};for(let u=0;u<d.length;u+=this.config.batchSize){let m=d.slice(u,u+this.config.batchSize),h=await Promise.all(m.map(b=>this.indexFile(b.filePath,g)));for(let b of h)s++,f++,l+=b.nodesCreated,c+=b.edgesCreated,!b.success&&b.errors.length>0&&n.push(...b.errors);}if(t&&d.length>0){let u=d[d.length-1]?.filePath??"";t({currentFile:u,processed:d.length,total:d.length,stage:"storing"});}}catch(o){let d=o instanceof Error?o.message:String(o);n.push({filePath:i,error:d});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:n.length===0,filesProcessed:s,nodesCreated:l,edgesCreated:c,errors:n,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],i=0,n=0,s=0,l=0,c=0,o=0;try{let g=await this.scanFiles(this.config.workspaceDir),u=g.results;for(let w of g.readErrors)r.push(w);let m=new Set(u.map(w=>w.filePath)),h=this.db.getAllFileHashes(),b=new Set(h.map(w=>w.file_path));for(let w of h)m.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),s++);let _=u.length,E=0,x=w=>{e&&e({currentFile:w.currentFile,processed:E,total:_,stage:w.stage});},T=Math.max(1,this.config.batchSize),N=new Map;for(let w of h)N.set(w.file_path,w.content_hash);for(let w=0;w<u.length;w+=T){let H=u.slice(w,w+T),Q=await Promise.all(H.map(M=>{let F=N.get(M.filePath);return F?F!==M.contentHash?this.indexFile(M.filePath,x).then($=>({file:M,kind:"updated",r:$})):Promise.resolve({file:M,kind:"skipped",r:null}):this.indexFile(M.filePath,x).then($=>({file:M,kind:"added",r:$}))}));for(let{kind:M,r:F}of Q)M==="skipped"?l++:F&&(F.success?F.nodesCreated===0?l++:(M==="added"?i++:n++,c+=F.nodesCreated,o+=F.edgesCreated):r.push(...F.errors));E+=H.length;}if(e&&_>0){let w=u[u.length-1]?.filePath??"";e({currentFile:w,processed:_,total:_,stage:"storing"});}let v=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(w=>w.file_path)),k=this.db.getAllFileHashes().filter(w=>!v.has(w.file_path)).map(w=>w.file_path);for(let w of k)this.dbWriter.deleteFileHash(w);}catch(g){let u=g instanceof Error?g.message:String(g);r.push({filePath:this.config.workspaceDir,error:u});}this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush();let d=new Date().toISOString(),p=Date.now()-t,f={timestamp:d,success:r.length===0,filesAdded:i,filesUpdated:n,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errorCount:r.length,errors:r,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(f)),{success:r.length===0,filesAdded:i,filesUpdated:n,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errors:r,duration:p}}async scanFiles(e){let t=[],r=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(m=>`**/*${m}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],l=this.config.ignorePatterns.map(m=>m.includes("/")||m.includes("*")?m:`**/${m}/**`),c=[...s,...l],o=await this.loadGitignore(e),d=e.replace(/\\/g,"/"),p=await Bt(n,{cwd:d,absolute:true,ignore:c,onlyFiles:true,followSymbolicLinks:false,dot:false}),f=o?p.filter(m=>!o.ignores(this.toRelativePosix(m,d),false)):p,g=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),u=[];for(let m of f){let h=Filesystem.normalize(m);this.parserManager.detectLanguage(h)&&u.push(h);}for(let m=0;m<u.length;m+=g){let h=u.slice(m,m+g),b=await Promise.all(h.map(async _=>{try{let E=await this.readFile(_),x=this.computeHash(E),T=this.parserManager.detectLanguage(_);return T?{filePath:_,language:T,contentHash:x,content:E}:null}catch(E){let x=E instanceof Error?E.message:String(E);return r.push({filePath:_,error:x}),B.warn("scanFiles read failed",{filePath:_,error:x}),null}}));for(let _ of b)_&&t.push(_);}return {results:t,readErrors:r}}async loadGitignore(e){try{let t=`${e.replace(/\\/g,"/")}/.gitignore`,r=await je.readFile(t,"utf-8"),i=Ignore.create();return i.add(r),B.debug("Loaded .gitignore",{path:t,lines:r.split(`
|
|
184
|
+
`).length}),i}catch(t){return t.code!=="ENOENT"&&B.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:String(t)}),null}}toRelativePosix(e,t){let r=e;return r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/\\/g,"/"),r.startsWith("/")&&(r=r.slice(1)),r}async readFile(e){try{return await je.readFile(e,"utf-8")}catch(t){throw new c("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(t),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let t=[];for(let r of e){let i=this.splitIdentifier(r.name);for(let n of i)n.length>0&&t.push({segment:n,name:r.name});}if(t.length!==0)try{this.db.insertNameSegmentsBatch(t);}catch(r){B.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:t.length,error:String(r)});for(let{segment:i,name:n}of t)try{this.db.insertNameSegment(i,n);}catch(s){B.warn("insertNameSegment failed",{nodeName:n,segment:i,error:String(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let t=[],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 s of n.split(/\s+/)){let l=s.toLowerCase();l.length>0&&t.push(l);}return t}storeEdges(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n))),i=e.filter(n=>n.source!==n.target&&r.has(n.source)&&r.has(n.target)).map((n,s)=>({id:`${n.source}:${n.relation}:${n.target}:${s}`,source:n.source,target:n.target,relation:n.relation,created_at:new Date().toISOString()}));i.length>0&&this.dbWriter.insertEdges(i),this.storeUnresolvedRefs(e,t,r);}storeUnresolvedRefs(e,t,r){let i=new Map,n=(o,d)=>{let p=i.get(o);p||(p=[],i.set(o,p)),p.includes(d)||p.push(d);};for(let o of t){let d=this.nodeExtractor.generateNodeId(o);n(o.name,d);let p=o.metadata?.originalName;typeof p=="string"&&p.length>0&&n(p,d);let f=o.name.lastIndexOf("@");if(f>0){let g=o.name.slice(0,f),u=g.lastIndexOf(".");u>0&&n(g.slice(u+1),d);}}let s=t[0]?.file_path??"",l=t[0]?.language??"unknown",c=[];for(let o of e){let d=r.has(o.source),p=r.has(o.target);if(d&&p)continue;let f=d?o.target:o.source,g=d?o.source:r.has(o.target)?o.target:void 0,u=f.includes(":")?f.split(":").pop()??f:f,m=i.get(u)??[];c.push({fromNodeId:g,referenceName:f,referenceKind:o.relation,line:o.line,col:o.col,filePath:o.filePath??s,language:l,candidates:m.length>0?m:void 0});}if(c.length!==0)try{this.db.insertUnresolvedRefsBatch(c);}catch(o){B.warn("insertUnresolvedRefsBatch failed, falling back to per-row insert",{batchSize:c.length,error:String(o)});for(let d of c)try{this.db.insertUnresolvedRef(d);}catch(p){B.warn("insertUnresolvedRef failed",{edgeId:`${d.fromNodeId??"?"}:${d.referenceKind}:${d.referenceName}`,error:String(p)});}}}getValidEdgeCount(e,t){let r=new Set(t.map(i=>this.nodeExtractor.generateNodeId(i)));return e.filter(i=>r.has(i.source)&&r.has(i.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),i=[],n=4,s=r.map((c,o)=>({index:o,batch:c})),l=[];for(let c=0;c<s.length;c+=n){let o=s.slice(c,c+n),d=await Promise.all(o.map(async({index:p,batch:f})=>{let g=[],u=f.map(m=>this.generateNodeEmbeddingText(m));try{let m=await this.config.embedding.doEmbed({values:u});for(let h=0;h<f.length;h++){let b=f[h];if(!b)continue;let _=m.embeddings[h];if(_){let E=new Float32Array(_),x=this.computeHash(this.generateNodeEmbeddingText(b));this.dbWriter.cacheEmbedding?.(x,E),g.push({nodeId:this.nodeExtractor.generateNodeId(b),embeddingText:u[h]||"",embedding:E});}}}catch{for(let h of f){if(!h)continue;let b=this.generateNodeEmbeddingText(h),_=await this.embedText(b);_&&g.push({nodeId:this.nodeExtractor.generateNodeId(h),embeddingText:b,embedding:_});}}return {index:p,embeddings:g}}));l.push(...d);}l.sort((c,o)=>c.index-o.index);for(let c of l)i.push(...c.embeddings);i.length>0&&this.dbWriter.storeNodeEmbeddings?.(i);}chunkArray(e,t){let r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return r}};function Gt(y,e,t){return new J(y,e,t)}function Ne(y){if(!y)return [];let e=y.split(/[^a-zA-Z0-9]+/),t=[];for(let r of e){if(!r)continue;let i=r.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);i&&t.push(...i);}return t.map(r=>r.toLowerCase()).filter(r=>r.length>0)}function Ge(y,e){if(y.length===0||e.length===0)return 0;let t=0;for(let r of y)e.includes(r)&&t++;return t/y.length}function Qe(y,e,t={}){let r=t.limit??20,i=t.minScore??.2;if(!y)return [];let n=Ne(y),s=[];for(let l of e){let c=l.id.split(":").pop()??"";if(c===y||l.name===y){s.push({nodeId:l.id,score:1,matchedPart:"full"});continue}let o=Ne(c),d=Ne(l.name),p=Ge(n,o),f=Ge(n,d),g=Math.max(p,f);g>=i&&s.push({nodeId:l.id,score:g,matchedPart:g>=.99?"full":"segment"});}return s.sort((l,c)=>c.score-l.score),s.slice(0,r)}var ve=Filesystem.toUnixPath,I=Log.create({service:"codebase.query"}),Vt=new Set(["AND","OR","NOT","NEAR"]),Yt=/[\p{L}\p{N}_]/u;function Kt(y){return y?y.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!Vt.has(t.toUpperCase())).filter(t=>Yt.test(t)).join(" "):""}var X=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a$1(this,"db");a$1(this,"embedding");a$1(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:i=this.config.minScore,language:n,filePath:s,astType:l,enableFts:c=true,includeEdges:o=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:f=this.config.hybrid.textWeight,enableEmbedding:g=true}=t;I.debug("search() called",{query:e,astType:l,language:n,enableEmbedding:g,enableFts:c,minScore:i});let u=[],m=new Map;if(g&&this.embedding){let _=await this.vectorSearchNodes(e,r*2,i);I.debug("vectorSearchNodes results",{count:_.length,astTypeFilter:l});for(let E of _){if(n&&E.language!==n||l&&E.astType!==l)continue;let x={...E,source:"vector",vectorScore:E.score,hybridScore:E.score*p};u.push(x),m.set(x.id,x);}I.debug("after vector filter",{resultsCount:u.length});}if(c&&this.db.isFtsAvailable()){let _=Kt(e);_||I.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let E=_?this.db.searchNodesFts(_,r*2):[];I.debug("FTS results before filter",{count:E.length});for(let x of E){if(n&&x.language!==n||s&&!x.file_path.includes(ve(s))||l&&x.ast_type!==l)continue;let T=this.normalizeScore(x.score),N=m.get(x.id);if(N)N.ftsScore=T,N.hybridScore=N.vectorScore*p+T*f;else {let v={id:x.id,name:x.name,astType:x.ast_type,language:x.language,filePath:x.file_path,text:x.text,snippet:x.text.slice(0,200),startLine:x.start_line,startCol:x.start_col,endLine:x.end_line,endCol:x.end_col,score:T,source:"fts",ftsScore:T,hybridScore:T*f};u.push(v),m.set(v.id,v);}}I.debug("after FTS filter",{resultsCount:u.length});}if(!c||!this.db.isFtsAvailable()||u.length===0){try{let _=this.db.queryNodes({limit:r*2,astType:l,language:n,filePath:s}),E=new Set(u.map(w=>w.id)),x=e.toLowerCase(),T=x.split(/\s+/).filter(w=>w.length>0),N=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=T.map(w=>({term:w,regex:new RegExp(N(w),"gi")})),k=[];for(let w of _){if(s&&!w.file_path.includes(ve(s)))continue;let H=w.name.toLowerCase(),Q=w.text.toLowerCase(),M=0;if(v.some(({term:D})=>H.includes(D))){let D=0;for(let{regex:ne}of v){let ae=H.match(ne);D+=ae?ae.length:0;}M=.8*Math.min(D/v.length,1);}let F=0;if(v.some(({term:D})=>Q.includes(D))){let D=0;for(let{regex:Ye}of v){let Pe=Q.match(Ye);D+=Pe?Pe.length:0;}F=.5*Math.min(D/v.length,1);let ne=Q.indexOf(x),ae=ne===-1?0:Math.max(0,1-ne/Q.length)*.2;F+=ae;}let $=Math.max(M,F);$>0&&k.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:$});}k.sort((w,H)=>H.score-w.score),u.push(...k.slice(0,r));}catch{}if(u.length===0)try{let _=this.db.queryNodes({limit:1e3}),E=Qe(e,_,{limit:r,minScore:.5});I.debug("name-segment matches",{count:E.length,query:e});for(let x of E){let T=this.db.getNodeById(x.nodeId);if(!T||n&&T.language!==n||l&&T.ast_type!==l||s&&!T.file_path.includes(ve(s)))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:x.score,source:"structural",hybridScore:x.score};u.push(N),m.set(N.id,N);}}catch(_){I.debug("name-segment channel error",{error:_ instanceof Error?_.message:String(_)});}}let b=u.filter(_=>_.hybridScore>=i).sort((_,E)=>E.hybridScore-_.hybridScore).slice(0,r).map(_=>({id:_.id,name:_.name,ast_type:_.astType,language:_.language,file_path:_.filePath,start_line:_.startLine,start_col:_.startCol,end_line:_.endLine,end_col:_.endCol,text:_.text,created_at:new Date().toISOString()}));if(o&&b.length>0){let _=b.map(T=>T.id),E=this.db.queryEdges({sourceOrTarget:_}),x=new Map;for(let T of E)T.source!==T.target&&(x.has(T.source)||x.set(T.source,[]),x.get(T.source).push(T));return b.map(T=>{let N=x.get(T.id)||[];return {...T,edges:N.slice(0,d)}})}return b.map(_=>({..._,edges:[]}))}async vectorSearchNodes(e,t,r,i){if(I.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,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 s=new Float32Array(n),l,c=5e3;if(i&&i.length>0){let g=i.map(()=>"?").join(",");l=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${g})`,i);}else l=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[c]);I.debug("vectorSearchNodes vectors loaded",{count:l.length});let o=[];for(let g of l){let u=new Float32Array(g.embedding.buffer,g.embedding.byteOffset,g.embedding.length/4),m=this.cosineSimilarity(s,u);m<r||(o.push({nodeId:g.node_id,score:m}),o.length>t&&(o.sort((h,b)=>b.score-h.score),o.splice(t)));}if(o.length===0)return I.debug("vectorSearchNodes done - no results above minScore"),[];o.sort((g,u)=>u.score-g.score);let d=o.map(g=>g.nodeId);I.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let p=this.db.queryNodes({ids:d}),f=new Map(o.map(g=>[g.nodeId,g.score]));return I.debug("vectorSearchNodes done",{nodesFound:p.length}),p.map(g=>({id:g.id,name:g.name,astType:g.ast_type,language:g.language,filePath:g.file_path,text:g.text??"",snippet:(g.text??"").slice(0,200),startLine:g.start_line??0,startCol:g.start_col??0,endLine:g.end_line??0,endCol:g.end_col??0,score:f.get(g.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({sourceOrTarget:[e.id],limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,i=0,n=0;for(let s=0;s<e.length;s++){let l=e[s],c=t[s];r+=l*c,i+=l*l,n+=c*c;}return i===0||n===0?0:r/(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(t){throw new g("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}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(t=>t.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(t){throw new g("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let i of t){let n=this.db.getNodeById(i.source),s=this.db.getNodeById(i.target);n&&s&&r.push({edge:i,sourceNode:n,targetNode:s});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:i="both",limit:n=100}=t;I.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:r,direction:i,limit:n});let s=[],l=[],c=new Set,o=new Set,d=r&&r.length>0?r:[void 0],p=f=>{for(let g of d){let u=g===void 0?{}:{relation:g},m=f==="outgoing"?this.db.queryEdges({source:e,...u,limit:n}):this.db.queryEdges({target:e,...u,limit:n});for(let h of m){if(o.has(h.id))continue;o.add(h.id),s.push(h);let b=f==="outgoing"?h.target:h.source,_=this.db.getNodeById(b);_&&!c.has(_.id)&&(l.push(_),c.add(_.id));}}};return (i==="outgoing"||i==="both")&&p("outgoing"),(i==="incoming"||i==="both")&&p("incoming"),{nodes:l.slice(0,n),edges:s.slice(0,n)}}queryCallGraph(e,t=2){let r=new Map,i=new Set,n=(s,l)=>{if(l>t||i.has(s))return;i.add(s);let c=[],o=[],d=this.db.queryEdges({target:s,relation:"CALLS"});for(let f of d)c.push(f.source),n(f.source,l+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let f of p)o.push(f.target),n(f.target,l+1);r.set(s,{callers:c,callees:o});};return n(e,0),r}queryInheritance(e){I.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let t=[],r=[],i=new Set,n=new Set,s=c=>{if(i.has(c))return;i.add(c);let o=this.db.queryEdges({source:c,relation:"EXTENDS"}),d=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let f=this.db.getNodeById(p.target);f&&(t.push(f),s(p.target));}},l=c=>{if(n.has(c))return;n.add(c);let o=this.db.queryEdges({target:c,relation:"EXTENDS"}),d=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let f=this.db.getNodeById(p.source);f&&(r.push(f),l(p.source));}};return s(e),l(e),{ancestors:t,descendants:r}}queryMembers(e,t){let r=t?Array.isArray(t)?t:[t]:["HAS_METHOD","HAS_PROPERTY"],i=[],n=new Set;for(let s of r){let l=this.db.queryEdges({source:e,relation:s});for(let c of l){if(n.has(c.target))continue;n.add(c.target);let o=this.db.getNodeById(c.target);o&&i.push(o);}}return i}queryOverrides(e){let t=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),r=[],i=new Set;for(let n of t){if(i.has(n.target))continue;i.add(n.target);let s=this.db.getNodeById(n.target);s&&r.push(s);}return r}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Jt(y){return new X(y)}var ye;(u=>{let y=Log.create({service:"codebase-llm"}),e=null;function r(m){i()||(e={models:m.models,options:{graph:m.options?.graph}},y.info("Llm initialized",{graphLlm:!!m.models.graphLlm,embeddingLlm:!!m.models.embeddingLlm}));}u.init=r;function i(){return e!==null}u.isInitialized=i;function n(){e=null;}u._resetForTest=n;function s(){return e?{graphLlm:!!e.models.graphLlm,embeddingLlm:!!e.models.embeddingLlm}:{graphLlm:false,embeddingLlm:false}}u.capabilities=s;function l(){return e?.models.graphLlm}u.getGraphLlm=l;function c(){return e?.models.embeddingLlm}u.getEmbeddingLlm=c;async function o(m,h){if(!e||!e.models.graphLlm)return y.debug("Llm.generateText: graphLlm not configured, return empty string"),"";try{return (await streamText({model:e.models.graphLlm,prompt:m,maxOutputTokens:h?.maxOutputTokens??e.options.graph?.maxOutputTokens,temperature:h?.temperature??e.options.graph?.temperature})).text}catch(b){return y.error("Llm.generateText failed",{error:b instanceof Error?b.message:String(b)}),""}}u.generateText=o;async function d(m){if(!e||!e.models.graphLlm)return {score:-1,details:"graphLlm not configured",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]};let h=p(m.gold,m.predicted),b=await o(h,{maxOutputTokens:1024,temperature:0,...m.options});return f(b)}u.evaluateExtraction=d;function p(m,h){return `You are a code knowledge graph extraction quality evaluator.
|
|
185
|
+
|
|
186
|
+
Given:
|
|
187
|
+
- **Gold (ground truth)**: a reference extraction produced by a human annotator
|
|
188
|
+
- **Predicted**: an automatic extraction produced by the codebase extractor
|
|
189
|
+
|
|
190
|
+
Both Gold and Predicted support TWO input formats \u2014 auto-detect by JSON shape:
|
|
191
|
+
|
|
192
|
+
**Format A (flat symbol list, common for search/recall eval):**
|
|
193
|
+
{ "expected": ["MemorySystem", "NoteKnowledge"], "query": "core classes" } // gold
|
|
194
|
+
{ "actual": ["MemorySystem", "./parser"] } // predicted
|
|
195
|
+
|
|
196
|
+
**Format B (structured extraction, for full MRO eval):**
|
|
197
|
+
{ "entities": [{"name": "Foo", "type": "class"}], "relations": [{"source": "Foo", "target": "Bar", "relation": "EXTENDS"}] } // gold
|
|
198
|
+
{ "entities": [{"name": "Foo", "type": "class"}], "relations": [] } // predicted
|
|
199
|
+
|
|
200
|
+
Scoring dimensions (be strict):
|
|
201
|
+
1. **Entity name match**: case-insensitive exact match preferred; consider semantic synonyms (e.g. "UserService" \u2248 "UserSvc"); reject type-mismatched candidates (file paths vs class names).
|
|
202
|
+
2. **Relation endpoints**: source/target must point to same conceptual entity as in gold.
|
|
203
|
+
3. **Relation type accuracy**: e.g. CALLS vs REFERENCES vs IMPORTS are distinct.
|
|
204
|
+
4. **Type/category match**: an entity in predicted must have the same type/category as its gold counterpart (e.g. don't count a file_path as a class).
|
|
205
|
+
|
|
206
|
+
Output JSON schema (REQUIRED):
|
|
207
|
+
{
|
|
208
|
+
"score": <number between 0 and 1>,
|
|
209
|
+
"details": "<short explanation of what matched, what was missed, what was wrong>",
|
|
210
|
+
"missing_entities": [<entity names missing from predicted>],
|
|
211
|
+
"extra_entities": [<entity names in predicted but not gold or wrong type>],
|
|
212
|
+
"wrong_relations": [<relation strings like "source->target:TYPE" that are wrong>],
|
|
213
|
+
"missing_relations": [<relation strings missing from predicted>]
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
Scoring guide:
|
|
217
|
+
- 1.0: all entities + all relations match perfectly
|
|
218
|
+
- 0.7-0.9: most entities match, minor relations off
|
|
219
|
+
- 0.4-0.6: ~half match, significant misses
|
|
220
|
+
- 0.0-0.3: little to no match (e.g. predicted is file paths, gold is class names)
|
|
221
|
+
|
|
222
|
+
OUTPUT FORMAT RULES (MUST FOLLOW):
|
|
223
|
+
- Output ONLY the raw JSON object above, with NO surrounding markdown code fences (no \`\`\`json, no \`\`\`).
|
|
224
|
+
- Start your response with the character { and end with }.
|
|
225
|
+
- Do NOT add any explanatory text before or after the JSON.
|
|
226
|
+
- Do NOT wrap in any kind of code block.
|
|
227
|
+
- Output the JSON on a single line or with newlines, both are acceptable as long as it's valid JSON.
|
|
228
|
+
|
|
229
|
+
Gold:
|
|
230
|
+
${m}
|
|
231
|
+
|
|
232
|
+
Predicted:
|
|
233
|
+
${h}`}function f(m){let h={score:0,details:"",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]},b=m??"",_=b.trim();if(!_)return {...h,details:"LLM returned empty text"};let E=_,x=E.match(/```(?:json|JSON)?\s*([\s\S]*?)\s*```/);x&&(E=(x[1]??"").trim());let T=E.match(/\{[\s\S]*\}/);if(T)try{let v=JSON.parse(T[0]);return g(v)}catch{}for(let v of E.split(`
|
|
234
|
+
`)){let k=v.trim();if(k.startsWith("{"))try{let w=JSON.parse(k);return g(w)}catch{}}let N=E.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let v of N){let k=v;k.endsWith("%")&&(k=String(parseFloat(k)/100));let w=parseFloat(k);if(!Number.isNaN(w)&&w>=0&&w<=1)return {...h,score:w,details:`LLM returned non-JSON output; score extracted via heuristic from: ${b.slice(0,200)}`}}return {...h,details:`Failed to parse LLM output: ${b.slice(0,200)}`}}u.parseEvaluationResult=f;function g(m){return {score:typeof m.score=="number"?Math.max(0,Math.min(1,m.score)):0,details:typeof m.details=="string"?m.details:"",missingEntities:Array.isArray(m.missing_entities)?m.missing_entities.filter(b=>typeof b=="string"):[],extraEntities:Array.isArray(m.extra_entities)?m.extra_entities.filter(b=>typeof b=="string"):[],wrongRelations:Array.isArray(m.wrong_relations)?m.wrong_relations.filter(b=>typeof b=="string"):[],missingRelations:Array.isArray(m.missing_relations)?m.missing_relations.filter(b=>typeof b=="string"):[]}}})(ye||(ye={}));var P=Log.create({service:"codebase"}),cr={database:{path:getDefaultDatabasePath(xdgData,"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},Ie=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...cr,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,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},ye.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let i=this.resolveDbPath();d(U.dirname(i)),this.db=new n(i),this.parserManager=new V,this.queryInterface=new X(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=dr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new ue({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new ce(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new J(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){P.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>P.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,P.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){P.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{P.error("Interval sync failed",{error:String(t)});}));},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=>{P.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 U.isAbsolute(e)?e:U.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return P.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 t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),P.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return P.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-5WEDJY6M.mjs'),r=this.config.workspaceDir,i=e?.debounceMs??200,n=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let l=null,c=new Set,o=()=>{l=null;let p=c.size;c.clear(),p!==0&&(P.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(f=>{P.error("auto-sync after file change failed",{error:f instanceof Error?f.message:String(f)});}));},d=()=>{l&&clearTimeout(l),l=setTimeout(o,i);};return s.on((p,f)=>{P.debug("file change",{event:p,relPath:f}),c.add(f),d();}),n&&this.sync().catch(p=>{P.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),P.info("file watcher started",{workspaceDir:r,debounceMs:i}),{stop:async()=>{l&&(clearTimeout(l),l=null),await s.stop(),this.fileWatcher=null,P.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}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,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}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 t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,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){P.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){P.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){P.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,P.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 rn(y){let e=new Ie(y);return await e.initialize(),e}function dr(){try{let e=U.dirname(fileURLToPath(import.meta.url));for(let t=0;t<8;t++){let r=U.join(e,"package.json");try{let n=JSON.parse(readFileSync(r,"utf-8"));if(n&&n.name==="@easbot/codebase"&&typeof n.version=="string")return n.version}catch{}let i=U.dirname(e);if(i===e)break;e=i;}}catch{}return "0.0.0"}export{Oe as a,Me as b,V as c,Tt as d,wt as e,Y as f,At as g,K as h,Wt as i,J as j,Gt as k,Qe as l,X as m,Jt as n,Ie as o,rn as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJDULI4R5_cjs=require('./chunk-JDULI4R5.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var R=class extends Error{constructor(n,l,a){super(n);chunkTS4OAYIJ_cjs.a(this,"code",l);chunkTS4OAYIJ_cjs.a(this,"details",a);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};utils.Log.create({service:"codebase-service"});var N=utils.Filesystem.toUnixPath;async function k(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=N(n.file),r=a.filter(c=>N(c.file_path).endsWith(o)||N(c.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(c=>c.ast_type.includes(o)||c.name.toLowerCase().includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let d=chunkJDULI4R5_cjs.l(n.name,a,{limit:10,minScore:.5});if(d.length===0)throw new P(n.name);if(d.length===1){let o=e.getNode(d[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:d.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of d){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new L(n.name,s)}async function C(e){let t=chunk7XCIIOM6_cjs.c(e.rootDir),n=new chunkJDULI4R5_cjs.o({workspaceDir:e.workspaceDir,database:{path:t,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 de(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:N(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),d=await(await C(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(o)||N(r.file_path).includes(o));}let s=d.map(o=>({node:o,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function ue(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:d}}var pe=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function me(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,c=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;c.length>0;){let g=c.shift();if(g.depth>=d)continue;if(r.size>=s){u=true;break}let f=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??pe,limit:s-r.size+1});for(let h of f.edges){p.push(h);let $=h.source===g.nodeId?h.target:h.source;if(!r.has($)&&(r.set($,g.depth+1),c.push({nodeId:$,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),y=m.length>0?a.queryNodes({ids:m}):[],E=new Map(y.map(g=>[g.id,g])),b=[];for(let[g,f]of r.entries()){let h=E.get(g);h&&b.push({node:h,depth:f});}return {root:i,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var ge=["CALLS","IMPORTS","TYPE_REFERENCES"];async function fe(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,o=t.relationTypes??ge,r=new Set([i.id]),c=[],p=[i.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),y=o.map(()=>"?").join(","),E=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${y})`,[...p,...o]),b=[],g=new Set;for(let f of E)if(!r.has(f.source)&&!g.has(f.source)&&(g.add(f.source),r.add(f.source),b.push(f.source),r.size-1>=s))break;if(b.length>0){let f=b.slice(0,10),h=a.queryNodes({ids:f}),$=new Map(h.map(I=>[I.id,I])),re=f.map(I=>{let B=$.get(I);return {id:I,name:B?.name??"(unknown)",filePath:B?N(B.file_path):"(unknown)",relation:"CALLS"}});c.push({depth:u,count:b.length,sample:re});}p=b;}return {root:i,totalImpacted:r.size-1,buckets:c}}var he=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function ye(e,t){return A(e,t,"incoming")}async function be(e,t){return A(e,t,"outgoing")}async function A(e,t,n,l){let a=await C(e),i=a.getQuery(),d=a.getDatabase(),{node:s}=await k(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??he,c=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of c.edges){let y=de(m,s.id,d,n==="incoming"?"in":"out");y&&p.push(y);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ee(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await C(e);l.getQuery();l.getDatabase();let s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=N(p.node.file_path),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,c=[];for(let[p,u]of o){let m=u.slice(0,r),y=[];for(let E of m){let b=await A(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await A(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"outgoing");y.push({node:E.node,callers:b.callers,callees:g.callers});}c.push({file:p,symbols:y});}return {query:t.query,entryPoints:c,totalHits:s.length}}async function xe(e,t){return await(await C(e)).getStatus()}async function Ne(e,t){return await(await C(e)).healthCheck()}var Pe=utils.Filesystem.toUnixPath;function Ce(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Se(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function x(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Pe(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Ce(e),modifiers:Se(e)}}function T(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e,t,n){return e.map((l,a)=>({node:x(l),source:t[a]??"basic",score:n[a]??0,snippet:(l.text??"").slice(0,200).replace(/\s+/g," ").trim(),edges:(l.edges??[]).slice(0,10).map(i=>T(i))}))}function j(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var $e=utils.Log.create({service:"codebase-format-truncate"}),Q="**`",Ie="**",Z=24e3,ee=25e3;async function D(e,t={}){let n=t.softLimit??Z,l=t.hardCeiling??ee,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
|
|
2
2
|
${Q}`),o=d.lastIndexOf(`
|
|
3
3
|
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let c=r>0?d.slice(0,r):d,u=c+"\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:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}catch(m){return $e.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}}function _(e,t={}){let n=t.softLimit??Z,l=t.hardCeiling??ee;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
4
|
${Q}`),d=a.lastIndexOf(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkJDULI4R5_cjs=require('./chunk-JDULI4R5.cjs'),chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs');require('./chunk-7XCIIOM6.cjs'),require('./chunk-TS4OAYIJ.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.o}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.h}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.b}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.j}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.f}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.c}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.m}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.p}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.i}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.k}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.g}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.n}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.d}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.e}});Object.defineProperty(exports,"ConfigError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.e}});Object.defineProperty(exports,"DatabaseError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.b}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.n}});Object.defineProperty(exports,"FileSystemError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.c}});Object.defineProperty(exports,"IndexError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.f}});Object.defineProperty(exports,"ParserError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.a}});Object.defineProperty(exports,"QueryError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.g}});Object.defineProperty(exports,"SchemaError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.d}});Object.defineProperty(exports,"UnsupportedLanguageError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.h}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{o as CodeBase,h as EdgeExtractor,b as FILE_EXTENSION_MAP,j as Indexer,f as NodeExtractor,c as ParserManager,m as QueryInterface,p as createCodebase,i as createEdgeExtractor,k as createIndexer,g as createNodeExtractor,n as createQueryInterface,d as getParserManager,e as resetParserManager}from'./chunk-VBIXWHTD.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-Z4Y3VCYS.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {d,z as z$1,e,C,f as f$1,B,g,A,h,i,j,D as D$1,k,l,b,c,a as a$1}from'./chunk-PSPE6FME.mjs';import'./chunk-LBEWQNER.mjs';import'./chunk-Z4Y3VCYS.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';import {ToolRegistry,createAndStartStdioServer}from'@easbot/mcp';import {Log}from'@easbot/utils';var f=Log.create({service:"codebase-mcp-stdio"}),Y=["query","node","context","impact","callers","callees","explore","status","doctor"],U;(o=>{let n;function r(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Y],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function c(s,i){let u=r()(),l=new ToolRegistry;ce(l,s);let g=u.toolNames;f.info("starting codebase MCP stdio server",{id:i.id,name:i.name,toolCount:g.length});let y=await createAndStartStdioServer(i,l),b=null,q=new Promise(d=>{b=d;}),S=d=>{f.info("received signal, stopping MCP server",{signal:d}),b?.();},x=()=>S("SIGINT"),T=()=>S("SIGTERM");process.on("SIGINT",x),process.on("SIGTERM",T);try{await q;}finally{try{process.off("SIGINT",x),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await y.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await s.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:i.id,name:i.name,version:i.version,tools:g}}o.start=c;function e(){return r()().toolNames}o.getToolNames=e;function t(){n=void 0;}o.__resetForTests=t;})(U||(U={}));var G={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},Q={type:"object",properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},X={type:"object",properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},edgesLimit:{type:"number",description:"Max edges to return (default 50).",default:50}},required:[]},V={type:"object",properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"}},required:[]},z={type:"object",properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols.",default:50,minimum:1,maximum:200}},required:[]},P={type:"object",properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return.",default:20,minimum:1,maximum:200}},required:[]},K=P,J={type:"object",properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},D={type:"object",properties:{}},Z={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 20). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 20). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
|
|
1
|
+
import {d,z as z$1,e,C,f as f$1,B,g,A,h,i,j,D as D$1,k,l,b,c,a as a$1}from'./chunk-TGMIUXU3.mjs';import'./chunk-VBIXWHTD.mjs';import'./chunk-Z4Y3VCYS.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';import {ToolRegistry,createAndStartStdioServer}from'@easbot/mcp';import {Log}from'@easbot/utils';var f=Log.create({service:"codebase-mcp-stdio"}),Y=["query","node","context","impact","callers","callees","explore","status","doctor"],U;(o=>{let n;function r(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Y],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function c(s,i){let u=r()(),l=new ToolRegistry;ce(l,s);let g=u.toolNames;f.info("starting codebase MCP stdio server",{id:i.id,name:i.name,toolCount:g.length});let y=await createAndStartStdioServer(i,l),b=null,q=new Promise(d=>{b=d;}),S=d=>{f.info("received signal, stopping MCP server",{signal:d}),b?.();},x=()=>S("SIGINT"),T=()=>S("SIGTERM");process.on("SIGINT",x),process.on("SIGTERM",T);try{await q;}finally{try{process.off("SIGINT",x),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await y.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await s.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:i.id,name:i.name,version:i.version,tools:g}}o.start=c;function e(){return r()().toolNames}o.getToolNames=e;function t(){n=void 0;}o.__resetForTests=t;})(U||(U={}));var G={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},Q={type:"object",properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},X={type:"object",properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},edgesLimit:{type:"number",description:"Max edges to return (default 50).",default:50}},required:[]},V={type:"object",properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"}},required:[]},z={type:"object",properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols.",default:50,minimum:1,maximum:200}},required:[]},P={type:"object",properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return.",default:20,minimum:1,maximum:200}},required:[]},K=P,J={type:"object",properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},D={type:"object",properties:{}},Z={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 20). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 20). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
|
|
2
2
|
|
|
3
3
|
WHEN TO USE: Diagnostic only \u2014 check whether the index is up-to-date or stale. Skip unless debugging.
|
|
4
4
|
|