@easbot/codebase 0.2.5 → 0.2.7
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/LICENSE +21 -21
- package/dist/chunks/log-KODK2DAN.cjs +1 -0
- package/dist/chunks/log-VXZJYFAH.mjs +1 -0
- package/dist/index.cjs +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +4 -4
- package/dist/chunks/log-BXSFPAB3.cjs +0 -1
- package/dist/chunks/log-JVQMUDSH.mjs +0 -1
- /package/dist/chunks/{chunk-UDQ4RD27.cjs → chunk-342WQCLU.cjs} +0 -0
- /package/dist/chunks/{chunk-T4X2DOE5.mjs → chunk-5H5FNWL2.mjs} +0 -0
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 houjallen
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 houjallen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk342WQCLU_cjs=require('./chunk-342WQCLU.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunk342WQCLU_cjs.c}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{c as Log}from'./chunk-5H5FNWL2.mjs';
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk342WQCLU_cjs=require('./chunks/chunk-342WQCLU.cjs'),z=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),ie=require('fs'),Ee=require('better-sqlite3'),utils=require('@easbot/utils'),url=require('url'),Ce=require('fs/promises'),crypto=require('crypto'),Re=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var z__default=/*#__PURE__*/_interopDefault(z);var ie__default=/*#__PURE__*/_interopDefault(ie);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var Re__default=/*#__PURE__*/_interopDefault(Re);var ne={".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 $=class y extends Error{constructor(t,r,n){super(t);chunk342WQCLU_cjs.a(this,"name","ParserError");chunk342WQCLU_cjs.a(this,"filePath");chunk342WQCLU_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},P=class y extends Error{constructor(t,r,n){super(t);chunk342WQCLU_cjs.a(this,"name","DatabaseError");chunk342WQCLU_cjs.a(this,"operation");chunk342WQCLU_cjs.a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},Q=class y extends Error{constructor(t,r,n){super(t);chunk342WQCLU_cjs.a(this,"name","FileSystemError");chunk342WQCLU_cjs.a(this,"filePath");chunk342WQCLU_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r){super(t);chunk342WQCLU_cjs.a(this,"name","SchemaError");chunk342WQCLU_cjs.a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},H=class y extends Error{constructor(t,r){super(t);chunk342WQCLU_cjs.a(this,"name","ConfigError");chunk342WQCLU_cjs.a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},V=class y extends Error{constructor(t,r,n){super(t);chunk342WQCLU_cjs.a(this,"name","IndexError");chunk342WQCLU_cjs.a(this,"filePath");chunk342WQCLU_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},B=class y extends Error{constructor(t,r,n){super(t);chunk342WQCLU_cjs.a(this,"name","QueryError");chunk342WQCLU_cjs.a(this,"params");chunk342WQCLU_cjs.a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Y=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);chunk342WQCLU_cjs.a(this,"name","UnsupportedLanguageError");chunk342WQCLU_cjs.a(this,"extension");chunk342WQCLU_cjs.a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=utils.Filesystem.normalize,T=chunk342WQCLU_cjs.c.create({service:"codebase-database"}),q=class{constructor(e){chunk342WQCLU_cjs.a(this,"db");chunk342WQCLU_cjs.a(this,"dbPath");chunk342WQCLU_cjs.a(this,"closed",false);chunk342WQCLU_cjs.a(this,"ftsAvailable",false);this.dbPath=w(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=z__default.default.dirname(this.dbPath);ie__default.default.existsSync(e)||ie__default.default.mkdirSync(e,{recursive:true});let t=new Ee__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
name TEXT NOT NULL,
|
|
@@ -103,6 +103,6 @@
|
|
|
103
103
|
`).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
104
104
|
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
105
105
|
VALUES (?, ?, ?)
|
|
106
|
-
`);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new P("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ae=
|
|
106
|
+
`);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new P("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ae=chunk342WQCLU_cjs.c.create({service:"codebase-parser"}),Ne={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"}};function Se(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&chunk342WQCLU_cjs.b?z__default.default.dirname(url.fileURLToPath(chunk342WQCLU_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function Te(y,e){let t=Se(),r=t;for(let n=0;n<10;n++){let s=z__default.default.join(r,"node_modules",y,e);if(utils.Filesystem.stat(s)!==void 0)return s;let i=z__default.default.dirname(r);if(i===r)break;r=i;}return z__default.default.join(t,"node_modules",y,e)}var O=class{constructor(){chunk342WQCLU_cjs.a(this,"parsers",new Map);chunk342WQCLU_cjs.a(this,"initialized",false);chunk342WQCLU_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"],s=await Promise.allSettled(n.map(async i=>{try{let o=Ne[i];if(!o)return ae.warn("No WASM config for language",{lang:i}),null;let a=Te(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return ae.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=z__default.default.extname(e).toLowerCase();return ne[t]??null}parse(e,t){if(!this.initialized)throw new $("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new $(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new $("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new Y(z__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;}},L=null;async function oe(){return L||(L=new O,await L.initialize()),L}function de(){L&&(L.dispose(),L=null);}var Ie={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},ve=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),M=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
|
|
107
107
|
`);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(ve.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);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 s=this.findNameInChildren(n,r);if(s)return s}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Ie))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
|
|
108
|
-
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function ce(){return new M}var A=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let F=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:F,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function le(){return new A}var D=class{constructor(e,t,r){chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"parserManager");chunkUDQ4RD27_cjs.a(this,"nodeExtractor");chunkUDQ4RD27_cjs.a(this,"edgeExtractor");chunkUDQ4RD27_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new M,this.edgeExtractor=new A,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new V("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),F=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Re__default.default(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=utils.Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Ce__default.default.readFile(e,"utf-8")}catch(t){throw new Q("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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ge(y,e,t){return new D(y,e,t)}var ue=utils.Filesystem.normalize,N=chunkUDQ4RD27_cjs.c.create({service:"codebase.query"}),k=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"embedding");chunkUDQ4RD27_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:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(ue(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(ue(i)))continue;let W=b.name.toLowerCase(),U=b.text.toLowerCase(),re=0;if(E.some(v=>W.includes(v))){let v=0;for(let j of E){let ee=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),X=W.match(ee);v+=X?X.length:0;}re=.8*Math.min(v/E.length,1);}let J=0;if(E.some(v=>U.includes(v))){let v=0;for(let X of E){let fe=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),se=U.match(fe);v+=se?se.length:0;}J=.5*Math.min(v/E.length,1);let j=U.indexOf(_),ee=j===-1?0:Math.max(0,1-j/U.length)*.2;J+=ee;}let Z=Math.max(re,J);Z>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:Z,source:"basic",hybridScore:Z});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let F=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&F.length>0){let h=F.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return F.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return F.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new B("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new B("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function pe(y){return new k(y)}var R=chunkUDQ4RD27_cjs.c.create({service:"codebase"}),ke={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},K=class{constructor(e={}){chunkUDQ4RD27_cjs.a(this,"config");chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"parserManager");chunkUDQ4RD27_cjs.a(this,"indexer");chunkUDQ4RD27_cjs.a(this,"queryInterface");chunkUDQ4RD27_cjs.a(this,"initialized",false);chunkUDQ4RD27_cjs.a(this,"dirty",false);chunkUDQ4RD27_cjs.a(this,"syncTimer");chunkUDQ4RD27_cjs.a(this,"syncingInProgress",false);this.config={...ke,...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},this.validateConfig();let n=this.resolveDbPath();this.db=new q(n),this.parserManager=new O;let s={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.indexer=new D(this.db,this.parserManager,s),this.queryInterface=new k(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunkUDQ4RD27_cjs.c.init({logDir:this.config.logDir||z__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>R.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,R.debug("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){R.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{R.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=>{R.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return z__default.default.isAbsolute(e)?e:z__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 R.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return R.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,R.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(y){let e=new K(y);return await e.initialize(),e}async function tr(y){let{Log:e}=await import('./chunks/log-BXSFPAB3.cjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}exports.CodeBase=K;exports.ConfigError=H;exports.DatabaseError=P;exports.DatabaseManager=q;exports.EdgeExtractor=A;exports.FILE_EXTENSION_MAP=ne;exports.FileSystemError=Q;exports.IndexError=V;exports.Indexer=D;exports.NodeExtractor=M;exports.ParserError=$;exports.ParserManager=O;exports.QueryError=B;exports.QueryInterface=k;exports.SchemaError=G;exports.UnsupportedLanguageError=Y;exports.createCodebase=$e;exports.createEdgeExtractor=le;exports.createIndexer=ge;exports.createNodeExtractor=ce;exports.createQueryInterface=pe;exports.getParserManager=oe;exports.initLog=tr;exports.resetParserManager=de;
|
|
108
|
+
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function ce(){return new M}var A=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let F=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:F,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function le(){return new A}var D=class{constructor(e,t,r){chunk342WQCLU_cjs.a(this,"db");chunk342WQCLU_cjs.a(this,"parserManager");chunk342WQCLU_cjs.a(this,"nodeExtractor");chunk342WQCLU_cjs.a(this,"edgeExtractor");chunk342WQCLU_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new M,this.edgeExtractor=new A,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new V("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),F=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Re__default.default(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=utils.Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Ce__default.default.readFile(e,"utf-8")}catch(t){throw new Q("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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ge(y,e,t){return new D(y,e,t)}var ue=utils.Filesystem.normalize,N=chunk342WQCLU_cjs.c.create({service:"codebase.query"}),k=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunk342WQCLU_cjs.a(this,"db");chunk342WQCLU_cjs.a(this,"embedding");chunk342WQCLU_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:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(ue(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(ue(i)))continue;let W=b.name.toLowerCase(),U=b.text.toLowerCase(),re=0;if(E.some(v=>W.includes(v))){let v=0;for(let j of E){let ee=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),X=W.match(ee);v+=X?X.length:0;}re=.8*Math.min(v/E.length,1);}let J=0;if(E.some(v=>U.includes(v))){let v=0;for(let X of E){let fe=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),se=U.match(fe);v+=se?se.length:0;}J=.5*Math.min(v/E.length,1);let j=U.indexOf(_),ee=j===-1?0:Math.max(0,1-j/U.length)*.2;J+=ee;}let Z=Math.max(re,J);Z>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:Z,source:"basic",hybridScore:Z});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let F=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&F.length>0){let h=F.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return F.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return F.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new B("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new B("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function pe(y){return new k(y)}var R=chunk342WQCLU_cjs.c.create({service:"codebase"}),ke={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},K=class{constructor(e={}){chunk342WQCLU_cjs.a(this,"config");chunk342WQCLU_cjs.a(this,"db");chunk342WQCLU_cjs.a(this,"parserManager");chunk342WQCLU_cjs.a(this,"indexer");chunk342WQCLU_cjs.a(this,"queryInterface");chunk342WQCLU_cjs.a(this,"initialized",false);chunk342WQCLU_cjs.a(this,"dirty",false);chunk342WQCLU_cjs.a(this,"syncTimer");chunk342WQCLU_cjs.a(this,"syncingInProgress",false);this.config={...ke,...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},this.validateConfig();let n=this.resolveDbPath();this.db=new q(n),this.parserManager=new O;let s={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.indexer=new D(this.db,this.parserManager,s),this.queryInterface=new k(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunk342WQCLU_cjs.c.init({logDir:this.config.logDir||z__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>R.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,R.debug("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){R.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{R.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=>{R.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return z__default.default.isAbsolute(e)?e:z__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 R.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return R.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,R.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(y){let e=new K(y);return await e.initialize(),e}async function tr(y){let{Log:e}=await import('./chunks/log-KODK2DAN.cjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}exports.CodeBase=K;exports.ConfigError=H;exports.DatabaseError=P;exports.DatabaseManager=q;exports.EdgeExtractor=A;exports.FILE_EXTENSION_MAP=ne;exports.FileSystemError=Q;exports.IndexError=V;exports.Indexer=D;exports.NodeExtractor=M;exports.ParserError=$;exports.ParserManager=O;exports.QueryError=B;exports.QueryInterface=k;exports.SchemaError=G;exports.UnsupportedLanguageError=Y;exports.createCodebase=$e;exports.createEdgeExtractor=le;exports.createIndexer=ge;exports.createNodeExtractor=ce;exports.createQueryInterface=pe;exports.getParserManager=oe;exports.initLog=tr;exports.resetParserManager=de;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {c,a,b}from'./chunks/chunk-
|
|
1
|
+
import {c,a,b}from'./chunks/chunk-5H5FNWL2.mjs';import H from'path';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import ae from'fs';import be from'better-sqlite3';import {Filesystem}from'@easbot/utils';import {fileURLToPath}from'url';import we from'fs/promises';import {createHash}from'crypto';import Fe from'fast-glob';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 q=class y extends Error{constructor(t,r,n){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},L=class y extends Error{constructor(t,r,n){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r,n){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},V=class y extends Error{constructor(t,r){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},B=class y extends Error{constructor(t,r){super(t);a(this,"name","ConfigError");a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Y=class y extends Error{constructor(t,r,n){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},U=class y extends Error{constructor(t,r,n){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},K=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var R=Filesystem.normalize,T=c.create({service:"codebase-database"}),z=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=R(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=H.dirname(this.dbPath);ae.existsSync(e)||ae.mkdirSync(e,{recursive:true});let t=new be(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
name TEXT NOT NULL,
|
|
@@ -105,4 +105,4 @@ import {c,a,b}from'./chunks/chunk-T4X2DOE5.mjs';import H from'path';import {xdgD
|
|
|
105
105
|
VALUES (?, ?, ?)
|
|
106
106
|
`);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new L("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var oe=c.create({service:"codebase-parser"}),Se={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"}};function Te(){return typeof import.meta<"u"&&import.meta.url?H.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function Ie(y,e){let t=Te(),r=t;for(let n=0;n<10;n++){let s=H.join(r,"node_modules",y,e);if(Filesystem.stat(s)!==void 0)return s;let i=H.dirname(r);if(i===r)break;r=i;}return H.join(t,"node_modules",y,e)}var M=class{constructor(){a(this,"parsers",new Map);a(this,"initialized",false);a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),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"],s=await Promise.allSettled(n.map(async i=>{try{let o=Se[i];if(!o)return oe.warn("No WASM config for language",{lang:i}),null;let a=Ie(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return oe.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=H.extname(e).toLowerCase();return ie[t]??null}parse(e,t){if(!this.initialized)throw new q("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new q(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new q("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new K(H.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;}},O=null;async function de(){return O||(O=new M,await O.initialize()),O}function ce(){O&&(O.dispose(),O=null);}var ve={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Ce=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),A=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
|
|
107
107
|
`);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(Ce.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);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 s=this.findNameInChildren(n,r);if(s)return s}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(ve))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
|
|
108
|
-
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function le(){return new A}var D=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let P=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:P,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function ge(){return new D}var k=class{constructor(e,t,r){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new A,this.edgeExtractor=new D,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Y("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),P=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Fe(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await we.readFile(e,"utf-8")}catch(t){throw new G("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ue(y,e,t){return new k(y,e,t)}var pe=Filesystem.normalize,N=c.create({service:"codebase.query"}),$=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(pe(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(pe(i)))continue;let W=b.name.toLowerCase(),j=b.text.toLowerCase(),se=0;if(E.some(v=>W.includes(v))){let v=0;for(let X of E){let te=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),Q=W.match(te);v+=Q?Q.length:0;}se=.8*Math.min(v/E.length,1);}let Z=0;if(E.some(v=>j.includes(v))){let v=0;for(let Q of E){let ye=new RegExp(Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),ne=j.match(ye);v+=ne?ne.length:0;}Z=.5*Math.min(v/E.length,1);let X=j.indexOf(_),te=X===-1?0:Math.max(0,1-X/j.length)*.2;Z+=te;}let ee=Math.max(se,Z);ee>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:ee,source:"basic",hybridScore:ee});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let P=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&P.length>0){let h=P.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return P.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return P.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new U("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new U("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function he(y){return new $(y)}var F=c.create({service:"codebase"}),$e={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},J=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);this.config={...$e,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new z(n),this.parserManager=new M;let s={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.indexer=new k(this.db,this.parserManager,s),this.queryInterface=new $(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await c.init({logDir:this.config.logDir||H.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>F.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,F.debug("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){F.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{F.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=>{F.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new B("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new B("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return H.isAbsolute(e)?e:H.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 F.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return F.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,F.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function qe(y){let e=new J(y);return await e.initialize(),e}async function rr(y){let{Log:e}=await import('./chunks/log-JVQMUDSH.mjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}export{J as CodeBase,B as ConfigError,L as DatabaseError,z as DatabaseManager,D as EdgeExtractor,ie as FILE_EXTENSION_MAP,G as FileSystemError,Y as IndexError,k as Indexer,A as NodeExtractor,q as ParserError,M as ParserManager,U as QueryError,$ as QueryInterface,V as SchemaError,K as UnsupportedLanguageError,qe as createCodebase,ge as createEdgeExtractor,ue as createIndexer,le as createNodeExtractor,he as createQueryInterface,de as getParserManager,rr as initLog,ce as resetParserManager};
|
|
108
|
+
`)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function le(){return new A}var D=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let P=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:P,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function ge(){return new D}var k=class{constructor(e,t,r){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new A,this.edgeExtractor=new D,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Y("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),P=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Fe(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await we.readFile(e,"utf-8")}catch(t){throw new G("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ue(y,e,t){return new k(y,e,t)}var pe=Filesystem.normalize,N=c.create({service:"codebase.query"}),$=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(pe(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(pe(i)))continue;let W=b.name.toLowerCase(),j=b.text.toLowerCase(),se=0;if(E.some(v=>W.includes(v))){let v=0;for(let X of E){let te=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),Q=W.match(te);v+=Q?Q.length:0;}se=.8*Math.min(v/E.length,1);}let Z=0;if(E.some(v=>j.includes(v))){let v=0;for(let Q of E){let ye=new RegExp(Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),ne=j.match(ye);v+=ne?ne.length:0;}Z=.5*Math.min(v/E.length,1);let X=j.indexOf(_),te=X===-1?0:Math.max(0,1-X/j.length)*.2;Z+=te;}let ee=Math.max(se,Z);ee>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:ee,source:"basic",hybridScore:ee});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let P=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&P.length>0){let h=P.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return P.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return P.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new U("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new U("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function he(y){return new $(y)}var F=c.create({service:"codebase"}),$e={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},J=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);this.config={...$e,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new z(n),this.parserManager=new M;let s={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.indexer=new k(this.db,this.parserManager,s),this.queryInterface=new $(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await c.init({logDir:this.config.logDir||H.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>F.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,F.debug("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){F.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{F.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=>{F.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new B("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new B("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return H.isAbsolute(e)?e:H.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 F.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return F.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,F.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function qe(y){let e=new J(y);return await e.initialize(),e}async function rr(y){let{Log:e}=await import('./chunks/log-VXZJYFAH.mjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}export{J as CodeBase,B as ConfigError,L as DatabaseError,z as DatabaseManager,D as EdgeExtractor,ie as FILE_EXTENSION_MAP,G as FileSystemError,Y as IndexError,k as Indexer,A as NodeExtractor,q as ParserError,M as ParserManager,U as QueryError,$ as QueryInterface,V as SchemaError,K as UnsupportedLanguageError,qe as createCodebase,ge as createEdgeExtractor,ue as createIndexer,le as createNodeExtractor,he as createQueryInterface,de as getParserManager,rr as initLog,ce as resetParserManager};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easbot/codebase",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
4
4
|
"description": "Code Knowledge Graph SDK for EASBot - Property Graph model for code indexing and querying with Tree-sitter parsing, FTS hybrid search, and incremental updates",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -69,9 +69,9 @@
|
|
|
69
69
|
"web-tree-sitter": "^0.26.8",
|
|
70
70
|
"xdg-basedir": "^5.1.0",
|
|
71
71
|
"zod": "^4.4.3",
|
|
72
|
-
"@easbot/local-model-sdk": "0.2.
|
|
73
|
-
"@easbot/
|
|
74
|
-
"@easbot/
|
|
72
|
+
"@easbot/local-model-sdk": "0.2.7",
|
|
73
|
+
"@easbot/utils": "0.2.7",
|
|
74
|
+
"@easbot/types": "0.2.7"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
77
|
"@biomejs/biome": "^2.4.14",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkUDQ4RD27_cjs=require('./chunk-UDQ4RD27.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunkUDQ4RD27_cjs.c}});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{c as Log}from'./chunk-T4X2DOE5.mjs';
|
|
File without changes
|
|
File without changes
|