@easbot/codebase 0.3.12 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/chunks/{chunk-Z4Y3VCYS.mjs → chunk-3LYXIQYD.mjs} +1 -1
  2. package/dist/chunks/{chunk-RLZHDTHY.cjs → chunk-4A5VTYP7.cjs} +2 -2
  3. package/dist/chunks/{chunk-4KHRTABC.cjs → chunk-7DCULBXU.cjs} +6 -6
  4. package/dist/chunks/{chunk-7PW7HWOC.cjs → chunk-ADKQ7Q5L.cjs} +1 -1
  5. package/dist/chunks/{chunk-RPRDGNXG.cjs → chunk-AWWGTQOD.cjs} +1 -1
  6. package/dist/chunks/{chunk-W25T3SKH.mjs → chunk-CH3THMQI.mjs} +2 -2
  7. package/dist/chunks/{chunk-XQID3NKI.mjs → chunk-CUMSGE6Z.mjs} +1 -1
  8. package/dist/chunks/{chunk-DMRAZKIP.cjs → chunk-F7PTGJKR.cjs} +19 -19
  9. package/dist/chunks/{chunk-U5G7MP3K.cjs → chunk-LDFLM2CU.cjs} +1 -1
  10. package/dist/chunks/{chunk-P566CDI2.mjs → chunk-TURKZSUP.mjs} +1 -1
  11. package/dist/chunks/{chunk-PLRTEGLZ.mjs → chunk-Z66TPGV5.mjs} +13 -13
  12. package/dist/chunks/{chunk-7ZBQQZOA.mjs → chunk-ZL7LUJKP.mjs} +1 -1
  13. package/dist/chunks/cli-handler-O4FJ3VNT.mjs +1 -0
  14. package/dist/chunks/cli-handler-VTJIOO3G.cjs +1 -0
  15. package/dist/chunks/{code-base-MC4K4ST4.mjs → code-base-EC3JAMYN.mjs} +1 -1
  16. package/dist/chunks/code-base-FF7YI5C7.cjs +1 -0
  17. package/dist/chunks/database-manager-AR4NY5FD.mjs +1 -0
  18. package/dist/chunks/database-manager-WBTGLHRS.cjs +1 -0
  19. package/dist/chunks/file-watcher-DAS74BJ6.cjs +1 -0
  20. package/dist/chunks/file-watcher-OUSHAYHW.mjs +1 -0
  21. package/dist/chunks/{interfaces-4KLR5CPG.cjs → interfaces-55GBUBWQ.cjs} +1 -1
  22. package/dist/chunks/{interfaces-KGAFAHKZ.mjs → interfaces-IKVZFMWU.mjs} +1 -1
  23. package/dist/chunks/{stdio-server-C7OYLX4I.mjs → stdio-server-6FUGUP2N.mjs} +1 -1
  24. package/dist/chunks/{stdio-server-UDX3QZNZ.cjs → stdio-server-P2JPIJI7.cjs} +6 -6
  25. package/dist/chunks/sync-E3JJBUOP.mjs +1 -0
  26. package/dist/chunks/sync-EB2UCUW3.cjs +1 -0
  27. package/dist/cli.cjs +1 -1
  28. package/dist/cli.mjs +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.mjs +1 -1
  31. package/package.json +6 -6
  32. package/dist/chunks/cli-handler-47R23IC3.cjs +0 -1
  33. package/dist/chunks/cli-handler-KSSK773Z.mjs +0 -1
  34. package/dist/chunks/code-base-HBPZXJQZ.cjs +0 -1
  35. package/dist/chunks/database-manager-DRLNOQ6C.cjs +0 -1
  36. package/dist/chunks/database-manager-WOYUSWKD.mjs +0 -1
  37. package/dist/chunks/file-watcher-EASGLNDX.mjs +0 -1
  38. package/dist/chunks/file-watcher-P3ACFOV5.cjs +0 -1
  39. package/dist/chunks/sync-6VAWF5IL.mjs +0 -1
  40. package/dist/chunks/sync-OSAGPUO2.cjs +0 -1
  41. /package/dist/chunks/{chunk-TS4OAYIJ.cjs → chunk-NL2AZBPZ.cjs} +0 -0
  42. /package/dist/chunks/{chunk-G3IYU6TZ.mjs → chunk-TFZFSTQF.mjs} +0 -0
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-G3IYU6TZ.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},g=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},u=class o extends Error{constructor(t,s){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.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}}},A=class o extends Error{constructor(t,s){super(t);a(this,"name","ConfigError");a(this,"field");this.field=s,Object.setPrototypeOf(this,o.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 o extends Error{constructor(t,s,r){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},x=class o extends Error{constructor(t,s,r){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var D=Log.create({service:"codebase-schema-migrations"}),p=1,V=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
1
+ import {a}from'./chunk-TFZFSTQF.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},g=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},u=class o extends Error{constructor(t,s){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.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}}},A=class o extends Error{constructor(t,s){super(t);a(this,"name","ConfigError");a(this,"field");this.field=s,Object.setPrototypeOf(this,o.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 o extends Error{constructor(t,s,r){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},x=class o extends Error{constructor(t,s,r){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var D=Log.create({service:"codebase-schema-migrations"}),p=1,V=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
2
2
  id TEXT PRIMARY KEY,
3
3
  name TEXT NOT NULL,
4
4
  ast_type TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ParserError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},g=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","DatabaseError");chunkTS4OAYIJ_cjs.a(this,"operation");chunkTS4OAYIJ_cjs.a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},M=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","FileSystemError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},u=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","SchemaError");chunkTS4OAYIJ_cjs.a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.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}}},A=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ConfigError");chunkTS4OAYIJ_cjs.a(this,"field");this.field=s,Object.setPrototypeOf(this,o.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 o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","IndexError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},x=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","QueryError");chunkTS4OAYIJ_cjs.a(this,"params");chunkTS4OAYIJ_cjs.a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);chunkTS4OAYIJ_cjs.a(this,"name","UnsupportedLanguageError");chunkTS4OAYIJ_cjs.a(this,"extension");chunkTS4OAYIJ_cjs.a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
1
+ 'use strict';var chunkNL2AZBPZ_cjs=require('./chunk-NL2AZBPZ.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkNL2AZBPZ_cjs.a(this,"name","ParserError");chunkNL2AZBPZ_cjs.a(this,"filePath");chunkNL2AZBPZ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},g=class o extends Error{constructor(t,s,r){super(t);chunkNL2AZBPZ_cjs.a(this,"name","DatabaseError");chunkNL2AZBPZ_cjs.a(this,"operation");chunkNL2AZBPZ_cjs.a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},M=class o extends Error{constructor(t,s,r){super(t);chunkNL2AZBPZ_cjs.a(this,"name","FileSystemError");chunkNL2AZBPZ_cjs.a(this,"filePath");chunkNL2AZBPZ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},u=class o extends Error{constructor(t,s){super(t);chunkNL2AZBPZ_cjs.a(this,"name","SchemaError");chunkNL2AZBPZ_cjs.a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.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}}},A=class o extends Error{constructor(t,s){super(t);chunkNL2AZBPZ_cjs.a(this,"name","ConfigError");chunkNL2AZBPZ_cjs.a(this,"field");this.field=s,Object.setPrototypeOf(this,o.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 o extends Error{constructor(t,s,r){super(t);chunkNL2AZBPZ_cjs.a(this,"name","IndexError");chunkNL2AZBPZ_cjs.a(this,"filePath");chunkNL2AZBPZ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.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}}},x=class o extends Error{constructor(t,s,r){super(t);chunkNL2AZBPZ_cjs.a(this,"name","QueryError");chunkNL2AZBPZ_cjs.a(this,"params");chunkNL2AZBPZ_cjs.a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);chunkNL2AZBPZ_cjs.a(this,"name","UnsupportedLanguageError");chunkNL2AZBPZ_cjs.a(this,"extension");chunkNL2AZBPZ_cjs.a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
2
2
  id TEXT PRIMARY KEY,
3
3
  name TEXT NOT NULL,
4
4
  ast_type TEXT NOT NULL,
@@ -67,7 +67,7 @@
67
67
  )`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function D(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
68
68
  id INTEGER PRIMARY KEY,
69
69
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
70
- )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"dbPath");chunkTS4OAYIJ_cjs.a(this,"closed",false);chunkTS4OAYIJ_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkNL2AZBPZ_cjs.a(this,"db");chunkNL2AZBPZ_cjs.a(this,"dbPath");chunkNL2AZBPZ_cjs.a(this,"closed",false);chunkNL2AZBPZ_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
71
71
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
72
72
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
73
  `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),Q=require('path'),fs=require('fs'),url=require('url'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),utils=require('@easbot/utils'),worker_threads=require('worker_threads'),module$1=require('module'),$e=require('fs/promises'),crypto=require('crypto'),ai=require('ai');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Q__default=/*#__PURE__*/_interopDefault(Q);var $e__default=/*#__PURE__*/_interopDefault($e);var ke={".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 se=utils.Filesystem.toUnixPath,Ke=`
1
+ 'use strict';var chunk4A5VTYP7_cjs=require('./chunk-4A5VTYP7.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkNL2AZBPZ_cjs=require('./chunk-NL2AZBPZ.cjs'),Q=require('path'),fs=require('fs'),url=require('url'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),utils=require('@easbot/utils'),worker_threads=require('worker_threads'),module$1=require('module'),$e=require('fs/promises'),crypto=require('crypto'),ai=require('ai');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Q__default=/*#__PURE__*/_interopDefault(Q);var $e__default=/*#__PURE__*/_interopDefault($e);var ke={".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 se=utils.Filesystem.toUnixPath,Ke=`
2
2
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4
4
  `,Je=`
@@ -13,7 +13,7 @@
13
13
  `,rt=`
14
14
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
15
15
  VALUES (?, ?, ?)
16
- `;var nt="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",it="DELETE FROM nodes WHERE file_path = ?";var at="DELETE FROM file_hashes WHERE file_path = ?",$="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",st="DELETE FROM meta WHERE key = ?",oe=class{constructor(e,t,r={}){chunkTS4OAYIJ_cjs.a(this,"db",e);chunkTS4OAYIJ_cjs.a(this,"writeBackend",t);chunkTS4OAYIJ_cjs.a(this,"options",r);}insertNodes(e){if(e.length===0)return;let t=[];for(let r of e){let n=r.file_path.replace(/\\/g,"/");t.push({sql:Ke,params:[r.id,r.name,r.ast_type,r.language,n,r.start_line,r.start_col,r.end_line,r.end_col,r.text,r.created_at]}),this.options.ftsAvailable&&(t.push({sql:Xe,params:[r.id]}),t.push({sql:Ze,params:[r.id,r.name,r.ast_type,r.language,n,r.text]}));}this.writeBackend.enqueue(t);}insertEdges(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:Je,params:[r.id,r.source,r.target,r.relation,r.created_at]});this.writeBackend.enqueue(t);}setFileHash(e,t){this.writeBackend.enqueue([{sql:et,params:[se(e),t,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,t){this.writeBackend.enqueue([{sql:tt,params:[e,Buffer.from(t.buffer,t.byteOffset,t.byteLength)]}]);}storeNodeEmbeddings(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:rt,params:[r.nodeId,r.embeddingText,Buffer.from(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength)]});this.writeBackend.enqueue(t);}deleteEdgesByFile(e){let t=se(e);return this.writeBackend.enqueue([{sql:nt,params:[t,t]}]),-1}deleteNodesByFile(e){let t=se(e);return this.writeBackend.enqueue([{sql:it,params:[t]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:at,params:[se(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,t){this.writeBackend.enqueue([{sql:$,params:[e,t]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:st,params:[e]}]);}markIndexed(e,t,r){let n=[{sql:$,params:["indexed_with_version",e]},{sql:$,params:["indexed_with_extraction_version",String(t)]},{sql:$,params:["index_state","complete"]},{sql:$,params:["last_index_state_change",r]}];this.writeBackend.enqueue(n);}setIndexState(e){let t=new Date().toISOString(),r=[{sql:$,params:["index_state",e]},{sql:$,params:["last_index_state_change",t]}];this.writeBackend.enqueue(r);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function ot(){return `
16
+ `;var nt="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",it="DELETE FROM nodes WHERE file_path = ?";var at="DELETE FROM file_hashes WHERE file_path = ?",$="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",st="DELETE FROM meta WHERE key = ?",oe=class{constructor(e,t,r={}){chunkNL2AZBPZ_cjs.a(this,"db",e);chunkNL2AZBPZ_cjs.a(this,"writeBackend",t);chunkNL2AZBPZ_cjs.a(this,"options",r);}insertNodes(e){if(e.length===0)return;let t=[];for(let r of e){let n=r.file_path.replace(/\\/g,"/");t.push({sql:Ke,params:[r.id,r.name,r.ast_type,r.language,n,r.start_line,r.start_col,r.end_line,r.end_col,r.text,r.created_at]}),this.options.ftsAvailable&&(t.push({sql:Xe,params:[r.id]}),t.push({sql:Ze,params:[r.id,r.name,r.ast_type,r.language,n,r.text]}));}this.writeBackend.enqueue(t);}insertEdges(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:Je,params:[r.id,r.source,r.target,r.relation,r.created_at]});this.writeBackend.enqueue(t);}setFileHash(e,t){this.writeBackend.enqueue([{sql:et,params:[se(e),t,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,t){this.writeBackend.enqueue([{sql:tt,params:[e,Buffer.from(t.buffer,t.byteOffset,t.byteLength)]}]);}storeNodeEmbeddings(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:rt,params:[r.nodeId,r.embeddingText,Buffer.from(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength)]});this.writeBackend.enqueue(t);}deleteEdgesByFile(e){let t=se(e);return this.writeBackend.enqueue([{sql:nt,params:[t,t]}]),-1}deleteNodesByFile(e){let t=se(e);return this.writeBackend.enqueue([{sql:it,params:[t]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:at,params:[se(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,t){this.writeBackend.enqueue([{sql:$,params:[e,t]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:st,params:[e]}]);}markIndexed(e,t,r){let n=[{sql:$,params:["indexed_with_version",e]},{sql:$,params:["indexed_with_extraction_version",String(t)]},{sql:$,params:["index_state","complete"]},{sql:$,params:["last_index_state_change",r]}];this.writeBackend.enqueue(n);}setIndexState(e){let t=new Date().toISOString(),r=[{sql:$,params:["index_state",e]},{sql:$,params:["last_index_state_change",t]}];this.writeBackend.enqueue(r);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function ot(){return `
17
17
  const { parentPort } = require('node:worker_threads');
18
18
 
19
19
  if (parentPort !== null) {
@@ -178,10 +178,10 @@ if (parentPort !== null) {
178
178
 
179
179
  port.postMessage({ type: 'ready' });
180
180
  }
181
- `}function xe(f,e){return new worker_threads.Worker(ct(e.betterSqlite3Path),{eval:true})}var de=utils.Log.create({service:"codebase.better-sqlite3-resolver"}),qe=module$1.createRequire(chunkTS4OAYIJ_cjs.b);async function Ae(f={}){try{let s=qe.resolve("better-sqlite3");if(s)return de.debug("better-sqlite3 resolved from monorepo",{resolved:s}),{absolutePath:utils.Filesystem.normalize(s),source:"monorepo"}}catch(s){de.debug("better-sqlite3 not in current resolve paths",{error:s instanceof Error?s.message:String(s)});}let e=process.env.EASBOT_CACHE_PATH,t=f.installPath??e??`${process.cwd()}/.easbot/cache`,r=utils.Filesystem.normalize(t),n=f.version??"latest";de.info("better-sqlite3 not found locally, installing to cache",{installPath:r,version:n,envCache:e});let i;try{i=await utils.Shell.install("better-sqlite3",n,r);}catch(s){throw new le(`Failed to install better-sqlite3@${n} into ${r}: ${s instanceof Error?s.message:String(s)}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,r)}try{let s=qe.resolve("better-sqlite3",{paths:[i]}),l=utils.Filesystem.normalize(s),c=r===utils.Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return de.info("better-sqlite3 installed and resolved",{resolved:l,installPath:r}),{absolutePath:l,source:c}}catch(s){throw new le(`Installed better-sqlite3 to ${i} but cannot resolve entry from there: ${s instanceof Error?s.message:String(s)}`,i)}}var le=class extends Error{constructor(t,r){super(t);chunkTS4OAYIJ_cjs.a(this,"installPath");this.name="BetterSqlite3ResolveError",this.installPath=r;}};var ee=utils.Log.create({service:"database.async-write"}),Te,Z,pe=class{constructor(e){chunkTS4OAYIJ_cjs.a(this,"worker");chunkTS4OAYIJ_cjs.a(this,"mock");chunkTS4OAYIJ_cjs.a(this,"dbPath");chunkTS4OAYIJ_cjs.a(this,"batchSize");chunkTS4OAYIJ_cjs.a(this,"batchIntervalMs");chunkTS4OAYIJ_cjs.a(this,"queueMax");chunkTS4OAYIJ_cjs.a(this,"bufferedStatements",[]);chunkTS4OAYIJ_cjs.a(this,"pendingRequests",new Map);chunkTS4OAYIJ_cjs.a(this,"nextRequestId",1);chunkTS4OAYIJ_cjs.a(this,"flushTimer",null);chunkTS4OAYIJ_cjs.a(this,"ready");chunkTS4OAYIJ_cjs.a(this,"disposed",false);if(this.dbPath=e.dbPath,this.mock=e.mock??false,this.batchSize=e.batchSize??100,this.batchIntervalMs=e.batchIntervalMs??50,this.queueMax=e.queueMax??1e3,this.mock)this.worker=Fe(),this.ready=this.waitForReady();else {let t=e.betterSqlite3Path;t?(this.worker=xe(this.dbPath,{betterSqlite3Path:t}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await mt();this.worker=xe(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",t=>{let r=t;if(r.type==="debug_error"){ee.error("AsyncWriteBackend statement failed (debug)",{sql:r.sql?.slice(0,200),paramsCount:r.paramsCount,params:r.paramsJson,error:r.error});return}if(typeof r.requestId!="number"||r.requestId<1)return;let n=this.pendingRequests.get(r.requestId);n&&(this.pendingRequests.delete(r.requestId),clearTimeout(n.timer),r.type==="write_batch_ack"?n.resolve():r.type==="error"&&n.reject(new Error(r.error??"worker write error")));});}requireWorker(){if(!this.worker)throw new Error("AsyncWriteBackend worker not initialized yet (call installAckHandler / waitForReady only after spawn)");return this.worker}waitForReady(){let e=this.requireWorker();return new Promise((t,r)=>{let n=setTimeout(()=>r(new Error("worker init timeout")),1e4),i=s=>{if(s.type==="ready"){clearTimeout(n),e.off("message",i);let l=setTimeout(()=>r(new Error("worker open timeout")),1e4),c=o=>{o.type==="open_ack"&&o.requestId===0?(clearTimeout(l),e.off("message",c),t()):o.type==="error"&&o.requestId===0&&(clearTimeout(l),e.off("message",c),r(new Error(o.error??"worker open error")));};e.on("message",c),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else s.type==="error"&&s.requestId===-1&&(clearTimeout(n),e.off("message",i),r(new Error(s.error??"unknown init error")));};e.on("message",i);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new Error("AsyncWriteBackend \u5DF2 dispose");if(!this.worker)throw new Error("AsyncWriteBackend worker not ready yet (await backend.ready before enqueue)");let t=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+t>=this.queueMax)throw new Error(`AsyncWriteBackend queue overflow (pending=${this.pendingRequests.size}, buffered=${this.bufferedStatements.length}, max=${this.queueMax})`);this.bufferedStatements.push(...e),this.bufferedStatements.length>=this.batchSize?this.flushBuffer():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flushBuffer(),this.batchIntervalMs));}flushBuffer(){if(!this.worker||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.bufferedStatements.length===0))return;let e=this.bufferedStatements;this.bufferedStatements=[];let t=this.nextRequestId++,r={resolve:()=>{},reject:n=>{ee.error("AsyncWriteBackend write failed",{error:n.message,requestId:t});},timer:setTimeout(()=>{this.pendingRequests.delete(t),r.reject(new Error(`AsyncWriteBackend write timeout (${t})`));},3e4)};this.pendingRequests.set(t,r),this.worker.postMessage({type:"write_batch",statements:e,requestId:t});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT??"3600000",10)||36e5){if(this.flushBuffer(),this.pendingRequests.size===0)return;let t=this.pendingRequests.size,r=Date.now();await new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),l=setInterval(()=>{let o=this.pendingRequests.size,d=Math.floor((Date.now()-r)/1e3);o>0&&d>0&&d%5===0&&ee.info("flush in progress",{pending:o,initial:t,elapsedSec:d});},1e3),c=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(s),clearInterval(c),clearInterval(l),n());},5);});}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){ee.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:e instanceof Error?e.message:String(e)});}this.worker&&(this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate());}pendingCount(){return this.pendingRequests.size}};async function mt(){return Te||(Z||(Z=Ae().then(f=>(Te=f.absolutePath,Z=void 0,ee.info("better-sqlite3 resolved for AsyncWriteBackend",{path:f.absolutePath,source:f.source}),f.absolutePath)).catch(f=>{throw Z=void 0,f})),Z)}var Oe=utils.Log.create({service:"codebase-parser"}),ht={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"},zig:{package:"@tree-sitter-grammars/tree-sitter-zig",wasmFile:"tree-sitter-zig.wasm"}};function _t(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-4KHRTABC.cjs', document.baseURI).href)) })<"u"&&chunkTS4OAYIJ_cjs.b?Q__default.default.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function bt(f,e){let t=_t(),r=t;for(let n=0;n<10;n++){let i=Q__default.default.join(r,"node_modules",f,e);if(utils.Filesystem.stat(i)!==void 0)return i;let s=Q__default.default.dirname(r);if(s===r)break;r=s;}return Q__default.default.join(t,"node_modules",f,e)}var U=class{constructor(){chunkTS4OAYIJ_cjs.a(this,"parsers",new Map);chunkTS4OAYIJ_cjs.a(this,"initialized",false);chunkTS4OAYIJ_cjs.a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],i=await Promise.allSettled(n.map(async s=>{try{let l=ht[s];if(!l)return Oe.warn("No WASM config for language",{lang:s}),null;let c=bt(l.package,l.wasmFile),o=await r.load(c),d=new t;return d.setLanguage(o),{lang:s,parser:d,language:o}}catch(l){return Oe.warn("Failed to load parser",{lang:s,error:String(l)}),null}}));for(let s of i)if(s.status==="fulfilled"&&s.value){let{lang:l,parser:c,language:o}=s.value;this.parsers.set(l,{parser:c,language:o});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=Q__default.default.extname(e).toLowerCase();return ke[t]??null}parse(e,t){if(!this.initialized)throw new chunkRLZHDTHY_cjs.a("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new chunkRLZHDTHY_cjs.a(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new chunkRLZHDTHY_cjs.a("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new chunkRLZHDTHY_cjs.h(Q__default.default.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},j=null;async function xt(){return j||(j=new U,await j.initialize()),j}function Tt(){j&&(j.dispose(),j=null);}var F={class_declaration:"class_declaration",class_item:"class_declaration",class_definition:"class_declaration",abstract_class_declaration:"class_declaration",class_specifier:"class_declaration",record_declaration:"class_declaration",interface_declaration:"interface_declaration",protocol_declaration:"interface_declaration",function_declaration:"function_definition",function_definition:"function_definition",function_item:"function_definition",function_expression:"function_definition",arrow_function:"function_definition",method_definition:"method_definition",method_declaration:"method_definition",method:"method_definition",method_invocation:"method_definition",public_field_definition:"property_declaration",field_definition:"property_declaration",property_signature:"property_declaration",field_declaration:"field_declaration",property_declaration:"property_declaration",val_definition:"property_declaration",var_definition:"property_declaration",variable_declaration:"variable_declaration",lexical_declaration:"variable_declaration",variable_declarator:"variable_declaration",assignment:"variable_declaration",module:"module_declaration",internal_module:"module_declaration",ambient_declaration:"module_declaration",namespace_declaration:"module_declaration",namespace_definition:"module_declaration",mod_item:"module_declaration",import_declaration:"import_declaration",import_statement:"import_declaration",import_from_statement:"import_declaration",use_declaration:"import_declaration",use_list:"import_declaration",using_directive:"import_declaration",require:"import_declaration",require_relative:"import_declaration",preproc_include:"import_declaration",include_directive:"import_declaration",struct_declaration:"struct_declaration",struct_definition:"struct_declaration",struct_item:"struct_declaration",struct_specifier:"struct_declaration",trait_item:"trait_declaration",trait_definition:"trait_declaration",impl_item:"impl_item",enum_declaration:"enum_declaration",enum_item:"enum_declaration",enum_specifier:"enum_declaration",type_alias_declaration:"type_alias_declaration",type_declaration:"type_declaration",class:"class_declaration",decorator:"decorator",annotation:"annotation",marker_annotation:"annotation",attribute:"attribute",attribute_item:"attribute",modifiers:"modifiers",decorated_expression:"decorator",attribute_decorator:"decorator",export_statement:"export_statement",const_item:"constant_declaration",constant_declaration:"constant_declaration",function:"function_definition"},we={language:"ts",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["module","internal_module","ambient_declaration"],methodTypes:["method_definition","function_declaration"],propertyTypes:["public_field_definition","property_signature"],functionTypes:["function_declaration"],typeAliasTypes:["type_alias_declaration"],enumTypes:["enum_declaration"],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:["export_statement"],ambientDeclarationTypes:["ambient_declaration"]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","extends_type_clause"],implementsClauseTypes:["implements_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","abstract_class_declaration","function_declaration","method_definition","export_statement"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},wt={...we,language:"tsx"},Et={language:"js",rawTypes:{classTypes:["class_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_definition"],propertyTypes:["public_field_definition","field_definition"],functionTypes:["function_declaration","function_expression","arrow_function"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},St={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["argument_list","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["function_definition","class_definition","decorated_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["identifier","typed_parameter","default_parameter","list_splat_pattern","dictionary_splat_pattern"],typeInWrapper:["type","identifier"],declaratorStyle:"wrapper"}},Nt={language:"java",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["import_declaration"],annotationTypes:["annotation","marker_annotation","modifiers"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass","extends_clause"],implementsClauseTypes:["super_interfaces","implements_clause","interface_list"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration","interface_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["formal_parameter"],typeInWrapper:["type_identifier","generic_type","array_type","integral_type","floating_point_type","boolean_type"],declaratorStyle:"wrapper"}},vt={language:"csharp",rawTypes:{classTypes:["class_declaration","record_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration","property_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["using_directive"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_list","super"],implementsClauseTypes:["base_list"],fallbackToFirstIdentifier:true,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["parameter"],typeInWrapper:["predefined_type","identifier","generic_name","array_type","nullable_type"],declaratorStyle:"wrapper"}},It={language:"c",rawTypes:{classTypes:["struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","union_specifier","enum_specifier"],declaratorStyle:"declarator"}},Pt={language:"cpp",rawTypes:{classTypes:["class_specifier","struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_class_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_specifier","function_definition"]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","class_specifier","enum_specifier","scoped_identifier","template_type","auto"],declaratorStyle:"declarator"}},Ct={language:"rs",rawTypes:{classTypes:["struct_item","enum_item","impl_item"],interfaceTypes:["trait_item"],moduleTypes:["mod_item"],methodTypes:["function_item"],propertyTypes:["field_declaration"],functionTypes:["function_item"],typeAliasTypes:["type_declaration"],enumTypes:["enum_item"],importTypes:["use_declaration"],annotationTypes:["attribute_item"],variableTypes:["const_item"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_item","struct_item","trait_item"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","reference_type","slice_type","array_type","generic_type","scoped_identifier","pointer_type","unit_type","never_type"],declaratorStyle:"wrapper"}},Lt={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],annotationTypes:[],variableTypes:[],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","variadic_parameter"],typeInWrapper:["type_identifier","pointer_type","slice_type","map_type","channel_type","array_type","function_type","qualified_type","generic_type"],declaratorStyle:"wrapper"}},Rt={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],annotationTypes:[],variableTypes:["assignment"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"method_parameters",paramTypes:["identifier","required_parameter","optional_parameter","splat_parameter","hash_splat_parameter","block_parameter","keyword_rest_parameter"],typeInWrapper:[],declaratorStyle:"wrapper"}},kt={language:"php",rawTypes:{classTypes:["class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["namespace_definition"],methodTypes:["method_declaration"],propertyTypes:["property_declaration"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["namespace_use_declaration"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_clause"],implementsClauseTypes:["class_interface_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","method_declaration","function_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["simple_parameter","variadic_parameter","property_promotion_parameter"],typeInWrapper:["named_type","primitive_type","optional_type"],declaratorStyle:"wrapper"}},Mt={language:"scala",rawTypes:{classTypes:["class_definition"],interfaceTypes:["trait_definition"],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["val_definition","var_definition"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_declaration"],annotationTypes:["annotation"],variableTypes:["val_definition","var_definition"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause"],implementsClauseTypes:["with_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_definition","class_definition","trait_definition"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","generic_type","scoped_type_identifier","function_type","tuple_type","refined_type"],declaratorStyle:"wrapper"}},Ft={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["identifier","optional_type","array_type","pointer_type","slice_type"],declaratorStyle:"wrapper"}},De=new Map([["ts",we],["tsx",wt],["js",Et],["py",St],["java",Nt],["csharp",vt],["c",It],["cpp",Pt],["rs",Ct],["go",Lt],["php",kt],["scala",Mt],["zig",Ft],["ruby",Rt]]);function q(f){return De.get(f)??we}Array.from(De.keys());function We(f){let e=q(f),t=new Set;for(let r of [e.rawTypes.classTypes,e.rawTypes.interfaceTypes,e.rawTypes.moduleTypes,e.rawTypes.methodTypes,e.rawTypes.propertyTypes,e.rawTypes.functionTypes,e.rawTypes.typeAliasTypes,e.rawTypes.enumTypes,e.rawTypes.importTypes,e.rawTypes.annotationTypes,e.rawTypes.variableTypes,e.rawTypes.exportTypes,e.rawTypes.ambientDeclarationTypes])for(let n of r)t.add(n);return t}function ze(f){let e=q(f),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(r);for(let r of e.rawTypes.propertyTypes)t.add(r);return t}function L(f,e){return q(f).normalizeMap[e]??e}var V=class{extractNodes(e,t,r,n){let i=[],s=t.split(`
181
+ `}function xe(f,e){return new worker_threads.Worker(ct(e.betterSqlite3Path),{eval:true})}var de=utils.Log.create({service:"codebase.better-sqlite3-resolver"}),qe=module$1.createRequire(chunkNL2AZBPZ_cjs.b);async function Ae(f={}){try{let s=qe.resolve("better-sqlite3");if(s)return de.debug("better-sqlite3 resolved from monorepo",{resolved:s}),{absolutePath:utils.Filesystem.normalize(s),source:"monorepo"}}catch(s){de.debug("better-sqlite3 not in current resolve paths",{error:s instanceof Error?s.message:String(s)});}let e=process.env.EASBOT_CACHE_PATH,t=f.installPath??e??`${process.cwd()}/.easbot/cache`,r=utils.Filesystem.normalize(t),n=f.version??"latest";de.info("better-sqlite3 not found locally, installing to cache",{installPath:r,version:n,envCache:e});let i;try{i=await utils.Shell.install("better-sqlite3",n,r);}catch(s){throw new le(`Failed to install better-sqlite3@${n} into ${r}: ${s instanceof Error?s.message:String(s)}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,r)}try{let s=qe.resolve("better-sqlite3",{paths:[i]}),l=utils.Filesystem.normalize(s),c=r===utils.Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return de.info("better-sqlite3 installed and resolved",{resolved:l,installPath:r}),{absolutePath:l,source:c}}catch(s){throw new le(`Installed better-sqlite3 to ${i} but cannot resolve entry from there: ${s instanceof Error?s.message:String(s)}`,i)}}var le=class extends Error{constructor(t,r){super(t);chunkNL2AZBPZ_cjs.a(this,"installPath");this.name="BetterSqlite3ResolveError",this.installPath=r;}};var ee=utils.Log.create({service:"database.async-write"}),Te,Z,pe=class{constructor(e){chunkNL2AZBPZ_cjs.a(this,"worker");chunkNL2AZBPZ_cjs.a(this,"mock");chunkNL2AZBPZ_cjs.a(this,"dbPath");chunkNL2AZBPZ_cjs.a(this,"batchSize");chunkNL2AZBPZ_cjs.a(this,"batchIntervalMs");chunkNL2AZBPZ_cjs.a(this,"queueMax");chunkNL2AZBPZ_cjs.a(this,"bufferedStatements",[]);chunkNL2AZBPZ_cjs.a(this,"pendingRequests",new Map);chunkNL2AZBPZ_cjs.a(this,"nextRequestId",1);chunkNL2AZBPZ_cjs.a(this,"flushTimer",null);chunkNL2AZBPZ_cjs.a(this,"ready");chunkNL2AZBPZ_cjs.a(this,"disposed",false);if(this.dbPath=e.dbPath,this.mock=e.mock??false,this.batchSize=e.batchSize??100,this.batchIntervalMs=e.batchIntervalMs??50,this.queueMax=e.queueMax??1e3,this.mock)this.worker=Fe(),this.ready=this.waitForReady();else {let t=e.betterSqlite3Path;t?(this.worker=xe(this.dbPath,{betterSqlite3Path:t}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await mt();this.worker=xe(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",t=>{let r=t;if(r.type==="debug_error"){ee.error("AsyncWriteBackend statement failed (debug)",{sql:r.sql?.slice(0,200),paramsCount:r.paramsCount,params:r.paramsJson,error:r.error});return}if(typeof r.requestId!="number"||r.requestId<1)return;let n=this.pendingRequests.get(r.requestId);n&&(this.pendingRequests.delete(r.requestId),clearTimeout(n.timer),r.type==="write_batch_ack"?n.resolve():r.type==="error"&&n.reject(new Error(r.error??"worker write error")));});}requireWorker(){if(!this.worker)throw new Error("AsyncWriteBackend worker not initialized yet (call installAckHandler / waitForReady only after spawn)");return this.worker}waitForReady(){let e=this.requireWorker();return new Promise((t,r)=>{let n=setTimeout(()=>r(new Error("worker init timeout")),1e4),i=s=>{if(s.type==="ready"){clearTimeout(n),e.off("message",i);let l=setTimeout(()=>r(new Error("worker open timeout")),1e4),c=o=>{o.type==="open_ack"&&o.requestId===0?(clearTimeout(l),e.off("message",c),t()):o.type==="error"&&o.requestId===0&&(clearTimeout(l),e.off("message",c),r(new Error(o.error??"worker open error")));};e.on("message",c),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else s.type==="error"&&s.requestId===-1&&(clearTimeout(n),e.off("message",i),r(new Error(s.error??"unknown init error")));};e.on("message",i);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new Error("AsyncWriteBackend \u5DF2 dispose");if(!this.worker)throw new Error("AsyncWriteBackend worker not ready yet (await backend.ready before enqueue)");let t=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+t>=this.queueMax)throw new Error(`AsyncWriteBackend queue overflow (pending=${this.pendingRequests.size}, buffered=${this.bufferedStatements.length}, max=${this.queueMax})`);this.bufferedStatements.push(...e),this.bufferedStatements.length>=this.batchSize?this.flushBuffer():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flushBuffer(),this.batchIntervalMs));}flushBuffer(){if(!this.worker||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.bufferedStatements.length===0))return;let e=this.bufferedStatements;this.bufferedStatements=[];let t=this.nextRequestId++,r={resolve:()=>{},reject:n=>{ee.error("AsyncWriteBackend write failed",{error:n.message,requestId:t});},timer:setTimeout(()=>{this.pendingRequests.delete(t),r.reject(new Error(`AsyncWriteBackend write timeout (${t})`));},3e4)};this.pendingRequests.set(t,r),this.worker.postMessage({type:"write_batch",statements:e,requestId:t});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT??"3600000",10)||36e5){if(this.flushBuffer(),this.pendingRequests.size===0)return;let t=this.pendingRequests.size,r=Date.now();await new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),l=setInterval(()=>{let o=this.pendingRequests.size,d=Math.floor((Date.now()-r)/1e3);o>0&&d>0&&d%5===0&&ee.info("flush in progress",{pending:o,initial:t,elapsedSec:d});},1e3),c=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(s),clearInterval(c),clearInterval(l),n());},5);});}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){ee.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:e instanceof Error?e.message:String(e)});}this.worker&&(this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate());}pendingCount(){return this.pendingRequests.size}};async function mt(){return Te||(Z||(Z=Ae().then(f=>(Te=f.absolutePath,Z=void 0,ee.info("better-sqlite3 resolved for AsyncWriteBackend",{path:f.absolutePath,source:f.source}),f.absolutePath)).catch(f=>{throw Z=void 0,f})),Z)}var Oe=utils.Log.create({service:"codebase-parser"}),ht={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"},zig:{package:"@tree-sitter-grammars/tree-sitter-zig",wasmFile:"tree-sitter-zig.wasm"}};function _t(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-7DCULBXU.cjs', document.baseURI).href)) })<"u"&&chunkNL2AZBPZ_cjs.b?Q__default.default.dirname(url.fileURLToPath(chunkNL2AZBPZ_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function bt(f,e){let t=_t(),r=t;for(let n=0;n<10;n++){let i=Q__default.default.join(r,"node_modules",f,e);if(utils.Filesystem.stat(i)!==void 0)return i;let s=Q__default.default.dirname(r);if(s===r)break;r=s;}return Q__default.default.join(t,"node_modules",f,e)}var U=class{constructor(){chunkNL2AZBPZ_cjs.a(this,"parsers",new Map);chunkNL2AZBPZ_cjs.a(this,"initialized",false);chunkNL2AZBPZ_cjs.a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],i=await Promise.allSettled(n.map(async s=>{try{let l=ht[s];if(!l)return Oe.warn("No WASM config for language",{lang:s}),null;let c=bt(l.package,l.wasmFile),o=await r.load(c),d=new t;return d.setLanguage(o),{lang:s,parser:d,language:o}}catch(l){return Oe.warn("Failed to load parser",{lang:s,error:String(l)}),null}}));for(let s of i)if(s.status==="fulfilled"&&s.value){let{lang:l,parser:c,language:o}=s.value;this.parsers.set(l,{parser:c,language:o});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=Q__default.default.extname(e).toLowerCase();return ke[t]??null}parse(e,t){if(!this.initialized)throw new chunk4A5VTYP7_cjs.a("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new chunk4A5VTYP7_cjs.a(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new chunk4A5VTYP7_cjs.a("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new chunk4A5VTYP7_cjs.h(Q__default.default.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},j=null;async function xt(){return j||(j=new U,await j.initialize()),j}function Tt(){j&&(j.dispose(),j=null);}var F={class_declaration:"class_declaration",class_item:"class_declaration",class_definition:"class_declaration",abstract_class_declaration:"class_declaration",class_specifier:"class_declaration",record_declaration:"class_declaration",interface_declaration:"interface_declaration",protocol_declaration:"interface_declaration",function_declaration:"function_definition",function_definition:"function_definition",function_item:"function_definition",function_expression:"function_definition",arrow_function:"function_definition",method_definition:"method_definition",method_declaration:"method_definition",method:"method_definition",method_invocation:"method_definition",public_field_definition:"property_declaration",field_definition:"property_declaration",property_signature:"property_declaration",field_declaration:"field_declaration",property_declaration:"property_declaration",val_definition:"property_declaration",var_definition:"property_declaration",variable_declaration:"variable_declaration",lexical_declaration:"variable_declaration",variable_declarator:"variable_declaration",assignment:"variable_declaration",module:"module_declaration",internal_module:"module_declaration",ambient_declaration:"module_declaration",namespace_declaration:"module_declaration",namespace_definition:"module_declaration",mod_item:"module_declaration",import_declaration:"import_declaration",import_statement:"import_declaration",import_from_statement:"import_declaration",use_declaration:"import_declaration",use_list:"import_declaration",using_directive:"import_declaration",require:"import_declaration",require_relative:"import_declaration",preproc_include:"import_declaration",include_directive:"import_declaration",struct_declaration:"struct_declaration",struct_definition:"struct_declaration",struct_item:"struct_declaration",struct_specifier:"struct_declaration",trait_item:"trait_declaration",trait_definition:"trait_declaration",impl_item:"impl_item",enum_declaration:"enum_declaration",enum_item:"enum_declaration",enum_specifier:"enum_declaration",type_alias_declaration:"type_alias_declaration",type_declaration:"type_declaration",class:"class_declaration",decorator:"decorator",annotation:"annotation",marker_annotation:"annotation",attribute:"attribute",attribute_item:"attribute",modifiers:"modifiers",decorated_expression:"decorator",attribute_decorator:"decorator",export_statement:"export_statement",const_item:"constant_declaration",constant_declaration:"constant_declaration",function:"function_definition"},we={language:"ts",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["module","internal_module","ambient_declaration"],methodTypes:["method_definition","function_declaration"],propertyTypes:["public_field_definition","property_signature"],functionTypes:["function_declaration"],typeAliasTypes:["type_alias_declaration"],enumTypes:["enum_declaration"],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:["export_statement"],ambientDeclarationTypes:["ambient_declaration"]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","extends_type_clause"],implementsClauseTypes:["implements_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","abstract_class_declaration","function_declaration","method_definition","export_statement"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},wt={...we,language:"tsx"},Et={language:"js",rawTypes:{classTypes:["class_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_definition"],propertyTypes:["public_field_definition","field_definition"],functionTypes:["function_declaration","function_expression","arrow_function"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},St={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["argument_list","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["function_definition","class_definition","decorated_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["identifier","typed_parameter","default_parameter","list_splat_pattern","dictionary_splat_pattern"],typeInWrapper:["type","identifier"],declaratorStyle:"wrapper"}},Nt={language:"java",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["import_declaration"],annotationTypes:["annotation","marker_annotation","modifiers"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass","extends_clause"],implementsClauseTypes:["super_interfaces","implements_clause","interface_list"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration","interface_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["formal_parameter"],typeInWrapper:["type_identifier","generic_type","array_type","integral_type","floating_point_type","boolean_type"],declaratorStyle:"wrapper"}},vt={language:"csharp",rawTypes:{classTypes:["class_declaration","record_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration","property_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["using_directive"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_list","super"],implementsClauseTypes:["base_list"],fallbackToFirstIdentifier:true,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["parameter"],typeInWrapper:["predefined_type","identifier","generic_name","array_type","nullable_type"],declaratorStyle:"wrapper"}},It={language:"c",rawTypes:{classTypes:["struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","union_specifier","enum_specifier"],declaratorStyle:"declarator"}},Pt={language:"cpp",rawTypes:{classTypes:["class_specifier","struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_class_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_specifier","function_definition"]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","class_specifier","enum_specifier","scoped_identifier","template_type","auto"],declaratorStyle:"declarator"}},Ct={language:"rs",rawTypes:{classTypes:["struct_item","enum_item","impl_item"],interfaceTypes:["trait_item"],moduleTypes:["mod_item"],methodTypes:["function_item"],propertyTypes:["field_declaration"],functionTypes:["function_item"],typeAliasTypes:["type_declaration"],enumTypes:["enum_item"],importTypes:["use_declaration"],annotationTypes:["attribute_item"],variableTypes:["const_item"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_item","struct_item","trait_item"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","reference_type","slice_type","array_type","generic_type","scoped_identifier","pointer_type","unit_type","never_type"],declaratorStyle:"wrapper"}},Lt={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],annotationTypes:[],variableTypes:[],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","variadic_parameter"],typeInWrapper:["type_identifier","pointer_type","slice_type","map_type","channel_type","array_type","function_type","qualified_type","generic_type"],declaratorStyle:"wrapper"}},Rt={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],annotationTypes:[],variableTypes:["assignment"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"method_parameters",paramTypes:["identifier","required_parameter","optional_parameter","splat_parameter","hash_splat_parameter","block_parameter","keyword_rest_parameter"],typeInWrapper:[],declaratorStyle:"wrapper"}},kt={language:"php",rawTypes:{classTypes:["class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["namespace_definition"],methodTypes:["method_declaration"],propertyTypes:["property_declaration"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["namespace_use_declaration"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_clause"],implementsClauseTypes:["class_interface_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","method_declaration","function_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["simple_parameter","variadic_parameter","property_promotion_parameter"],typeInWrapper:["named_type","primitive_type","optional_type"],declaratorStyle:"wrapper"}},Mt={language:"scala",rawTypes:{classTypes:["class_definition"],interfaceTypes:["trait_definition"],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["val_definition","var_definition"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_declaration"],annotationTypes:["annotation"],variableTypes:["val_definition","var_definition"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause"],implementsClauseTypes:["with_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_definition","class_definition","trait_definition"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","generic_type","scoped_type_identifier","function_type","tuple_type","refined_type"],declaratorStyle:"wrapper"}},Ft={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["identifier","optional_type","array_type","pointer_type","slice_type"],declaratorStyle:"wrapper"}},De=new Map([["ts",we],["tsx",wt],["js",Et],["py",St],["java",Nt],["csharp",vt],["c",It],["cpp",Pt],["rs",Ct],["go",Lt],["php",kt],["scala",Mt],["zig",Ft],["ruby",Rt]]);function q(f){return De.get(f)??we}Array.from(De.keys());function We(f){let e=q(f),t=new Set;for(let r of [e.rawTypes.classTypes,e.rawTypes.interfaceTypes,e.rawTypes.moduleTypes,e.rawTypes.methodTypes,e.rawTypes.propertyTypes,e.rawTypes.functionTypes,e.rawTypes.typeAliasTypes,e.rawTypes.enumTypes,e.rawTypes.importTypes,e.rawTypes.annotationTypes,e.rawTypes.variableTypes,e.rawTypes.exportTypes,e.rawTypes.ambientDeclarationTypes])for(let n of r)t.add(n);return t}function ze(f){let e=q(f),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(r);for(let r of e.rawTypes.propertyTypes)t.add(r);return t}function L(f,e){return q(f).normalizeMap[e]??e}var V=class{extractNodes(e,t,r,n){let i=[],s=t.split(`
182
182
  `),l=We(r),c=ze(r);return this.walkTree(e.rootNode,i,r,n,s,l,c),i}walkTree(e,t,r,n,i,s,l,c,o){if(s.has(e.type)){let d=this.extractNode(e,r,n,i,c,o,l);d&&(t.push(d),d.name&&(c=this.generateNodeId(d)),l.has(e.type)||(o=d.name??o));}for(let d=0;d<e.childCount;d++){let p=e.children[d];p&&this.walkTree(p,t,r,n,i,s,l,c,o);}}extractNode(e,t,r,n,i,s,l){let c=this.getNodeName(e,t);if(!c)return null;let o=e.startPosition,d=e.endPosition,p=this.getNodeText(e,n),g=l.has(e.type),m=g&&s?`${s}.${c}@${o.row+1}`:c,u=g?this.extractParameterTypes(e,t):[];return {name:m,ast_type:L(t,e.type),language:t,file_path:r,start_line:o.row+1,start_col:o.column,end_line:d.row+1,end_col:d.column,text:p,parent_id:i,metadata:g?{originalName:c,parameterTypes:u}:void 0}}extractParameterTypes(e,t){let n=q(t).parameters;if(!n)return [];let i=new Set(n.typeInWrapper),s=[],l=c=>{for(let o of c.children)if(o.type===n.wrapperType)return o;return null};if(n.declaratorStyle==="declarator"){for(let c of e.children)if(c.type==="function_declarator"||c.type==="pointer_declarator"){let o=l(c);if(o){for(let d of o.children)if(n.paramTypes.includes(d.type)){let p=this.findTypeInNode(d,i);p&&s.push(p);}return s}}}else {let c=l(e);if(c){for(let o of c.children)if(n.paramTypes.includes(o.type)){let d=this.findTypeInNode(o,i);d&&s.push(d);}}}return s}findTypeInNode(e,t){for(let r of e.children)if(t.has(r.type))return r.text;return null}getNodeName(e,t){switch(e.type){case "class_declaration":case "class_definition":case "abstract_class_declaration":case "class":case "interface_declaration":case "protocol_declaration":case "trait_item":case "trait_definition":case "struct_item":case "struct_declaration":case "struct_definition":case "struct_specifier":case "enum_item":case "enum_declaration":case "enum_specifier":case "type_alias_declaration":case "record_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "function_expression":case "arrow_function":case "function":case "method_definition":case "method_declaration":case "method":case "method_invocation":case "singleton_method":return this.findNameInChildren(e,["name","property_identifier","function_name"])??this.findNameInGrandchildren(e,["function_declarator","declarator","name"],["identifier","property_identifier","field_identifier","name"]);case "public_field_definition":case "field_definition":case "field_declaration":case "property_signature":case "property_declaration":case "val_definition":case "var_definition":return this.findNameInGrandchildren(e,["variable_declarator","declarator","property_element"],["identifier","name"])??this.findNameInChildren(e,["name","property_identifier","field_identifier"]);case "module":case "internal_module":case "ambient_declaration":case "namespace_declaration":case "namespace_definition":case "mod_item":case "type_declaration":if(e.type==="namespace_definition"){for(let n of e.children)if(n.type==="namespace_name")return n.text}return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["type_spec","type_alias","namespace_name"],["type_identifier","identifier","name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "import_from_statement":case "use_declaration":case "use_list":case "namespace_use_declaration":case "namespace_use_clause":case "using_directive":case "require":case "require_relative":case "preproc_include":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);case "attribute_item":case "attribute":case "annotation":case "marker_annotation":case "decorator":return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["attribute","decorator"],["identifier","name","token_tree"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let i=this.findNameInChildren(n,r);if(i)return i}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"||t.type==="dotted_name"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
183
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function qt(){return new V}var a={class_declaration:"class_declaration",class_definition:"class_definition",class_specifier:"class_specifier",interface_declaration:"interface_declaration",struct_item:"struct_item",struct_declaration:"struct_declaration",struct_specifier:"struct_specifier",type_declaration:"type_declaration",type_alias_declaration:"type_alias_declaration",enum_declaration:"enum_declaration",record_declaration:"record_declaration",function_declaration:"function_declaration",function_definition:"function_definition",function_item:"function_item",method_declaration:"method_declaration",method_definition:"method_definition",method_invocation:"method_invocation",invocation_expression:"invocation_expression",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_parameters",simple_parameter:"simple_parameter",typed_param:"typed_param",argument:"argument",field_declaration:"field_declaration",property_declaration:"property_declaration",public_field_definition:"public_field_definition",field_definition:"field_definition",property_signature:"property_signature",type_identifier:"type_identifier",type_annotation:"type_annotation",generic_type:"generic_type",named_type:"named_type",primitive_type:"primitive_type",return_type:"return_type",pointer_type:"pointer_type",reference_type:"reference_type",array_type:"array_type",sized_type_specifier:"sized_type_specifier",void_type:"void_type",predefined_type:"predefined_type",this:"this",function_declarator:"function_declarator",pointer_declarator:"pointer_declarator",declarator:"declarator",identifier:"identifier",property_identifier:"property_identifier",field_identifier:"field_identifier",name:"name",type_spec:"type_spec",super:"super",required_parameter:"required_parameter",optional_parameter:"optional_parameter",aliased_import:"aliased_import",relative_import:"relative_import",import_prefix:"import_prefix",import_statement:"import_statement",import_from_statement:"import_from_statement",namespace_use_declaration:"namespace_use_declaration",scoped_identifier:"scoped_identifier",qualified_name:"qualified_name",dotted_name:"dotted_name",dotted_identifier:"dotted_identifier",module_name:"module_name",namespace_name:"namespace_name",system_lib_string:"system_lib_string",string_literal:"string_literal",string:"string",string_content:"string_content",interpreted_string_literal:"interpreted_string_literal",interpreted_string_literal_content:"interpreted_string_literal_content",annotation:"annotation",attribute:"attribute",call:"call",call_expression:"call_expression",method_call_expression:"method_call_expression",function_call:"function_call",function_call_expression:"function_call_expression",member_call_expression:"member_call_expression",builtin_call_expression:"builtin_call_expression",member_expression:"member_expression",member_access:"member_access",member_access_expression:"member_access_expression",field_access:"field_access",field_expression:"field_expression",new_expression:"new_expression",object_creation_expression:"object_creation_expression",instance_expression:"instance_expression",scoped_type_identifier:"scoped_type_identifier",selector_expression:"selector_expression",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",parameters:"parameters",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Ee={extends:"extends",implements:"implements"},He="new",te={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function ue(f,e){e(f);for(let t of f.children)ue(t,e);}function A(f){for(let e of f.children)if(e.type===a.identifier||e.type===a.type_identifier||e.type===a.property_identifier||e.type===a.field_identifier||e.type===a.name)return e.text;return null}function me(f){for(let e=f.children.length-1;e>=0;e--){let t=f.children[e];if(t&&(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name))return t.text}return null}function ge(f,e){for(let t of f.children)if(e.includes(t.type))return t;return null}function D(f,e){for(let t of f.children){if(e.includes(t.type))return t;let r=D(t,e);if(r)return r}return null}function W(f,e){for(let t of f.children)if(e.includes(t.type)){let r=A(t);if(r)return r;for(let n of t.children){let i=A(n);if(i)return i}}for(let t of f.children){let r=W(t,e);if(r)return r}return null}function re(f){let e=f.indexOf("<");if(e<0)return f;let t=0,r=null;for(let n=e;n<f.length;n++){let i=f[n];if(r){i===r&&(r=null);continue}if(i==='"'||i==="'"||i==="`"){r=i;continue}if(i==="<")t++;else if(i===">"&&(t--,t===0))return f.slice(0,e).trim()}return f}function Be(f){let e=q(f),t=new Set;for(let r of e.rawTypes.classTypes)t.add(L(f,r));for(let r of e.rawTypes.interfaceTypes)t.add(L(f,r));for(let r of e.rawTypes.moduleTypes)t.add(L(f,r));return t}function At(f){let e=q(f),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(L(f,r));return t}function Ot(f){let e=q(f),t=new Set;for(let r of e.rawTypes.propertyTypes)t.add(L(f,r));return t}var Y=class{extractEdges(e,t,r,n){let i=[],s=new Map;for(let c of t){let o=s.get(c.name);o||(o=[],s.set(c.name,o)),o.push(c);}let l=new Map;for(let[c,o]of s){let d=o[0];d&&l.set(c,d);}return this.extractContainsEdges(t,i),this.extractCallEdges(e.rootNode,t,i,r,n,l),this.extractInheritanceEdges(e.rootNode,t,i,r,n,l),this.extractImportEdges(e.rootNode,t,i,r,n),this.extractTypeReferences(e.rootNode,t,i,r,n,l),this.extractAnnotationEdges(e.rootNode,t,i,r,n),this.extractHasMethodEdges(t,i,r),this.extractHasPropertyEdges(t,i,r),this.extractOverrideEdges(t,i,r,n),i}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,i,s){let l=new Set([a.call_expression,a.call,a.method_call_expression,a.function_call,a.function_call_expression,a.member_call_expression,a.method_invocation,a.invocation_expression,a.builtin_call_expression,a.new_expression,a.object_creation_expression,a.instance_expression]);this.walkTree(e,c=>{if(l.has(c.type)){let o=this.findEnclosingFunction(c,t,s),d=this.extractCalleeName(c);if(o&&d){let p=`${n}:*:*:${d}`;r.push({source:o.id,target:p,relation:"CALLS",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:i});}}});}extractInheritanceEdges(e,t,r,n,i,s){let l=q(n),c=new Set(l.rawTypes.classTypes),o=new Set(l.rawTypes.interfaceTypes),d=this.buildImportAliasMap(e,n);this.walkTree(e,p=>{if(c.has(p.type)){let g=A(p);if(!g)return;let m=`${n}:${i}:${L(n,p.type)}:${g}`,u=ge(p,[...l.inheritance.extendsClauseTypes]);u||(u=D(p,[...l.inheritance.extendsClauseTypes]));let h=[];u?(h=this.extractClauseNames(u,n),l.inheritance.stripTemplateArgs&&(h=h.map(y=>re(y)))):l.inheritance.fallbackToFirstIdentifier&&(h=this.collectNamedIdentifiers(p).filter(y=>y!==g).slice(0,1));for(let y of h){if(!y||y===g)continue;let _=L(n,l.rawTypes.classTypes[0]??"class_declaration"),x=d.get(y)??y,E=`${n}:${i}:${_}:${x}`;r.push({source:m,target:E,relation:"EXTENDS",line:(u?.startPosition?.row??p.startPosition?.row??-1)+1,col:(u?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}for(let y of l.inheritance.implementsClauseTypes){let _=ge(p,[y]);if(_||(_=D(p,[y])),_){let x=this.extractClauseNames(_,n);l.inheritance.stripTemplateArgs&&(x=x.map(E=>re(E)));for(let E of x){if(!E)continue;let b=l.rawTypes.interfaceTypes[0]??l.rawTypes.classTypes[0]??a.interface_declaration,T=d.get(E)??E,N=`${n}:${i}:${b}:${T}`;r.push({source:m,target:N,relation:"IMPLEMENTS",line:(_?.startPosition?.row??p.startPosition?.row??-1)+1,col:(_?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}}}return}if(o.has(p.type)){let g=A(p);if(!g)return;let m=`${n}:${i}:${L(n,p.type)}:${g}`;for(let u of l.inheritance.extendsClauseTypes){let h=D(p,[u]);if(h){let y=this.extractClauseNames(h,n);l.inheritance.stripTemplateArgs&&(y=y.map(_=>re(_)));for(let _ of y){if(_===g)continue;let x=L(n,l.rawTypes.interfaceTypes[0]??"interface_declaration"),E=d.get(_)??_,b=`${n}:${i}:${x}:${E}`;r.push({source:m,target:b,relation:"EXTENDS",line:(h?.startPosition?.row??p.startPosition?.row??-1)+1,col:(h?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}break}}}});}collectTypeAnnotations(e){let t=[],r=new Set([a.type_annotation,"type",a.reference_type,a.pointer_type,a.generic_type,a.array_type,a.named_type,a.primitive_type]),n=i=>{if(r.has(i.type)){t.push(i);return}for(let s of i.children)n(s);};return n(e),t}collectNamedIdentifiers(e){let t=[],r=new Set,n=i=>{if(i.type===a.identifier||i.type===a.type_identifier||i.type===a.attribute){let s=i.text;r.has(s)||(r.add(s),t.push(s));return}for(let s of i.namedChildren)s&&n(s);};return n(e),t}extractClauseNames(e,t){let r=[],n=new Set,i=o=>{!o||n.has(o)||(n.add(o),r.push(o));},s=new Set([a.scoped_identifier,a.scoped_type_identifier,a.qualified_name,a.dotted_name,a.dotted_identifier]),l=new Set([a.identifier,a.type_identifier,a.name,a.attribute]),c=o=>{if(s.has(o.type)){i(o.text);return}if(l.has(o.type)){if(o.type===a.name&&(o.text===Ee.extends||o.text===Ee.implements))return;i(o.text);return}if(o.type===a.generic_type){let d=o.childForFieldName?.("name")?.text??o.namedChildren[0]?.text;d&&i(d);return}for(let d of o.namedChildren)d&&c(d);};return c(e),r}extractImportEdges(e,t,r,n,i){let s=q(n),l=new Set(s.rawTypes.importTypes),c=new Set;this.walkTree(e,o=>{if(l.has(o.type)){let d,p=this.extractImportWholePath(o);p?d=[p]:d=this.extractImportPaths(o);for(let g of d){if(!g||c.has(g))continue;c.add(g);let m=`${n}:${i}:module:file`;r.push({source:m,target:g,relation:"IMPORTS",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}}});}walkTree(e,t){ue(e,t);}findEnclosingFunction(e,t,r){let n=e,i=new Set([a.function_declaration,a.function_definition,a.method_definition,a.method_declaration,a.function_item]);for(;n;){if(i.has(n.type)){let s=A(n)??W(n,[a.function_declarator,a.declarator]);if(s){let l=r.get(s);if(l)return {id:this.generateNodeId(l),name:s};let c=t[0],o=c?.language??"ts",d=c?.file_path??"";return {id:`${o}:${d}:function_definition:${s}`,name:s}}}n=n.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;let r=new Set([a.member_expression,a.field_access,a.attribute,a.member_access,a.member_access_expression,a.member_call_expression,a.field_expression,a.selector_expression,a.constant]);if(t.type===a.variable_name&&e.type===a.member_call_expression){let n=e.childForFieldName?.("name");if(n)return n.text;let i=e.children.find(s=>s.type===a.name);if(i)return i.text}if(r.has(t.type)){let n=t.childForFieldName?.("property");if(n)return n.text;let i=t.childForFieldName?.("field");if(i)return i.text;let s=t.childForFieldName?.("name");if(s)return s.text;for(let l=t.children.length-1;l>=0;l--){let c=t.children[l];if(c&&(c.type===a.identifier||c.type===a.property_identifier||c.type===a.name||c.type===a.field_identifier||c.type===a.constant))return c.text}}if(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name||t.type===a.constant)return t.text;if(t.type===a.this){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===a.identifier&&t.text.includes(".")){let n=t.text.split(".");return n[n.length-1]??t.text}if(t.type===a.super){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===He){for(let n of e.children)if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.name||n.type===a.scoped_identifier)return n.text}return null}extractImportPaths(e){let t=this.extractPythonImportPaths(e);if(t.length>0)return t;let r=new Set([a.string,a.string_literal,a.string_content,a.interpreted_string_literal,a.interpreted_string_literal_content,a.system_lib_string]),n=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),i=[],s=c=>{if(r.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)s(o);};if(s(e),i.length>0)return i;let l=c=>{if(n.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)l(o);};return l(e),i}extractPythonImportPaths(e){let t=e.type;if(t!==a.import_statement&&t!==a.import_from_statement)return [];let r=[];if(t===a.import_statement){for(let n of e.children)if(n.type===a.dotted_name)r.push(n.text);else if(n.type===a.aliased_import){let i=n.childForFieldName?.("name");if(i)r.push(i.text);else for(let s of n.children)if(s.type===a.dotted_name||s.type===a.identifier){r.push(s.text);break}}}else for(let n of e.children){if(n.type===a.dotted_name){r.push(n.text);break}if(n.type===a.relative_import){let i=n.childForFieldName?.(a.import_prefix),s=n.childForFieldName?.(a.module_name),l="";i&&(l+=i.text),s&&(l+=s.text),l?r.push(l):r.push(n.text);break}}return r}extractImportWholePath(e){let t=new Set([a.qualified_name,a.scoped_identifier,a.dotted_name,a.dotted_identifier,a.module_name,a.namespace_name,a.namespace_use_clause,a.name,a.identifier,a.string,a.string_literal,a.interpreted_string_literal,a.system_lib_string]);return (n=>{if(t.has(n.type)){let i=n.text;return (i.startsWith('"')||i.startsWith("'")||i.startsWith("<"))&&(i=i.slice(1,-1)),n.type===a.namespace_use_clause&&i.includes(" as ")&&(i=i.split(" as ")[0]??i),i}if(n.type===a.namespace_use_declaration||n.type===a.namespace_use_clause){for(let i of n.children)if(t.has(i.type)){let s=i.text;return (s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),i.type===a.namespace_use_clause&&s.includes(" as ")&&(s=s.split(" as ")[0]??s),s}}return null})(e)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,i,s){let l=new Set([a.function_declaration,a.function_definition,a.function_item,a.method_declaration,a.method_definition,a.variable_declaration,a.lexical_declaration,a.property_declaration,a.field_declaration,a.typed_param,a.identifier]),c=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),o=new Set([a.formal_parameters,a.parameter,a.parameter_declaration,a.formal_parameter,a.simple_parameter,a.typed_param,a.argument,a.required_parameter,a.optional_parameter,a.parameter,a.parameters]);this.walkTree(e,d=>{if(l.has(d.type)&&d.type!==a.lexical_declaration&&d.type!==a.variable_declaration){let m=d.childForFieldName?.("name")?.text??me(d)??A(d)??W(d,[a.function_declarator,a.pointer_declarator,a.declarator]);if(!m)return;let u=null,h=[a.return_type,a.type_annotation,"type",a.pointer_type,a.array_type,a.void_type];for(let b of h){for(let T of d.children)if(T.type===b){u=T;break}if(u)break}let y=new Set([a.type_identifier,a.generic_type,a.array_type,a.identifier,a.struct_specifier,a.class_specifier,a.named_type,a.primitive_type]),_=new Set([a.function_declarator,a.pointer_declarator,a.declarator]);if(!u){for(let b of d.children)if(y.has(b.type)){if(b.type===a.void_type)continue;let T=me(d);if(T&&b.text===T||_.has(b.type))continue;u=b;break}}let x=new Set([a.type_identifier,a.pointer_type,a.array_type]);if(!u){let b=false;for(let T of d.children){if(T.type==="->"||T.text==="->"){b=true;continue}if(b&&x.has(T.type)){u=T;break}}}if(u){let b=this.extractTypeName(u);if(b&&!te.void_any_null.has(b)){let T=this.resolveTypeNodeId(b,n,i);T&&r.push({source:this.generateNodeIdFromName(m,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}let E=D(d,["type_parameter","generic_type"]);if(E){let b=this.extractTypeName(E);if(b){let T=this.resolveTypeNodeId(b,n,i);T&&r.push({source:this.generateNodeIdFromName(m,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(E.startPosition?.row??-1)+1,col:(E.startPosition?.column??-1)+1,filePath:i});}}}if(c.has(d.type)){let m=this.findEnclosingClass(d,t);if(m){for(let u of d.children)if(u.type===a.type_identifier){let h=u.text,y=this.resolveTypeNodeId(h,n,i);y&&r.push({source:m.id,target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}let p=new Set([a.type_annotation,a.annotation,"type",a.reference_type,a.pointer_type,a.type_identifier,a.struct_specifier,a.class_specifier,a.array_type,a.sized_type_specifier,a.named_type,a.primitive_type,a.slice_type,a.array_type,a.map_type,a.channel_type]);if(o.has(d.type)){for(let m of d.children)if(p.has(m.type)){let u=this.extractTypeName(m);if(u&&!te.string_number_boolean.has(u)){let h=this.resolveTypeNodeId(u,n,i);if(h){let y=this.findEnclosingFunction(d,t,s);y&&r.push({source:y.id,target:h,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:i});}}}if((n==="zig"||n==="csharp")&&d.type===a.parameter&&d.children.length>=2){let m=n==="zig"?2:0,u=d.children[m];if(u&&u.type===a.identifier){let h=u.text;if(h&&!te.string_number_boolean.has(h)){let y=this.resolveTypeNodeId(h,n,i);if(y){let _=this.findEnclosingFunction(d,t,s);_&&r.push({source:_.id,target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}}if(new Set([a.variable_declaration,a.lexical_declaration,a.public_field_definition,a.field_definition,a.field_declaration,a.property_declaration,a.property_signature,a.assignment]).has(d.type)){let m=this.collectTypeAnnotations(d);for(let u of m){let h=this.extractTypeName(u);if(h&&!te.string_number_boolean.has(h)&&h!=="any"){let y=this.resolveTypeNodeId(h,n,i);if(y){let _=A(d)??W(d,["variable_declarator"])??A(d);_&&r.push({source:this.generateNodeIdFromName(_,"variable_declaration",n,i),target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}});}extractHasMethodEdges(e,t,r){let n=Be(r),i=At(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_METHOD");}extractHasPropertyEdges(e,t,r){let n=Be(r),i=Ot(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_PROPERTY");}emitContainerToMemberEdges(e,t,r,n,i){let s=new Map;for(let l of e){let c=s.get(l.file_path);c||(c=[],s.set(l.file_path,c)),c.push(l);}for(let l of s.values()){l.sort((o,d)=>o.start_line-d.start_line);let c=[];for(let o of l){for(;c.length>0&&(c[c.length-1]?.end_line??1/0)<o.start_line;)c.pop();if(r.has(o.ast_type))c.push(o);else if(n.has(o.ast_type)){let d=c[c.length-1];if(d){let p=this.generateNodeId(d),g=this.generateNodeId(o);t.push({source:p,target:g,relation:i});}}}}}extractOverrideEdges(e,t,r,n){let i=q(r),s=new Set;for(let d of i.rawTypes.classTypes)s.add(L(r,d));for(let d of i.rawTypes.interfaceTypes)s.add(L(r,d));let l=e.filter(d=>s.has(d.ast_type));if(l.length===0)return;let c=new Map;for(let d of e){let p=c.get(d.file_path);p||(p=[],c.set(d.file_path,p)),p.push(d);}let o=new Map;for(let d of t)if(d.relation==="EXTENDS"){let p;for(let m of c.values())if(p=m.find(u=>this.generateNodeId(u)===d.target),p)break;if(!p)continue;let g=o.get(d.source);g||(g=[],o.set(d.source,g)),g.push(p);}for(let d of l){let p=o.get(this.generateNodeId(d))??[];if(p.length===0)continue;let g=this.collectMemberIdsByName(d,c,"HAS_METHOD",r);if(g.size===0)continue;let m=new Set,u=[],h=[...p];for(;h.length>0;){let y=h.shift();if(m.has(this.generateNodeId(y)))continue;m.add(this.generateNodeId(y)),u.push(y);let _=o.get(this.generateNodeId(y))??[];h.push(..._);}for(let[y,_]of g){let x=_[0];if(!x)continue;let E=null;for(let b of u){let N=this.collectMemberIdsByName(b,c,"HAS_METHOD",r).get(y);if(!(!N||N.length===0)){E=N[0]??null;break}}if(E&&E!==x){let b=this.generateNodeId(d);if(t.some(v=>v.relation==="METHOD_OVERRIDES"&&v.source===b&&v.target===E))continue;t.push({source:b,target:E,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,t,r,n){let i=new Map,s=t.get(e.file_path);if(!s)return i;let l=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let c of s)if(l.has(c.ast_type)&&c.start_line>=e.start_line&&c.end_line<=e.end_line){let o=c.metadata?.originalName??c.name,d=c.metadata?.parameterTypes??[],p=d.length>0?`${o}|${d.join(",")}`:o,g=i.get(p);g||(g=[],i.set(p,g));let m=this.generateNodeId(c);g.push(m);}return i}buildImportAliasMap(e,t){let r=new Map;return this.walkTree(e,n=>{if(n.type===a.namespace_use_clause){let i=n.children,s=i.findIndex(l=>l.type==="as");if(s>=0){let l=i.slice(0,s).find(o=>o.type===a.qualified_name),c=i[s+1];l&&c&&c.type===a.name&&c.text&&r.set(c.text,l.text);}}}),r}findEnclosingClass(e,t){let r=e.parent,n=new Set([a.class_declaration,a.class_definition,a.struct_specifier,a.struct_declaration,a.struct_item,a.type_declaration,a.record_declaration,a.class_specifier,a.enum_declaration]);for(;r;){if(n.has(r.type)){let i=A(r)??W(r,[a.type_spec,a.name]);if(i){let s=t.find(d=>d.name===i);if(s)return {id:this.generateNodeId(s),name:i};let l=t[0],c=l?.language??"ts",o=l?.file_path??"";return {id:`${c}:${o}:${r.type}:${i}`,name:i}}}r=r.parent;}return null}extractAnnotationEdges(e,t,r,n,i){let s=q(n),l=new Set(s.rawTypes.annotationTypes),c=new Set(s.annotation.annotatableTypes);this.walkTree(e,o=>{if(l.has(o.type)){let d=this.extractTypeName(o)||A(o);if(!d)return;let p=o.parent;for(;p;){if(c.has(p.type)){let g=A(p),m=p.type;if(!g&&(p.type===a.decorated_definition||p.type===a.export_statement)){let u=W(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),h=D(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]);u&&(g=u,m=h?.type??"function_definition");}if(g){let u=this.generateNodeIdFromName(g,m,n,i),h=`${n}:${i}:annotation:${d}`;r.push({source:h,target:u,relation:"ANNOTATES",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===a.type_identifier||e.type===a.identifier||e.type===a.predefined_type||e.type===a.name)return e.text;let t=new Set([a.type_identifier,a.identifier,a.name]);for(let n of e.children)if(t.has(n.type))return n.text;for(let n of e.children)if(n.type===a.predefined_type)return n.text;let r=new Set([a.pointer_type,a.reference_type,a.array_type,a.generic_type,a.slice_type,a.map_type,a.channel_type,a.parenthesized_type]);for(let n of e.children)if(r.has(n.type)){let i=this.extractTypeName(n);if(i)return i}return null}resolveTypeNodeId(e,t,r){let n=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let i of n)return `${t}:${r}:${i}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${L(r,t)}:${e}`}};function Dt(){return new Y}var z=utils.Log.create({service:"codebase-indexer"}),K=class{constructor(e,t,r,n){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"parserManager");chunkTS4OAYIJ_cjs.a(this,"nodeExtractor");chunkTS4OAYIJ_cjs.a(this,"edgeExtractor");chunkTS4OAYIJ_cjs.a(this,"config");chunkTS4OAYIJ_cjs.a(this,"writeProxy",null);this.db=e,this.parserManager=t,this.nodeExtractor=new V,this.edgeExtractor=new Y,this.config=r,this.writeProxy=n??null;}async flushPendingWrites(){this.writeProxy&&await this.writeProxy.flush();}get dbWriter(){return this.writeProxy?this.writeProxy:this.db}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let i=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(i){let s=new Float32Array(i);return this.dbWriter.cacheEmbedding?.(t,s),s}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],i=0,s=0,l=null;try{let c=this.parserManager.detectLanguage(e);if(!c)throw new chunkRLZHDTHY_cjs.f("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let o=await this.readFile(e),d=this.computeHash(o);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),t?.({currentFile:e,processed:0,total:1,stage:"extracting"}),l=this.parserManager.parse(o,c);let p=this.nodeExtractor.extractNodes(l,o,c,e);i=p.length;let g=this.edgeExtractor.extractEdges(l,p,c,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let m=this.getValidEdgeCount(g,p);this.storeEdges(g,p),s=m,this.config.embedding&&p.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(p)),this.dbWriter.setFileHash(e,d),this.writeProxy&&this.writeProxy.flush();}catch(c){let o=c instanceof Error?c.message:String(c);n.push({filePath:e,error:o});}finally{if(l)try{l.delete();}catch(c){z.warn("tree.delete failed",{filePath:e,error:String(c)});}}return {success:n.length===0,filesProcessed:1,nodesCreated:i,edgesCreated:s,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,i=[],s=0,l=0,c=0;try{let o=await this.scanFiles(n);for(let u of o.readErrors)i.push(u);let d=o.results,p=d.length,g=0,m=u=>{t&&t({currentFile:u.currentFile,processed:g,total:d.length,stage:u.stage});};for(let u=0;u<d.length;u+=this.config.batchSize){let h=d.slice(u,u+this.config.batchSize),y=await Promise.all(h.map(_=>this.indexFile(_.filePath,m)));for(let _ of y)s++,g++,l+=_.nodesCreated,c+=_.edgesCreated,!_.success&&_.errors.length>0&&i.push(..._.errors);}if(t&&d.length>0){let u=d[d.length-1]?.filePath??"";t({currentFile:u,processed:d.length,total:d.length,stage:"storing"});}}catch(o){let d=o instanceof Error?o.message:String(o);i.push({filePath:n,error:d});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:i.length===0,filesProcessed:s,nodesCreated:l,edgesCreated:c,errors:i,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,i=0,s=0,l=0,c=0,o=0;try{let m=await this.scanFiles(this.config.workspaceDir),u=m.results;for(let w of m.readErrors)r.push(w);let h=new Set(u.map(w=>w.filePath)),y=this.db.getAllFileHashes(),_=new Set(y.map(w=>w.file_path));for(let w of y)h.has(w.file_path)||(this.dbWriter.deleteFtsByFile?.(w.file_path),this.dbWriter.deleteNodesByFile(w.file_path),this.dbWriter.deleteEdgesByFile(w.file_path),this.dbWriter.deleteFileHash(w.file_path),s++);let x=u.length,E=0,b=w=>{e&&e({currentFile:w.currentFile,processed:E,total:x,stage:w.stage});},T=Math.max(1,this.config.batchSize),N=new Map;for(let w of y)N.set(w.file_path,w.content_hash);for(let w=0;w<u.length;w+=T){let H=u.slice(w,w+T),G=await Promise.all(H.map(k=>{let M=N.get(k.filePath);return M?M!==k.contentHash?this.indexFile(k.filePath,b).then(B=>({file:k,kind:"updated",r:B})):Promise.resolve({file:k,kind:"skipped",r:null}):this.indexFile(k.filePath,b).then(B=>({file:k,kind:"added",r:B}))}));for(let{kind:k,r:M}of G)k==="skipped"?l++:M&&(M.success?M.nodesCreated===0?l++:(k==="added"?n++:i++,c+=M.nodesCreated,o+=M.edgesCreated):r.push(...M.errors));E+=H.length;}if(e&&x>0){let w=u[u.length-1]?.filePath??"";e({currentFile:w,processed:x,total:x,stage:"storing"});}this.writeProxy&&await this.writeProxy.flush();let v=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(w=>w.file_path)),R=this.db.getAllFileHashes().filter(w=>!v.has(w.file_path)).map(w=>w.file_path);for(let w of R)this.dbWriter.deleteFileHash(w);}catch(m){let u=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:u});}this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush();let d=new Date().toISOString(),p=Date.now()-t,g={timestamp:d,success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errorCount:r.length,errors:r,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(g)),{success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errors:r,duration:p}}async scanFiles(e){let t=[],r=[],i=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(y=>`**/*${y}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],l=this.config.ignorePatterns.map(y=>y.includes("/")||y.includes("*")?y:`**/${y}/**`),c=[...s,...l],o=await this.loadGitignore(e),d=new Set;for(let y of i){let _=await utils.Glob.scan(y,{cwd:e,absolute:true,include:"file",dot:false,symlink:false,ignore:c});for(let x of _)d.has(x)||d.add(x);}let p=Array.from(d),g=e.replace(/\\/g,"/"),m=o?p.filter(y=>!o.ignores(this.toRelativePosix(y,g),false)):p,u=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),h=[];for(let y of m){let _=utils.Filesystem.normalize(y);this.parserManager.detectLanguage(_)&&h.push(_);}for(let y=0;y<h.length;y+=u){let _=h.slice(y,y+u),x=await Promise.all(_.map(async E=>{try{let b=await this.readFile(E),T=this.computeHash(b),N=this.parserManager.detectLanguage(E);return N?{filePath:E,language:N,contentHash:T,content:b}:null}catch(b){let T=b instanceof Error?b.message:String(b);return r.push({filePath:E,error:T}),z.warn("scanFiles read failed",{filePath:E,error:T}),null}}));for(let E of x)E&&t.push(E);}return {results:t,readErrors:r}}async loadGitignore(e){try{let t=`${e.replace(/\\/g,"/")}/.gitignore`,r=await $e__default.default.readFile(t,"utf-8"),n=utils.Ignore.create();return n.add(r),z.debug("Loaded .gitignore",{path:t,lines:r.split(`
184
- `).length}),n}catch(t){return t.code!=="ENOENT"&&z.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:String(t)}),null}}toRelativePosix(e,t){let r=e;return r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/\\/g,"/"),r.startsWith("/")&&(r=r.slice(1)),r}async readFile(e){try{return await $e__default.default.readFile(e,"utf-8")}catch(t){throw new chunkRLZHDTHY_cjs.c("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(t),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let t=[];for(let r of e){let n=this.splitIdentifier(r.name);for(let i of n)i.length>0&&t.push({segment:i,name:r.name});}if(t.length!==0)try{this.db.insertNameSegmentsBatch(t);}catch(r){z.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:t.length,error:String(r)});for(let{segment:n,name:i}of t)try{this.db.insertNameSegment(n,i);}catch(s){z.warn("insertNameSegment failed",{nodeName:i,segment:n,error:String(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let t=[],i=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let s of i.split(/\s+/)){let l=s.toLowerCase();l.length>0&&t.push(l);}return t}storeEdges(e,t){let r=new Set(t.map(i=>this.nodeExtractor.generateNodeId(i))),n=e.filter(i=>i.source!==i.target&&r.has(i.source)&&r.has(i.target)).map((i,s)=>({id:`${i.source}:${i.relation}:${i.target}:${s}`,source:i.source,target:i.target,relation:i.relation,created_at:new Date().toISOString()}));n.length>0&&this.dbWriter.insertEdges(n),this.storeUnresolvedRefs(e,t,r);}storeUnresolvedRefs(e,t,r){let n=new Map,i=(o,d)=>{let p=n.get(o);p||(p=[],n.set(o,p)),p.includes(d)||p.push(d);};for(let o of t){let d=this.nodeExtractor.generateNodeId(o);i(o.name,d);let p=o.metadata?.originalName;typeof p=="string"&&p.length>0&&i(p,d);let g=o.name.lastIndexOf("@");if(g>0){let m=o.name.slice(0,g),u=m.lastIndexOf(".");u>0&&i(m.slice(u+1),d);}}let s=t[0]?.file_path??"",l=t[0]?.language??"unknown",c=[];for(let o of e){let d=r.has(o.source),p=r.has(o.target);if(d&&p)continue;let g=d?o.target:o.source,m=d?o.source:r.has(o.target)?o.target:void 0,u=g.includes(":")?g.split(":").pop()??g:g,h=n.get(u)??[];c.push({fromNodeId:m,referenceName:g,referenceKind:o.relation,line:o.line,col:o.col,filePath:o.filePath??s,language:l,candidates:h.length>0?h:void 0});}if(c.length!==0)try{this.db.insertUnresolvedRefsBatch(c);}catch(o){z.warn("insertUnresolvedRefsBatch failed, falling back to per-row insert",{batchSize:c.length,error:String(o)});for(let d of c)try{this.db.insertUnresolvedRef(d);}catch(p){z.warn("insertUnresolvedRef failed",{edgeId:`${d.fromNodeId??"?"}:${d.referenceKind}:${d.referenceName}`,error:String(p)});}}}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[],i=4,s=r.map((c,o)=>({index:o,batch:c})),l=[];for(let c=0;c<s.length;c+=i){let o=s.slice(c,c+i),d=await Promise.all(o.map(async({index:p,batch:g})=>{let m=[],u=g.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:u});for(let y=0;y<g.length;y++){let _=g[y];if(!_)continue;let x=h.embeddings[y];if(x){let E=new Float32Array(x),b=this.computeHash(this.generateNodeEmbeddingText(_));this.dbWriter.cacheEmbedding?.(b,E),m.push({nodeId:this.nodeExtractor.generateNodeId(_),embeddingText:u[y]||"",embedding:E});}}}catch{for(let y of g){if(!y)continue;let _=this.generateNodeEmbeddingText(y),x=await this.embedText(_);x&&m.push({nodeId:this.nodeExtractor.generateNodeId(y),embeddingText:_,embedding:x});}}return {index:p,embeddings:m}}));l.push(...d);}l.sort((c,o)=>c.index-o.index);for(let c of l)n.push(...c.embeddings);n.length>0&&this.dbWriter.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function jt(f,e,t){return new K(f,e,t)}function Se(f){if(!f)return [];let e=f.split(/[^a-zA-Z0-9]+/),t=[];for(let r of e){if(!r)continue;let n=r.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);n&&t.push(...n);}return t.map(r=>r.toLowerCase()).filter(r=>r.length>0)}function je(f,e){if(f.length===0||e.length===0)return 0;let t=0;for(let r of f)e.includes(r)&&t++;return t/f.length}function Ge(f,e,t={}){let r=t.limit??20,n=t.minScore??.2;if(!f)return [];let i=Se(f),s=[];for(let l of e){let c=l.id.split(":").pop()??"";if(c===f||l.name===f){s.push({nodeId:l.id,score:1,matchedPart:"full"});continue}let o=Se(c),d=Se(l.name),p=je(i,o),g=je(i,d),m=Math.max(p,g);m>=n&&s.push({nodeId:l.id,score:m,matchedPart:m>=.99?"full":"segment"});}return s.sort((l,c)=>c.score-l.score),s.slice(0,r)}var Ne=utils.Filesystem.toUnixPath,P=utils.Log.create({service:"codebase.query"}),Ut=new Set(["AND","OR","NOT","NEAR"]),Vt=/[\p{L}\p{N}_]/u;function Yt(f){return f?f.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!Ut.has(t.toUpperCase())).filter(t=>Vt.test(t)).join(" "):""}var J=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"embedding");chunkTS4OAYIJ_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:i,filePath:s,astType:l,enableFts:c=true,includeEdges:o=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:g=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;P.debug("search() called",{query:e,astType:l,language:i,enableEmbedding:m,enableFts:c,minScore:n});let u=[],h=new Map;if(m&&this.embedding){let x=await this.vectorSearchNodes(e,r*2,n);P.debug("vectorSearchNodes results",{count:x.length,astTypeFilter:l});for(let E of x){if(i&&E.language!==i||l&&E.astType!==l)continue;let b={...E,source:"vector",vectorScore:E.score,hybridScore:E.score*p};u.push(b),h.set(b.id,b);}P.debug("after vector filter",{resultsCount:u.length});}if(c&&this.db.isFtsAvailable()){let x=Yt(e);x||P.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let E=x?this.db.searchNodesFts(x,r*2):[];P.debug("FTS results before filter",{count:E.length});for(let b of E){if(i&&b.language!==i||s&&!b.file_path.includes(Ne(s))||l&&b.ast_type!==l)continue;let T=this.normalizeScore(b.score),N=h.get(b.id);if(N)N.ftsScore=T,N.hybridScore=N.vectorScore*p+T*g;else {let v={id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:T,source:"fts",ftsScore:T,hybridScore:T*g};u.push(v),h.set(v.id,v);}}P.debug("after FTS filter",{resultsCount:u.length});}if(!c||!this.db.isFtsAvailable()||u.length===0){try{let x=this.db.queryNodes({limit:r*2,astType:l,language:i,filePath:s}),E=new Set(u.map(w=>w.id)),b=e.toLowerCase(),T=b.split(/\s+/).filter(w=>w.length>0),N=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=T.map(w=>({term:w,regex:new RegExp(N(w),"gi")})),R=[];for(let w of x){if(s&&!w.file_path.includes(Ne(s)))continue;let H=w.name.toLowerCase(),G=w.text.toLowerCase(),k=0;if(v.some(({term:O})=>H.includes(O))){let O=0;for(let{regex:ne}of v){let ie=H.match(ne);O+=ie?ie.length:0;}k=.8*Math.min(O/v.length,1);}let M=0;if(v.some(({term:O})=>G.includes(O))){let O=0;for(let{regex:Ve}of v){let Ie=G.match(Ve);O+=Ie?Ie.length:0;}M=.5*Math.min(O/v.length,1);let ne=G.indexOf(b),ie=ne===-1?0:Math.max(0,1-ne/G.length)*.2;M+=ie;}let B=Math.max(k,M);B>0&&R.push({id:w.id,name:w.name,astType:w.ast_type,language:w.language,filePath:w.file_path,text:w.text,snippet:w.text.slice(0,200),startLine:w.start_line,startCol:w.start_col,endLine:w.end_line,endCol:w.end_col,score:B,source:"basic",hybridScore:B});}R.sort((w,H)=>H.score-w.score),u.push(...R.slice(0,r));}catch{}if(u.length===0)try{let x=this.db.queryNodes({limit:1e3}),E=Ge(e,x,{limit:r,minScore:.5});P.debug("name-segment matches",{count:E.length,query:e});for(let b of E){let T=this.db.getNodeById(b.nodeId);if(!T||i&&T.language!==i||l&&T.ast_type!==l||s&&!T.file_path.includes(Ne(s)))continue;let N={id:T.id,name:T.name,astType:T.ast_type,language:T.language,filePath:T.file_path,text:T.text??"",snippet:(T.text??"").slice(0,200),startLine:T.start_line??0,startCol:T.start_col??0,endLine:T.end_line??0,endCol:T.end_col??0,score:b.score,source:"structural",hybridScore:b.score};u.push(N),h.set(N.id,N);}}catch(x){P.debug("name-segment channel error",{error:x instanceof Error?x.message:String(x)});}}let _=u.filter(x=>x.hybridScore>=n).sort((x,E)=>E.hybridScore-x.hybridScore).slice(0,r).map(x=>({id:x.id,name:x.name,ast_type:x.astType,language:x.language,file_path:x.filePath,start_line:x.startLine,start_col:x.startCol,end_line:x.endLine,end_col:x.endCol,text:x.text,created_at:new Date().toISOString()}));if(o&&_.length>0){let x=_.map(T=>T.id),E=this.db.queryEdges({sourceOrTarget:x}),b=new Map;for(let T of E)T.source!==T.target&&(b.has(T.source)||b.set(T.source,[]),b.get(T.source).push(T));return _.map(T=>{let N=b.get(T.id)||[];return {...T,edges:N.slice(0,d)}})}return _.map(x=>({...x,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(P.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return P.debug("vectorSearchNodes skip - no embedding model"),[];let i=await this.embedText(e);if(!i)return P.debug("vectorSearchNodes skip - no embedding result"),[];let s=new Float32Array(i),l,c=5e3;if(n&&n.length>0){let m=n.map(()=>"?").join(",");l=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${m})`,n);}else l=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[c]);P.debug("vectorSearchNodes vectors loaded",{count:l.length});let o=[];for(let m of l){let u=new Float32Array(m.embedding.buffer,m.embedding.byteOffset,m.embedding.length/4),h=this.cosineSimilarity(s,u);h<r||(o.push({nodeId:m.node_id,score:h}),o.length>t&&(o.sort((y,_)=>_.score-y.score),o.splice(t)));}if(o.length===0)return P.debug("vectorSearchNodes done - no results above minScore"),[];o.sort((m,u)=>u.score-m.score);let d=o.map(m=>m.nodeId);P.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let p=this.db.queryNodes({ids:d}),g=new Map(o.map(m=>[m.nodeId,m.score]));return P.debug("vectorSearchNodes done",{nodesFound:p.length}),p.map(m=>({id:m.id,name:m.name,astType:m.ast_type,language:m.language,filePath:m.file_path,text:m.text??"",snippet:(m.text??"").slice(0,200),startLine:m.start_line??0,startCol:m.start_col??0,endLine:m.end_line??0,endCol:m.end_col??0,score:g.get(m.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({sourceOrTarget:[e.id],limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++){let l=e[s],c=t[s];r+=l*c,n+=l*l,i+=c*c;}return n===0||i===0?0:r/(Math.sqrt(n)*Math.sqrt(i))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){P.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(t){throw new chunkRLZHDTHY_cjs.g("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){P.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(t=>t.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(t){throw new chunkRLZHDTHY_cjs.g("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let i=this.db.getNodeById(n.source),s=this.db.getNodeById(n.target);i&&s&&r.push({edge:n,sourceNode:i,targetNode:s});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:i=100}=t;P.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:r,direction:n,limit:i});let s=[],l=[],c=new Set,o=new Set,d=r&&r.length>0?r:[void 0],p=g=>{for(let m of d){let u=m===void 0?{}:{relation:m},h=g==="outgoing"?this.db.queryEdges({source:e,...u,limit:i}):this.db.queryEdges({target:e,...u,limit:i});for(let y of h){if(o.has(y.id))continue;o.add(y.id),s.push(y);let _=g==="outgoing"?y.target:y.source,x=this.db.getNodeById(_);x&&!c.has(x.id)&&(l.push(x),c.add(x.id));}}};return (n==="outgoing"||n==="both")&&p("outgoing"),(n==="incoming"||n==="both")&&p("incoming"),{nodes:l.slice(0,i),edges:s.slice(0,i)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,i=(s,l)=>{if(l>t||n.has(s))return;n.add(s);let c=[],o=[],d=this.db.queryEdges({target:s,relation:"CALLS"});for(let g of d)c.push(g.source),i(g.source,l+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let g of p)o.push(g.target),i(g.target,l+1);r.set(s,{callers:c,callees:o});};return i(e,0),r}queryInheritance(e){P.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let t=[],r=[],n=new Set,i=new Set,s=c=>{if(n.has(c))return;n.add(c);let o=this.db.queryEdges({source:c,relation:"EXTENDS"}),d=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let g=this.db.getNodeById(p.target);g&&(t.push(g),s(p.target));}},l=c=>{if(i.has(c))return;i.add(c);let o=this.db.queryEdges({target:c,relation:"EXTENDS"}),d=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let g=this.db.getNodeById(p.source);g&&(r.push(g),l(p.source));}};return s(e),l(e),{ancestors:t,descendants:r}}queryMembers(e,t){let r=t?Array.isArray(t)?t:[t]:["HAS_METHOD","HAS_PROPERTY"],n=[],i=new Set;for(let s of r){let l=this.db.queryEdges({source:e,relation:s});for(let c of l){if(i.has(c.target))continue;i.add(c.target);let o=this.db.getNodeById(c.target);o&&n.push(o);}}return n}queryOverrides(e){let t=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),r=[],n=new Set;for(let i of t){if(n.has(i.target))continue;n.add(i.target);let s=this.db.getNodeById(i.target);s&&r.push(s);}return r}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Kt(f){return new J(f)}var fe;(u=>{let f=utils.Log.create({service:"codebase-llm"}),e=null;function r(h){n()||(e={models:h.models,options:{graph:h.options?.graph}},f.info("Llm initialized",{graphLlm:!!h.models.graphLlm,embeddingLlm:!!h.models.embeddingLlm}));}u.init=r;function n(){return e!==null}u.isInitialized=n;function i(){e=null;}u._resetForTest=i;function s(){return e?{graphLlm:!!e.models.graphLlm,embeddingLlm:!!e.models.embeddingLlm}:{graphLlm:false,embeddingLlm:false}}u.capabilities=s;function l(){return e?.models.graphLlm}u.getGraphLlm=l;function c(){return e?.models.embeddingLlm}u.getEmbeddingLlm=c;async function o(h,y){if(!e?.models.graphLlm)return f.debug("Llm.generateText: graphLlm not configured, return empty string"),"";try{return (await ai.streamText({model:e.models.graphLlm,prompt:h,maxOutputTokens:y?.maxOutputTokens??e.options.graph?.maxOutputTokens,temperature:y?.temperature??e.options.graph?.temperature})).text}catch(_){return f.error("Llm.generateText failed",{error:_ instanceof Error?_.message:String(_)}),""}}u.generateText=o;async function d(h){if(!e?.models.graphLlm)return {score:-1,details:"graphLlm not configured",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]};let y=p(h.gold,h.predicted),_=await o(y,{maxOutputTokens:1024,temperature:0,...h.options});return g(_)}u.evaluateExtraction=d;function p(h,y){return `You are a code knowledge graph extraction quality evaluator.
183
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function qt(){return new V}var a={class_declaration:"class_declaration",class_definition:"class_definition",class_specifier:"class_specifier",interface_declaration:"interface_declaration",struct_item:"struct_item",struct_declaration:"struct_declaration",struct_specifier:"struct_specifier",type_declaration:"type_declaration",type_alias_declaration:"type_alias_declaration",enum_declaration:"enum_declaration",record_declaration:"record_declaration",function_declaration:"function_declaration",function_definition:"function_definition",function_item:"function_item",method_declaration:"method_declaration",method_definition:"method_definition",method_invocation:"method_invocation",invocation_expression:"invocation_expression",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_parameters",simple_parameter:"simple_parameter",typed_param:"typed_param",argument:"argument",field_declaration:"field_declaration",property_declaration:"property_declaration",public_field_definition:"public_field_definition",field_definition:"field_definition",property_signature:"property_signature",type_identifier:"type_identifier",type_annotation:"type_annotation",generic_type:"generic_type",named_type:"named_type",primitive_type:"primitive_type",return_type:"return_type",pointer_type:"pointer_type",reference_type:"reference_type",array_type:"array_type",sized_type_specifier:"sized_type_specifier",void_type:"void_type",predefined_type:"predefined_type",this:"this",function_declarator:"function_declarator",pointer_declarator:"pointer_declarator",declarator:"declarator",identifier:"identifier",property_identifier:"property_identifier",field_identifier:"field_identifier",name:"name",type_spec:"type_spec",super:"super",required_parameter:"required_parameter",optional_parameter:"optional_parameter",aliased_import:"aliased_import",relative_import:"relative_import",import_prefix:"import_prefix",import_statement:"import_statement",import_from_statement:"import_from_statement",namespace_use_declaration:"namespace_use_declaration",scoped_identifier:"scoped_identifier",qualified_name:"qualified_name",dotted_name:"dotted_name",dotted_identifier:"dotted_identifier",module_name:"module_name",namespace_name:"namespace_name",system_lib_string:"system_lib_string",string_literal:"string_literal",string:"string",string_content:"string_content",interpreted_string_literal:"interpreted_string_literal",interpreted_string_literal_content:"interpreted_string_literal_content",annotation:"annotation",attribute:"attribute",call:"call",call_expression:"call_expression",method_call_expression:"method_call_expression",function_call:"function_call",function_call_expression:"function_call_expression",member_call_expression:"member_call_expression",builtin_call_expression:"builtin_call_expression",member_expression:"member_expression",member_access:"member_access",member_access_expression:"member_access_expression",field_access:"field_access",field_expression:"field_expression",new_expression:"new_expression",object_creation_expression:"object_creation_expression",instance_expression:"instance_expression",scoped_type_identifier:"scoped_type_identifier",selector_expression:"selector_expression",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",parameters:"parameters",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Ee={extends:"extends",implements:"implements"},He="new",te={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function ue(f,e){e(f);for(let t of f.children)ue(t,e);}function A(f){for(let e of f.children)if(e.type===a.identifier||e.type===a.type_identifier||e.type===a.property_identifier||e.type===a.field_identifier||e.type===a.name)return e.text;return null}function me(f){for(let e=f.children.length-1;e>=0;e--){let t=f.children[e];if(t&&(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name))return t.text}return null}function ge(f,e){for(let t of f.children)if(e.includes(t.type))return t;return null}function D(f,e){for(let t of f.children){if(e.includes(t.type))return t;let r=D(t,e);if(r)return r}return null}function W(f,e){for(let t of f.children)if(e.includes(t.type)){let r=A(t);if(r)return r;for(let n of t.children){let i=A(n);if(i)return i}}for(let t of f.children){let r=W(t,e);if(r)return r}return null}function re(f){let e=f.indexOf("<");if(e<0)return f;let t=0,r=null;for(let n=e;n<f.length;n++){let i=f[n];if(r){i===r&&(r=null);continue}if(i==='"'||i==="'"||i==="`"){r=i;continue}if(i==="<")t++;else if(i===">"&&(t--,t===0))return f.slice(0,e).trim()}return f}function Be(f){let e=q(f),t=new Set;for(let r of e.rawTypes.classTypes)t.add(L(f,r));for(let r of e.rawTypes.interfaceTypes)t.add(L(f,r));for(let r of e.rawTypes.moduleTypes)t.add(L(f,r));return t}function At(f){let e=q(f),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(L(f,r));return t}function Ot(f){let e=q(f),t=new Set;for(let r of e.rawTypes.propertyTypes)t.add(L(f,r));return t}var Y=class{extractEdges(e,t,r,n){let i=[],s=new Map;for(let c of t){let o=s.get(c.name);o||(o=[],s.set(c.name,o)),o.push(c);}let l=new Map;for(let[c,o]of s){let d=o[0];d&&l.set(c,d);}return this.extractContainsEdges(t,i),this.extractCallEdges(e.rootNode,t,i,r,n,l),this.extractInheritanceEdges(e.rootNode,t,i,r,n,l),this.extractImportEdges(e.rootNode,t,i,r,n),this.extractTypeReferences(e.rootNode,t,i,r,n,l),this.extractAnnotationEdges(e.rootNode,t,i,r,n),this.extractHasMethodEdges(t,i,r),this.extractHasPropertyEdges(t,i,r),this.extractOverrideEdges(t,i,r,n),i}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,i,s){let l=new Set([a.call_expression,a.call,a.method_call_expression,a.function_call,a.function_call_expression,a.member_call_expression,a.method_invocation,a.invocation_expression,a.builtin_call_expression,a.new_expression,a.object_creation_expression,a.instance_expression]);this.walkTree(e,c=>{if(l.has(c.type)){let o=this.findEnclosingFunction(c,t,s),d=this.extractCalleeName(c);if(o&&d){let p=`${n}:*:*:${d}`;r.push({source:o.id,target:p,relation:"CALLS",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:i});}}});}extractInheritanceEdges(e,t,r,n,i,s){let l=q(n),c=new Set(l.rawTypes.classTypes),o=new Set(l.rawTypes.interfaceTypes),d=this.buildImportAliasMap(e,n);this.walkTree(e,p=>{if(c.has(p.type)){let g=A(p);if(!g)return;let m=`${n}:${i}:${L(n,p.type)}:${g}`,u=ge(p,[...l.inheritance.extendsClauseTypes]);u||(u=D(p,[...l.inheritance.extendsClauseTypes]));let h=[];u?(h=this.extractClauseNames(u,n),l.inheritance.stripTemplateArgs&&(h=h.map(y=>re(y)))):l.inheritance.fallbackToFirstIdentifier&&(h=this.collectNamedIdentifiers(p).filter(y=>y!==g).slice(0,1));for(let y of h){if(!y||y===g)continue;let _=L(n,l.rawTypes.classTypes[0]??"class_declaration"),x=d.get(y)??y,E=`${n}:${i}:${_}:${x}`;r.push({source:m,target:E,relation:"EXTENDS",line:(u?.startPosition?.row??p.startPosition?.row??-1)+1,col:(u?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}for(let y of l.inheritance.implementsClauseTypes){let _=ge(p,[y]);if(_||(_=D(p,[y])),_){let x=this.extractClauseNames(_,n);l.inheritance.stripTemplateArgs&&(x=x.map(E=>re(E)));for(let E of x){if(!E)continue;let b=l.rawTypes.interfaceTypes[0]??l.rawTypes.classTypes[0]??a.interface_declaration,T=d.get(E)??E,N=`${n}:${i}:${b}:${T}`;r.push({source:m,target:N,relation:"IMPLEMENTS",line:(_?.startPosition?.row??p.startPosition?.row??-1)+1,col:(_?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}}}return}if(o.has(p.type)){let g=A(p);if(!g)return;let m=`${n}:${i}:${L(n,p.type)}:${g}`;for(let u of l.inheritance.extendsClauseTypes){let h=D(p,[u]);if(h){let y=this.extractClauseNames(h,n);l.inheritance.stripTemplateArgs&&(y=y.map(_=>re(_)));for(let _ of y){if(_===g)continue;let x=L(n,l.rawTypes.interfaceTypes[0]??"interface_declaration"),E=d.get(_)??_,b=`${n}:${i}:${x}:${E}`;r.push({source:m,target:b,relation:"EXTENDS",line:(h?.startPosition?.row??p.startPosition?.row??-1)+1,col:(h?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}break}}}});}collectTypeAnnotations(e){let t=[],r=new Set([a.type_annotation,"type",a.reference_type,a.pointer_type,a.generic_type,a.array_type,a.named_type,a.primitive_type]),n=i=>{if(r.has(i.type)){t.push(i);return}for(let s of i.children)n(s);};return n(e),t}collectNamedIdentifiers(e){let t=[],r=new Set,n=i=>{if(i.type===a.identifier||i.type===a.type_identifier||i.type===a.attribute){let s=i.text;r.has(s)||(r.add(s),t.push(s));return}for(let s of i.namedChildren)s&&n(s);};return n(e),t}extractClauseNames(e,t){let r=[],n=new Set,i=o=>{!o||n.has(o)||(n.add(o),r.push(o));},s=new Set([a.scoped_identifier,a.scoped_type_identifier,a.qualified_name,a.dotted_name,a.dotted_identifier]),l=new Set([a.identifier,a.type_identifier,a.name,a.attribute]),c=o=>{if(s.has(o.type)){i(o.text);return}if(l.has(o.type)){if(o.type===a.name&&(o.text===Ee.extends||o.text===Ee.implements))return;i(o.text);return}if(o.type===a.generic_type){let d=o.childForFieldName?.("name")?.text??o.namedChildren[0]?.text;d&&i(d);return}for(let d of o.namedChildren)d&&c(d);};return c(e),r}extractImportEdges(e,t,r,n,i){let s=q(n),l=new Set(s.rawTypes.importTypes),c=new Set;this.walkTree(e,o=>{if(l.has(o.type)){let d,p=this.extractImportWholePath(o);p?d=[p]:d=this.extractImportPaths(o);for(let g of d){if(!g||c.has(g))continue;c.add(g);let m=`${n}:${i}:module:file`;r.push({source:m,target:g,relation:"IMPORTS",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}}});}walkTree(e,t){ue(e,t);}findEnclosingFunction(e,t,r){let n=e,i=new Set([a.function_declaration,a.function_definition,a.method_definition,a.method_declaration,a.function_item]);for(;n;){if(i.has(n.type)){let s=A(n)??W(n,[a.function_declarator,a.declarator]);if(s){let l=r.get(s);if(l)return {id:this.generateNodeId(l),name:s};let c=t[0],o=c?.language??"ts",d=c?.file_path??"";return {id:`${o}:${d}:function_definition:${s}`,name:s}}}n=n.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;let r=new Set([a.member_expression,a.field_access,a.attribute,a.member_access,a.member_access_expression,a.member_call_expression,a.field_expression,a.selector_expression,a.constant]);if(t.type===a.variable_name&&e.type===a.member_call_expression){let n=e.childForFieldName?.("name");if(n)return n.text;let i=e.children.find(s=>s.type===a.name);if(i)return i.text}if(r.has(t.type)){let n=t.childForFieldName?.("property");if(n)return n.text;let i=t.childForFieldName?.("field");if(i)return i.text;let s=t.childForFieldName?.("name");if(s)return s.text;for(let l=t.children.length-1;l>=0;l--){let c=t.children[l];if(c&&(c.type===a.identifier||c.type===a.property_identifier||c.type===a.name||c.type===a.field_identifier||c.type===a.constant))return c.text}}if(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name||t.type===a.constant)return t.text;if(t.type===a.this){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===a.identifier&&t.text.includes(".")){let n=t.text.split(".");return n[n.length-1]??t.text}if(t.type===a.super){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===He){for(let n of e.children)if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.name||n.type===a.scoped_identifier)return n.text}return null}extractImportPaths(e){let t=this.extractPythonImportPaths(e);if(t.length>0)return t;let r=new Set([a.string,a.string_literal,a.string_content,a.interpreted_string_literal,a.interpreted_string_literal_content,a.system_lib_string]),n=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),i=[],s=c=>{if(r.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)s(o);};if(s(e),i.length>0)return i;let l=c=>{if(n.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)l(o);};return l(e),i}extractPythonImportPaths(e){let t=e.type;if(t!==a.import_statement&&t!==a.import_from_statement)return [];let r=[];if(t===a.import_statement){for(let n of e.children)if(n.type===a.dotted_name)r.push(n.text);else if(n.type===a.aliased_import){let i=n.childForFieldName?.("name");if(i)r.push(i.text);else for(let s of n.children)if(s.type===a.dotted_name||s.type===a.identifier){r.push(s.text);break}}}else for(let n of e.children){if(n.type===a.dotted_name){r.push(n.text);break}if(n.type===a.relative_import){let i=n.childForFieldName?.(a.import_prefix),s=n.childForFieldName?.(a.module_name),l="";i&&(l+=i.text),s&&(l+=s.text),l?r.push(l):r.push(n.text);break}}return r}extractImportWholePath(e){let t=new Set([a.qualified_name,a.scoped_identifier,a.dotted_name,a.dotted_identifier,a.module_name,a.namespace_name,a.namespace_use_clause,a.name,a.identifier,a.string,a.string_literal,a.interpreted_string_literal,a.system_lib_string]);return (n=>{if(t.has(n.type)){let i=n.text;return (i.startsWith('"')||i.startsWith("'")||i.startsWith("<"))&&(i=i.slice(1,-1)),n.type===a.namespace_use_clause&&i.includes(" as ")&&(i=i.split(" as ")[0]??i),i}if(n.type===a.namespace_use_declaration||n.type===a.namespace_use_clause){for(let i of n.children)if(t.has(i.type)){let s=i.text;return (s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),i.type===a.namespace_use_clause&&s.includes(" as ")&&(s=s.split(" as ")[0]??s),s}}return null})(e)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,i,s){let l=new Set([a.function_declaration,a.function_definition,a.function_item,a.method_declaration,a.method_definition,a.variable_declaration,a.lexical_declaration,a.property_declaration,a.field_declaration,a.typed_param,a.identifier]),c=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),o=new Set([a.formal_parameters,a.parameter,a.parameter_declaration,a.formal_parameter,a.simple_parameter,a.typed_param,a.argument,a.required_parameter,a.optional_parameter,a.parameter,a.parameters]);this.walkTree(e,d=>{if(l.has(d.type)&&d.type!==a.lexical_declaration&&d.type!==a.variable_declaration){let m=d.childForFieldName?.("name")?.text??me(d)??A(d)??W(d,[a.function_declarator,a.pointer_declarator,a.declarator]);if(!m)return;let u=null,h=[a.return_type,a.type_annotation,"type",a.pointer_type,a.array_type,a.void_type];for(let b of h){for(let T of d.children)if(T.type===b){u=T;break}if(u)break}let y=new Set([a.type_identifier,a.generic_type,a.array_type,a.identifier,a.struct_specifier,a.class_specifier,a.named_type,a.primitive_type]),_=new Set([a.function_declarator,a.pointer_declarator,a.declarator]);if(!u){for(let b of d.children)if(y.has(b.type)){if(b.type===a.void_type)continue;let T=me(d);if(T&&b.text===T||_.has(b.type))continue;u=b;break}}let x=new Set([a.type_identifier,a.pointer_type,a.array_type]);if(!u){let b=false;for(let T of d.children){if(T.type==="->"||T.text==="->"){b=true;continue}if(b&&x.has(T.type)){u=T;break}}}if(u){let b=this.extractTypeName(u);if(b&&!te.void_any_null.has(b)){let T=this.resolveTypeNodeId(b,n,i);T&&r.push({source:this.generateNodeIdFromName(m,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}let E=D(d,["type_parameter","generic_type"]);if(E){let b=this.extractTypeName(E);if(b){let T=this.resolveTypeNodeId(b,n,i);T&&r.push({source:this.generateNodeIdFromName(m,d.type,n,i),target:T,relation:"TYPE_REFERENCES",line:(E.startPosition?.row??-1)+1,col:(E.startPosition?.column??-1)+1,filePath:i});}}}if(c.has(d.type)){let m=this.findEnclosingClass(d,t);if(m){for(let u of d.children)if(u.type===a.type_identifier){let h=u.text,y=this.resolveTypeNodeId(h,n,i);y&&r.push({source:m.id,target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}let p=new Set([a.type_annotation,a.annotation,"type",a.reference_type,a.pointer_type,a.type_identifier,a.struct_specifier,a.class_specifier,a.array_type,a.sized_type_specifier,a.named_type,a.primitive_type,a.slice_type,a.array_type,a.map_type,a.channel_type]);if(o.has(d.type)){for(let m of d.children)if(p.has(m.type)){let u=this.extractTypeName(m);if(u&&!te.string_number_boolean.has(u)){let h=this.resolveTypeNodeId(u,n,i);if(h){let y=this.findEnclosingFunction(d,t,s);y&&r.push({source:y.id,target:h,relation:"TYPE_REFERENCES",line:(m.startPosition?.row??-1)+1,col:(m.startPosition?.column??-1)+1,filePath:i});}}}if((n==="zig"||n==="csharp")&&d.type===a.parameter&&d.children.length>=2){let m=n==="zig"?2:0,u=d.children[m];if(u&&u.type===a.identifier){let h=u.text;if(h&&!te.string_number_boolean.has(h)){let y=this.resolveTypeNodeId(h,n,i);if(y){let _=this.findEnclosingFunction(d,t,s);_&&r.push({source:_.id,target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}}if(new Set([a.variable_declaration,a.lexical_declaration,a.public_field_definition,a.field_definition,a.field_declaration,a.property_declaration,a.property_signature,a.assignment]).has(d.type)){let m=this.collectTypeAnnotations(d);for(let u of m){let h=this.extractTypeName(u);if(h&&!te.string_number_boolean.has(h)&&h!=="any"){let y=this.resolveTypeNodeId(h,n,i);if(y){let _=A(d)??W(d,["variable_declarator"])??A(d);_&&r.push({source:this.generateNodeIdFromName(_,"variable_declaration",n,i),target:y,relation:"TYPE_REFERENCES",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:i});}}}}});}extractHasMethodEdges(e,t,r){let n=Be(r),i=At(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_METHOD");}extractHasPropertyEdges(e,t,r){let n=Be(r),i=Ot(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_PROPERTY");}emitContainerToMemberEdges(e,t,r,n,i){let s=new Map;for(let l of e){let c=s.get(l.file_path);c||(c=[],s.set(l.file_path,c)),c.push(l);}for(let l of s.values()){l.sort((o,d)=>o.start_line-d.start_line);let c=[];for(let o of l){for(;c.length>0&&(c[c.length-1]?.end_line??1/0)<o.start_line;)c.pop();if(r.has(o.ast_type))c.push(o);else if(n.has(o.ast_type)){let d=c[c.length-1];if(d){let p=this.generateNodeId(d),g=this.generateNodeId(o);t.push({source:p,target:g,relation:i});}}}}}extractOverrideEdges(e,t,r,n){let i=q(r),s=new Set;for(let d of i.rawTypes.classTypes)s.add(L(r,d));for(let d of i.rawTypes.interfaceTypes)s.add(L(r,d));let l=e.filter(d=>s.has(d.ast_type));if(l.length===0)return;let c=new Map;for(let d of e){let p=c.get(d.file_path);p||(p=[],c.set(d.file_path,p)),p.push(d);}let o=new Map;for(let d of t)if(d.relation==="EXTENDS"){let p;for(let m of c.values())if(p=m.find(u=>this.generateNodeId(u)===d.target),p)break;if(!p)continue;let g=o.get(d.source);g||(g=[],o.set(d.source,g)),g.push(p);}for(let d of l){let p=o.get(this.generateNodeId(d))??[];if(p.length===0)continue;let g=this.collectMemberIdsByName(d,c,"HAS_METHOD",r);if(g.size===0)continue;let m=new Set,u=[],h=[...p];for(;h.length>0;){let y=h.shift();if(m.has(this.generateNodeId(y)))continue;m.add(this.generateNodeId(y)),u.push(y);let _=o.get(this.generateNodeId(y))??[];h.push(..._);}for(let[y,_]of g){let x=_[0];if(!x)continue;let E=null;for(let b of u){let N=this.collectMemberIdsByName(b,c,"HAS_METHOD",r).get(y);if(!(!N||N.length===0)){E=N[0]??null;break}}if(E&&E!==x){let b=this.generateNodeId(d);if(t.some(v=>v.relation==="METHOD_OVERRIDES"&&v.source===b&&v.target===E))continue;t.push({source:b,target:E,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,t,r,n){let i=new Map,s=t.get(e.file_path);if(!s)return i;let l=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let c of s)if(l.has(c.ast_type)&&c.start_line>=e.start_line&&c.end_line<=e.end_line){let o=c.metadata?.originalName??c.name,d=c.metadata?.parameterTypes??[],p=d.length>0?`${o}|${d.join(",")}`:o,g=i.get(p);g||(g=[],i.set(p,g));let m=this.generateNodeId(c);g.push(m);}return i}buildImportAliasMap(e,t){let r=new Map;return this.walkTree(e,n=>{if(n.type===a.namespace_use_clause){let i=n.children,s=i.findIndex(l=>l.type==="as");if(s>=0){let l=i.slice(0,s).find(o=>o.type===a.qualified_name),c=i[s+1];l&&c&&c.type===a.name&&c.text&&r.set(c.text,l.text);}}}),r}findEnclosingClass(e,t){let r=e.parent,n=new Set([a.class_declaration,a.class_definition,a.struct_specifier,a.struct_declaration,a.struct_item,a.type_declaration,a.record_declaration,a.class_specifier,a.enum_declaration]);for(;r;){if(n.has(r.type)){let i=A(r)??W(r,[a.type_spec,a.name]);if(i){let s=t.find(d=>d.name===i);if(s)return {id:this.generateNodeId(s),name:i};let l=t[0],c=l?.language??"ts",o=l?.file_path??"";return {id:`${c}:${o}:${r.type}:${i}`,name:i}}}r=r.parent;}return null}extractAnnotationEdges(e,t,r,n,i){let s=q(n),l=new Set(s.rawTypes.annotationTypes),c=new Set(s.annotation.annotatableTypes);this.walkTree(e,o=>{if(l.has(o.type)){let d=this.extractTypeName(o)||A(o);if(!d)return;let p=o.parent;for(;p;){if(c.has(p.type)){let g=A(p),m=p.type;if(!g&&(p.type===a.decorated_definition||p.type===a.export_statement)){let u=W(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),h=D(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]);u&&(g=u,m=h?.type??"function_definition");}if(g){let u=this.generateNodeIdFromName(g,m,n,i),h=`${n}:${i}:annotation:${d}`;r.push({source:h,target:u,relation:"ANNOTATES",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===a.type_identifier||e.type===a.identifier||e.type===a.predefined_type||e.type===a.name)return e.text;let t=new Set([a.type_identifier,a.identifier,a.name]);for(let n of e.children)if(t.has(n.type))return n.text;for(let n of e.children)if(n.type===a.predefined_type)return n.text;let r=new Set([a.pointer_type,a.reference_type,a.array_type,a.generic_type,a.slice_type,a.map_type,a.channel_type,a.parenthesized_type]);for(let n of e.children)if(r.has(n.type)){let i=this.extractTypeName(n);if(i)return i}return null}resolveTypeNodeId(e,t,r){let n=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let i of n)return `${t}:${r}:${i}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${L(r,t)}:${e}`}};function Dt(){return new Y}var z=utils.Log.create({service:"codebase-indexer"}),K=class{constructor(e,t,r,n){chunkNL2AZBPZ_cjs.a(this,"db");chunkNL2AZBPZ_cjs.a(this,"parserManager");chunkNL2AZBPZ_cjs.a(this,"nodeExtractor");chunkNL2AZBPZ_cjs.a(this,"edgeExtractor");chunkNL2AZBPZ_cjs.a(this,"config");chunkNL2AZBPZ_cjs.a(this,"writeProxy",null);this.db=e,this.parserManager=t,this.nodeExtractor=new V,this.edgeExtractor=new Y,this.config=r,this.writeProxy=n??null;}async flushPendingWrites(){this.writeProxy&&await this.writeProxy.flush();}get dbWriter(){return this.writeProxy?this.writeProxy:this.db}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let i=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(i){let s=new Float32Array(i);return this.dbWriter.cacheEmbedding?.(t,s),s}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],i=0,s=0,l=null;try{let c=this.parserManager.detectLanguage(e);if(!c)throw new chunk4A5VTYP7_cjs.f("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let o=await this.readFile(e),d=this.computeHash(o);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),t?.({currentFile:e,processed:0,total:1,stage:"extracting"}),l=this.parserManager.parse(o,c);let p=this.nodeExtractor.extractNodes(l,o,c,e);i=p.length;let g=this.edgeExtractor.extractEdges(l,p,c,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let m=this.getValidEdgeCount(g,p);this.storeEdges(g,p),s=m,this.config.embedding&&p.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(p)),this.dbWriter.setFileHash(e,d),this.writeProxy&&this.writeProxy.flush();}catch(c){let o=c instanceof Error?c.message:String(c);n.push({filePath:e,error:o});}finally{if(l)try{l.delete();}catch(c){z.warn("tree.delete failed",{filePath:e,error:String(c)});}}return {success:n.length===0,filesProcessed:1,nodesCreated:i,edgesCreated:s,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,i=[],s=0,l=0,c=0;try{let o=await this.scanFiles(n);for(let u of o.readErrors)i.push(u);let d=o.results,p=d.length,g=0,m=u=>{t&&t({currentFile:u.currentFile,processed:g,total:d.length,stage:u.stage});};for(let u=0;u<d.length;u+=this.config.batchSize){let h=d.slice(u,u+this.config.batchSize),y=await Promise.all(h.map(_=>this.indexFile(_.filePath,m)));for(let _ of y)s++,g++,l+=_.nodesCreated,c+=_.edgesCreated,!_.success&&_.errors.length>0&&i.push(..._.errors);}if(t&&d.length>0){let u=d[d.length-1]?.filePath??"";t({currentFile:u,processed:d.length,total:d.length,stage:"storing"});}}catch(o){let d=o instanceof Error?o.message:String(o);i.push({filePath:n,error:d});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:i.length===0,filesProcessed:s,nodesCreated:l,edgesCreated:c,errors:i,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,i=0,s=0,l=0,c=0,o=0;try{let m=await this.scanFiles(this.config.workspaceDir),u=m.results;for(let w of m.readErrors)r.push(w);let h=new Set(u.map(w=>w.filePath)),y=this.db.getAllFileHashes(),_=new Set(y.map(w=>w.file_path));for(let w of y)h.has(w.file_path)||(this.dbWriter.deleteFtsByFile?.(w.file_path),this.dbWriter.deleteNodesByFile(w.file_path),this.dbWriter.deleteEdgesByFile(w.file_path),this.dbWriter.deleteFileHash(w.file_path),s++);let x=u.length,E=0,b=w=>{e&&e({currentFile:w.currentFile,processed:E,total:x,stage:w.stage});},T=Math.max(1,this.config.batchSize),N=new Map;for(let w of y)N.set(w.file_path,w.content_hash);for(let w=0;w<u.length;w+=T){let H=u.slice(w,w+T),G=await Promise.all(H.map(k=>{let M=N.get(k.filePath);return M?M!==k.contentHash?this.indexFile(k.filePath,b).then(B=>({file:k,kind:"updated",r:B})):Promise.resolve({file:k,kind:"skipped",r:null}):this.indexFile(k.filePath,b).then(B=>({file:k,kind:"added",r:B}))}));for(let{kind:k,r:M}of G)k==="skipped"?l++:M&&(M.success?M.nodesCreated===0?l++:(k==="added"?n++:i++,c+=M.nodesCreated,o+=M.edgesCreated):r.push(...M.errors));E+=H.length;}if(e&&x>0){let w=u[u.length-1]?.filePath??"";e({currentFile:w,processed:x,total:x,stage:"storing"});}this.writeProxy&&await this.writeProxy.flush();let v=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(w=>w.file_path)),R=this.db.getAllFileHashes().filter(w=>!v.has(w.file_path)).map(w=>w.file_path);for(let w of R)this.dbWriter.deleteFileHash(w);}catch(m){let u=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:u});}this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush();let d=new Date().toISOString(),p=Date.now()-t,g={timestamp:d,success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errorCount:r.length,errors:r,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(g)),{success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:l,nodesCreated:c,edgesCreated:o,errors:r,duration:p}}async scanFiles(e){let t=[],r=[],i=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(y=>`**/*${y}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],l=this.config.ignorePatterns.map(y=>y.includes("/")||y.includes("*")?y:`**/${y}/**`),c=[...s,...l],o=await this.loadGitignore(e),d=new Set;for(let y of i){let _=await utils.Glob.scan(y,{cwd:e,absolute:true,include:"file",dot:false,symlink:false,ignore:c});for(let x of _)d.has(x)||d.add(x);}let p=Array.from(d),g=e.replace(/\\/g,"/"),m=o?p.filter(y=>!o.ignores(this.toRelativePosix(y,g),false)):p,u=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),h=[];for(let y of m){let _=utils.Filesystem.normalize(y);this.parserManager.detectLanguage(_)&&h.push(_);}for(let y=0;y<h.length;y+=u){let _=h.slice(y,y+u),x=await Promise.all(_.map(async E=>{try{let b=await this.readFile(E),T=this.computeHash(b),N=this.parserManager.detectLanguage(E);return N?{filePath:E,language:N,contentHash:T,content:b}:null}catch(b){let T=b instanceof Error?b.message:String(b);return r.push({filePath:E,error:T}),z.warn("scanFiles read failed",{filePath:E,error:T}),null}}));for(let E of x)E&&t.push(E);}return {results:t,readErrors:r}}async loadGitignore(e){try{let t=`${e.replace(/\\/g,"/")}/.gitignore`,r=await $e__default.default.readFile(t,"utf-8"),n=utils.Ignore.create();return n.add(r),z.debug("Loaded .gitignore",{path:t,lines:r.split(`
184
+ `).length}),n}catch(t){return t.code!=="ENOENT"&&z.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:String(t)}),null}}toRelativePosix(e,t){let r=e;return r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/\\/g,"/"),r.startsWith("/")&&(r=r.slice(1)),r}async readFile(e){try{return await $e__default.default.readFile(e,"utf-8")}catch(t){throw new chunk4A5VTYP7_cjs.c("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(t),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let t=[];for(let r of e){let n=this.splitIdentifier(r.name);for(let i of n)i.length>0&&t.push({segment:i,name:r.name});}if(t.length!==0)try{this.db.insertNameSegmentsBatch(t);}catch(r){z.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:t.length,error:String(r)});for(let{segment:n,name:i}of t)try{this.db.insertNameSegment(n,i);}catch(s){z.warn("insertNameSegment failed",{nodeName:i,segment:n,error:String(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let t=[],i=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let s of i.split(/\s+/)){let l=s.toLowerCase();l.length>0&&t.push(l);}return t}storeEdges(e,t){let r=new Set(t.map(i=>this.nodeExtractor.generateNodeId(i))),n=e.filter(i=>i.source!==i.target&&r.has(i.source)&&r.has(i.target)).map((i,s)=>({id:`${i.source}:${i.relation}:${i.target}:${s}`,source:i.source,target:i.target,relation:i.relation,created_at:new Date().toISOString()}));n.length>0&&this.dbWriter.insertEdges(n),this.storeUnresolvedRefs(e,t,r);}storeUnresolvedRefs(e,t,r){let n=new Map,i=(o,d)=>{let p=n.get(o);p||(p=[],n.set(o,p)),p.includes(d)||p.push(d);};for(let o of t){let d=this.nodeExtractor.generateNodeId(o);i(o.name,d);let p=o.metadata?.originalName;typeof p=="string"&&p.length>0&&i(p,d);let g=o.name.lastIndexOf("@");if(g>0){let m=o.name.slice(0,g),u=m.lastIndexOf(".");u>0&&i(m.slice(u+1),d);}}let s=t[0]?.file_path??"",l=t[0]?.language??"unknown",c=[];for(let o of e){let d=r.has(o.source),p=r.has(o.target);if(d&&p)continue;let g=d?o.target:o.source,m=d?o.source:r.has(o.target)?o.target:void 0,u=g.includes(":")?g.split(":").pop()??g:g,h=n.get(u)??[];c.push({fromNodeId:m,referenceName:g,referenceKind:o.relation,line:o.line,col:o.col,filePath:o.filePath??s,language:l,candidates:h.length>0?h:void 0});}if(c.length!==0)try{this.db.insertUnresolvedRefsBatch(c);}catch(o){z.warn("insertUnresolvedRefsBatch failed, falling back to per-row insert",{batchSize:c.length,error:String(o)});for(let d of c)try{this.db.insertUnresolvedRef(d);}catch(p){z.warn("insertUnresolvedRef failed",{edgeId:`${d.fromNodeId??"?"}:${d.referenceKind}:${d.referenceName}`,error:String(p)});}}}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[],i=4,s=r.map((c,o)=>({index:o,batch:c})),l=[];for(let c=0;c<s.length;c+=i){let o=s.slice(c,c+i),d=await Promise.all(o.map(async({index:p,batch:g})=>{let m=[],u=g.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:u});for(let y=0;y<g.length;y++){let _=g[y];if(!_)continue;let x=h.embeddings[y];if(x){let E=new Float32Array(x),b=this.computeHash(this.generateNodeEmbeddingText(_));this.dbWriter.cacheEmbedding?.(b,E),m.push({nodeId:this.nodeExtractor.generateNodeId(_),embeddingText:u[y]||"",embedding:E});}}}catch{for(let y of g){if(!y)continue;let _=this.generateNodeEmbeddingText(y),x=await this.embedText(_);x&&m.push({nodeId:this.nodeExtractor.generateNodeId(y),embeddingText:_,embedding:x});}}return {index:p,embeddings:m}}));l.push(...d);}l.sort((c,o)=>c.index-o.index);for(let c of l)n.push(...c.embeddings);n.length>0&&this.dbWriter.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function jt(f,e,t){return new K(f,e,t)}function Se(f){if(!f)return [];let e=f.split(/[^a-zA-Z0-9]+/),t=[];for(let r of e){if(!r)continue;let n=r.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);n&&t.push(...n);}return t.map(r=>r.toLowerCase()).filter(r=>r.length>0)}function je(f,e){if(f.length===0||e.length===0)return 0;let t=0;for(let r of f)e.includes(r)&&t++;return t/f.length}function Ge(f,e,t={}){let r=t.limit??20,n=t.minScore??.2;if(!f)return [];let i=Se(f),s=[];for(let l of e){let c=l.id.split(":").pop()??"";if(c===f||l.name===f){s.push({nodeId:l.id,score:1,matchedPart:"full"});continue}let o=Se(c),d=Se(l.name),p=je(i,o),g=je(i,d),m=Math.max(p,g);m>=n&&s.push({nodeId:l.id,score:m,matchedPart:m>=.99?"full":"segment"});}return s.sort((l,c)=>c.score-l.score),s.slice(0,r)}var Ne=utils.Filesystem.toUnixPath,P=utils.Log.create({service:"codebase.query"}),Ut=new Set(["AND","OR","NOT","NEAR"]),Vt=/[\p{L}\p{N}_]/u;function Yt(f){return f?f.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!Ut.has(t.toUpperCase())).filter(t=>Vt.test(t)).join(" "):""}var J=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkNL2AZBPZ_cjs.a(this,"db");chunkNL2AZBPZ_cjs.a(this,"embedding");chunkNL2AZBPZ_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:i,filePath:s,astType:l,enableFts:c=true,includeEdges:o=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:g=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;P.debug("search() called",{query:e,astType:l,language:i,enableEmbedding:m,enableFts:c,minScore:n});let u=[],h=new Map;if(m&&this.embedding){let x=await this.vectorSearchNodes(e,r*2,n);P.debug("vectorSearchNodes results",{count:x.length,astTypeFilter:l});for(let E of x){if(i&&E.language!==i||l&&E.astType!==l)continue;let b={...E,source:"vector",vectorScore:E.score,hybridScore:E.score*p};u.push(b),h.set(b.id,b);}P.debug("after vector filter",{resultsCount:u.length});}if(c&&this.db.isFtsAvailable()){let x=Yt(e);x||P.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let E=x?this.db.searchNodesFts(x,r*2):[];P.debug("FTS results before filter",{count:E.length});for(let b of E){if(i&&b.language!==i||s&&!b.file_path.includes(Ne(s))||l&&b.ast_type!==l)continue;let T=this.normalizeScore(b.score),N=h.get(b.id);if(N)N.ftsScore=T,N.hybridScore=N.vectorScore*p+T*g;else {let v={id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:T,source:"fts",ftsScore:T,hybridScore:T*g};u.push(v),h.set(v.id,v);}}P.debug("after FTS filter",{resultsCount:u.length});}if(!c||!this.db.isFtsAvailable()||u.length===0){try{let x=this.db.queryNodes({limit:r*2,astType:l,language:i,filePath:s}),E=new Set(u.map(w=>w.id)),b=e.toLowerCase(),T=b.split(/\s+/).filter(w=>w.length>0),N=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=T.map(w=>({term:w,regex:new RegExp(N(w),"gi")})),R=[];for(let w of x){if(s&&!w.file_path.includes(Ne(s)))continue;let H=w.name.toLowerCase(),G=w.text.toLowerCase(),k=0;if(v.some(({term:O})=>H.includes(O))){let O=0;for(let{regex:ne}of v){let ie=H.match(ne);O+=ie?ie.length:0;}k=.8*Math.min(O/v.length,1);}let M=0;if(v.some(({term:O})=>G.includes(O))){let O=0;for(let{regex:Ve}of v){let Ie=G.match(Ve);O+=Ie?Ie.length:0;}M=.5*Math.min(O/v.length,1);let ne=G.indexOf(b),ie=ne===-1?0:Math.max(0,1-ne/G.length)*.2;M+=ie;}let B=Math.max(k,M);B>0&&R.push({id:w.id,name:w.name,astType:w.ast_type,language:w.language,filePath:w.file_path,text:w.text,snippet:w.text.slice(0,200),startLine:w.start_line,startCol:w.start_col,endLine:w.end_line,endCol:w.end_col,score:B,source:"basic",hybridScore:B});}R.sort((w,H)=>H.score-w.score),u.push(...R.slice(0,r));}catch{}if(u.length===0)try{let x=this.db.queryNodes({limit:1e3}),E=Ge(e,x,{limit:r,minScore:.5});P.debug("name-segment matches",{count:E.length,query:e});for(let b of E){let T=this.db.getNodeById(b.nodeId);if(!T||i&&T.language!==i||l&&T.ast_type!==l||s&&!T.file_path.includes(Ne(s)))continue;let N={id:T.id,name:T.name,astType:T.ast_type,language:T.language,filePath:T.file_path,text:T.text??"",snippet:(T.text??"").slice(0,200),startLine:T.start_line??0,startCol:T.start_col??0,endLine:T.end_line??0,endCol:T.end_col??0,score:b.score,source:"structural",hybridScore:b.score};u.push(N),h.set(N.id,N);}}catch(x){P.debug("name-segment channel error",{error:x instanceof Error?x.message:String(x)});}}let _=u.filter(x=>x.hybridScore>=n).sort((x,E)=>E.hybridScore-x.hybridScore).slice(0,r).map(x=>({id:x.id,name:x.name,ast_type:x.astType,language:x.language,file_path:x.filePath,start_line:x.startLine,start_col:x.startCol,end_line:x.endLine,end_col:x.endCol,text:x.text,created_at:new Date().toISOString()}));if(o&&_.length>0){let x=_.map(T=>T.id),E=this.db.queryEdges({sourceOrTarget:x}),b=new Map;for(let T of E)T.source!==T.target&&(b.has(T.source)||b.set(T.source,[]),b.get(T.source).push(T));return _.map(T=>{let N=b.get(T.id)||[];return {...T,edges:N.slice(0,d)}})}return _.map(x=>({...x,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(P.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return P.debug("vectorSearchNodes skip - no embedding model"),[];let i=await this.embedText(e);if(!i)return P.debug("vectorSearchNodes skip - no embedding result"),[];let s=new Float32Array(i),l,c=5e3;if(n&&n.length>0){let m=n.map(()=>"?").join(",");l=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${m})`,n);}else l=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[c]);P.debug("vectorSearchNodes vectors loaded",{count:l.length});let o=[];for(let m of l){let u=new Float32Array(m.embedding.buffer,m.embedding.byteOffset,m.embedding.length/4),h=this.cosineSimilarity(s,u);h<r||(o.push({nodeId:m.node_id,score:h}),o.length>t&&(o.sort((y,_)=>_.score-y.score),o.splice(t)));}if(o.length===0)return P.debug("vectorSearchNodes done - no results above minScore"),[];o.sort((m,u)=>u.score-m.score);let d=o.map(m=>m.nodeId);P.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let p=this.db.queryNodes({ids:d}),g=new Map(o.map(m=>[m.nodeId,m.score]));return P.debug("vectorSearchNodes done",{nodesFound:p.length}),p.map(m=>({id:m.id,name:m.name,astType:m.ast_type,language:m.language,filePath:m.file_path,text:m.text??"",snippet:(m.text??"").slice(0,200),startLine:m.start_line??0,startCol:m.start_col??0,endLine:m.end_line??0,endCol:m.end_col??0,score:g.get(m.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({sourceOrTarget:[e.id],limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++){let l=e[s],c=t[s];r+=l*c,n+=l*l,i+=c*c;}return n===0||i===0?0:r/(Math.sqrt(n)*Math.sqrt(i))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){P.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(t){throw new chunk4A5VTYP7_cjs.g("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){P.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(t=>t.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(t){throw new chunk4A5VTYP7_cjs.g("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let i=this.db.getNodeById(n.source),s=this.db.getNodeById(n.target);i&&s&&r.push({edge:n,sourceNode:i,targetNode:s});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:i=100}=t;P.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:r,direction:n,limit:i});let s=[],l=[],c=new Set,o=new Set,d=r&&r.length>0?r:[void 0],p=g=>{for(let m of d){let u=m===void 0?{}:{relation:m},h=g==="outgoing"?this.db.queryEdges({source:e,...u,limit:i}):this.db.queryEdges({target:e,...u,limit:i});for(let y of h){if(o.has(y.id))continue;o.add(y.id),s.push(y);let _=g==="outgoing"?y.target:y.source,x=this.db.getNodeById(_);x&&!c.has(x.id)&&(l.push(x),c.add(x.id));}}};return (n==="outgoing"||n==="both")&&p("outgoing"),(n==="incoming"||n==="both")&&p("incoming"),{nodes:l.slice(0,i),edges:s.slice(0,i)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,i=(s,l)=>{if(l>t||n.has(s))return;n.add(s);let c=[],o=[],d=this.db.queryEdges({target:s,relation:"CALLS"});for(let g of d)c.push(g.source),i(g.source,l+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let g of p)o.push(g.target),i(g.target,l+1);r.set(s,{callers:c,callees:o});};return i(e,0),r}queryInheritance(e){P.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let t=[],r=[],n=new Set,i=new Set,s=c=>{if(n.has(c))return;n.add(c);let o=this.db.queryEdges({source:c,relation:"EXTENDS"}),d=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let g=this.db.getNodeById(p.target);g&&(t.push(g),s(p.target));}},l=c=>{if(i.has(c))return;i.add(c);let o=this.db.queryEdges({target:c,relation:"EXTENDS"}),d=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...o,...d]){let g=this.db.getNodeById(p.source);g&&(r.push(g),l(p.source));}};return s(e),l(e),{ancestors:t,descendants:r}}queryMembers(e,t){let r=t?Array.isArray(t)?t:[t]:["HAS_METHOD","HAS_PROPERTY"],n=[],i=new Set;for(let s of r){let l=this.db.queryEdges({source:e,relation:s});for(let c of l){if(i.has(c.target))continue;i.add(c.target);let o=this.db.getNodeById(c.target);o&&n.push(o);}}return n}queryOverrides(e){let t=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),r=[],n=new Set;for(let i of t){if(n.has(i.target))continue;n.add(i.target);let s=this.db.getNodeById(i.target);s&&r.push(s);}return r}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function Kt(f){return new J(f)}var fe;(u=>{let f=utils.Log.create({service:"codebase-llm"}),e=null;function r(h){n()||(e={models:h.models,options:{graph:h.options?.graph}},f.info("Llm initialized",{graphLlm:!!h.models.graphLlm,embeddingLlm:!!h.models.embeddingLlm}));}u.init=r;function n(){return e!==null}u.isInitialized=n;function i(){e=null;}u._resetForTest=i;function s(){return e?{graphLlm:!!e.models.graphLlm,embeddingLlm:!!e.models.embeddingLlm}:{graphLlm:false,embeddingLlm:false}}u.capabilities=s;function l(){return e?.models.graphLlm}u.getGraphLlm=l;function c(){return e?.models.embeddingLlm}u.getEmbeddingLlm=c;async function o(h,y){if(!e?.models.graphLlm)return f.debug("Llm.generateText: graphLlm not configured, return empty string"),"";try{return (await ai.streamText({model:e.models.graphLlm,prompt:h,maxOutputTokens:y?.maxOutputTokens??e.options.graph?.maxOutputTokens,temperature:y?.temperature??e.options.graph?.temperature})).text}catch(_){return f.error("Llm.generateText failed",{error:_ instanceof Error?_.message:String(_)}),""}}u.generateText=o;async function d(h){if(!e?.models.graphLlm)return {score:-1,details:"graphLlm not configured",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]};let y=p(h.gold,h.predicted),_=await o(y,{maxOutputTokens:1024,temperature:0,...h.options});return g(_)}u.evaluateExtraction=d;function p(h,y){return `You are a code knowledge graph extraction quality evaluator.
185
185
 
186
186
  Given:
187
187
  - **Gold (ground truth)**: a reference extraction produced by a human annotator
@@ -231,4 +231,4 @@ ${h}
231
231
 
232
232
  Predicted:
233
233
  ${y}`}function g(h){let y={score:0,details:"",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]},_=h??"",x=_.trim();if(!x)return {...y,details:"LLM returned empty text"};let E=x,b=E.match(/```(?:json|JSON)?\s*([\s\S]*?)\s*```/);b&&(E=(b[1]??"").trim());let T=E.match(/\{[\s\S]*\}/);if(T)try{let v=JSON.parse(T[0]);return m(v)}catch{}for(let v of E.split(`
234
- `)){let R=v.trim();if(R.startsWith("{"))try{let w=JSON.parse(R);return m(w)}catch{}}let N=E.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let v of N){let R=v;R.endsWith("%")&&(R=String(parseFloat(R)/100));let w=parseFloat(R);if(!Number.isNaN(w)&&w>=0&&w<=1)return {...y,score:w,details:`LLM returned non-JSON output; score extracted via heuristic from: ${_.slice(0,200)}`}}return {...y,details:`Failed to parse LLM output: ${_.slice(0,200)}`}}u.parseEvaluationResult=g;function m(h){return {score:typeof h.score=="number"?Math.max(0,Math.min(1,h.score)):0,details:typeof h.details=="string"?h.details:"",missingEntities:Array.isArray(h.missing_entities)?h.missing_entities.filter(_=>typeof _=="string"):[],extraEntities:Array.isArray(h.extra_entities)?h.extra_entities.filter(_=>typeof _=="string"):[],wrongRelations:Array.isArray(h.wrong_relations)?h.wrong_relations.filter(_=>typeof _=="string"):[],missingRelations:Array.isArray(h.missing_relations)?h.missing_relations.filter(_=>typeof _=="string"):[]}}})(fe||(fe={}));var C=utils.Log.create({service:"codebase"}),or={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},ve=class{constructor(e={}){chunkTS4OAYIJ_cjs.a(this,"config");chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"writeBackend",null);chunkTS4OAYIJ_cjs.a(this,"writeProxy",null);chunkTS4OAYIJ_cjs.a(this,"parserManager");chunkTS4OAYIJ_cjs.a(this,"indexer");chunkTS4OAYIJ_cjs.a(this,"queryInterface");chunkTS4OAYIJ_cjs.a(this,"initialized",false);chunkTS4OAYIJ_cjs.a(this,"dirty",false);chunkTS4OAYIJ_cjs.a(this,"syncTimer");chunkTS4OAYIJ_cjs.a(this,"syncingInProgress",false);chunkTS4OAYIJ_cjs.a(this,"codebasePackageVersion");chunkTS4OAYIJ_cjs.a(this,"fileWatcher",null);this.config={...or,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},fe.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n=this.resolveDbPath();chunk7XCIIOM6_cjs.d(Q__default.default.dirname(n)),this.db=new chunkRLZHDTHY_cjs.n(n),this.parserManager=new U,this.queryInterface=new J(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=cr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new pe({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new oe(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new K(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){C.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>C.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,C.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){C.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{C.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=>{C.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new chunkRLZHDTHY_cjs.e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new chunkRLZHDTHY_cjs.e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Q__default.default.isAbsolute(e)?e:Q__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return C.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,chunkRLZHDTHY_cjs.m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,chunkRLZHDTHY_cjs.m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),C.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return C.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-P3ACFOV5.cjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let l=null,c=new Set,o=()=>{l=null;let p=c.size;c.clear(),p!==0&&(C.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(g=>{C.error("auto-sync after file change failed",{error:g instanceof Error?g.message:String(g)});}));},d=()=>{l&&clearTimeout(l),l=setTimeout(o,n);};return s.on((p,g)=>{C.debug("file change",{event:p,relPath:g}),c.add(g),d();}),i&&this.sync().catch(p=>{C.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),C.info("file watcher started",{workspaceDir:r,debounceMs:n}),{stop:async()=>{l&&(clearTimeout(l),l=null),await s.stop(),this.fileWatcher=null,C.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){C.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){C.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){C.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,C.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function Yn(f){let e=new ve(f);return await e.initialize(),e}function cr(){try{let e=Q__default.default.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b));for(let t=0;t<8;t++){let r=Q__default.default.join(e,"package.json");try{let i=JSON.parse(fs.readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=Q__default.default.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}exports.a=Ae;exports.b=ke;exports.c=U;exports.d=xt;exports.e=Tt;exports.f=V;exports.g=qt;exports.h=Y;exports.i=Dt;exports.j=K;exports.k=jt;exports.l=Ge;exports.m=J;exports.n=Kt;exports.o=ve;exports.p=Yn;
234
+ `)){let R=v.trim();if(R.startsWith("{"))try{let w=JSON.parse(R);return m(w)}catch{}}let N=E.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let v of N){let R=v;R.endsWith("%")&&(R=String(parseFloat(R)/100));let w=parseFloat(R);if(!Number.isNaN(w)&&w>=0&&w<=1)return {...y,score:w,details:`LLM returned non-JSON output; score extracted via heuristic from: ${_.slice(0,200)}`}}return {...y,details:`Failed to parse LLM output: ${_.slice(0,200)}`}}u.parseEvaluationResult=g;function m(h){return {score:typeof h.score=="number"?Math.max(0,Math.min(1,h.score)):0,details:typeof h.details=="string"?h.details:"",missingEntities:Array.isArray(h.missing_entities)?h.missing_entities.filter(_=>typeof _=="string"):[],extraEntities:Array.isArray(h.extra_entities)?h.extra_entities.filter(_=>typeof _=="string"):[],wrongRelations:Array.isArray(h.wrong_relations)?h.wrong_relations.filter(_=>typeof _=="string"):[],missingRelations:Array.isArray(h.missing_relations)?h.missing_relations.filter(_=>typeof _=="string"):[]}}})(fe||(fe={}));var C=utils.Log.create({service:"codebase"}),or={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},ve=class{constructor(e={}){chunkNL2AZBPZ_cjs.a(this,"config");chunkNL2AZBPZ_cjs.a(this,"db");chunkNL2AZBPZ_cjs.a(this,"writeBackend",null);chunkNL2AZBPZ_cjs.a(this,"writeProxy",null);chunkNL2AZBPZ_cjs.a(this,"parserManager");chunkNL2AZBPZ_cjs.a(this,"indexer");chunkNL2AZBPZ_cjs.a(this,"queryInterface");chunkNL2AZBPZ_cjs.a(this,"initialized",false);chunkNL2AZBPZ_cjs.a(this,"dirty",false);chunkNL2AZBPZ_cjs.a(this,"syncTimer");chunkNL2AZBPZ_cjs.a(this,"syncingInProgress",false);chunkNL2AZBPZ_cjs.a(this,"codebasePackageVersion");chunkNL2AZBPZ_cjs.a(this,"fileWatcher",null);this.config={...or,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},fe.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n=this.resolveDbPath();chunk7XCIIOM6_cjs.d(Q__default.default.dirname(n)),this.db=new chunk4A5VTYP7_cjs.n(n),this.parserManager=new U,this.queryInterface=new J(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=cr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new pe({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new oe(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new K(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){C.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>C.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,C.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){C.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{C.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=>{C.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new chunk4A5VTYP7_cjs.e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new chunk4A5VTYP7_cjs.e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return Q__default.default.isAbsolute(e)?e:Q__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return C.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,chunk4A5VTYP7_cjs.m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,chunk4A5VTYP7_cjs.m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),C.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return C.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-DAS74BJ6.cjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let l=null,c=new Set,o=()=>{l=null;let p=c.size;c.clear(),p!==0&&(C.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(g=>{C.error("auto-sync after file change failed",{error:g instanceof Error?g.message:String(g)});}));},d=()=>{l&&clearTimeout(l),l=setTimeout(o,n);};return s.on((p,g)=>{C.debug("file change",{event:p,relPath:g}),c.add(g),d();}),i&&this.sync().catch(p=>{C.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),C.info("file watcher started",{workspaceDir:r,debounceMs:n}),{stop:async()=>{l&&(clearTimeout(l),l=null),await s.stop(),this.fileWatcher=null,C.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){C.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){C.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){C.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,C.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function Yn(f){let e=new ve(f);return await e.initialize(),e}function cr(){try{let e=Q__default.default.dirname(url.fileURLToPath(chunkNL2AZBPZ_cjs.b));for(let t=0;t<8;t++){let r=Q__default.default.join(e,"package.json");try{let i=JSON.parse(fs.readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=Q__default.default.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}exports.a=Ae;exports.b=ke;exports.c=U;exports.d=xt;exports.e=Tt;exports.f=V;exports.g=qt;exports.h=Y;exports.i=Dt;exports.j=K;exports.k=jt;exports.l=Ge;exports.m=J;exports.n=Kt;exports.o=ve;exports.p=Yn;
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkJVX6PHPN_cjs=require('./chunk-JVX6PHPN.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),path=require('path');function E(t){let e={},n=[];for(let s of t)s==="--json"?e.json=true:s==="--quiet"||s==="-q"?e.quiet=true:s==="--help"||s==="-h"?e.help=true:s==="--no-embed"?e.noEmbed=true:s==="--embed"?e.noEmbed=false:s.startsWith("-")||n.push(s);return e.dir=n[0],e}async function w(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkJVX6PHPN_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.c(e),{CodeBase:s}=await import('./code-base-HBPZXJQZ.cjs'),{DEFAULT_EMBEDDING_CONFIG:p,DEFAULT_INDEXER_CONFIG:m,DEFAULT_PARSER_CONFIG:h}=await import('@easbot/types'),i=new s({workspaceDir:e,database:{path:n,walMode:true},embedding:t.noEmbed===false?p:void 0,indexer:m,parser:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),l,a={_lastPct:-1,_lastProgressAt:0};try{await i.initialize();let r=await i.sync(t.quiet?void 0:o=>{let b=Math.max(o.total,1),d=Math.min(100,Math.floor(o.processed/b*100)),c=Date.now(),g=d!==a._lastPct,y=c-a._lastProgressAt>3e4;if(g||y){let D=String(d).padStart(3," ");console.error(` \u{1F4A1} [${D}%] ${o.stage}: ${o.processed}/${o.total} files`),a._lastPct=d,a._lastProgressAt=c;}}),S=i.getDatabase().getIndexState();l={rootDir:e,success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,nodesCreated:r.nodesCreated,edgesCreated:r.edgesCreated,errorCount:r.errors.length,errors:r.errors,durationMs:r.duration,indexState:S};}finally{await i.close();}return l}function M(t){let e=[];if(e.push("Codebase sync"),e.push(` rootDir: ${t.rootDir}`),e.push(` success: ${t.success?"\u2713":"\u2717"}`),e.push(` indexState: ${t.indexState}`),e.push(` files added: ${t.filesAdded}`),e.push(` files updated: ${t.filesUpdated}`),e.push(` files deleted: ${t.filesDeleted}`),e.push(` files skipped: ${t.filesSkipped}`),e.push(` nodes created: ${t.nodesCreated}`),e.push(` edges created: ${t.edgesCreated}`),e.push(` duration: ${t.durationMs}ms`),t.errorCount>0){e.push(` errors (${t.errorCount}):`);for(let n of t.errors.slice(0,10))e.push(` - ${n.filePath}: ${n.error}`);t.errors.length>10&&e.push(` ... and ${t.errors.length-10} more`);}return e.join(`
1
+ 'use strict';var chunkJVX6PHPN_cjs=require('./chunk-JVX6PHPN.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),path=require('path');function E(t){let e={},n=[];for(let s of t)s==="--json"?e.json=true:s==="--quiet"||s==="-q"?e.quiet=true:s==="--help"||s==="-h"?e.help=true:s==="--no-embed"?e.noEmbed=true:s==="--embed"?e.noEmbed=false:s.startsWith("-")||n.push(s);return e.dir=n[0],e}async function w(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkJVX6PHPN_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.c(e),{CodeBase:s}=await import('./code-base-FF7YI5C7.cjs'),{DEFAULT_EMBEDDING_CONFIG:p,DEFAULT_INDEXER_CONFIG:m,DEFAULT_PARSER_CONFIG:h}=await import('@easbot/types'),i=new s({workspaceDir:e,database:{path:n,walMode:true},embedding:t.noEmbed===false?p:void 0,indexer:m,parser:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),l,a={_lastPct:-1,_lastProgressAt:0};try{await i.initialize();let r=await i.sync(t.quiet?void 0:o=>{let b=Math.max(o.total,1),d=Math.min(100,Math.floor(o.processed/b*100)),c=Date.now(),g=d!==a._lastPct,y=c-a._lastProgressAt>3e4;if(g||y){let D=String(d).padStart(3," ");console.error(` \u{1F4A1} [${D}%] ${o.stage}: ${o.processed}/${o.total} files`),a._lastPct=d,a._lastProgressAt=c;}}),S=i.getDatabase().getIndexState();l={rootDir:e,success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,nodesCreated:r.nodesCreated,edgesCreated:r.edgesCreated,errorCount:r.errors.length,errors:r.errors,durationMs:r.duration,indexState:S};}finally{await i.close();}return l}function M(t){let e=[];if(e.push("Codebase sync"),e.push(` rootDir: ${t.rootDir}`),e.push(` success: ${t.success?"\u2713":"\u2717"}`),e.push(` indexState: ${t.indexState}`),e.push(` files added: ${t.filesAdded}`),e.push(` files updated: ${t.filesUpdated}`),e.push(` files deleted: ${t.filesDeleted}`),e.push(` files skipped: ${t.filesSkipped}`),e.push(` nodes created: ${t.nodesCreated}`),e.push(` edges created: ${t.edgesCreated}`),e.push(` duration: ${t.durationMs}ms`),t.errorCount>0){e.push(` errors (${t.errorCount}):`);for(let n of t.errors.slice(0,10))e.push(` - ${n.filePath}: ${n.error}`);t.errors.length>10&&e.push(` ... and ${t.errors.length-10} more`);}return e.join(`
2
2
  `)}exports.a=E;exports.b=w;exports.c=M;