@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
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),Q=require('path'),fs=require('fs'),url=require('url'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),utils=require('@easbot/utils'),worker_threads=require('worker_threads'),qe=require('fs/promises'),crypto=require('crypto'),Ct=require('fast-glob'),ai=require('ai');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Q__default=/*#__PURE__*/_interopDefault(Q);var qe__default=/*#__PURE__*/_interopDefault(qe);var Ct__default=/*#__PURE__*/_interopDefault(Ct);var Ie={".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 ie=utils.Filesystem.toUnixPath,$e=`
|
|
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
|
-
`,je=`
|
|
5
|
-
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?)
|
|
7
|
-
`,Ge="DELETE FROM nodes_fts WHERE rowid = (SELECT rowid FROM nodes_fts WHERE id = ?)",Qe="INSERT INTO nodes_fts (id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)";var Ue=`
|
|
8
|
-
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
9
|
-
VALUES (?, ?, ?)
|
|
10
|
-
`,Ve=`
|
|
11
|
-
INSERT OR IGNORE INTO embedding_cache (content_hash, embedding)
|
|
12
|
-
VALUES (?, ?)
|
|
13
|
-
`,Ye=`
|
|
14
|
-
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
15
|
-
VALUES (?, ?, ?)
|
|
16
|
-
`;var Ke="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",Je="DELETE FROM nodes WHERE file_path = ?";var Xe="DELETE FROM file_hashes WHERE file_path = ?",$="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",Ze="DELETE FROM meta WHERE key = ?",ae=class{constructor(e,t,r={}){chunkTS4OAYIJ_cjs.a(this,"db",e);chunkTS4OAYIJ_cjs.a(this,"writeBackend",t);chunkTS4OAYIJ_cjs.a(this,"options",r);}insertNodes(e){if(e.length===0)return;let t=[];for(let r of e){let n=r.file_path.replace(/\\/g,"/");t.push({sql:$e,params:[r.id,r.name,r.ast_type,r.language,n,r.start_line,r.start_col,r.end_line,r.end_col,r.text,r.created_at]}),this.options.ftsAvailable&&(t.push({sql:Ge,params:[r.id]}),t.push({sql:Qe,params:[r.id,r.name,r.ast_type,r.language,n,r.text]}));}this.writeBackend.enqueue(t);}insertEdges(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:je,params:[r.id,r.source,r.target,r.relation,r.created_at]});this.writeBackend.enqueue(t);}setFileHash(e,t){this.writeBackend.enqueue([{sql:Ue,params:[ie(e),t,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,t){this.writeBackend.enqueue([{sql:Ve,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:Ye,params:[r.nodeId,r.embeddingText,Buffer.from(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength)]});this.writeBackend.enqueue(t);}deleteEdgesByFile(e){let t=ie(e);return this.writeBackend.enqueue([{sql:Ke,params:[t,t]}]),-1}deleteNodesByFile(e){let t=ie(e);return this.writeBackend.enqueue([{sql:Je,params:[t]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:Xe,params:[ie(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,t){this.writeBackend.enqueue([{sql:$,params:[e,t]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:Ze,params:[e]}]);}markIndexed(e,t,r){let n=[{sql:$,params:["indexed_with_version",e]},{sql:$,params:["indexed_with_extraction_version",String(t)]},{sql:$,params:["index_state","complete"]},{sql:$,params:["last_index_state_change",r]}];this.writeBackend.enqueue(n);}setIndexState(e){let t=new Date().toISOString(),r=[{sql:$,params:["index_state",e]},{sql:$,params:["last_index_state_change",t]}];this.writeBackend.enqueue(r);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function et(){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 Pe(){return new worker_threads.Worker(et(),{eval:true})}function tt(){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('better-sqlite3');
|
|
69
|
-
} catch (err) {
|
|
70
|
-
port.postMessage({ type: 'error', requestId: -1, error: 'better-sqlite3 not installed: ' + 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 Ce(y){return new worker_threads.Worker(tt(),{eval:true})}var se=utils.Log.create({service:"database.async-write"}),oe=class{constructor(e){chunkTS4OAYIJ_cjs.a(this,"worker");chunkTS4OAYIJ_cjs.a(this,"mock");chunkTS4OAYIJ_cjs.a(this,"dbPath");chunkTS4OAYIJ_cjs.a(this,"batchSize");chunkTS4OAYIJ_cjs.a(this,"batchIntervalMs");chunkTS4OAYIJ_cjs.a(this,"queueMax");chunkTS4OAYIJ_cjs.a(this,"bufferedStatements",[]);chunkTS4OAYIJ_cjs.a(this,"pendingRequests",new Map);chunkTS4OAYIJ_cjs.a(this,"nextRequestId",1);chunkTS4OAYIJ_cjs.a(this,"flushTimer",null);chunkTS4OAYIJ_cjs.a(this,"ready");chunkTS4OAYIJ_cjs.a(this,"disposed",false);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=Pe():this.worker=Ce(this.dbPath),this.ready=this.waitForReady(),this.installAckHandler();}installAckHandler(){this.worker.on("message",e=>{let t=e;if(t.type==="debug_error"){se.error("AsyncWriteBackend statement failed (debug)",{sql:t.sql?.slice(0,200),paramsCount:t.paramsCount,params:t.paramsJson,error:t.error});return}if(typeof t.requestId!="number"||t.requestId<1)return;let r=this.pendingRequests.get(t.requestId);r&&(this.pendingRequests.delete(t.requestId),clearTimeout(r.timer),t.type==="write_batch_ack"?r.resolve():t.type==="error"&&r.reject(new Error(t.error??"worker write error")));});}waitForReady(){return new Promise((e,t)=>{let r=setTimeout(()=>t(new Error("worker init timeout")),1e4),n=i=>{if(i.type==="ready"){clearTimeout(r),this.worker.off("message",n);let c=setTimeout(()=>t(new Error("worker open timeout")),1e4),l=o=>{o.type==="open_ack"&&o.requestId===0?(clearTimeout(c),this.worker.off("message",l),e()):o.type==="error"&&o.requestId===0&&(clearTimeout(c),this.worker.off("message",l),t(new Error(o.error??"worker open error")));};this.worker.on("message",l),this.worker.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else i.type==="error"&&i.requestId===-1&&(clearTimeout(r),this.worker.off("message",n),t(new Error(i.error??"unknown init error")));};this.worker.on("message",n);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new Error("AsyncWriteBackend \u5DF2 dispose");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.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:n=>{se.error("AsyncWriteBackend write failed",{error:n.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((n,i)=>{let c=setTimeout(()=>i(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),l=setInterval(()=>{let s=this.pendingRequests.size,d=Math.floor((Date.now()-r)/1e3);s>0&&d>0&&d%5===0&&se.info("flush in progress",{pending:s,initial:t,elapsedSec:d});},1e3),o=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(c),clearInterval(o),clearInterval(l),n());},5);});}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){se.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:e instanceof Error?e.message:String(e)});}this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate();}pendingCount(){return this.pendingRequests.size}};var Le=utils.Log.create({service:"codebase-parser"}),st={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 ot(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-ABKFCPSL.cjs', document.baseURI).href)) })<"u"&&chunkTS4OAYIJ_cjs.b?Q__default.default.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function ct(y,e){let t=ot(),r=t;for(let n=0;n<10;n++){let i=Q__default.default.join(r,"node_modules",y,e);if(utils.Filesystem.stat(i)!==void 0)return i;let c=Q__default.default.dirname(r);if(c===r)break;r=c;}return Q__default.default.join(t,"node_modules",y,e)}var U=class{constructor(){chunkTS4OAYIJ_cjs.a(this,"parsers",new Map);chunkTS4OAYIJ_cjs.a(this,"initialized",false);chunkTS4OAYIJ_cjs.a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),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 n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],i=await Promise.allSettled(n.map(async c=>{try{let l=st[c];if(!l)return Le.warn("No WASM config for language",{lang:c}),null;let o=ct(l.package,l.wasmFile),s=await r.load(o),d=new t;return d.setLanguage(s),{lang:c,parser:d,language:s}}catch(l){return Le.warn("Failed to load parser",{lang:c,error:String(l)}),null}}));for(let c of i)if(c.status==="fulfilled"&&c.value){let{lang:l,parser:o,language:s}=c.value;this.parsers.set(l,{parser:o,language:s});}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=Q__default.default.extname(e).toLowerCase();return Ie[t]??null}parse(e,t){if(!this.initialized)throw new chunkRLZHDTHY_cjs.a("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new chunkRLZHDTHY_cjs.a(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new chunkRLZHDTHY_cjs.a("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new chunkRLZHDTHY_cjs.h(Q__default.default.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;}},j=null;async function dt(){return j||(j=new U,await j.initialize()),j}function lt(){j&&(j.dispose(),j=null);}var F={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"},ye={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:F,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"}},pt={...ye,language:"tsx"},ut={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:F,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},mt={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,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"}},gt={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:F,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"}},ft={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:F,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"}},yt={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:F,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"}},ht={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:F,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"}},_t={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:F,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"}},bt={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:F,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"}},xt={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:F,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"}},Tt={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:F,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"}},Et={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:F,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"}},wt={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:F,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"}},Me=new Map([["ts",ye],["tsx",pt],["js",ut],["py",mt],["java",gt],["csharp",ft],["c",yt],["cpp",ht],["rs",_t],["go",bt],["php",Tt],["scala",Et],["zig",wt],["ruby",xt]]);function A(y){return Me.get(y)??ye}Array.from(Me.keys());function Re(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 n of r)t.add(n);return t}function ke(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 L(y,e){return A(y).normalizeMap[e]??e}var V=class{extractNodes(e,t,r,n){let i=[],c=t.split(`
|
|
182
|
-
`),l=Re(r),o=ke(r);return this.walkTree(e.rootNode,i,r,n,c,l,o),i}walkTree(e,t,r,n,i,c,l,o,s){if(c.has(e.type)){let d=this.extractNode(e,r,n,i,o,s,l);d&&(t.push(d),d.name&&(o=this.generateNodeId(d)),l.has(e.type)||(s=d.name??s));}for(let d=0;d<e.childCount;d++){let p=e.children[d];p&&this.walkTree(p,t,r,n,i,c,l,o,s);}}extractNode(e,t,r,n,i,c,l){let o=this.getNodeName(e,t);if(!o)return null;let s=e.startPosition,d=e.endPosition,p=this.getNodeText(e,n),f=l.has(e.type),g=f&&c?`${c}.${o}@${s.row+1}`:o,u=f?this.extractParameterTypes(e,t):[];return {name:g,ast_type:L(t,e.type),language:t,file_path:r,start_line:s.row+1,start_col:s.column,end_line:d.row+1,end_col:d.column,text:p,parent_id:i,metadata:f?{originalName:o,parameterTypes:u}:void 0}}extractParameterTypes(e,t){let n=A(t).parameters;if(!n)return [];let i=new Set(n.typeInWrapper),c=[],l=o=>{for(let s of o.children)if(s.type===n.wrapperType)return s;return null};if(n.declaratorStyle==="declarator"){for(let o of e.children)if(o.type==="function_declarator"||o.type==="pointer_declarator"){let s=l(o);if(s){for(let d of s.children)if(n.paramTypes.includes(d.type)){let p=this.findTypeInNode(d,i);p&&c.push(p);}return c}}}else {let o=l(e);if(o){for(let s of o.children)if(n.paramTypes.includes(s.type)){let d=this.findTypeInNode(s,i);d&&c.push(d);}}}return c}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 n of e.children)if(n.type==="namespace_name")return n.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 n=e.childForFieldName?.(r);if(n?.text)return n.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 n of e.children)if(t.includes(n.type)){let i=this.findNameInChildren(n,r);if(i)return i}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,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
|
|
183
|
-
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function St(){return new V}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"},he={extends:"extends",implements:"implements"},Fe="new",Z={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function ce(y,e){e(y);for(let t of y.children)ce(t,e);}function q(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 de(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 le(y,e){for(let t of y.children)if(e.includes(t.type))return t;return null}function D(y,e){for(let t of y.children){if(e.includes(t.type))return t;let r=D(t,e);if(r)return r}return null}function W(y,e){for(let t of y.children)if(e.includes(t.type)){let r=q(t);if(r)return r;for(let n of t.children){let i=q(n);if(i)return i}}for(let t of y.children){let r=W(t,e);if(r)return r}return null}function ee(y){let e=y.indexOf("<");if(e<0)return y;let t=0,r=null;for(let n=e;n<y.length;n++){let i=y[n];if(r){i===r&&(r=null);continue}if(i==='"'||i==="'"||i==="`"){r=i;continue}if(i==="<")t++;else if(i===">"&&(t--,t===0))return y.slice(0,e).trim()}return y}function Ae(y){let e=A(y),t=new Set;for(let r of e.rawTypes.classTypes)t.add(L(y,r));for(let r of e.rawTypes.interfaceTypes)t.add(L(y,r));for(let r of e.rawTypes.moduleTypes)t.add(L(y,r));return t}function Nt(y){let e=A(y),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(L(y,r));return t}function It(y){let e=A(y),t=new Set;for(let r of e.rawTypes.propertyTypes)t.add(L(y,r));return t}var Y=class{extractEdges(e,t,r,n){let i=[],c=new Map;for(let o of t){let s=c.get(o.name);s||(s=[],c.set(o.name,s)),s.push(o);}let l=new Map;for(let[o,s]of c){let d=s[0];d&&l.set(o,d);}return this.extractContainsEdges(t,i),this.extractCallEdges(e.rootNode,t,i,r,n,l),this.extractInheritanceEdges(e.rootNode,t,i,r,n,l),this.extractImportEdges(e.rootNode,t,i,r,n),this.extractTypeReferences(e.rootNode,t,i,r,n,l),this.extractAnnotationEdges(e.rootNode,t,i,r,n),this.extractHasMethodEdges(t,i,r),this.extractHasPropertyEdges(t,i,r),this.extractOverrideEdges(t,i,r,n),i}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,n,i,c){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,o=>{if(l.has(o.type)){let s=this.findEnclosingFunction(o,t,c),d=this.extractCalleeName(o);if(s&&d){let p=`${n}:*:*:${d}`;r.push({source:s.id,target:p,relation:"CALLS",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}}});}extractInheritanceEdges(e,t,r,n,i,c){let l=A(n),o=new Set(l.rawTypes.classTypes),s=new Set(l.rawTypes.interfaceTypes),d=this.buildImportAliasMap(e,n);this.walkTree(e,p=>{if(o.has(p.type)){let f=q(p);if(!f)return;let g=`${n}:${i}:${L(n,p.type)}:${f}`,u=le(p,[...l.inheritance.extendsClauseTypes]);u||(u=D(p,[...l.inheritance.extendsClauseTypes]));let m=[];u?(m=this.extractClauseNames(u,n),l.inheritance.stripTemplateArgs&&(m=m.map(h=>ee(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=L(n,l.rawTypes.classTypes[0]??"class_declaration"),_=d.get(h)??h,w=`${n}:${i}:${b}:${_}`;r.push({source:g,target:w,relation:"EXTENDS",line:(u?.startPosition?.row??p.startPosition?.row??-1)+1,col:(u?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}for(let h of l.inheritance.implementsClauseTypes){let b=le(p,[h]);if(b||(b=D(p,[h])),b){let _=this.extractClauseNames(b,n);l.inheritance.stripTemplateArgs&&(_=_.map(w=>ee(w)));for(let w of _){if(!w)continue;let x=l.rawTypes.interfaceTypes[0]??l.rawTypes.classTypes[0]??a.interface_declaration,T=d.get(w)??w,N=`${n}:${i}:${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:i});}}}return}if(s.has(p.type)){let f=q(p);if(!f)return;let g=`${n}:${i}:${L(n,p.type)}:${f}`;for(let u of l.inheritance.extendsClauseTypes){let m=D(p,[u]);if(m){let h=this.extractClauseNames(m,n);l.inheritance.stripTemplateArgs&&(h=h.map(b=>ee(b)));for(let b of h){if(b===f)continue;let _=L(n,l.rawTypes.interfaceTypes[0]??"interface_declaration"),w=d.get(b)??b,x=`${n}:${i}:${_}:${w}`;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:i});}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]),n=i=>{if(r.has(i.type)){t.push(i);return}for(let c of i.children)n(c);};return n(e),t}collectNamedIdentifiers(e){let t=[],r=new Set,n=i=>{if(i.type===a.identifier||i.type===a.type_identifier||i.type===a.attribute){let c=i.text;r.has(c)||(r.add(c),t.push(c));return}for(let c of i.namedChildren)c&&n(c);};return n(e),t}extractClauseNames(e,t){let r=[],n=new Set,i=s=>{!s||n.has(s)||(n.add(s),r.push(s));},c=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]),o=s=>{if(c.has(s.type)){i(s.text);return}if(l.has(s.type)){if(s.type===a.name&&(s.text===he.extends||s.text===he.implements))return;i(s.text);return}if(s.type===a.generic_type){let d=s.childForFieldName?.("name")?.text??s.namedChildren[0]?.text;d&&i(d);return}for(let d of s.namedChildren)d&&o(d);};return o(e),r}extractImportEdges(e,t,r,n,i){let c=A(n),l=new Set(c.rawTypes.importTypes),o=new Set;this.walkTree(e,s=>{if(l.has(s.type)){let d,p=this.extractImportWholePath(s);p?d=[p]:d=this.extractImportPaths(s);for(let f of d){if(!f||o.has(f))continue;o.add(f);let g=`${n}:${i}:module:file`;r.push({source:g,target:f,relation:"IMPORTS",line:(s.startPosition?.row??-1)+1,col:(s.startPosition?.column??-1)+1,filePath:i});}}});}walkTree(e,t){ce(e,t);}findEnclosingFunction(e,t,r){let n=e,i=new Set([a.function_declaration,a.function_definition,a.method_definition,a.method_declaration,a.function_item]);for(;n;){if(i.has(n.type)){let c=q(n)??W(n,[a.function_declarator,a.declarator]);if(c){let l=r.get(c);if(l)return {id:this.generateNodeId(l),name:c};let o=t[0],s=o?.language??"ts",d=o?.file_path??"";return {id:`${s}:${d}:function_definition:${c}`,name:c}}}n=n.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 n=e.childForFieldName?.("name");if(n)return n.text;let i=e.children.find(c=>c.type===a.name);if(i)return i.text}if(r.has(t.type)){let n=t.childForFieldName?.("property");if(n)return n.text;let i=t.childForFieldName?.("field");if(i)return i.text;let c=t.childForFieldName?.("name");if(c)return c.text;for(let l=t.children.length-1;l>=0;l--){let o=t.children[l];if(o&&(o.type===a.identifier||o.type===a.property_identifier||o.type===a.name||o.type===a.field_identifier||o.type===a.constant))return o.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 n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===a.identifier&&t.text.includes(".")){let n=t.text.split(".");return n[n.length-1]??t.text}if(t.type===a.super){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===Fe){for(let n of e.children)if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.name||n.type===a.scoped_identifier)return n.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]),n=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),i=[],c=o=>{if(r.has(o.type)){let s=o.text;(s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),i.push(s);return}for(let s of o.children)c(s);};if(c(e),i.length>0)return i;let l=o=>{if(n.has(o.type)){let s=o.text;(s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),i.push(s);return}for(let s of o.children)l(s);};return l(e),i}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 n of e.children)if(n.type===a.dotted_name)r.push(n.text);else if(n.type===a.aliased_import){let i=n.childForFieldName?.("name");if(i)r.push(i.text);else for(let c of n.children)if(c.type===a.dotted_name||c.type===a.identifier){r.push(c.text);break}}}else for(let n of e.children){if(n.type===a.dotted_name){r.push(n.text);break}if(n.type===a.relative_import){let i=n.childForFieldName?.(a.import_prefix),c=n.childForFieldName?.(a.module_name),l="";i&&(l+=i.text),c&&(l+=c.text),l?r.push(l):r.push(n.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 (n=>{if(t.has(n.type)){let i=n.text;return (i.startsWith('"')||i.startsWith("'")||i.startsWith("<"))&&(i=i.slice(1,-1)),n.type===a.namespace_use_clause&&i.includes(" as ")&&(i=i.split(" as ")[0]??i),i}if(n.type===a.namespace_use_declaration||n.type===a.namespace_use_clause){for(let i of n.children)if(t.has(i.type)){let c=i.text;return (c.startsWith('"')||c.startsWith("'")||c.startsWith("<"))&&(c=c.slice(1,-1)),i.type===a.namespace_use_clause&&c.includes(" as ")&&(c=c.split(" as ")[0]??c),c}}return null})(e)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,i,c){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]),o=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),s=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??de(d)??q(d)??W(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=de(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&&!Z.void_any_null.has(x)){let T=this.resolveTypeNodeId(x,n,i);T&&r.push({source:this.generateNodeIdFromName(g,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}let w=D(d,["type_parameter","generic_type"]);if(w){let x=this.extractTypeName(w);if(x){let T=this.resolveTypeNodeId(x,n,i);T&&r.push({source:this.generateNodeIdFromName(g,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(w.startPosition?.row??-1)+1,col:(w.startPosition?.column??-1)+1,filePath:i});}}}if(o.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,n,i);h&&r.push({source:g.id,target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}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(s.has(d.type)){for(let g of d.children)if(p.has(g.type)){let u=this.extractTypeName(g);if(u&&!Z.string_number_boolean.has(u)){let m=this.resolveTypeNodeId(u,n,i);if(m){let h=this.findEnclosingFunction(d,t,c);h&&r.push({source:h.id,target:m,relation:"TYPE_REFERENCES",line:(g.startPosition?.row??-1)+1,col:(g.startPosition?.column??-1)+1,filePath:i});}}}if((n==="zig"||n==="csharp")&&d.type===a.parameter&&d.children.length>=2){let g=n==="zig"?2:0,u=d.children[g];if(u&&u.type===a.identifier){let m=u.text;if(m&&!Z.string_number_boolean.has(m)){let h=this.resolveTypeNodeId(m,n,i);if(h){let b=this.findEnclosingFunction(d,t,c);b&&r.push({source:b.id,target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}}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&&!Z.string_number_boolean.has(m)&&m!=="any"){let h=this.resolveTypeNodeId(m,n,i);if(h){let b=q(d)??W(d,["variable_declarator"])??q(d);b&&r.push({source:this.generateNodeIdFromName(b,"variable_declaration",n,i),target:h,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}});}extractHasMethodEdges(e,t,r){let n=Ae(r),i=Nt(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_METHOD");}extractHasPropertyEdges(e,t,r){let n=Ae(r),i=It(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_PROPERTY");}emitContainerToMemberEdges(e,t,r,n,i){let c=new Map;for(let l of e){let o=c.get(l.file_path);o||(o=[],c.set(l.file_path,o)),o.push(l);}for(let l of c.values()){l.sort((s,d)=>s.start_line-d.start_line);let o=[];for(let s of l){for(;o.length>0&&(o[o.length-1]?.end_line??1/0)<s.start_line;)o.pop();if(r.has(s.ast_type))o.push(s);else if(n.has(s.ast_type)){let d=o[o.length-1];if(d){let p=this.generateNodeId(d),f=this.generateNodeId(s);t.push({source:p,target:f,relation:i});}}}}}extractOverrideEdges(e,t,r,n){let i=A(r),c=new Set;for(let d of i.rawTypes.classTypes)c.add(L(r,d));for(let d of i.rawTypes.interfaceTypes)c.add(L(r,d));let l=e.filter(d=>c.has(d.ast_type));if(l.length===0)return;let o=new Map;for(let d of e){let p=o.get(d.file_path);p||(p=[],o.set(d.file_path,p)),p.push(d);}let s=new Map;for(let d of t)if(d.relation==="EXTENDS"){let p;for(let g of o.values())if(p=g.find(u=>this.generateNodeId(u)===d.target),p)break;if(!p)continue;let f=s.get(d.source);f||(f=[],s.set(d.source,f)),f.push(p);}for(let d of l){let p=s.get(this.generateNodeId(d))??[];if(p.length===0)continue;let f=this.collectMemberIdsByName(d,o,"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=s.get(this.generateNodeId(h))??[];m.push(...b);}for(let[h,b]of f){let _=b[0];if(!_)continue;let w=null;for(let x of u){let N=this.collectMemberIdsByName(x,o,"HAS_METHOD",r).get(h);if(!(!N||N.length===0)){w=N[0]??null;break}}if(w&&w!==_){let x=this.generateNodeId(d);if(t.some(I=>I.relation==="METHOD_OVERRIDES"&&I.source===x&&I.target===w))continue;t.push({source:x,target:w,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,t,r,n){let i=new Map,c=t.get(e.file_path);if(!c)return i;let l=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let o of c)if(l.has(o.ast_type)&&o.start_line>=e.start_line&&o.end_line<=e.end_line){let s=o.metadata?.originalName??o.name,d=o.metadata?.parameterTypes??[],p=d.length>0?`${s}|${d.join(",")}`:s,f=i.get(p);f||(f=[],i.set(p,f));let g=this.generateNodeId(o);f.push(g);}return i}buildImportAliasMap(e,t){let r=new Map;return this.walkTree(e,n=>{if(n.type===a.namespace_use_clause){let i=n.children,c=i.findIndex(l=>l.type==="as");if(c>=0){let l=i.slice(0,c).find(s=>s.type===a.qualified_name),o=i[c+1];l&&o&&o.type===a.name&&o.text&&r.set(o.text,l.text);}}}),r}findEnclosingClass(e,t){let r=e.parent,n=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(n.has(r.type)){let i=q(r)??W(r,[a.type_spec,a.name]);if(i){let c=t.find(d=>d.name===i);if(c)return {id:this.generateNodeId(c),name:i};let l=t[0],o=l?.language??"ts",s=l?.file_path??"";return {id:`${o}:${s}:${r.type}:${i}`,name:i}}}r=r.parent;}return null}extractAnnotationEdges(e,t,r,n,i){let c=A(n),l=new Set(c.rawTypes.annotationTypes),o=new Set(c.annotation.annotatableTypes);this.walkTree(e,s=>{if(l.has(s.type)){let d=this.extractTypeName(s)||q(s);if(!d)return;let p=s.parent;for(;p;){if(o.has(p.type)){let f=q(p),g=p.type;if(!f&&(p.type===a.decorated_definition||p.type===a.export_statement)){let u=W(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),m=D(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,n,i),m=`${n}:${i}:annotation:${d}`;r.push({source:m,target:u,relation:"ANNOTATES",line:(s.startPosition?.row??-1)+1,col:(s.startPosition?.column??-1)+1,filePath:i});}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 n of e.children)if(t.has(n.type))return n.text;for(let n of e.children)if(n.type===a.predefined_type)return n.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 n of e.children)if(r.has(n.type)){let i=this.extractTypeName(n);if(i)return i}return null}resolveTypeNodeId(e,t,r){let n=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let i of n)return `${t}:${r}:${i}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${L(r,t)}:${e}`}};function vt(){return new Y}var z=utils.Log.create({service:"codebase-indexer"}),K=class{constructor(e,t,r,n){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"parserManager");chunkTS4OAYIJ_cjs.a(this,"nodeExtractor");chunkTS4OAYIJ_cjs.a(this,"edgeExtractor");chunkTS4OAYIJ_cjs.a(this,"config");chunkTS4OAYIJ_cjs.a(this,"writeProxy",null);this.db=e,this.parserManager=t,this.nodeExtractor=new V,this.edgeExtractor=new Y,this.config=r,this.writeProxy=n??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 i=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(i){let c=new Float32Array(i);return this.dbWriter.cacheEmbedding?.(t,c),c}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],i=0,c=0,l=null;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new chunkRLZHDTHY_cjs.f("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let s=await this.readFile(e),d=this.computeHash(s);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(s,o);let p=this.nodeExtractor.extractNodes(l,s,o,e);i=p.length;let f=this.edgeExtractor.extractEdges(l,p,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let g=this.getValidEdgeCount(f,p);this.storeEdges(f,p),c=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(o){let s=o instanceof Error?o.message:String(o);n.push({filePath:e,error:s});}finally{if(l)try{l.delete();}catch(o){z.warn("tree.delete failed",{filePath:e,error:String(o)});}}return {success:n.length===0,filesProcessed:1,nodesCreated:i,edgesCreated:c,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,i=[],c=0,l=0,o=0;try{let s=await this.scanFiles(n);for(let u of s.readErrors)i.push(u);let d=s.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)c++,f++,l+=b.nodesCreated,o+=b.edgesCreated,!b.success&&b.errors.length>0&&i.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(s){let d=s instanceof Error?s.message:String(s);i.push({filePath:n,error:d});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:i.length===0,filesProcessed:c,nodesCreated:l,edgesCreated:o,errors:i,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,i=0,c=0,l=0,o=0,s=0;try{let g=await this.scanFiles(this.config.workspaceDir),u=g.results;for(let E of g.readErrors)r.push(E);let m=new Set(u.map(E=>E.filePath)),h=this.db.getAllFileHashes(),b=new Set(h.map(E=>E.file_path));for(let E of h)m.has(E.file_path)||(this.dbWriter.deleteFtsByFile?.(E.file_path),this.dbWriter.deleteNodesByFile(E.file_path),this.dbWriter.deleteEdgesByFile(E.file_path),this.dbWriter.deleteFileHash(E.file_path),c++);let _=u.length,w=0,x=E=>{e&&e({currentFile:E.currentFile,processed:w,total:_,stage:E.stage});},T=Math.max(1,this.config.batchSize),N=new Map;for(let E of h)N.set(E.file_path,E.content_hash);for(let E=0;E<u.length;E+=T){let H=u.slice(E,E+T),G=await Promise.all(H.map(R=>{let k=N.get(R.filePath);return k?k!==R.contentHash?this.indexFile(R.filePath,x).then(B=>({file:R,kind:"updated",r:B})):Promise.resolve({file:R,kind:"skipped",r:null}):this.indexFile(R.filePath,x).then(B=>({file:R,kind:"added",r:B}))}));for(let{kind:R,r:k}of G)R==="skipped"?l++:k&&(k.success?k.nodesCreated===0?l++:(R==="added"?n++:i++,o+=k.nodesCreated,s+=k.edgesCreated):r.push(...k.errors));w+=H.length;}if(e&&_>0){let E=u[u.length-1]?.filePath??"";e({currentFile:E,processed:_,total:_,stage:"storing"});}let I=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(E=>E.file_path)),M=this.db.getAllFileHashes().filter(E=>!I.has(E.file_path)).map(E=>E.file_path);for(let E of M)this.dbWriter.deleteFileHash(E);}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:n,filesUpdated:i,filesDeleted:c,filesSkipped:l,nodesCreated:o,edgesCreated:s,errorCount:r.length,errors:r,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(f)),{success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:c,filesSkipped:l,nodesCreated:o,edgesCreated:s,errors:r,duration:p}}async scanFiles(e){let t=[],r=[],i=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(m=>`**/*${m}`),c=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],l=this.config.ignorePatterns.map(m=>m.includes("/")||m.includes("*")?m:`**/${m}/**`),o=[...c,...l],s=await this.loadGitignore(e),d=e.replace(/\\/g,"/"),p=await Ct__default.default(i,{cwd:d,absolute:true,ignore:o,onlyFiles:true,followSymbolicLinks:false,dot:false}),f=s?p.filter(m=>!s.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=utils.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 w=await this.readFile(_),x=this.computeHash(w),T=this.parserManager.detectLanguage(_);return T?{filePath:_,language:T,contentHash:x,content:w}:null}catch(w){let x=w instanceof Error?w.message:String(w);return r.push({filePath:_,error:x}),z.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 qe__default.default.readFile(t,"utf-8"),n=utils.Ignore.create();return n.add(r),z.debug("Loaded .gitignore",{path:t,lines:r.split(`
|
|
184
|
-
`).length}),n}catch(t){return t.code!=="ENOENT"&&z.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 qe__default.default.readFile(e,"utf-8")}catch(t){throw new chunkRLZHDTHY_cjs.c("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.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 n=this.splitIdentifier(r.name);for(let i of n)i.length>0&&t.push({segment:i,name:r.name});}if(t.length!==0)try{this.db.insertNameSegmentsBatch(t);}catch(r){z.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:t.length,error:String(r)});for(let{segment:n,name:i}of t)try{this.db.insertNameSegment(n,i);}catch(c){z.warn("insertNameSegment failed",{nodeName:i,segment:n,error:String(c)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let t=[],i=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let c of i.split(/\s+/)){let l=c.toLowerCase();l.length>0&&t.push(l);}return t}storeEdges(e,t){let r=new Set(t.map(i=>this.nodeExtractor.generateNodeId(i))),n=e.filter(i=>i.source!==i.target&&r.has(i.source)&&r.has(i.target)).map((i,c)=>({id:`${i.source}:${i.relation}:${i.target}:${c}`,source:i.source,target:i.target,relation:i.relation,created_at:new Date().toISOString()}));n.length>0&&this.dbWriter.insertEdges(n),this.storeUnresolvedRefs(e,t,r);}storeUnresolvedRefs(e,t,r){let n=new Map,i=(s,d)=>{let p=n.get(s);p||(p=[],n.set(s,p)),p.includes(d)||p.push(d);};for(let s of t){let d=this.nodeExtractor.generateNodeId(s);i(s.name,d);let p=s.metadata?.originalName;typeof p=="string"&&p.length>0&&i(p,d);let f=s.name.lastIndexOf("@");if(f>0){let g=s.name.slice(0,f),u=g.lastIndexOf(".");u>0&&i(g.slice(u+1),d);}}let c=t[0]?.file_path??"",l=t[0]?.language??"unknown",o=[];for(let s of e){let d=r.has(s.source),p=r.has(s.target);if(d&&p)continue;let f=d?s.target:s.source,g=d?s.source:r.has(s.target)?s.target:void 0,u=f.includes(":")?f.split(":").pop()??f:f,m=n.get(u)??[];o.push({fromNodeId:g,referenceName:f,referenceKind:s.relation,line:s.line,col:s.col,filePath:s.filePath??c,language:l,candidates:m.length>0?m:void 0});}if(o.length!==0)try{this.db.insertUnresolvedRefsBatch(o);}catch(s){z.warn("insertUnresolvedRefsBatch failed, falling back to per-row insert",{batchSize:o.length,error:String(s)});for(let d of o)try{this.db.insertUnresolvedRef(d);}catch(p){z.warn("insertUnresolvedRef failed",{edgeId:`${d.fromNodeId??"?"}:${d.referenceKind}:${d.referenceName}`,error:String(p)});}}}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[],i=4,c=r.map((o,s)=>({index:s,batch:o})),l=[];for(let o=0;o<c.length;o+=i){let s=c.slice(o,o+i),d=await Promise.all(s.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 w=new Float32Array(_),x=this.computeHash(this.generateNodeEmbeddingText(b));this.dbWriter.cacheEmbedding?.(x,w),g.push({nodeId:this.nodeExtractor.generateNodeId(b),embeddingText:u[h]||"",embedding:w});}}}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((o,s)=>o.index-s.index);for(let o of l)n.push(...o.embeddings);n.length>0&&this.dbWriter.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function kt(y,e,t){return new K(y,e,t)}function _e(y){if(!y)return [];let e=y.split(/[^a-zA-Z0-9]+/),t=[];for(let r of e){if(!r)continue;let n=r.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);n&&t.push(...n);}return t.map(r=>r.toLowerCase()).filter(r=>r.length>0)}function Oe(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 De(y,e,t={}){let r=t.limit??20,n=t.minScore??.2;if(!y)return [];let i=_e(y),c=[];for(let l of e){let o=l.id.split(":").pop()??"";if(o===y||l.name===y){c.push({nodeId:l.id,score:1,matchedPart:"full"});continue}let s=_e(o),d=_e(l.name),p=Oe(i,s),f=Oe(i,d),g=Math.max(p,f);g>=n&&c.push({nodeId:l.id,score:g,matchedPart:g>=.99?"full":"segment"});}return c.sort((l,o)=>o.score-l.score),c.slice(0,r)}var be=utils.Filesystem.toUnixPath,v=utils.Log.create({service:"codebase.query"}),qt=new Set(["AND","OR","NOT","NEAR"]),Ot=/[\p{L}\p{N}_]/u;function Dt(y){return y?y.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!qt.has(t.toUpperCase())).filter(t=>Ot.test(t)).join(" "):""}var J=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"embedding");chunkTS4OAYIJ_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:i,filePath:c,astType:l,enableFts:o=true,includeEdges:s=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:f=this.config.hybrid.textWeight,enableEmbedding:g=true}=t;v.debug("search() called",{query:e,astType:l,language:i,enableEmbedding:g,enableFts:o,minScore:n});let u=[],m=new Map;if(g&&this.embedding){let _=await this.vectorSearchNodes(e,r*2,n);v.debug("vectorSearchNodes results",{count:_.length,astTypeFilter:l});for(let w of _){if(i&&w.language!==i||l&&w.astType!==l)continue;let x={...w,source:"vector",vectorScore:w.score,hybridScore:w.score*p};u.push(x),m.set(x.id,x);}v.debug("after vector filter",{resultsCount:u.length});}if(o&&this.db.isFtsAvailable()){let _=Dt(e);_||v.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let w=_?this.db.searchNodesFts(_,r*2):[];v.debug("FTS results before filter",{count:w.length});for(let x of w){if(i&&x.language!==i||c&&!x.file_path.includes(be(c))||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 I={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(I),m.set(I.id,I);}}v.debug("after FTS filter",{resultsCount:u.length});}if(!o||!this.db.isFtsAvailable()||u.length===0){try{let _=this.db.queryNodes({limit:r*2,astType:l,language:i,filePath:c}),w=new Set(u.map(E=>E.id)),x=e.toLowerCase(),T=x.split(/\s+/).filter(E=>E.length>0),N=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),I=T.map(E=>({term:E,regex:new RegExp(N(E),"gi")})),M=[];for(let E of _){if(c&&!E.file_path.includes(be(c)))continue;let H=E.name.toLowerCase(),G=E.text.toLowerCase(),R=0;if(I.some(({term:O})=>H.includes(O))){let O=0;for(let{regex:te}of I){let re=H.match(te);O+=re?re.length:0;}R=.8*Math.min(O/I.length,1);}let k=0;if(I.some(({term:O})=>G.includes(O))){let O=0;for(let{regex:He}of I){let Te=G.match(He);O+=Te?Te.length:0;}k=.5*Math.min(O/I.length,1);let te=G.indexOf(x),re=te===-1?0:Math.max(0,1-te/G.length)*.2;k+=re;}let B=Math.max(R,k);B>0&&M.push({id:E.id,name:E.name,astType:E.ast_type,language:E.language,filePath:E.file_path,text:E.text,snippet:E.text.slice(0,200),startLine:E.start_line,startCol:E.start_col,endLine:E.end_line,endCol:E.end_col,score:B,source:"basic",hybridScore:B});}M.sort((E,H)=>H.score-E.score),u.push(...M.slice(0,r));}catch{}if(u.length===0)try{let _=this.db.queryNodes({limit:1e3}),w=De(e,_,{limit:r,minScore:.5});v.debug("name-segment matches",{count:w.length,query:e});for(let x of w){let T=this.db.getNodeById(x.nodeId);if(!T||i&&T.language!==i||l&&T.ast_type!==l||c&&!T.file_path.includes(be(c)))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(_){v.debug("name-segment channel error",{error:_ instanceof Error?_.message:String(_)});}}let b=u.filter(_=>_.hybridScore>=n).sort((_,w)=>w.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(s&&b.length>0){let _=b.map(T=>T.id),w=this.db.queryEdges({sourceOrTarget:_}),x=new Map;for(let T of w)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,n){if(v.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return v.debug("vectorSearchNodes skip - no embedding model"),[];let i=await this.embedText(e);if(!i)return v.debug("vectorSearchNodes skip - no embedding result"),[];let c=new Float32Array(i),l,o=5e3;if(n&&n.length>0){let g=n.map(()=>"?").join(",");l=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${g})`,n);}else l=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[o]);v.debug("vectorSearchNodes vectors loaded",{count:l.length});let s=[];for(let g of l){let u=new Float32Array(g.embedding.buffer,g.embedding.byteOffset,g.embedding.length/4),m=this.cosineSimilarity(c,u);m<r||(s.push({nodeId:g.node_id,score:m}),s.length>t&&(s.sort((h,b)=>b.score-h.score),s.splice(t)));}if(s.length===0)return v.debug("vectorSearchNodes done - no results above minScore"),[];s.sort((g,u)=>u.score-g.score);let d=s.map(g=>g.nodeId);v.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let p=this.db.queryNodes({ids:d}),f=new Map(s.map(g=>[g.nodeId,g.score]));return v.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,n=0,i=0;for(let c=0;c<e.length;c++){let l=e[c],o=t[c];r+=l*o,n+=l*l,i+=o*o;}return n===0||i===0?0:r/(Math.sqrt(n)*Math.sqrt(i))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){v.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 chunkRLZHDTHY_cjs.g("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){v.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 chunkRLZHDTHY_cjs.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 n of t){let i=this.db.getNodeById(n.source),c=this.db.getNodeById(n.target);i&&c&&r.push({edge:n,sourceNode:i,targetNode:c});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:i=100}=t;v.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:r,direction:n,limit:i});let c=[],l=[],o=new Set,s=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:i}):this.db.queryEdges({target:e,...u,limit:i});for(let h of m){if(s.has(h.id))continue;s.add(h.id),c.push(h);let b=f==="outgoing"?h.target:h.source,_=this.db.getNodeById(b);_&&!o.has(_.id)&&(l.push(_),o.add(_.id));}}};return (n==="outgoing"||n==="both")&&p("outgoing"),(n==="incoming"||n==="both")&&p("incoming"),{nodes:l.slice(0,i),edges:c.slice(0,i)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,i=(c,l)=>{if(l>t||n.has(c))return;n.add(c);let o=[],s=[],d=this.db.queryEdges({target:c,relation:"CALLS"});for(let f of d)o.push(f.source),i(f.source,l+1);let p=this.db.queryEdges({source:c,relation:"CALLS"});for(let f of p)s.push(f.target),i(f.target,l+1);r.set(c,{callers:o,callees:s});};return i(e,0),r}queryInheritance(e){v.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let t=[],r=[],n=new Set,i=new Set,c=o=>{if(n.has(o))return;n.add(o);let s=this.db.queryEdges({source:o,relation:"EXTENDS"}),d=this.db.queryEdges({source:o,relation:"IMPLEMENTS"});for(let p of [...s,...d]){let f=this.db.getNodeById(p.target);f&&(t.push(f),c(p.target));}},l=o=>{if(i.has(o))return;i.add(o);let s=this.db.queryEdges({target:o,relation:"EXTENDS"}),d=this.db.queryEdges({target:o,relation:"IMPLEMENTS"});for(let p of [...s,...d]){let f=this.db.getNodeById(p.source);f&&(r.push(f),l(p.source));}};return c(e),l(e),{ancestors:t,descendants:r}}queryMembers(e,t){let r=t?Array.isArray(t)?t:[t]:["HAS_METHOD","HAS_PROPERTY"],n=[],i=new Set;for(let c of r){let l=this.db.queryEdges({source:e,relation:c});for(let o of l){if(i.has(o.target))continue;i.add(o.target);let s=this.db.getNodeById(o.target);s&&n.push(s);}}return n}queryOverrides(e){let t=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),r=[],n=new Set;for(let i of t){if(n.has(i.target))continue;n.add(i.target);let c=this.db.getNodeById(i.target);c&&r.push(c);}return r}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Wt(y){return new J(y)}var pe;(u=>{let y=utils.Log.create({service:"codebase-llm"}),e=null;function r(m){n()||(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 n(){return e!==null}u.isInitialized=n;function i(){e=null;}u._resetForTest=i;function c(){return e?{graphLlm:!!e.models.graphLlm,embeddingLlm:!!e.models.embeddingLlm}:{graphLlm:false,embeddingLlm:false}}u.capabilities=c;function l(){return e?.models.graphLlm}u.getGraphLlm=l;function o(){return e?.models.embeddingLlm}u.getEmbeddingLlm=o;async function s(m,h){if(!e||!e.models.graphLlm)return y.debug("Llm.generateText: graphLlm not configured, return empty string"),"";try{return (await ai.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=s;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 s(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 w=_,x=w.match(/```(?:json|JSON)?\s*([\s\S]*?)\s*```/);x&&(w=(x[1]??"").trim());let T=w.match(/\{[\s\S]*\}/);if(T)try{let I=JSON.parse(T[0]);return g(I)}catch{}for(let I of w.split(`
|
|
234
|
-
`)){let M=I.trim();if(M.startsWith("{"))try{let E=JSON.parse(M);return g(E)}catch{}}let N=w.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let I of N){let M=I;M.endsWith("%")&&(M=String(parseFloat(M)/100));let E=parseFloat(M);if(!Number.isNaN(E)&&E>=0&&E<=1)return {...h,score:E,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"):[]}}})(pe||(pe={}));var P=utils.Log.create({service:"codebase"}),Kt={database:{path:types.getDefaultDatabasePath(xdgBasedir.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:types.DEFAULT_SYNC_CONFIG},xe=class{constructor(e={}){chunkTS4OAYIJ_cjs.a(this,"config");chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"writeBackend",null);chunkTS4OAYIJ_cjs.a(this,"writeProxy",null);chunkTS4OAYIJ_cjs.a(this,"parserManager");chunkTS4OAYIJ_cjs.a(this,"indexer");chunkTS4OAYIJ_cjs.a(this,"queryInterface");chunkTS4OAYIJ_cjs.a(this,"initialized",false);chunkTS4OAYIJ_cjs.a(this,"dirty",false);chunkTS4OAYIJ_cjs.a(this,"syncTimer");chunkTS4OAYIJ_cjs.a(this,"syncingInProgress",false);chunkTS4OAYIJ_cjs.a(this,"codebasePackageVersion");chunkTS4OAYIJ_cjs.a(this,"fileWatcher",null);this.config={...Kt,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},pe.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n=this.resolveDbPath();chunk7XCIIOM6_cjs.d(Q__default.default.dirname(n)),this.db=new chunkRLZHDTHY_cjs.n(n),this.parserManager=new U,this.queryInterface=new J(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=Jt();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new oe({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new ae(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new K(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 chunkRLZHDTHY_cjs.e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new chunkRLZHDTHY_cjs.e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Q__default.default.isAbsolute(e)?e:Q__default.default.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,chunkRLZHDTHY_cjs.m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,chunkRLZHDTHY_cjs.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-LZZUEGMY.cjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,c=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=c;try{await c.start();}catch(p){throw this.fileWatcher=null,p}let l=null,o=new Set,s=()=>{l=null;let p=o.size;o.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(s,n);};return c.on((p,f)=>{P.debug("file change",{event:p,relPath:f}),o.add(f),d();}),i&&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:n}),{stop:async()=>{l&&(clearTimeout(l),l=null),await c.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 On(y){let e=new xe(y);return await e.initialize(),e}function Jt(){try{let e=Q__default.default.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b));for(let t=0;t<8;t++){let r=Q__default.default.join(e,"package.json");try{let i=JSON.parse(fs.readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=Q__default.default.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}exports.a=Ie;exports.b=U;exports.c=dt;exports.d=lt;exports.e=V;exports.f=St;exports.g=Y;exports.h=vt;exports.i=K;exports.j=kt;exports.k=De;exports.l=J;exports.m=Wt;exports.n=xe;exports.o=On;
|