@zipbul/gildash 0.13.0 → 0.15.0

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 (34) hide show
  1. package/dist/index.js +9 -9
  2. package/dist/migrations/0008_external_imports.sql +26 -0
  3. package/dist/migrations/meta/_journal.json +7 -0
  4. package/dist/src/common/path-utils.d.ts +8 -0
  5. package/dist/src/errors.d.ts +0 -10
  6. package/dist/src/extractor/imports-extractor.d.ts +4 -2
  7. package/dist/src/extractor/relation-extractor.d.ts +2 -2
  8. package/dist/src/extractor/types.d.ts +5 -3
  9. package/dist/src/gildash/context.d.ts +1 -1
  10. package/dist/src/gildash/index.d.ts +1 -0
  11. package/dist/src/gildash/semantic-api.d.ts +2 -0
  12. package/dist/src/gildash/types.d.ts +15 -23
  13. package/dist/src/index.d.ts +8 -3
  14. package/dist/src/indexer/index-coordinator.d.ts +5 -4
  15. package/dist/src/indexer/relation-indexer.d.ts +6 -2
  16. package/dist/src/parser/ast-utils.d.ts +0 -4
  17. package/dist/src/parser/index.d.ts +1 -1
  18. package/dist/src/parser/jsdoc-parser.d.ts +1 -1
  19. package/dist/src/parser/parse-source.d.ts +1 -1
  20. package/dist/src/parser/types.d.ts +3 -1
  21. package/dist/src/search/annotation-search.d.ts +1 -1
  22. package/dist/src/search/relation-search.d.ts +9 -3
  23. package/dist/src/search/symbol-search.d.ts +50 -6
  24. package/dist/src/semantic/index.d.ts +8 -1
  25. package/dist/src/semantic/tsc-program.d.ts +1 -1
  26. package/dist/src/semantic/type-collector.d.ts +7 -0
  27. package/dist/src/semantic/types.d.ts +9 -0
  28. package/dist/src/store/connection.d.ts +1 -1
  29. package/dist/src/store/repositories/annotation.repository.d.ts +1 -1
  30. package/dist/src/store/repositories/relation.repository.d.ts +8 -3
  31. package/dist/src/store/repositories/symbol.repository.d.ts +1 -1
  32. package/dist/src/store/schema.d.ts +38 -2
  33. package/dist/src/watcher/project-watcher.d.ts +1 -1
  34. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- var L$=Object.defineProperty;var I$=(u)=>u;function D$(u,_){this[u]=I$.bind(null,_)}var A$=(u,_)=>{for(var g in _)L$(u,g,{get:_[g],enumerable:!0,configurable:!0,set:D$.bind(_,g)})};var n_=import.meta.require;import{isErr as vu}from"@zipbul/result";import Eu from"path";import{existsSync as b0}from"fs";import{err as G_,isErr as q$}from"@zipbul/result";import{Database as j$}from"bun:sqlite";import{mkdirSync as F$,unlinkSync as v_,existsSync as E_}from"fs";import{dirname as n$,join as b_}from"path";import{drizzle as G$}from"drizzle-orm/bun-sqlite";import{migrate as v$}from"drizzle-orm/bun-sqlite/migrator";class w extends Error{type;constructor(u,_,g){super(_,g);this.type=u;this.name="GildashError"}}function $u(u,_,g){return new w(u,_,g!==void 0?{cause:g}:void 0)}var Yu=".gildash",yu="gildash.db";var u_={};A$(u_,{watcherOwner:()=>T$,symbols:()=>b,symbolChangelog:()=>Ju,relations:()=>L,files:()=>o,annotations:()=>Nu});import{sql as C$}from"drizzle-orm";import{sqliteTable as Du,text as n,integer as _u,real as S$,index as Qu,primaryKey as R$,foreignKey as fu,check as k$}from"drizzle-orm/sqlite-core";var o=Du("files",{project:n("project").notNull(),filePath:n("file_path").notNull(),mtimeMs:S$("mtime_ms").notNull(),size:_u("size").notNull(),contentHash:n("content_hash").notNull(),updatedAt:n("updated_at").notNull(),lineCount:_u("line_count")},(u)=>[R$({columns:[u.project,u.filePath]})]),b=Du("symbols",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),filePath:n("file_path").notNull(),kind:n("kind").notNull(),name:n("name").notNull(),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),isExported:_u("is_exported").notNull().default(0),signature:n("signature"),fingerprint:n("fingerprint"),detailJson:n("detail_json"),contentHash:n("content_hash").notNull(),indexedAt:n("indexed_at").notNull(),resolvedType:n("resolved_type"),structuralFingerprint:n("structural_fingerprint")},(u)=>[Qu("idx_symbols_project_file").on(u.project,u.filePath),Qu("idx_symbols_project_kind").on(u.project,u.kind),Qu("idx_symbols_project_name").on(u.project,u.name),Qu("idx_symbols_fingerprint").on(u.project,u.fingerprint),fu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),L=Du("relations",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),type:n("type").notNull(),srcFilePath:n("src_file_path").notNull(),srcSymbolName:n("src_symbol_name"),dstProject:n("dst_project").notNull(),dstFilePath:n("dst_file_path").notNull(),dstSymbolName:n("dst_symbol_name"),metaJson:n("meta_json")},(u)=>[Qu("idx_relations_src").on(u.project,u.srcFilePath),Qu("idx_relations_dst").on(u.dstProject,u.dstFilePath),Qu("idx_relations_type").on(u.project,u.type),Qu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),fu({columns:[u.project,u.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade"),fu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Nu=Du("annotations",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),filePath:n("file_path").notNull(),tag:n("tag").notNull(),value:n("value").notNull().default(""),source:n("source").notNull(),symbolName:n("symbol_name"),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),indexedAt:n("indexed_at").notNull()},(u)=>[Qu("idx_annotations_project_file").on(u.project,u.filePath),Qu("idx_annotations_project_tag").on(u.project,u.tag),Qu("idx_annotations_project_symbol").on(u.project,u.symbolName),fu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Ju=Du("symbol_changelog",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),changeType:n("change_type").notNull(),symbolName:n("symbol_name").notNull(),symbolKind:n("symbol_kind").notNull(),filePath:n("file_path").notNull(),oldName:n("old_name"),oldFilePath:n("old_file_path"),fingerprint:n("fingerprint"),changedAt:n("changed_at").notNull(),isFullIndex:_u("is_full_index").notNull().default(0),indexRunId:n("index_run_id").notNull()},(u)=>[Qu("idx_changelog_project_changed_at").on(u.project,u.changedAt),Qu("idx_changelog_project_name").on(u.project,u.symbolName),Qu("idx_changelog_project_run").on(u.project,u.indexRunId)]),T$=Du("watcher_owner",{id:_u("id").primaryKey(),pid:_u("pid").notNull(),startedAt:n("started_at").notNull(),heartbeatAt:n("heartbeat_at").notNull(),instanceId:n("instance_id")},(u)=>[k$("watcher_owner_singleton",C$`${u.id} = 1`)]);class __{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=b_(u.projectRoot,Yu,yu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{F$(n$(this.dbPath),{recursive:!0}),this.client=new j$(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=G$(this.client,{schema:u_}),v$(this.drizzle,{migrationsFolder:b_(import.meta.dirname,"migrations")});let u=this.client.prepare("PRAGMA foreign_key_check").all();if(u.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(u.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(u){if(this.isCorruptionError(u)&&E_(this.dbPath)){this.closeClient(),v_(this.dbPath);for(let g of["-wal","-shm"]){let $=this.dbPath+g;if(E_($))v_($)}let _=this.open();if(q$(_))return G_($u("store",`Failed to recover database at ${this.dbPath}`,_.data));return _}return G_($u("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let _=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return _.transaction(()=>u(this))()}finally{this.txDepth--}}let g=`sp_${this.txDepth++}`;_.run(`SAVEPOINT "${g}"`);try{let $=u(this);return _.run(`RELEASE SAVEPOINT "${g}"`),$}catch($){throw _.run(`ROLLBACK TO SAVEPOINT "${g}"`),_.run(`RELEASE SAVEPOINT "${g}"`),$}finally{this.txDepth--}}immediateTransaction(u){let _=this.requireClient();this.txDepth++,_.run("BEGIN IMMEDIATE");try{let g=u();return _.run("COMMIT"),g}catch(g){throw _.run("ROLLBACK"),g}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((_)=>_.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}replaceOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}touchOwner(u){let _=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(_,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let _=u;if(typeof _.function!=="function")return;_.function.call(u,"regexp",(g,$)=>{try{return new RegExp(g).test($)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(u){if(!(u instanceof Error))return!1;let _=u.message.toLowerCase();return _.includes("malformed")||_.includes("corrupt")||_.includes("not a database")||_.includes("disk i/o error")||_.includes("sqlite_corrupt")}}import{eq as Tu,and as y_}from"drizzle-orm";class g_{db;constructor(u){this.db=u}getFile(u,_){return this.db.drizzleDb.select().from(o).where(y_(Tu(o.project,u),Tu(o.filePath,_))).get()??null}upsertFile(u){this.db.drizzleDb.insert(o).values({project:u.project,filePath:u.filePath,mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}}).run()}getAllFiles(u){return this.db.drizzleDb.select().from(o).where(Tu(o.project,u)).all()}getFilesMap(u){let _=this.getAllFiles(u),g=new Map;for(let $ of _)g.set($.filePath,$);return g}deleteFile(u,_){this.db.drizzleDb.delete(o).where(y_(Tu(o.project,u),Tu(o.filePath,_))).run()}}import{eq as e,and as Ku,sql as Pu,count as E$}from"drizzle-orm";function Au(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((_)=>_.trim()).filter((_)=>_.length>0).map((_)=>`"${_.replaceAll('"','""')}"*`).join(" ")}var f_=50;class $_{db;constructor(u){this.db=u}replaceFileSymbols(u,_,g,$){if(this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,_))).run(),!$.length)return;let J=new Date().toISOString(),O=$.map((N)=>({project:u,filePath:_,kind:N.kind??"unknown",name:N.name??"",startLine:N.startLine??0,startColumn:N.startColumn??0,endLine:N.endLine??0,endColumn:N.endColumn??0,isExported:N.isExported??0,signature:N.signature??null,fingerprint:N.fingerprint??null,detailJson:N.detailJson??null,contentHash:g,indexedAt:N.indexedAt??J,resolvedType:N.resolvedType??null,structuralFingerprint:N.structuralFingerprint??null}));for(let N=0;N<O.length;N+=f_)this.db.drizzleDb.insert(b).values(O.slice(N,N+f_)).run()}getFileSymbols(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.filePath,_))).all()}searchByName(u,_,g={}){let $=g.limit??50,J=Au(_);if(!J)return[];return this.db.drizzleDb.select().from(b).where(Ku(Pu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${J})`,e(b.project,u),g.kind?e(b.kind,g.kind):void 0)).orderBy(b.name).limit($).all()}searchByKind(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.kind,_))).orderBy(b.name).all()}getStats(u){let _=this.db.drizzleDb.select({symbolCount:E$(),fileCount:Pu`COUNT(DISTINCT ${b.filePath})`}).from(b).where(e(b.project,u)).get();return{symbolCount:_?.symbolCount??0,fileCount:_?.fileCount??0}}getByFingerprint(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.fingerprint,_))).all()}deleteFileSymbols(u,_){this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,_))).run()}searchByQuery(u){let _=this.db.drizzleDb.select().from(b).where(Ku(u.ftsQuery?Pu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?e(b.name,u.exactName):void 0,u.project!==void 0?e(b.project,u.project):void 0,u.kind?e(b.kind,u.kind):void 0,u.filePath!==void 0?e(b.filePath,u.filePath):void 0,u.isExported!==void 0?e(b.isExported,u.isExported?1:0):void 0,u.decorator?Pu`${b.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${u.decorator})`:void 0,u.resolvedType!==void 0?e(b.resolvedType,u.resolvedType):void 0)).orderBy(b.name);if(!u.regex)return _.limit(u.limit).all();let g;try{g=new RegExp(u.regex)}catch{throw new w("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let J of[5,20,100]){let O=u.limit*J,N=_.limit(O).all();if($=N.filter((z)=>g.test(z.name)),$.length>=u.limit||N.length<O)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as c,and as Wu,isNull as P_,or as b$}from"drizzle-orm";class J_{db;constructor(u){this.db=u}replaceFileRelations(u,_,g){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).run(),!g.length)return;for(let J of g)$.drizzleDb.insert(L).values({project:u,type:J.type??"unknown",srcFilePath:J.srcFilePath??_,srcSymbolName:J.srcSymbolName??null,dstProject:J.dstProject??u,dstFilePath:J.dstFilePath??"",dstSymbolName:J.dstSymbolName??null,metaJson:J.metaJson??null}).run()})}getOutgoing(u,_,g){if(g!==void 0)return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.srcFilePath,_),b$(c(L.srcSymbolName,g),P_(L.srcSymbolName)))).all();return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).all()}getIncoming(u){let{dstProject:_,dstFilePath:g}=u;return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.dstProject,_),c(L.dstFilePath,g))).all()}getByType(u,_){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.type,_))).all()}deleteFileRelations(u,_){this.db.drizzleDb.delete(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).run()}searchRelations(u){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(u.project!==void 0?c(L.project,u.project):void 0,u.srcFilePath!==void 0?c(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?c(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?c(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?c(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?c(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?c(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:_,oldFile:g,oldSymbol:$,newFile:J,newSymbol:O,newDstProject:N}=u,z=$===null?Wu(c(L.dstProject,_),c(L.dstFilePath,g),P_(L.dstSymbolName)):Wu(c(L.dstProject,_),c(L.dstFilePath,g),c(L.dstSymbolName,$)),Q={dstFilePath:J,dstSymbolName:O};if(N!==void 0)Q.dstProject=N;this.db.drizzleDb.update(L).set(Q).where(z).run()}}import{err as m_}from"@zipbul/result";import{subscribe as y$}from"@parcel/watcher";import Q_ from"path";var f$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],P$=new Set(["package.json","tsconfig.json"]);function m$(u){return u.replaceAll("\\","/")}function h$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class N_{#u;#_;#g;#J;#$;#N;constructor(u,_=y$,g=console){this.#_=u.projectRoot,this.#g=[...f$,...u.ignorePatterns??[]],this.#J=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=_,this.#N=g}async start(u){try{this.#u=await this.#$(this.#_,(_,g)=>{if(_){this.#N.error($u("watcher","Callback error",_));return}try{for(let $ of g){let J=m$(Q_.relative(this.#_,$.path));if(J.startsWith(".."))continue;let O=Q_.basename(J),N=Q_.extname(J).toLowerCase();if(!P$.has(O)&&!this.#J.has(N))continue;if(J.endsWith(".d.ts"))continue;u({eventType:h$($.type),filePath:J})}}catch($){this.#N.error($u("watcher","Callback error",$))}},{ignore:this.#g})}catch(_){return m_($u("watcher","Failed to subscribe watcher",_))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return m_($u("watcher","Failed to close watcher",u))}}}import z_ from"path";import{promises as x$}from"fs";var i$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function mu(u){let _=[];for await(let g of x$.glob("**/package.json",{cwd:u,exclude:i$})){let $=z_.dirname(g).replaceAll("\\","/"),J=z_.join(u,g),O=await Bun.file(J).json(),N=typeof O?.name==="string"&&O.name.length>0?O.name:z_.basename($==="."?u:$);_.push({dir:$,project:N})}return _.sort((g,$)=>$.dir.length-g.dir.length),_}function s(u,_,g="default"){let $=u.replaceAll("\\","/");for(let J of _){if(J.dir===".")return J.project;if($===J.dir||$.startsWith(`${J.dir}/`))return J.project}return g}import h_ from"path";var Zu=new Map;async function p$(u){let _=Bun.file(u);if(!await _.exists())return null;try{let g=await _.text(),$=Bun.JSONC.parse(g);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function qu(u){if(Zu.has(u))return Zu.get(u)??null;let _=h_.join(u,"tsconfig.json"),g=await p$(_);if(!g)return Zu.set(u,null),null;let $=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!$)return Zu.set(u,null),null;let J=typeof $.baseUrl==="string"?$.baseUrl:null,O=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!J&&!O)return Zu.set(u,null),null;let N=J?h_.resolve(u,J):u,z=new Map;if(O)for(let[V,W]of Object.entries(O)){if(!Array.isArray(W))continue;let U=W.filter((X)=>typeof X==="string");z.set(V,U)}let Q={baseUrl:N,paths:z};return Zu.set(u,Q),Q}function hu(u){if(u){Zu.delete(u);return}Zu.clear()}import x_ from"path";function xu(u,_){return x_.relative(u,_).replaceAll("\\","/")}function Cu(u,_){return x_.resolve(u,_)}function Ou(u){let _=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(_)).toString(16).padStart(16,"0")}import{isErr as e_}from"@zipbul/result";import{err as l$}from"@zipbul/result";import{parseSync as d$}from"oxc-parser";function ju(u,_,g,$=d$){try{let{program:J,errors:O,comments:N}=$(u,_,g);return{filePath:u,program:J,errors:O,comments:N,sourceText:_}}catch(J){return l$($u("parse",`Failed to parse file: ${u}`,J))}}import{promises as c$}from"fs";import{join as r$}from"path";async function i_(u){let{projectRoot:_,extensions:g,ignorePatterns:$,fileRepo:J}=u,O=J.getFilesMap(),N=new Set,z=[],Q=[],V=$.map((U)=>new Bun.Glob(U));for await(let U of c$.glob("**/*",{cwd:_})){if(!g.some((Z)=>U.endsWith(Z)))continue;if(U.startsWith("node_modules/")||U.includes("/node_modules/"))continue;if(V.some((Z)=>Z.match(U)))continue;N.add(U);let X=r$(_,U),M=Bun.file(X),{size:I,lastModified:D}=M,T=O.get(U);if(!T){let Z=await M.text(),K=Ou(Z);z.push({filePath:U,contentHash:K,mtimeMs:D,size:I});continue}if(T.mtimeMs===D&&T.size===I){Q.push({filePath:U,contentHash:T.contentHash,mtimeMs:D,size:I});continue}let j=await M.text(),h=Ou(j);if(h===T.contentHash)Q.push({filePath:U,contentHash:h,mtimeMs:D,size:I});else z.push({filePath:U,contentHash:h,mtimeMs:D,size:I})}let W=[];for(let U of O.keys())if(!N.has(U))W.push(U);return{changed:z,unchanged:Q,deleted:W}}function iu(u){let _=[0];for(let g=0;g<u.length;g++)if(u[g]===`
3
- `)_.push(g+1);return _}function wu(u,_){let g=0,$=u.length-1;while(g<$){let J=g+$+1>>1;if(u[J]<=_)g=J;else $=J-1}return{line:g+1,column:_-u[g]}}import{err as a$}from"@zipbul/result";import{parse as s$}from"comment-parser";function pu(u){try{let _=u.trim();if(_.startsWith("/**"))_=_.slice(3);if(_.endsWith("*/"))_=_.slice(0,-2);let $=s$(`/** ${_} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((J)=>({tag:J.tag??"",name:J.name??"",type:J.type??"",description:J.description??"",optional:J.optional??!1,...J.default!==void 0?{default:J.default}:{}}))}}catch(_){return a$($u("parse","Failed to parse JSDoc comment",_))}}import{isErr as t$}from"@zipbul/result";function Su(u){let{program:_,sourceText:g,comments:$}=u,J=iu(g),O=$.filter((Z)=>Z.type==="Block"&&Z.value.startsWith("*")).sort((Z,K)=>Z.end-K.end),N=_.body.map((Z)=>Z.start??0).sort((Z,K)=>Z-K);function z(Z,K){return{start:wu(J,Z),end:wu(J,K)}}function Q(Z){let K=0,B=O.length-1,R=-1;while(K<=B){let S=K+B>>>1;if(O[S].end<=Z)R=S,K=S+1;else B=S-1}if(R<0)return;let q=O[R];K=0,B=N.length-1;while(K<=B){let S=K+B>>>1,G=N[S];if(G<=q.end)K=S+1;else if(G>=Z)B=S-1;else return}return`/*${q.value}*/`}function V(Z){if(!Z)return;let K=Z.typeAnnotation??Z;return g.slice(K.start,K.end)}function W(Z){if(!Z||Z.length===0)return[];return Z.map((K)=>{let B=K.expression;if(!B)return{name:"unknown"};if(B.type==="CallExpression"){let R=B.callee?.name??B.callee?.property?.name??"unknown",q=(B.arguments??[]).map((S)=>g.slice(S.start,S.end));return{name:R,arguments:q.length>0?q:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:g.slice(B.start,B.end)}})}function U(Z){let K=Z.type==="TSParameterProperty"?Z.parameter:Z;if(K?.type==="RestElement"){let E=`...${K.argument?.name??"unknown"}`,p=K.typeAnnotation,gu=p?V(p):void 0,r={name:E,isOptional:!1};if(gu)r.type=gu;return r}if(K?.type==="AssignmentPattern"){let{left:y,right:E}=K,p=y?.name??"unknown",gu=y?.typeAnnotation,r=gu?V(gu):void 0,uu=g.slice(E.start,E.end),Y=W(y?.decorators??[]),A={name:p,isOptional:!0,defaultValue:uu};if(r)A.type=r;if(Y.length>0)A.decorators=Y;return A}let B=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,q=K?.typeAnnotation,S=q?V(q):void 0,G=W(K?.decorators??[]),f={name:B,isOptional:R};if(S)f.type=S;if(G.length>0)f.decorators=G;return f}function X(Z,K){let B=[];if(K?.async)B.push("async");if(Z.static)B.push("static");if(Z.abstract)B.push("abstract");if(Z.readonly)B.push("readonly");if(Z.override)B.push("override");if(Z.declare)B.push("declare");if(Z.const)B.push("const");let R=Z.accessibility;if(R==="private")B.push("private");else if(R==="protected")B.push("protected");else if(R==="public")B.push("public");return B}function M(Z){let K=[];if(Z.superClass){let R=g.slice(Z.superClass.start,Z.superClass.end);K.push({kind:"extends",name:R})}let B=Z.implements??[];for(let R of B){let q=R.expression??R,S=g.slice(q.start,q.end);K.push({kind:"implements",name:S})}return K}function I(Z){let K=[];for(let B of Z.extends??[]){let R=B.expression??B,q=g.slice(R.start,R.end);K.push({kind:"extends",name:q})}return K}function D(Z){let K=[];for(let B of Z)if(B.type==="MethodDefinition"){let R=B.key?.name??"unknown",q=B.value,S=B.kind??"method",G=S==="constructor"?"constructor":S==="get"?"getter":S==="set"?"setter":"method",f=X(B,q),y=(q?.params??[]).map(U),E=V(q?.returnType),p={kind:"method",name:R,span:z(B.start,B.end),isExported:!1,methodKind:G,modifiers:f,parameters:y.length>0?y:void 0,returnType:E};K.push(p)}else if(B.type==="PropertyDefinition"){let R=B.key?.name??"unknown",q=X(B),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:q};K.push(S)}return K}function T(Z){let K=[];for(let B of Z)if(B.type==="TSMethodSignature"){let R=B.key?.name??"unknown",q=(B.params??[]).map(U),S=V(B.returnType);K.push({kind:"method",name:R,span:z(B.start,B.end),isExported:!1,modifiers:[],methodKind:"method",parameters:q.length>0?q:void 0,returnType:S})}else if(B.type==="TSPropertySignature"){let R=B.key?.name??"unknown",q=V(B.typeAnnotation),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:B.readonly?["readonly"]:[],returnType:q};K.push(S)}return K}function j(Z,K){let B=Z.type??"";if(B==="FunctionDeclaration"||B==="TSDeclareFunction"){let R=Z.id?.name??"default",q=(Z.params??[]).map(U),S=V(Z.returnType),G=X(Z,Z),f=W(Z.decorators??[]),y=Z.typeParameters?.params?.flatMap((p)=>{let gu=p.name?.name;return gu?[gu]:[]})||void 0,E={kind:"function",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:G,parameters:q.length>0?q:void 0,returnType:S,decorators:f.length>0?f:void 0};if(y&&y.length>0)E.typeParameters=y;return E}if(B==="ClassDeclaration"||B==="ClassExpression"){let R=Z.id?.name??"default",q=M(Z),S=D(Z.body?.body??[]),G=W(Z.decorators??[]),f=X(Z,Z),y=Z.typeParameters?.params?.flatMap((p)=>{let gu=p.name?.name;return gu?[gu]:[]})||void 0,E={kind:"class",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:f,heritage:q.length>0?q:void 0,members:S.length>0?S:void 0,decorators:G.length>0?G:void 0};if(y&&y.length>0)E.typeParameters=y;return E}if(B==="VariableDeclaration"){let R=[];for(let q of Z.declarations??[]){let{id:S,init:G}=q;if(S?.type==="ObjectPattern"){for(let r of S.properties??[]){let uu=r.value?.name??r.key?.name??"unknown";R.push({kind:"variable",name:uu,span:z(r.start??q.start,r.end??q.end),isExported:K,modifiers:[]})}continue}if(S?.type==="ArrayPattern"){for(let r of S.elements??[]){if(!r||r.type!=="Identifier")continue;let uu=r.name??"unknown";R.push({kind:"variable",name:uu,span:z(r.start??q.start,r.end??q.end),isExported:K,modifiers:[]})}continue}let f=S?.name??"unknown",y="variable",E,p;if(G?.type==="FunctionExpression"||G?.type==="ArrowFunctionExpression")y="function",E=(G.params??[]).map(U),p=V(G.returnType);let gu=[];R.push({kind:y,name:f,span:z(q.start,q.end),isExported:K,modifiers:gu,parameters:E,returnType:p})}if(R.length===0)return null;if(R.length===1)return R[0];return R}if(B==="TSTypeAliasDeclaration")return{kind:"type",name:Z.id?.name??"unknown",span:z(Z.start,Z.end),isExported:K,modifiers:[]};if(B==="TSInterfaceDeclaration"){let R=Z.id?.name??"unknown",q=I(Z),S=T(Z.body?.body??[]),G=Z.typeParameters?.params?.flatMap((y)=>{let E=y.name?.name;return E?[E]:[]})||void 0,f={kind:"interface",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:[],heritage:q.length>0?q:void 0,members:S.length>0?S:void 0};if(G&&G.length>0)f.typeParameters=G;return f}if(B==="TSEnumDeclaration"){let R=Z.id?.name??"unknown",q=X(Z),G=(Z.body?.members??[]).map((f)=>({kind:"property",name:f.id?.name??f.id?.value??"unknown",span:z(f.start,f.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:q,members:G.length>0?G:void 0}}return null}let h=[];for(let Z of _.body){let K=null,B=Z,R=typeof B.type==="string"?B.type:"";if(R==="ExportNamedDeclaration"){let S=Z;if(S.declaration){if(K=j(S.declaration,!0),K&&!Array.isArray(K))K.span=z(S.start,S.end);else if(Array.isArray(K))for(let G of K)G.span=z(S.start,S.end)}}else if(R==="ExportDefaultDeclaration"){let S=Z,G=S.declaration;if(G){if(K=j(G,!0),K&&!Array.isArray(K))K.name=G.id?.name??"default",K.isExported=!0,K.span=z(S.start,S.end)}}else K=j(Z,!1);let q=Array.isArray(K)?K:K?[K]:[];for(let S of q){let G=Z.start??0,f=Q(G);if(f){let y=pu(f);if(!t$(y))S.jsDoc=y}h.push(S)}}return h}function o$(u){if(u.kind==="function"||u.kind==="method"){let _=u.parameters?.length??0,g=u.modifiers.includes("async")?1:0;return`params:${_}|async:${g}`}return null}function e$(u){let _={};if(u.jsDoc)_.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)_.parameters=u.parameters;if(u.returnType!==void 0)_.returnType=u.returnType}if(u.heritage?.length)_.heritage=u.heritage;if(u.decorators?.length)_.decorators=u.decorators;if(u.typeParameters?.length)_.typeParameters=u.typeParameters;if(u.modifiers?.length)_.modifiers=u.modifiers;if(u.members?.length)_.members=u.members.map((g)=>{let $=g.modifiers.find((J)=>J==="private"||J==="protected"||J==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:$,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(_).length>0?JSON.stringify(_):null}function u0(u){let _=[u.kind];if(u.modifiers.length)_.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)_.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let g=[...u.heritage].sort(($,J)=>$.name.localeCompare(J.name)).map(($)=>`${$.kind}:${$.name}`).join(",");_.push(`her:${g}`)}if(u.decorators?.length)_.push(`dec:${[...u.decorators].map((g)=>g.name).sort().join(",")}`);if(u.methodKind)_.push(`mk:${u.methodKind}`);if(u.parameters)_.push(`p:${u.parameters.length}`);if(u.returnType)_.push(`rt:${u.returnType}`);if(u.members?.length){let g=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");_.push(`mem:${u.members.length}:${Ou(g)}`)}return Ou(_.join("|"))}function p_(u,_,g,$,J){let O=o$(u),N=Ou(`${_}|${u.kind}|${O??""}`),z=u0(u);return{project:g,filePath:$,kind:u.kind,name:_,startLine:u.span.start.line,startColumn:u.span.start.column,endLine:u.span.end.line,endColumn:u.span.end.column,isExported:u.isExported?1:0,signature:O,fingerprint:N,detailJson:e$(u),contentHash:J,indexedAt:new Date().toISOString(),structuralFingerprint:z}}function O_(u){let{parsed:_,project:g,filePath:$,contentHash:J,symbolRepo:O}=u,N=Su(_),z=[];for(let Q of N){z.push(p_(Q,Q.name,g,$,J));for(let V of Q.members??[])z.push(p_(V,`${Q.name}.${V.name}`,g,$,J))}O.replaceFileSymbols(g,$,J,z)}import{resolve as w_,dirname as _0,extname as g0}from"path";function Mu(u,_,g){let $=(J)=>{let O=g0(J);if(O==="")return[J+".ts",J+".d.ts",J+"/index.ts",J+"/index.d.ts",J+".mts",J+"/index.mts",J+".cts",J+"/index.cts"];if(O===".js")return[J.slice(0,-3)+".ts"];if(O===".mjs")return[J.slice(0,-4)+".mts"];if(O===".cjs")return[J.slice(0,-4)+".cts"];return[J]};if(_.startsWith(".")){let J=w_(_0(u),_);return $(J)}if(g)for(let[J,O]of g.paths){if(O.length===0)continue;let N=J.indexOf("*");if(N===-1){if(_===J){let z=[];for(let Q of O)z.push(...$(w_(g.baseUrl,Q)));return z}}else{let z=J.slice(0,N),Q=J.slice(N+1);if(_.startsWith(z)&&(Q===""||_.endsWith(Q))){let V=_.slice(z.length,Q===""?void 0:_.length-Q.length),W=[];for(let U of O)W.push(...$(w_(g.baseUrl,U.replace("*",V))));return W}}}return[]}function l_(u,_,g,$=Mu){let J=new Map,O=u.body??[];for(let N of O){if(N.type!=="ImportDeclaration")continue;let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.specifiers??[];for(let U of W)switch(U.type){case"ImportSpecifier":J.set(U.local.name,{path:V,importedName:U.imported.name});break;case"ImportDefaultSpecifier":J.set(U.local.name,{path:V,importedName:"default"});break;case"ImportNamespaceSpecifier":J.set(U.local.name,{path:V,importedName:"*"});break}}return J}var $0=new Set(["loc","start","end","scope"]);function Ru(u,_){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Ru($,_);return}let g=u;_(g);for(let $ of Object.keys(g)){if($0.has($))continue;let J=g[$];if(J&&typeof J==="object")Ru(J,_)}}function d_(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if((_.type==="StringLiteral"||_.type==="Literal")&&typeof _.value==="string")return _.value;return null}function Bu(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if(_.type==="Identifier"){let g=_.name;return{root:g,parts:[],full:g}}if(_.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(_.type==="Super")return{root:"super",parts:[],full:"super"};if(_.type==="MemberExpression"){let g=[],$=_;while($.type==="MemberExpression"){let N=$.property;if(!N||typeof N.name!=="string")return null;g.push(N.name),$=$.object}let J;if($.type==="Identifier")J=$.name;else if($.type==="ThisExpression")J="this";else if($.type==="Super")J="super";else return null;g.reverse();let O=[J,...g].join(".");return{root:J,parts:g,full:O}}return null}function c_(u,_,g,$=Mu){let J=[],O=u.body??[];for(let N of O){if(N.type==="ImportDeclaration"){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.importKind==="type",U=N.specifiers??[];if(U.length===0){let X={};if(W)X.isType=!0;J.push({type:W?"type-references":"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}else for(let X of U){let M=X.type,I=W||X.importKind==="type",D={};if(I)D.isType=!0;let T,j;if(M==="ImportDefaultSpecifier")T="default",j=X.local.name;else if(M==="ImportNamespaceSpecifier")T="*",j=X.local.name,D.importKind="namespace";else T=X.imported.name,j=X.local.name;J.push({type:I?"type-references":"imports",srcFilePath:_,srcSymbolName:j,dstFilePath:V,dstSymbolName:T,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}continue}if(N.type==="ExportAllDeclaration"&&N.source){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.exportKind==="type",U={isReExport:!0};if(W)U.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(U)});continue}if(N.type==="ExportNamedDeclaration"&&N.source){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.exportKind==="type",M={isReExport:!0,specifiers:(N.specifiers??[]).map((I)=>({local:I.local.name,exported:I.exported.name}))};if(W)M.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(M)})}}return Ru(u,(N)=>{if(N.type!=="ImportExpression")return;let z=d_(N.source);if(!z)return;let Q=$(_,z,g);if(Q.length===0)return;let V=Q[0];J.push({type:"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),J}function r_(u,_,g){let $=[],J=[],O=[];function N(){if(J.length>0)return J[J.length-1]??null;return null}function z(V){if(!V)return null;let W=g.get(V.root);if(V.parts.length===0){if(W)return{dstFilePath:W.path,dstSymbolName:W.importedName,resolution:"import"};return{dstFilePath:_,dstSymbolName:V.root,resolution:"local"}}else{if(W&&W.importedName==="*"){let U=V.parts[V.parts.length-1];return{dstFilePath:W.path,dstSymbolName:U,resolution:"namespace"}}return{dstFilePath:_,dstSymbolName:V.full,resolution:"local-member"}}}function Q(V){if(!V||typeof V!=="object")return;if(Array.isArray(V)){for(let X of V)Q(X);return}let W=V,U=typeof W.type==="string"?W.type:"";if(U==="ClassDeclaration"||U==="ClassExpression"){let X=W,M=X.id?.name??"AnonymousClass";O.push(M),Q(X.body),O.pop();return}if(U==="FunctionDeclaration"){let X=W,M=X.id?.name??"anonymous";J.push(M),Q(X.body),J.pop();return}if(U==="VariableDeclarator"&&W.init&&(W.init?.type==="FunctionExpression"||W.init?.type==="ArrowFunctionExpression")){let X=W,M=X.id?.name??"anonymous";J.push(M),Q(X.init?.body??X.init),J.pop();return}if(U==="MethodDefinition"&&W.value){let X=W,M=O[O.length-1]??"",I=X.key?.name??"anonymous",D=M?`${M}.${I}`:I;J.push(D),Q(X.value?.body),J.pop();return}if(U==="FunctionExpression"||U==="ArrowFunctionExpression"){let X=N(),M=X?`${X}.<anonymous>`:"<anonymous>";J.push(M),Q(W.body),J.pop();return}if(U==="CallExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let D=N(),T={};if(D===null)T.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}Q(X.callee);for(let D of X.arguments??[])Q(D);return}if(U==="NewExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let D=N(),T={isNew:!0};if(D===null)T.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(T)})}for(let D of X.arguments??[])Q(D);return}for(let X of Object.keys(W)){if(X==="loc"||X==="start"||X==="end"||X==="scope")continue;let M=W[X];if(M&&typeof M==="object")Q(M)}}return Q(u),$}function a_(u,_,g){let $=[];return Ru(u,(J)=>{if(J.type==="TSInterfaceDeclaration"){let z=J.id?.name??"AnonymousInterface",Q=J.extends??[];for(let V of Q){let W=V.expression??V,U=Bu(W);if(!U)continue;let X=W_(U,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:z,...X})}return}if(J.type!=="ClassDeclaration"&&J.type!=="ClassExpression")return;let O=J.id?.name??"AnonymousClass";if(J.superClass){let z=Bu(J.superClass);if(z){let Q=W_(z,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:O,...Q})}}let N=J.implements??[];for(let z of N){let Q=z.expression??z,V=Bu(Q);if(!V)continue;let W=W_(V,_,g);$.push({type:"implements",srcFilePath:_,srcSymbolName:O,...W})}}),$}function W_(u,_,g){let $=g.get(u.root);if($){if($.importedName==="*"){let J=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:J,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:_,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function lu(u,_,g,$=Mu){let J=l_(u,_,g,$),O=c_(u,_,g,$),N=r_(u,_,J),z=a_(u,_,J);return[...O,...N,...z]}function V_(u){let{ast:_,project:g,filePath:$,relationRepo:J,projectRoot:O,tsconfigPaths:N,knownFiles:z,boundaries:Q}=u,V=Cu(O,$),U=lu(_,V,N,z?(M,I,D)=>{let T=Mu(M,I,D);for(let j of T){let h=xu(O,j);if(Q){let Z=s(h,Q);if(z.has(`${Z}::${h}`))return[j]}else if(z.has(`${g}::${h}`))return[j]}return[]}:void 0),X=[];for(let M of U){let I=xu(O,M.dstFilePath);if(I.startsWith(".."))continue;let D=xu(O,M.srcFilePath),T=Q?s(I,Q):g;X.push({project:g,type:M.type,srcFilePath:D,srcSymbolName:M.srcSymbolName??null,dstProject:T,dstFilePath:I,dstSymbolName:M.dstSymbolName??null,metaJson:M.metaJson??null})}return J.replaceFileRelations(g,$,X),X.length}import{isErr as J0}from"@zipbul/result";var s_=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function Q0(u){let _=Su(u),g=[];for(let $ of _){g.push({name:$.name,startLine:$.span.start.line});for(let J of $.members??[])g.push({name:`${$.name}.${J.name}`,startLine:J.span.start.line})}return g.sort(($,J)=>$.startLine-J.startLine),g}function U_(u,_,g){let $=0,J=u.length-1;while($<=J){let O=$+J>>1;if(u[O].startLine<=_)$=O+1;else J=O-1}if($<u.length){let O=u[$];if(O.startLine-_<=g)return O.name}return null}function du(u,_,g){let $=wu(u,_),J=wu(u,g);return{start:$,end:J}}function t_(u){let{comments:_,sourceText:g}=u;if(!_.length)return[];let $=iu(g),J=Q0(u),O=[],N=[..._].sort((Q,V)=>Q.start-V.start),z=null;for(let Q of N)if(Q.type==="Block"&&Q.value.startsWith("*")){z=null;let V=`/*${Q.value}*/`,W=pu(V);if(J0(W))continue;let U=W;if(!U.tags?.length)continue;let X=wu($,Q.end),M=U_(J,X.line,3),I=g.slice(Q.start,Q.end);for(let D of U.tags){let T=[D.name,D.description].filter(Boolean).join(" "),j=`@${D.tag}`,h=I.indexOf(j),Z;if(h>=0){let K=Q.start+h,B=g.indexOf(`
4
- `,K),R=B>=0?Math.min(B,Q.end):Q.end;Z=du($,K,R)}else Z=du($,Q.start,Q.end);O.push({tag:D.tag,value:T,source:"jsdoc",span:Z,symbolName:M})}}else if(Q.type==="Block"){z=null;let V=Q.value.split(`
5
- `),W=0;for(let U of V){let X=U.replace(/^\s*\*?\s?/,""),M=s_.exec(X);if(M){let I=M[1],D=M[2]?.trim()??"",T=`@${I}`,j=U.indexOf(T),h=Q.start+2+W+(j>=0?j:0),Z=Q.start+2+W+U.length,K=du($,h,Z),B=wu($,Q.end),R=U_(J,B.line,3);O.push({tag:I,value:D,source:"block",span:K,symbolName:R})}W+=U.length+1}}else{let V=Q.value,W=s_.exec(V),U=wu($,Q.start),X=wu($,Q.end);if(W){let M=W[1],I=W[2]?.trim()??"",D=`@${M}`,T=V.indexOf(D),j=Q.start+2+(T>=0?T:0),h=du($,j,Q.end),Z=U_(J,X.line,3),K={tag:M,value:I,source:"line",span:h,symbolName:Z};O.push(K),z={annotation:K,endLine:X.line}}else if(z&&U.line===z.endLine+1){let M=V.trim();if(M)z.annotation.value+=" "+M,z.annotation.span.end=wu($,Q.end),z.endLine=X.line}else z=null}return O}function Y_(u){let{parsed:_,project:g,filePath:$,annotationRepo:J}=u,O=t_(_);if(J.deleteFileAnnotations(g,$),!O.length)return 0;let N=new Date().toISOString(),z=O.map((Q)=>({project:g,filePath:$,tag:Q.tag,value:Q.value,source:Q.source,symbolName:Q.symbolName,startLine:Q.span.start.line,startColumn:Q.span.start.column,endLine:Q.span.end.line,endColumn:Q.span.end.column,indexedAt:N}));return J.insertBatch(g,$,z),O.length}function o_(u,_){let g=[],$=[],J=[];for(let[W,U]of _)if(!u.has(W))g.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[W,U]of u)if(!_.has(W))$.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!g.length||!$.length)return{renamed:J,added:g,removed:$};let O=new Map,N=new Map;for(let W of g){let U=O.get(W.filePath)??[];U.push(W),O.set(W.filePath,U)}for(let W of $){let U=N.get(W.filePath)??[];U.push(W),N.set(W.filePath,U)}let z=new Set,Q=new Set;for(let[W,U]of O){let X=N.get(W);if(!X)continue;for(let M of new Set(U.map((I)=>I.kind))){let I=U.filter((Z)=>Z.kind===M&&!z.has(Z)),D=X.filter((Z)=>Z.kind===M&&!Q.has(Z));if(!I.length||!D.length)continue;let T=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.structuralFingerprint??null},j=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.startLine??0},h=new Map;for(let Z of D){let K=T(Z,u);if(!K)continue;let B=h.get(K)??[];B.push(Z),h.set(K,B)}for(let Z of I){if(z.has(Z))continue;let K=T(Z,_);if(!K)continue;let B=h.get(K);if(!B)continue;let R=B.filter((S)=>!Q.has(S));if(!R.length)continue;let q=R[0];if(R.length>1){let S=j(Z,_),G=Math.abs(j(q,u)-S);for(let f=1;f<R.length;f++){let y=Math.abs(j(R[f],u)-S);if(y<G)G=y,q=R[f]}}J.push({oldName:q.name,newName:Z.name,filePath:W,kind:M}),z.add(Z),Q.add(q)}}}let V=J.filter((W)=>!W.oldName.includes("."));for(let W of V){let U=`${W.oldName}.`,X=`${W.newName}.`,M=$.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(U)&&!Q.has(D)),I=g.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(X)&&!z.has(D));for(let D of M){let T=D.name.slice(U.length),j=I.find((h)=>h.name.slice(X.length)===T);if(j)J.push({oldName:D.name,newName:j.name,filePath:W.filePath,kind:D.kind}),z.add(j),Q.add(D)}}return{renamed:J,added:g.filter((W)=>!z.has(W)),removed:$.filter((W)=>!Q.has(W))}}var N0=100,ug=50;class Z_{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(u){this.opts=u,this.logger=u.logger??console,this.tsconfigPathsRaw=qu(u.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(u){return this.startIndex(u,!1)}onIndexed(u){return this.callbacks.add(u),()=>this.callbacks.delete(u)}handleWatcherEvent(u){if(u.filePath.endsWith("tsconfig.json")){hu(this.opts.projectRoot),this.tsconfigPathsRaw=qu(this.opts.projectRoot),this.fullIndex().catch((_)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",_)});return}if(u.filePath.endsWith("package.json")){let _=this.opts.discoverProjectsFn??mu;this.boundariesRefresh=_(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},N0)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,_){if(this.indexingLock){if(_)return this.pendingFullIndex=!0,new Promise(($,J)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:J})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(u,_).then(($)=>{return this.fireCallbacks($),$}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let $=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((J)=>{for(let O of $)O.resolve(J)}).catch((J)=>{for(let O of $)O.reject(J)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((J)=>this.logger.error("[IndexCoordinator] incremental drain error",J))}});return this.currentIndexing=g,g}async doIndex(u,_){let g=Date.now(),{fileRepo:$,symbolRepo:J,relationRepo:O,dbConnection:N}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let z,Q;if(u!==void 0)z=u.filter((Y)=>Y.eventType==="create"||Y.eventType==="change").map((Y)=>({filePath:Y.filePath,contentHash:"",mtimeMs:0,size:0})),Q=u.filter((Y)=>Y.eventType==="delete").map((Y)=>Y.filePath);else{let Y=new Map;for(let C of this.opts.boundaries)for(let[k,P]of $.getFilesMap(C.project))Y.set(k,P);let A=await i_({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Y}});z=A.changed,Q=A.deleted}let V=await this.tsconfigPathsRaw??void 0,W=new Map;for(let Y of Q){let A=s(Y,this.opts.boundaries),C=J.getFileSymbols(A,Y);W.set(Y,C)}let U=crypto.randomUUID(),X=new Map,M=new Map,I=(Y)=>({name:Y.name,filePath:Y.filePath,kind:Y.kind,fingerprint:Y.fingerprint,structuralFingerprint:Y.structuralFingerprint??null,startLine:Y.startLine,isExported:Y.isExported??0});if(_)for(let Y of this.opts.boundaries)for(let A of $.getAllFiles(Y.project))for(let C of J.getFileSymbols(Y.project,A.filePath))X.set(`${C.filePath}::${C.name}`,I(C));else{for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,Y.filePath))X.set(`${C.filePath}::${C.name}`,I(C))}for(let[,Y]of W)for(let A of Y)X.set(`${A.filePath}::${A.name}`,I(A))}let D=(Y)=>`${Y.type}|${Y.srcFilePath}|${Y.dstFilePath}|${Y.srcSymbolName??""}|${Y.dstSymbolName??""}|${Ou(Y.metaJson??"")}`,T=new Map;if(_)for(let Y of this.opts.boundaries)for(let A of $.getAllFiles(Y.project))for(let C of O.getOutgoing(Y.project,A.filePath))T.set(D(C),C);else{for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(A,Y.filePath))T.set(D(C),C)}for(let Y of Q){let A=s(Y,this.opts.boundaries);for(let C of O.getOutgoing(A,Y))T.set(D(C),C)}}let{annotationRepo:j,changelogRepo:h}=this.opts,Z=()=>{for(let Y of Q){let A=s(Y,this.opts.boundaries);if(J.deleteFileSymbols(A,Y),O.deleteFileRelations(A,Y),j)j.deleteFileAnnotations(A,Y);$.deleteFile(A,Y)}},K=0,B=async()=>{let{projectRoot:Y,boundaries:A}=this.opts,{parseCache:C}=this.opts,k=0,P=0,H=0,t=[],F=[];for(let v of z)try{let l=Cu(Y,v.filePath),Uu=Bun.file(l),Iu=await Uu.text(),j_=v.contentHash||Ou(Iu),F_=s(v.filePath,A);$.upsertFile({project:F_,filePath:v.filePath,mtimeMs:Uu.lastModified,size:Uu.size,contentHash:j_,updatedAt:new Date().toISOString(),lineCount:Iu.split(`
6
- `).length});let eu=(this.opts.parseSourceFn??ju)(l,Iu);if(e_(eu))throw eu.data;let H$=eu;F.push({filePath:v.filePath,text:Iu,contentHash:j_,parsed:H$,project:F_})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${v.filePath}:`,l),t.push(v.filePath)}let m=new Set;for(let v of A)for(let[l]of $.getFilesMap(v.project))m.add(`${v.project}::${l}`);return N.transaction(()=>{for(let v of F){if(O_({parsed:v.parsed,project:v.project,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:J}),P+=V_({ast:v.parsed.program,project:v.project,filePath:v.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:m,boundaries:A}),j)H+=Y_({parsed:v.parsed,project:v.project,filePath:v.filePath,annotationRepo:j});C.set(v.filePath,v.parsed),k+=J.getFileSymbols(v.project,v.filePath).length}}),{symbols:k,relations:P,annotations:H,failedFiles:t}},R=0,q=0,S=[];if(_){let{projectRoot:Y,boundaries:A}=this.opts,{parseCache:C}=this.opts,k=[];for(let H=0;H<z.length;H+=ug){let t=z.slice(H,H+ug),F=await Promise.allSettled(t.map(async(m)=>{let v=Cu(Y,m.filePath),l=Bun.file(v),Uu=await l.text(),Iu=m.contentHash||Ou(Uu);return{filePath:m.filePath,text:Uu,contentHash:Iu,mtimeMs:l.lastModified,size:l.size}}));for(let m=0;m<F.length;m++){let v=F[m];if(v.status==="fulfilled")k.push(v.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",v.reason),S.push(t[m].filePath)}}let P=[];N.transaction(()=>{for(let F of k){let m=s(F.filePath,A);$.deleteFile(m,F.filePath)}for(let F of Q){let m=s(F,A);if(J.deleteFileSymbols(m,F),O.deleteFileRelations(m,F),j)j.deleteFileAnnotations(m,F);$.deleteFile(m,F)}for(let F of k){let m=s(F.filePath,A);$.upsertFile({project:m,filePath:F.filePath,mtimeMs:F.mtimeMs,size:F.size,contentHash:F.contentHash,updatedAt:new Date().toISOString(),lineCount:F.text.split(`
7
- `).length})}let H=new Set;for(let F of A)for(let[m]of $.getFilesMap(F.project))H.add(`${F.project}::${m}`);let t=this.opts.parseSourceFn??ju;for(let F of k){let m=s(F.filePath,A),v=t(Cu(Y,F.filePath),F.text);if(e_(v))throw v.data;let l=v;if(P.push({filePath:F.filePath,parsed:l}),O_({parsed:l,project:m,filePath:F.filePath,contentHash:F.contentHash,symbolRepo:J}),j)K+=Y_({parsed:l,project:m,filePath:F.filePath,annotationRepo:j});q+=V_({ast:l.program,project:m,filePath:F.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:H,boundaries:A}),R+=J.getFileSymbols(m,F.filePath).length}});for(let H of P)C.set(H.filePath,H.parsed)}else{Z();let Y=await B();R=Y.symbols,q=Y.relations,K=Y.annotations,S=Y.failedFiles}for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,Y.filePath))M.set(`${C.filePath}::${C.name}`,I(C))}let G=new Map;for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(A,Y.filePath))G.set(D(C),C)}let f=(Y)=>({type:Y.type,srcFilePath:Y.srcFilePath,dstFilePath:Y.dstFilePath,srcSymbolName:Y.srcSymbolName,dstSymbolName:Y.dstSymbolName,dstProject:Y.dstProject,metaJson:Y.metaJson}),y={added:[...G.entries()].filter(([Y])=>!T.has(Y)).map(([,Y])=>f(Y)),removed:[...T.entries()].filter(([Y])=>!G.has(Y)).map(([,Y])=>f(Y))},E={added:[],modified:[],removed:[]};for(let[Y,A]of M){let C=X.get(Y);if(!C)E.added.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});else{let k=C.fingerprint!==A.fingerprint,P=C.isExported!==A.isExported,H=C.structuralFingerprint!==null&&A.structuralFingerprint!==null&&C.structuralFingerprint!==A.structuralFingerprint;if(k||P||H)E.modified.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)})}}for(let[Y,A]of X)if(!M.has(Y))E.removed.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});let p=o_(X,M),gu=new Set(p.renamed.map((Y)=>`${Y.filePath}::${Y.oldName}`)),r=new Set(p.renamed.map((Y)=>`${Y.filePath}::${Y.newName}`));E.added=E.added.filter((Y)=>!r.has(`${Y.filePath}::${Y.name}`)),E.removed=E.removed.filter((Y)=>!gu.has(`${Y.filePath}::${Y.name}`));let uu=[];if(!_){for(let[Y,A]of W)for(let C of A){if(!C.fingerprint)continue;let k=s(Y,this.opts.boundaries),P=J.getByFingerprint(k,C.fingerprint);if(P.length===1){let H=P[0];O.retargetRelations({dstProject:k,oldFile:Y,oldSymbol:C.name,newFile:H.filePath,newSymbol:H.name}),uu.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:Y,isExported:H.isExported??0})}}for(let Y of p.removed){let C=X.get(`${Y.filePath}::${Y.name}`)?.fingerprint;if(!C)continue;let k=s(Y.filePath,this.opts.boundaries),P=J.getByFingerprint(k,C);if(P.length===1){let H=P[0];if(H.filePath!==Y.filePath||H.name!==Y.name)O.retargetRelations({dstProject:k,oldFile:Y.filePath,oldSymbol:Y.name,newFile:H.filePath,newSymbol:H.name}),uu.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:Y.filePath,isExported:H.isExported??0})}}}if(uu.length){let Y=new Set(uu.map((C)=>`${C.filePath}::${C.name}`)),A=new Set(uu.map((C)=>`${C.oldFilePath}::${C.name}`));E.added=E.added.filter((C)=>!Y.has(`${C.filePath}::${C.name}`)),E.removed=E.removed.filter((C)=>!A.has(`${C.filePath}::${C.name}`))}if(h){let Y=new Date().toISOString(),A=_?1:0,C=[];for(let k of E.added){let P=`${k.filePath}::${k.name}`,H=M.get(P),t=s(k.filePath,this.opts.boundaries);C.push({project:t,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of E.modified){let P=M.get(`${k.filePath}::${k.name}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"modified",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of E.removed){let P=`${k.filePath}::${k.name}`,H=X.get(P),t=s(k.filePath,this.opts.boundaries);C.push({project:t,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of p.renamed){let P=M.get(`${k.filePath}::${k.newName}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"renamed",symbolName:k.newName,symbolKind:k.kind,filePath:k.filePath,oldName:k.oldName,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of uu){let P=M.get(`${k.filePath}::${k.name}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"moved",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:k.oldFilePath,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}if(C.length)try{N.transaction(()=>{h.insertBatch(C)})}catch(k){this.logger.error("[IndexCoordinator] changelog insert failed:",k)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let k=new Date(Date.now()-2592000000).toISOString();try{for(let P of this.opts.boundaries)h.pruneOlderThan(P.project,k)}catch(P){this.logger.error("[IndexCoordinator] changelog pruning failed:",P)}}}return{indexedFiles:z.length,removedFiles:Q.length,totalSymbols:R,totalRelations:q,totalAnnotations:K,durationMs:Date.now()-g,changedFiles:z.map((Y)=>Y.filePath),deletedFiles:[...Q],failedFiles:S,changedSymbols:E,renamedSymbols:p.renamed.map((Y)=>({oldName:Y.oldName,newName:Y.newName,filePath:Y.filePath,kind:Y.kind,isExported:Boolean(M.get(`${Y.filePath}::${Y.newName}`)?.isExported)})),movedSymbols:uu.map((Y)=>({name:Y.name,oldFilePath:Y.oldFilePath,newFilePath:Y.filePath,kind:Y.kind,isExported:Boolean(Y.isExported)})),changedRelations:y}}fireCallbacks(u){for(let _ of this.callbacks)try{_(u)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((_)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",_))}}}function z0(u){try{return process.kill(u,0),!0}catch(_){if(typeof _==="object"&&_&&"code"in _)return _.code!=="ESRCH";return!0}}function O0(u){let _=new Date(u).getTime();return Number.isNaN(_)?0:_}function _g(u,_,g={}){let $=g.now??Date.now,J=g.isAlive??z0,O=g.staleAfterSeconds??60,N=g.instanceId;return u.immediateTransaction(()=>{let z=u.selectOwner();if(!z)return u.insertOwner(_,N),"owner";let Q=Math.floor(($()-O0(z.heartbeat_at))/1000),V=J(z.pid);if(V&&N&&z.instance_id&&z.instance_id!==N&&z.pid!==_)return u.replaceOwner(_,N),"owner";if(V&&Q<O)return"reader";return u.replaceOwner(_,N),"owner"})}function gg(u,_){u.deleteOwner(_)}function $g(u,_){u.touchOwner(_)}class Fu{#u;#_=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#_.size}has(u){return this.#_.has(u)}get(u){if(!this.#_.has(u))return;let _=this.#_.get(u);return this.#_.delete(u),this.#_.set(u,_),_}set(u,_){if(this.#_.has(u))this.#_.delete(u);if(this.#_.set(u,_),this.#_.size>this.#u){let g=this.#_.keys().next().value;if(g!==void 0)this.#_.delete(g)}}delete(u){return this.#_.delete(u)}clear(){this.#_.clear()}}class X_{lru;constructor(u=500){this.lru=new Fu(u)}get(u){return this.lru.get(u)}set(u,_){this.lru.set(u,_)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function K_(u){let{symbolRepo:_,project:g,query:$}=u,J=$.project??g,O=$.limit??100,N={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:J,limit:O,resolvedType:$.resolvedType};if($.text)if($.exact)N.exactName=$.text;else{let Q=Au($.text);if(Q)N.ftsQuery=Q}if($.decorator)N.decorator=$.decorator;if($.regex)N.regex=$.regex;return _.searchByQuery(N).map((Q)=>({id:Q.id,filePath:Q.filePath,kind:Q.kind,name:Q.name,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}},isExported:Q.isExported===1,signature:Q.signature,fingerprint:Q.fingerprint,detail:Q.detailJson?(()=>{try{return JSON.parse(Q.detailJson)}catch{return{}}})():{}}))}function M_(u){let{relationRepo:_,project:g,query:$}=u;if($.srcFilePath&&$.srcFilePathPattern)throw new w("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if($.dstFilePath&&$.dstFilePathPattern)throw new w("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let J=$.project??g,O=$.limit??500,N=!!($.srcFilePathPattern||$.dstFilePathPattern),z=N?Number.MAX_SAFE_INTEGER:O,V=_.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:J,limit:z}).map((W)=>{let U;if(W.metaJson)try{U=JSON.parse(W.metaJson)}catch{}return{type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,dstProject:W.dstProject,metaJson:W.metaJson??void 0,meta:U}});if($.srcFilePathPattern||$.dstFilePathPattern){let W=$.srcFilePathPattern?new Bun.Glob($.srcFilePathPattern):null,U=$.dstFilePathPattern?new Bun.Glob($.dstFilePathPattern):null;V=V.filter((X)=>(!W||W.match(X.srcFilePath))&&(!U||U.match(X.dstFilePath)))}if(N&&V.length>O)V=V.slice(0,O);return V}import{findInFiles as w0,Lang as W0}from"@ast-grep/napi";async function B_(u){if(u.filePaths.length===0)return[];let _=[];return await w0(W0.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(g,$)=>{if(g){console.warn("[patternSearch] findInFiles callback error:",g);return}for(let J of $){let O=J.range();_.push({filePath:J.getRoot().filename(),startLine:O.start.line+1,endLine:O.end.line+1,matchedText:J.text()})}}),_}import d from"typescript";import{isErr as C0}from"@zipbul/result";import Vu from"typescript";import V0 from"path";import{err as H_}from"@zipbul/result";function U0(u){try{return n_("fs").readFileSync(u,"utf-8")}catch{return}}function Y0(u){try{return n_("fs").readFileSync(u,"utf-8")}catch{return}}class cu{#u;#_;#g=!1;__testing__;constructor(u,_){this.#u=u,this.#_=_,this.__testing__={host:_}}static create(u,_={}){let g=_.readConfigFile??U0,$=_.resolveNonTrackedFile??Y0,J=V0.dirname(u),O=g(u);if(O===void 0)return H_($u("semantic",`tsconfig not found: ${u}`));let N=Vu.parseJsonText(u,O),z=N.parseDiagnostics;if(z&&z.length>0){let U=z.map((X)=>Vu.flattenDiagnosticMessageText(X.messageText,`
8
- `)).join("; ");return H_($u("semantic",`tsconfig parse error: ${U}`))}let Q=Vu.parseJsonSourceFileConfigFileContent(N,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>g(U)!==void 0||$(U)!==void 0,readFile:(U)=>g(U)??$(U)},J);if(Q.errors.length>0){let U=Q.errors.filter((X)=>X.category===Vu.DiagnosticCategory.Error&&X.code!==18003);if(U.length>0){let X=U.map((M)=>Vu.flattenDiagnosticMessageText(M.messageText,`
9
- `)).join("; ");return H_($u("semantic",`tsconfig compile error: ${X}`))}}let V=new Jg(Q.fileNames,Q.options,J,$),W=Vu.createLanguageService(V);return new cu(W,V)}get isDisposed(){return this.#g}getProgram(){this.#J();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#J(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#J(),this.#u}notifyFileChanged(u,_){if(this.#g)return;this.#_.updateFile(u,_)}removeFile(u){if(this.#g)return;this.#_.removeFile(u)}dispose(){if(this.#g)return;this.#g=!0,this.#u.dispose()}#J(){if(this.#g)throw Error("TscProgram is disposed")}}class Jg{#u;#_;#g;#J;#$=new Map;constructor(u,_,g,$){this.#u=new Set(u),this.#_=_,this.#g=g,this.#J=$}updateFile(u,_){let g=this.#$.get(u);if(g)g.version+=1,g.content=_;else this.#$.set(u,{version:1,content:_})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((g)=>!this.#$.has(g)),...u]}getScriptVersion(u){let _=this.#$.get(u);return _?String(_.version):"0"}getScriptSnapshot(u){let _=this.#$.get(u);if(_)return Vu.ScriptSnapshot.fromString(_.content);let g=this.#J(u);if(g!==void 0)return Vu.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#_}getDefaultLibFileName(u){return Vu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#J(u)!==void 0}readFile(u){let _=this.#$.get(u);if(_)return _.content;return this.#J(u)}}import a from"typescript";import Z0 from"typescript";function zu(u,_){if(_<0||_>=u.getEnd())return;function g($){let J=$.getStart(u,!1),O=$.getEnd();if(_<J||_>=O)return;let N;return Z0.forEachChild($,(z)=>{if(!N)N=g(z)}),N??$}return g(u)}var L_=8;function X0(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function nu(u,_,g=0){let $=u.typeToString(_),J=_.flags,O=!!(J&a.TypeFlags.Union),N=!!(J&a.TypeFlags.Intersection),z;if(g<L_&&X0(_)){let U=u.getTypeArguments(_);if(U.length>0)z=U}let Q=!!(J&a.TypeFlags.TypeParameter)||z!==void 0&&z.length>0,V;if(O&&g<L_)V=_.types.map((U)=>nu(u,U,g+1));else if(N&&g<L_)V=_.types.map((U)=>nu(u,U,g+1));let W;if(z&&z.length>0)W=z.map((U)=>nu(u,U,g+1));return{text:$,flags:J,isUnion:O,isIntersection:N,isGeneric:Q,members:V,typeArguments:W}}function K0(u){return a.isFunctionDeclaration(u)||a.isVariableDeclaration(u)||a.isClassDeclaration(u)||a.isInterfaceDeclaration(u)||a.isTypeAliasDeclaration(u)||a.isEnumDeclaration(u)||a.isMethodDeclaration(u)||a.isPropertyDeclaration(u)||a.isPropertySignature(u)||a.isMethodSignature(u)}class I_{program;constructor(u){this.program=u}collectAt(u,_){let g=this.program.getProgram(),$=this.program.getChecker();if(_<0)return null;let J=g.getSourceFile(u);if(!J)return null;if(_>=J.getEnd())return null;let O=zu(J,_);if(!O)return null;if(!a.isIdentifier(O)&&!a.isTypeNode(O))return null;try{let N=$.getTypeAtLocation(O);return nu($,N)}catch{return null}}isAssignableTo(u,_,g,$){let J=this.program.getChecker(),O=this.program.getProgram(),N=O.getSourceFile(u);if(!N)return null;let z=zu(N,_);if(!z||!a.isIdentifier(z))return null;let Q=O.getSourceFile(g);if(!Q)return null;let V=zu(Q,$);if(!V||!a.isIdentifier(V))return null;try{let W=J.getTypeAtLocation(z),U=J.getTypeAtLocation(V);return J.isTypeAssignableTo(W,U)}catch{return null}}isAssignableToType(u,_,g,$){let J=this.program.getChecker(),N=this.program.getProgram().getSourceFile(u);if(!N)return null;let z=zu(N,_);if(!z||!a.isIdentifier(z)&&!a.isTypeNode(z))return null;let Q=`${u}.__gildash_probe__.ts`,V=`declare const __gildash_probe__: ${g};`;this.program.notifyFileChanged(Q,V);try{let W=J.getTypeAtLocation(z),X=this.program.getProgram().getSourceFile(Q);if(!X)return null;let M=this.program.getChecker(),I=X.statements[0];if(!I||!a.isVariableStatement(I))return null;let D=I.declarationList.declarations[0];if(!D)return null;let T=M.getTypeAtLocation(D.name);if($?.anyConstituent&&W.isUnion())return W.types.some((j)=>M.isTypeAssignableTo(j,T));return M.isTypeAssignableTo(W,T)}catch{return null}finally{this.program.removeFile(Q)}}collectFile(u){let _=new Map,g=this.program.getProgram(),$=this.program.getChecker(),J=g.getSourceFile(u);if(!J)return _;function O(N){if(K0(N)&&N.name&&a.isIdentifier(N.name)){let z=N.name;try{let Q=$.getTypeAtLocation(z),V=z.getStart(J);_.set(V,nu($,Q))}catch{}}a.forEachChild(N,O)}return O(J),_}}import Xu from"typescript";var M0=1000,B0=1;function H0(u){let _=u.declarations?.[0],g=_?.getSourceFile(),$=_?Xu.getNameOfDeclaration(_):void 0;return{name:u.getName(),filePath:g?.fileName??"",position:$?.getStart(g,!1)??_?.getStart(g,!1)??0}}function ru(u,_=0){let g=u.declarations?.[0],$=g?.getSourceFile(),J=g?Xu.getNameOfDeclaration(g):void 0,O=$?.fileName??"",N=J?.getStart($,!1)??g?.getStart($,!1)??0,z={name:u.getName(),filePath:O,position:N},Q=u;if(Q.parent)z.parent=H0(Q.parent);if(_<B0){let V=u.flags,W=!!(V&Xu.SymbolFlags.Enum),U=!!(V&(Xu.SymbolFlags.NamespaceModule|Xu.SymbolFlags.ValueModule)),X=!!(V&(Xu.SymbolFlags.Class|Xu.SymbolFlags.Interface));if(W&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(ru(I,_+1))}),z.members=M}else if(X&&u.members&&u.members.size>0){let M=[];u.members.forEach((I)=>{M.push(ru(I,_+1))}),z.members=M}if(U&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(ru(I,_+1))}),z.exports=M}}return z}class D_{#u;#_;#g=new Map;constructor(u,_=M0){this.#u=u,this.#_=new Fu(_)}get(u,_){if(this.#u.isDisposed)return null;let g=`${u}:${_}`,$=this.#_.get(g);if($!==void 0)return $;let O=this.#u.getProgram().getSourceFile(u);if(!O)return null;let N=zu(O,_);if(!N||!Xu.isIdentifier(N))return null;let Q=this.#u.getChecker().getSymbolAtLocation(N);if(!Q)return null;let V=ru(Q);this.#_.set(g,V);let W=this.#g.get(u);if(!W)W=new Set,this.#g.set(u,W);return W.add(g),V}invalidate(u){let _=this.#g.get(u);if(_){for(let g of _)this.#_.delete(g);this.#g.delete(u)}}clear(){this.#_.clear(),this.#g.clear()}}import L0 from"typescript";class A_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=zu($,_);if(!J||!L0.isIdentifier(J))return[];let N=this.#u.getLanguageService().findReferences(u,_);if(!N||N.length===0)return[];let z=[];for(let Q of N)for(let V of Q.references){let W=g.getSourceFile(V.fileName);if(!W)continue;let{line:U,character:X}=W.getLineAndCharacterOfPosition(V.textSpan.start);z.push({filePath:V.fileName,position:V.textSpan.start,line:U+1,column:X,isDefinition:V.isDefinition??!1,isWrite:V.isWriteAccess??!1})}return z}}import x from"typescript";function I0(u,_){let g=zu(u,_);if(!g)return;if(Qg(g))return g;let $=g.parent;for(let J=0;J<5&&$;J++){if(Qg($))return $;$=$.parent}return g}function Qg(u){return x.isClassDeclaration(u)||x.isClassExpression(u)||x.isFunctionDeclaration(u)||x.isFunctionExpression(u)||x.isArrowFunction(u)||x.isVariableDeclaration(u)||x.isObjectLiteralExpression(u)}function Ng(u){if(x.isClassDeclaration(u)||x.isClassExpression(u))return"class";if(x.isFunctionDeclaration(u)||x.isFunctionExpression(u)||x.isArrowFunction(u))return"function";if(x.isObjectLiteralExpression(u))return"object";if(x.isVariableDeclaration(u)&&u.initializer)return Ng(u.initializer);return"class"}function D0(u,_){if(x.isClassDeclaration(u)||x.isFunctionDeclaration(u))return u.name?.getText(_)??"";if(x.isClassExpression(u))return u.name?.getText(_)??"";if(x.isVariableDeclaration(u)&&x.isIdentifier(u.name))return u.name.getText(_);if(x.isFunctionExpression(u))return u.name?.getText(_)??"";if(x.isArrowFunction(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(_)}if(x.isObjectLiteralExpression(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(_)}return""}function A0(u){if(!x.isClassDeclaration(u)&&!x.isClassExpression(u))return!1;let _=u.heritageClauses;if(!_)return!1;return _.some((g)=>g.token===x.SyntaxKind.ImplementsKeyword)}class C_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=zu($,_);if(!J||!x.isIdentifier(J))return[];let N=this.#u.getLanguageService().getImplementationAtPosition(u,_);if(!N||N.length===0)return[];let z=[];for(let Q of N){if(Q.kind===x.ScriptElementKind.interfaceElement||Q.kind===x.ScriptElementKind.typeElement)continue;let V=g.getSourceFile(Q.fileName);if(!V)continue;let W=I0(V,Q.textSpan.start);if(!W)continue;let U=Ng(W),X=D0(W,V),M=A0(W);z.push({filePath:Q.fileName,symbolName:X,position:Q.textSpan.start,kind:U,isExplicit:M})}return z}}function zg(u){return d.canHaveModifiers(u)&&d.getModifiers(u)?.some((_)=>_.kind===d.SyntaxKind.ExportKeyword)===!0}function S0(u){if(d.isFunctionDeclaration(u))return"function";if(d.isClassDeclaration(u))return"class";if(d.isInterfaceDeclaration(u))return"interface";if(d.isTypeAliasDeclaration(u))return"type";if(d.isEnumDeclaration(u))return"enum";if(d.isVariableDeclaration(u))return"const";if(d.isVariableStatement(u))return"const";return"unknown"}function Og(u){if(u>=97&&u<=122)return!0;if(u>=65&&u<=90)return!0;if(u>=48&&u<=57)return!0;if(u===95||u===36)return!0;return!1}class au{#u;#_;#g;#J;#$;#N=!1;constructor(u,_,g,$,J){this.#u=u,this.#_=_,this.#g=g,this.#J=$,this.#$=J}static create(u,_={}){let g=cu.create(u,{readConfigFile:_.readConfigFile,resolveNonTrackedFile:_.resolveNonTrackedFile});if(C0(g))return g;let $=g,J=_.typeCollector??new I_($),O=_.symbolGraph??new D_($),N=_.referenceResolver??new A_($),z=_.implementationFinder??new C_($);return new au($,J,O,N,z)}get isDisposed(){return this.#N}collectTypeAt(u,_){return this.#Q(),this.#_.collectAt(u,_)}collectFileTypes(u){return this.#Q(),this.#_.collectFile(u)}findReferences(u,_){return this.#Q(),this.#J.findAt(u,_)}findImplementations(u,_){return this.#Q(),this.#$.findAt(u,_)}isTypeAssignableTo(u,_,g,$){return this.#Q(),this.#_.isAssignableTo(u,_,g,$)}isTypeAssignableToType(u,_,g,$){return this.#Q(),this.#_.isAssignableToType(u,_,g,$)}getSymbolNode(u,_){return this.#Q(),this.#g.get(u,_)}getModuleInterface(u){this.#Q();let _=this.#_.collectFile(u),g=[],J=this.#u.getProgram().getSourceFile(u);if(!J)return{filePath:u,exports:g};function O(N){if(d.isVariableStatement(N)&&zg(N)){for(let z of N.declarationList.declarations)if(d.isIdentifier(z.name)){let Q=z.name.getStart(J),V=_.get(Q)??null;g.push({name:z.name.text,kind:"const",resolvedType:V})}return}if((d.isFunctionDeclaration(N)||d.isClassDeclaration(N)||d.isInterfaceDeclaration(N)||d.isTypeAliasDeclaration(N)||d.isEnumDeclaration(N))&&zg(N)&&N.name){let z=N.name,Q=z.getStart(J),V=_.get(Q)??null;g.push({name:z.text,kind:S0(N),resolvedType:V});return}d.forEachChild(N,O)}return O(J),{filePath:u,exports:g}}notifyFileChanged(u,_){if(this.#N)return;this.#u.notifyFileChanged(u,_),this.#g.invalidate(u)}notifyFileDeleted(u){if(this.#N)return;this.#u.removeFile(u),this.#g.invalidate(u)}lineColumnToPosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return d.getPositionOfLineAndCharacter($,_-1,g)}catch{return null}}findNamePosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let J=$.getFullText(),O=_;while(O<J.length){let N=J.indexOf(g,O);if(N<0)return null;let z=N>0?J.charCodeAt(N-1):32,Q=N+g.length<J.length?J.charCodeAt(N+g.length):32;if(!Og(z)&&!Og(Q))return N;O=N+1}return null}getDiagnostics(u,_){this.#Q();let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J={[d.DiagnosticCategory.Error]:"error",[d.DiagnosticCategory.Warning]:"warning",[d.DiagnosticCategory.Suggestion]:"suggestion",[d.DiagnosticCategory.Message]:"suggestion"};return((_?.preEmit)?d.getPreEmitDiagnostics(g,$):g.getSemanticDiagnostics($)).map((N)=>{let z=1,Q=0;if(N.file&&N.start!==void 0){let V=d.getLineAndCharacterOfPosition(N.file,N.start);z=V.line+1,Q=V.character}return{filePath:N.file?.fileName??u,line:z,column:Q,message:d.flattenDiagnosticMessageText(N.messageText,`
10
- `),code:N.code,category:J[N.category]??"error"}})}dispose(){if(this.#N)return;this.#N=!0,this.#u.dispose(),this.#g.clear()}#Q(){if(this.#N)throw Error("SemanticLayer is disposed")}}import{eq as Hu,and as wg,sql as R0}from"drizzle-orm";var Wg=80;class S_{db;constructor(u){this.db=u}insertBatch(u,_,g){if(!g.length)return;let $=g.map((J)=>({project:u,filePath:_,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.startLine,startColumn:J.startColumn,endLine:J.endLine,endColumn:J.endColumn,indexedAt:J.indexedAt}));for(let J=0;J<$.length;J+=Wg)this.db.drizzleDb.insert(Nu).values($.slice(J,J+Wg)).run()}deleteFileAnnotations(u,_){this.db.drizzleDb.delete(Nu).where(wg(Hu(Nu.project,u),Hu(Nu.filePath,_))).run()}search(u){return this.db.drizzleDb.select().from(Nu).where(wg(u.project?Hu(Nu.project,u.project):void 0,u.tag?Hu(Nu.tag,u.tag):void 0,u.filePath?Hu(Nu.filePath,u.filePath):void 0,u.symbolName?Hu(Nu.symbolName,u.symbolName):void 0,u.source?Hu(Nu.source,u.source):void 0,u.ftsQuery?R0`${Nu.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as ku,and as Vg,sql as Gu,gt as k0,gte as T0}from"drizzle-orm";var Ug=80;class R_{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let _=u.map((g)=>({project:g.project,changeType:g.changeType,symbolName:g.symbolName,symbolKind:g.symbolKind,filePath:g.filePath,oldName:g.oldName,oldFilePath:g.oldFilePath,fingerprint:g.fingerprint,changedAt:g.changedAt,isFullIndex:g.isFullIndex,indexRunId:g.indexRunId}));for(let g=0;g<_.length;g+=Ug)this.db.drizzleDb.insert(Ju).values(_.slice(g,g+Ug)).run()}getSince(u){return this.db.drizzleDb.select().from(Ju).where(Vg(ku(Ju.project,u.project),T0(Ju.changedAt,u.since),u.symbolName?ku(Ju.symbolName,u.symbolName):void 0,u.changeTypes?.length?Gu`${Ju.changeType} IN (${Gu.join(u.changeTypes.map((_)=>Gu`${_}`),Gu`, `)})`:void 0,u.filePath?ku(Ju.filePath,u.filePath):void 0,u.includeFullIndex?void 0:ku(Ju.isFullIndex,0),u.indexRunId?ku(Ju.indexRunId,u.indexRunId):void 0,u.afterId?k0(Ju.id,u.afterId):void 0)).orderBy(Ju.id).limit(u.limit).all()}pruneOlderThan(u,_){return this.db.drizzleDb.delete(Ju).where(Vg(ku(Ju.project,u),Gu`${Ju.changedAt} < ${_}`)).run().changes}}function Yg(u){let{annotationRepo:_,project:g,query:$}=u,J=$.project??g,O=$.limit??100,N;if($.text){let Q=Au($.text);if(Q)N=Q}return _.search({project:J,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:N,limit:O}).map((Q)=>({tag:Q.tag,value:Q.value,source:Q.source,filePath:Q.filePath,symbolName:Q.symbolName,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}}}))}class su{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let _=[this.options.project,...this.options.additionalProjects??[]].flatMap((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of _){let{srcFilePath:$,dstFilePath:J}=g;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(J),!this.adjacencyList.has(J))this.adjacencyList.set(J,new Set);if(!this.reverseAdjacencyList.has(J))this.reverseAdjacencyList.set(J,new Set);this.reverseAdjacencyList.get(J).add($)}}patchFiles(u,_,g){let $=new Set([...u,..._]);for(let J of $){let O=this.adjacencyList.get(J);if(O){for(let z of O)this.reverseAdjacencyList.get(z)?.delete(J);O.clear()}let N=this.reverseAdjacencyList.get(J);if(N){for(let z of N)this.adjacencyList.get(z)?.delete(J);N.clear()}}for(let J of _)this.adjacencyList.delete(J),this.reverseAdjacencyList.delete(J);for(let J of u){let O=g(J);for(let N of O){if(!this.adjacencyList.has(N.srcFilePath))this.adjacencyList.set(N.srcFilePath,new Set);if(this.adjacencyList.get(N.srcFilePath).add(N.dstFilePath),!this.adjacencyList.has(N.dstFilePath))this.adjacencyList.set(N.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(N.dstFilePath))this.reverseAdjacencyList.set(N.dstFilePath,new Set);this.reverseAdjacencyList.get(N.dstFilePath).add(N.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.reverseAdjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}hasCycle(){let u=new Set,_=new Set;for(let g of this.adjacencyList.keys()){if(u.has(g))continue;let $=[{node:g,entered:!1}];while($.length>0){let J=$.pop();if(J.entered){_.delete(J.node);continue}if(_.has(J.node))return!0;if(u.has(J.node))continue;u.add(J.node),_.add(J.node),$.push({node:J.node,entered:!0});for(let O of this.adjacencyList.get(J.node)??[]){if(_.has(O))return!0;if(!u.has(O))$.push({node:O,entered:!1})}}}return!1}getAffectedByChange(u){let _=new Set;for(let g of u)for(let $ of this.getTransitiveDependents(g))_.add($);return Array.from(_)}getAdjacencyList(){let u=new Map;for(let[_,g]of this.adjacencyList)u.set(_,Array.from(g));return u}getTransitiveDependencies(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.adjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}getCyclePaths(u){let _=u?.maxCycles??1/0;if(_<=0)return[];let g=new Map;for(let[$,J]of this.adjacencyList)g.set($,Array.from(J));return G0(g,_)}}var q0=(u,_)=>u.localeCompare(_);function j0(u){let _=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(_.length===0)return[];let g=_;for(let $=1;$<_.length;$++){let J=_.slice($).concat(_.slice(0,$));if(J.join("::")<g.join("::"))g=J}return[...g]}function k_(u,_,g){let $=j0(g);if($.length===0)return!1;let J=$.join("->");if(u.has(J))return!1;return u.add(J),_.push($),!0}function F0(u){let _=0,g=[],$=new Set,J=new Map,O=new Map,N=[],z=(Q)=>{J.set(Q,_),O.set(Q,_),_+=1,g.push(Q),$.add(Q);for(let V of u.get(Q)??[])if(!J.has(V))z(V),O.set(Q,Math.min(O.get(Q)??0,O.get(V)??0));else if($.has(V))O.set(Q,Math.min(O.get(Q)??0,J.get(V)??0));if(O.get(Q)===J.get(Q)){let V=[],W="";do W=g.pop()??"",$.delete(W),V.push(W);while(W!==Q&&g.length>0);N.push(V)}};for(let Q of u.keys())if(!J.has(Q))z(Q);return{components:N}}function n0(u,_,g){let $=[],J=new Set,O=[...u].sort(q0),N=(z,Q,V)=>{Q.delete(z);let W=V.get(z);if(!W)return;for(let U of W)if(Q.has(U))N(U,Q,V);W.clear()};for(let z=0;z<O.length&&$.length<g;z++){let Q=O[z]??"",V=new Set(O.slice(z)),W=new Set,U=new Map,X=[],M=(D)=>(_.get(D)??[]).filter((T)=>V.has(T)),I=(D)=>{if($.length>=g)return!0;let T=!1;X.push(D),W.add(D);for(let j of M(D)){if($.length>=g)break;if(j===Q)k_(J,$,X.concat(Q)),T=!0;else if(!W.has(j)){if(I(j))T=!0}}if(T)N(D,W,U);else for(let j of M(D)){let h=U.get(j)??new Set;h.add(D),U.set(j,h)}return X.pop(),T};I(Q)}return $}function G0(u,_){let{components:g}=F0(u),$=[],J=new Set;for(let O of g){if($.length>=_)break;if(O.length===0)continue;if(O.length===1){let Q=O[0]??"";if((u.get(Q)??[]).includes(Q))k_(J,$,[Q,Q]);continue}let N=_-$.length,z=n0(O,u,N);for(let Q of z){if($.length>=_)break;k_(J,$,Q)}}return $}var v0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Lu(u,_){let g=_??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>v0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===g)return u.graphCache;let $=new su({relationRepo:u.relationRepo,project:_??u.defaultProject,additionalProjects:_?void 0:u.boundaries?.map((J)=>J.project)});return $.build(),u.graphCache=$,u.graphCacheKey=g,u.graphCacheBuiltAt=Date.now(),$}function Zg(u,_,g,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.dstFilePath)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getDependencies failed",{cause:J})}}function Xg(u,_,g,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{dstFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.srcFilePath)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getDependents failed",{cause:J})}}async function Kg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getAffectedByChange(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getAffected failed",{cause:$})}}async function Mg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).hasCycle()}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: hasCycle failed",{cause:g})}}async function Bg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getAdjacencyList()}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: getImportGraph failed",{cause:g})}}async function Hg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getTransitiveDependencies(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function Lg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getTransitiveDependents(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependents failed",{cause:$})}}async function Ig(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getCyclePaths(g)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getCyclePaths failed",{cause:$})}}async function Dg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=Lu(u,g);return{filePath:_,fanIn:$.getDependents(_).length,fanOut:$.getDependencies(_).length}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getFanMetrics failed",{cause:$})}}var y0=30000,Ag=15000,f0=10;function P0(u,_){return(g)=>{for(let $ of u.onFileChangedCallbacks)try{$(g)}catch(J){u.logger.error("[Gildash] onFileChanged callback threw:",J)}if(_.handleWatcherEvent?.(g),u.semanticLayer)if(g.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(g.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let J of u.onErrorCallbacks)try{J($ instanceof w?$:new w("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(g.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(g.filePath,$)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",J);for(let O of u.onErrorCallbacks)try{O(J instanceof w?J:new w("semantic","semantic notifyFileChanged failed",{cause:J}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,$);try{u.semanticLayer?.notifyFileDeleted(g.filePath)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",J)}})}}async function m0(u){if(!u.semanticLayer)return;let _=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(_.map(async(g)=>{try{let $=Eu.resolve(u.projectRoot,g.filePath),J=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,J)}catch{}}))}async function Cg(u,_){let g=u.coordinatorFactory?u.coordinatorFactory():new Z_({projectRoot:u.projectRoot,boundaries:u.boundaries,extensions:u.extensions,ignorePatterns:u.ignorePatterns,dbConnection:u.db,parseCache:u.parseCache,fileRepo:u.fileRepo,symbolRepo:u.symbolRepo,relationRepo:u.relationRepo,annotationRepo:u.annotationRepo??void 0,changelogRepo:u.changelogRepo??void 0,logger:u.logger});u.coordinator=g;for(let $ of u.onIndexedCallbacks)g.onIndexed($);if(g.onIndexed(($)=>{let J=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&J>0&&J<100){let O=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(N)=>{return[u.defaultProject,...u.boundaries.map((Q)=>Q.project)].flatMap((Q)=>O.getByType(Q,"imports").concat(O.getByType(Q,"type-references")).concat(O.getByType(Q,"re-exports"))).filter((Q)=>Q.srcFilePath===N||Q.dstFilePath===N).map((Q)=>({srcFilePath:Q.srcFilePath,dstFilePath:Q.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),_.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new N_({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(P0(u,g)).then((J)=>{if(vu(J))throw J.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},y0)}await g.fullIndex(),await m0(u)}function h0(u,_){let g=["SIGTERM","SIGINT","beforeExit"];for(let $ of g){let J=()=>{_().catch((O)=>u.logger.error("[Gildash] close error during signal",$,O))};if($==="beforeExit")process.on("beforeExit",J);else process.on($,J);u.signalHandlers.push([$,J])}}async function Sg(u){let{projectRoot:_,extensions:g=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:J=500,logger:O=console,existsSyncFn:N=b0,dbConnectionFactory:z,watcherFactory:Q,coordinatorFactory:V,repositoryFactory:W,acquireWatcherRoleFn:U=_g,releaseWatcherRoleFn:X=gg,updateHeartbeatFn:M=$g,discoverProjectsFn:I=mu,parseSourceFn:D=ju,extractSymbolsFn:T=Su,extractRelationsFn:j=lu,symbolSearchFn:h=K_,relationSearchFn:Z=M_,patternSearchFn:K=B_,loadTsconfigPathsFn:B=qu,readFileFn:R=async(p)=>Bun.file(p).text(),unlinkFn:q=async(p)=>{await Bun.file(p).unlink()},watchMode:S,semantic:G,semanticLayerFactory:f}=u;if(!Eu.isAbsolute(_))throw new w("validation",`Gildash: projectRoot must be an absolute path, got: "${_}"`);if(!N(_))throw new w("validation",`Gildash: projectRoot does not exist: "${_}"`);let y=z?z():new __({projectRoot:_}),E=y.open();if(vu(E))throw E.data;try{let p=await I(_),gu=p[0]?.project??Eu.basename(_),r=W?W():(()=>{let t=y;return{fileRepo:new g_(t),symbolRepo:new $_(t),relationRepo:new J_(t),parseCache:new X_(J)}})(),uu=W?null:y,Y=uu?new S_(uu):null,A=uu?new R_(uu):null,C=S??!0,k=crypto.randomUUID(),P;if(C)P=await Promise.resolve(U(y,process.pid,{instanceId:k}));else P="owner";let H={projectRoot:_,extensions:g,ignorePatterns:$,logger:O,defaultProject:gu,role:P,db:y,symbolRepo:r.symbolRepo,relationRepo:r.relationRepo,fileRepo:r.fileRepo,parseCache:r.parseCache,annotationRepo:Y,changelogRepo:A,annotationSearchFn:Yg,releaseWatcherRoleFn:X,parseSourceFn:D,extractSymbolsFn:T,extractRelationsFn:j,symbolSearchFn:h,relationSearchFn:Z,patternSearchFn:K,readFileFn:R,unlinkFn:q,existsSyncFn:N,acquireWatcherRoleFn:U,updateHeartbeatFn:M,watcherFactory:Q,coordinatorFactory:V,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:p,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(hu(_),H.tsconfigPaths=await B(_),G){let t=Eu.join(_,"tsconfig.json");try{if(f)H.semanticLayer=f(t);else{let F=au.create(t);if(vu(F))throw F.data;H.semanticLayer=F}}catch(F){if(F instanceof w)throw F;throw new w("semantic","Gildash: semantic layer creation failed",{cause:F})}}if(P==="owner")await Cg(H,{isWatchMode:C});else{let t=0,F=async()=>{try{let m=await Promise.resolve(H.acquireWatcherRoleFn(H.db,process.pid,{instanceId:H.instanceId}));if(t=0,m==="owner"){H.role="owner";for(let v of H.onRoleChangedCallbacks)try{v("owner")}catch(l){H.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(H.timer),H.timer=null;try{await Cg(H,{isWatchMode:!0})}catch(v){if(H.logger.error("[Gildash] owner promotion failed, reverting to reader",v),H.role="reader",H.timer!==null)clearInterval(H.timer),H.timer=null;if(H.watcher){let l=await H.watcher.close();if(vu(l))H.logger.error("[Gildash] watcher close error during promotion rollback",l.data);H.watcher=null}if(H.coordinator)await H.coordinator.shutdown().catch((l)=>H.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),H.coordinator=null;try{H.releaseWatcherRoleFn(H.db,process.pid)}catch(l){H.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}H.timer=setInterval(F,Ag)}}}catch(m){t++;let v=m instanceof w?m:new w("watcher","Gildash: healthcheck error",{cause:m});for(let l of H.onErrorCallbacks)try{l(v)}catch(Uu){H.logger.error("[Gildash] onError callback threw:",Uu)}if(H.logger.error("[Gildash] healthcheck error",m),t>=f0)H.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(H.timer),H.timer=null,ou(H).catch((l)=>H.logger.error("[Gildash] close error during healthcheck shutdown",l))}};H.timer=setInterval(F,Ag)}if(C)h0(H,()=>ou(H));return H}catch(p){if(y.close(),p instanceof w)throw p;throw new w("store","Gildash: initialization failed",{cause:p})}}async function ou(u,_){if(u.closed)return;u.closed=!0;let g=[];for(let[$,J]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",J);else process.off($,J);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){g.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(vu($))g.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){g.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(_?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(Eu.join(u.projectRoot,Yu,yu+$))}catch{}if(g.length>0)throw new w("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as Rg}from"@zipbul/result";function kg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=u.parseSourceFn(_,g,$);if(Rg(J))throw J.data;return u.parseCache.set(_,J),J}async function Tg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");let $=new Map,J=[];return await Promise.all(_.map(async(O)=>{try{let N=await u.readFileFn(O),z=u.parseSourceFn(O,N,g);if(!Rg(z))$.set(O,z);else J.push({filePath:O,error:z.data})}catch(N){J.push({filePath:O,error:N instanceof Error?N:Error(String(N))})}})),{parsed:$,failures:J}}function qg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.parseCache.get(_)}function jg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractSymbolsFn(_)}function Fg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractRelationsFn(_.program,_.filePath,u.tsconfigPaths??void 0)}import ng from"path";function Gg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(_??u.defaultProject)}catch(g){if(g instanceof w)throw g;throw new w("store","Gildash: getStats failed",{cause:g})}}function T_(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchSymbols failed",{cause:g})}}function vg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchRelations failed",{cause:g})}}function Eg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchAllSymbols failed",{cause:g})}}function bg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchAllRelations failed",{cause:g})}}function yg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(_??u.defaultProject)}catch(g){if(g instanceof w)throw g;throw new w("store","Gildash: listIndexedFiles failed",{cause:g})}}function fg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,dstFilePath:_,limit:1e4}})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getInternalRelations failed",{cause:$})}}function Pg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:g,limit:1}});if(O.length===0)return null;let N=O[0],z=N.detail,Q={...N,members:Array.isArray(z.members)?z.members:void 0,jsDoc:typeof z.jsDoc==="string"?z.jsDoc:void 0,parameters:typeof z.parameters==="string"?z.parameters:void 0,returnType:typeof z.returnType==="string"?z.returnType:void 0,heritage:Array.isArray(z.heritage)?z.heritage:void 0,decorators:Array.isArray(z.decorators)?z.decorators:void 0,typeParameters:typeof z.typeParameters==="string"?z.typeParameters:void 0};if(u.semanticLayer)try{let V=ng.isAbsolute(g)?g:ng.resolve(u.projectRoot,g),W=u.semanticLayer.lineColumnToPosition(V,N.span.start.line,N.span.start.column);if(W!==null){let U=u.semanticLayer.findNamePosition(V,W,N.name)??W,X=u.semanticLayer.collectTypeAt(V,U);if(X)Q.resolvedType=X}}catch{}return Q}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getFullSymbol failed",{cause:J})}}function mg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=g??u.defaultProject,J=u.fileRepo.getFile($,_);if(!J)throw new w("search",`Gildash: file '${_}' is not in the index`);let O=u.symbolRepo.getFileSymbols($,_),N=u.relationRepo.getOutgoing($,_);return{filePath:J.filePath,lineCount:J.lineCount??0,size:J.size,symbolCount:O.length,exportedSymbolCount:O.filter((z)=>z.isExported).length,relationCount:N.length}}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileStats failed",{cause:$})}}function hg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(g??u.defaultProject,_)}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileInfo failed",{cause:$})}}function xg(u,_,g){return T_(u,{filePath:_,project:g??void 0,limit:1e4})}function ig(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:g??u.defaultProject,query:{filePath:_,isExported:!0}}).map((O)=>({name:O.name,kind:O.kind,parameters:O.detail.parameters??void 0,returnType:O.detail.returnType??void 0,jsDoc:O.detail.jsDoc??void 0}));return{filePath:_,exports:J}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getModuleInterface failed",{cause:$})}}import i from"path";function bu(u,_,g,$){let J=$??u.defaultProject,O=i.isAbsolute(g)?i.relative(u.projectRoot,g):g,N=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:O,limit:1}});if(N.length===0)return null;let z=N[0],Q=i.isAbsolute(g)?g:i.resolve(u.projectRoot,g),V=u.semanticLayer.lineColumnToPosition(Q,z.span.start.line,z.span.start.column);if(V===null)return null;let W=u.semanticLayer.findNamePosition(Q,V,z.name)??V;return{sym:z,position:W,absPath:Q}}function pg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)return null;return u.semanticLayer.collectTypeAt(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getResolvedType failed",{cause:J})}}function lg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)throw new w("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findReferences(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getSemanticReferences failed",{cause:J})}}function dg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)throw new w("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findImplementations(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getImplementations failed",{cause:J})}}function cg(u,_,g,$,J,O){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let N=bu(u,_,g,O);if(!N)throw new w("search",`Gildash: source symbol '${_}' not found in '${g}'`);let z=bu(u,$,J,O);if(!z)throw new w("search",`Gildash: target symbol '${$}' not found in '${J}'`);return u.semanticLayer.isTypeAssignableTo(N.absPath,N.position,z.absPath,z.position)}catch(N){if(N instanceof w)throw N;throw new w("semantic","Gildash: isTypeAssignableTo failed",{cause:N})}}function rg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let g=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.collectFileTypes(g)}catch(g){if(g instanceof w)throw g;throw new w("semantic","Gildash: getFileTypes failed",{cause:g})}}function ag(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_),O=u.semanticLayer.lineColumnToPosition(J,g,$);if(O===null)return null;return u.semanticLayer.collectTypeAt(J,O)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: getResolvedTypeAt failed",{cause:J})}}function sg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let g=i.isAbsolute(_.source.filePath)?_.source.filePath:i.resolve(u.projectRoot,_.source.filePath),$=i.isAbsolute(_.target.filePath)?_.target.filePath:i.resolve(u.projectRoot,_.target.filePath),J=u.semanticLayer.lineColumnToPosition(g,_.source.line,_.source.column);if(J===null)return null;let O=u.semanticLayer.lineColumnToPosition($,_.target.line,_.target.column);if(O===null)return null;return u.semanticLayer.isTypeAssignableTo(g,J,$,O)}catch(g){if(g instanceof w)throw g;throw new w("semantic","Gildash: isTypeAssignableToAt failed",{cause:g})}}function tg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(_)}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function og(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.collectTypeAt($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:$})}}function eg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findReferences($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:$})}}function u$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findImplementations($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getImplementationsAtPosition failed",{cause:$})}}function _$(u,_,g,$,J){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let O=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_),N=i.isAbsolute($)?$:i.resolve(u.projectRoot,$);return u.semanticLayer.isTypeAssignableTo(O,g,N,J)}catch(O){if(O instanceof w)throw O;throw new w("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:O})}}function g$(u,_,g,$,J){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let O=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.isTypeAssignableToType(O,g,$,J)}catch(O){if(O instanceof w)throw O;throw new w("semantic","Gildash: isTypeAssignableToType failed",{cause:O})}}function $$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.lineColumnToPosition(J,g,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: lineColumnToPosition failed",{cause:J})}}function J$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findNamePosition(J,g,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: findNamePosition failed",{cause:J})}}function Q$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.getSymbolNode($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSymbolNode failed",{cause:$})}}function N$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.getDiagnostics($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSemanticDiagnostics failed",{cause:$})}}function z$(u,_){let g=new Map(u.map((z)=>[`${z.name}::${z.filePath}`,z])),$=new Map(_.map((z)=>[`${z.name}::${z.filePath}`,z])),J=[],O=[],N=[];for(let[z,Q]of $){let V=g.get(z);if(!V)J.push(Q);else if(V.fingerprint!==Q.fingerprint)N.push({before:V,after:Q})}for(let[z,Q]of g)if(!$.has(z))O.push(Q);return{added:J,removed:O,modified:N}}function O$(u,_){if(u.onIndexedCallbacks.add(_),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(_)};let g=u.coordinator.onIndexed(_);return()=>{u.onIndexedCallbacks.delete(_),g()}}async function w$(u){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.coordinator)throw new w("closed","Gildash: reindex() is not available for readers");try{let _=await u.coordinator.fullIndex();return tu(u),_}catch(_){if(_ instanceof w)throw _;throw new w("index","Gildash: reindex failed",{cause:_})}}function W$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=$??u.defaultProject,O=new Set,N=[],z=_,Q=g;for(;;){let V=`${Q}::${z}`;if(O.has(V))return{originalName:z,originalFilePath:Q,reExportChain:N,circular:!0};O.add(V);let W=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{type:"re-exports",srcFilePath:Q,limit:500}}),U,X;for(let M of W){let I;if(M.metaJson)try{let T=JSON.parse(M.metaJson);if(Array.isArray(T.specifiers))I=T.specifiers}catch{}if(!I)continue;let D=I.find((T)=>T.exported===z);if(!D)continue;U=M.dstFilePath,X=D.local;break}if(!U||!X)return{originalName:z,originalFilePath:Q,reExportChain:N,circular:!1};N.push({filePath:Q,exportedAs:z}),Q=U,z=X}}function V$(u,_){return u.onFileChangedCallbacks.add(_),()=>{u.onFileChangedCallbacks.delete(_)}}function U$(u,_){return u.onErrorCallbacks.add(_),()=>{u.onErrorCallbacks.delete(_)}}function Y$(u,_){return u.onRoleChangedCallbacks.add(_),()=>{u.onRoleChangedCallbacks.delete(_)}}async function Z$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=g?.project??u.defaultProject,J=g?.filePaths?g.filePaths:u.fileRepo.getAllFiles($).map((O)=>O.filePath);return await u.patternSearchFn({pattern:_,filePaths:J})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: findPattern failed",{cause:$})}}async function X$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=new Set,N=(z,Q,V)=>{let W=`${z}::${Q}`;if(O.has(W))return{symbolName:z,filePath:Q,kind:V,children:[]};O.add(W);let M=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{srcFilePath:Q,srcSymbolName:z,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>N(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:z,filePath:Q,kind:V,children:M}};return N(_,g)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getHeritageChain failed",{cause:J})}}function K$(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:_.project??u.defaultProject,query:_})}function M$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=_ instanceof Date?_.toISOString():_,J=g?.project??u.defaultProject,O=g?.limit??1000;return u.changelogRepo.getSince({project:J,since:$,symbolName:g?.symbolName,changeTypes:g?.changeTypes,filePath:g?.filePath,includeFullIndex:g?.includeFullIndex,indexRunId:g?.indexRunId,afterId:g?.afterId,limit:O}).map((z)=>({changeType:z.changeType,symbolName:z.symbolName,symbolKind:z.symbolKind,filePath:z.filePath,oldName:z.oldName,oldFilePath:z.oldFilePath,fingerprint:z.fingerprint,changedAt:z.changedAt,isFullIndex:z.isFullIndex===1,indexRunId:z.indexRunId}))}function B$(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let g=_ instanceof Date?_.toISOString():_,$=0,J=[u.defaultProject,...u.boundaries.map((N)=>N.project)],O=[...new Set(J)];for(let N of O)$+=u.changelogRepo.pruneOlderThan(N,g);return $}class q_{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(u){this._ctx=u}static async open(u){let _=await Sg(u);return new q_(_)}async close(u){return ou(this._ctx,u)}parseSource(u,_,g){return kg(this._ctx,u,_,g)}async batchParse(u,_){return Tg(this._ctx,u,_)}getParsedAst(u){return qg(this._ctx,u)}extractSymbols(u){return jg(this._ctx,u)}extractRelations(u){return Fg(this._ctx,u)}getStats(u){return Gg(this._ctx,u)}searchSymbols(u){return T_(this._ctx,u)}searchRelations(u){return vg(this._ctx,u)}searchAllSymbols(u){return Eg(this._ctx,u)}searchAllRelations(u){return bg(this._ctx,u)}listIndexedFiles(u){return yg(this._ctx,u)}getInternalRelations(u,_){return fg(this._ctx,u,_)}getFullSymbol(u,_,g){return Pg(this._ctx,u,_,g)}getFileStats(u,_){return mg(this._ctx,u,_)}getFileInfo(u,_){return hg(this._ctx,u,_)}getSymbolsByFile(u,_){return xg(this._ctx,u,_)}getModuleInterface(u,_){return ig(this._ctx,u,_)}getDependencies(u,_,g=1e4){return Zg(this._ctx,u,_,g)}getDependents(u,_,g=1e4){return Xg(this._ctx,u,_,g)}async getAffected(u,_){return Kg(this._ctx,u,_)}async hasCycle(u){return Mg(this._ctx,u)}async getImportGraph(u){return Bg(this._ctx,u)}async getTransitiveDependencies(u,_){return Hg(this._ctx,u,_)}async getTransitiveDependents(u,_){return Lg(this._ctx,u,_)}async getCyclePaths(u,_){return Ig(this._ctx,u,_)}async getFanMetrics(u,_){return Dg(this._ctx,u,_)}getResolvedType(u,_,g){return pg(this._ctx,u,_,g)}getSemanticReferences(u,_,g){return lg(this._ctx,u,_,g)}getImplementations(u,_,g){return dg(this._ctx,u,_,g)}isTypeAssignableTo(u,_,g,$,J){return cg(this._ctx,u,_,g,$,J)}getSemanticModuleInterface(u){return tg(this._ctx,u)}getFileTypes(u){return rg(this._ctx,u)}getResolvedTypeAt(u,_,g){return ag(this._ctx,u,_,g)}isTypeAssignableToAt(u){return sg(this._ctx,u)}getResolvedTypeAtPosition(u,_){return og(this._ctx,u,_)}getSemanticReferencesAtPosition(u,_){return eg(this._ctx,u,_)}getImplementationsAtPosition(u,_){return u$(this._ctx,u,_)}isTypeAssignableToAtPosition(u,_,g,$){return _$(this._ctx,u,_,g,$)}isTypeAssignableToType(u,_,g,$){return g$(this._ctx,u,_,g,$)}lineColumnToPosition(u,_,g){return $$(this._ctx,u,_,g)}findNamePosition(u,_,g){return J$(this._ctx,u,_,g)}getSymbolNode(u,_){return Q$(this._ctx,u,_)}getSemanticDiagnostics(u,_){return N$(this._ctx,u,_)}diffSymbols(u,_){return z$(u,_)}onIndexed(u){return O$(this._ctx,u)}async reindex(){return w$(this._ctx)}resolveSymbol(u,_,g){return W$(this._ctx,u,_,g)}async findPattern(u,_){return Z$(this._ctx,u,_)}async getHeritageChain(u,_,g){return X$(this._ctx,u,_,g)}onFileChanged(u){return V$(this._ctx,u)}onError(u){return U$(this._ctx,u)}onRoleChanged(u){return Y$(this._ctx,u)}searchAnnotations(u){return K$(this._ctx,u)}getSymbolChanges(u,_){return M$(this._ctx,u,_)}pruneChangelog(u){return B$(this._ctx,u)}}export{K_ as symbolSearch,M_ as relationSearch,B_ as patternSearch,$u as gildashError,w as GildashError,q_ as Gildash,su as DependencyGraph};
2
+ var g1=Object.defineProperty;var q1=(_)=>_;function S1(_,$){this[_]=q1.bind(null,$)}var T1=(_,$)=>{for(var J in $)g1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:S1.bind($,J)})};var P$=import.meta.require;import{isErr as n_}from"@zipbul/result";import m_ from"path";import{existsSync as cJ}from"fs";import{err as f$,isErr as E1}from"@zipbul/result";import{Database as v1}from"bun:sqlite";import{mkdirSync as b1,unlinkSync as n$,existsSync as m$}from"fs";import{dirname as y1,join as x$}from"path";import{drizzle as P1}from"drizzle-orm/bun-sqlite";import{migrate as f1}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};T1(Y$,{watcherOwner:()=>j1,symbols:()=>n,symbolChangelog:()=>Q_,relations:()=>G,files:()=>__,annotations:()=>Y_});import{sql as R1}from"drizzle-orm";import{sqliteTable as A_,text as b,integer as e,real as k1,index as z_,primaryKey as F1,foreignKey as W$,check as G1}from"drizzle-orm/sqlite-core";var __=A_("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:k1("mtime_ms").notNull(),size:e("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:e("line_count")},(_)=>[F1({columns:[_.project,_.filePath]})]),n=A_("symbols",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),isExported:e("is_exported").notNull().default(0),signature:b("signature"),fingerprint:b("fingerprint"),detailJson:b("detail_json"),contentHash:b("content_hash").notNull(),indexedAt:b("indexed_at").notNull(),resolvedType:b("resolved_type"),structuralFingerprint:b("structural_fingerprint")},(_)=>[z_("idx_symbols_project_file").on(_.project,_.filePath),z_("idx_symbols_project_kind").on(_.project,_.kind),z_("idx_symbols_project_name").on(_.project,_.name),z_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),G=A_("relations",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),type:b("type").notNull(),srcFilePath:b("src_file_path").notNull(),srcSymbolName:b("src_symbol_name"),dstProject:b("dst_project"),dstFilePath:b("dst_file_path"),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json"),specifier:b("specifier"),isExternal:e("is_external").notNull().default(0)},(_)=>[z_("idx_relations_src").on(_.project,_.srcFilePath),z_("idx_relations_dst").on(_.dstProject,_.dstFilePath),z_("idx_relations_type").on(_.project,_.type),z_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),z_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Y_=A_("annotations",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),tag:b("tag").notNull(),value:b("value").notNull().default(""),source:b("source").notNull(),symbolName:b("symbol_name"),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),indexedAt:b("indexed_at").notNull()},(_)=>[z_("idx_annotations_project_file").on(_.project,_.filePath),z_("idx_annotations_project_tag").on(_.project,_.tag),z_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Q_=A_("symbol_changelog",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),changeType:b("change_type").notNull(),symbolName:b("symbol_name").notNull(),symbolKind:b("symbol_kind").notNull(),filePath:b("file_path").notNull(),oldName:b("old_name"),oldFilePath:b("old_file_path"),fingerprint:b("fingerprint"),changedAt:b("changed_at").notNull(),isFullIndex:e("is_full_index").notNull().default(0),indexRunId:b("index_run_id").notNull()},(_)=>[z_("idx_changelog_project_changed_at").on(_.project,_.changedAt),z_("idx_changelog_project_name").on(_.project,_.symbolName),z_("idx_changelog_project_run").on(_.project,_.indexRunId)]),j1=A_("watcher_owner",{id:e("id").primaryKey(),pid:e("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull(),instanceId:b("instance_id")},(_)=>[G1("watcher_owner_singleton",R1`${_.id} = 1`)]);class Z${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=x$(_.projectRoot,L_,h_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{b1(y1(this.dbPath),{recursive:!0}),this.client=new v1(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=P1(this.client,{schema:Y$}),f1(this.drizzle,{migrationsFolder:x$(import.meta.dirname,"migrations")});let _=this.client.prepare("PRAGMA foreign_key_check").all();if(_.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(_.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(_){if(this.isCorruptionError(_)&&m$(this.dbPath)){this.closeClient(),n$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(m$(Q))n$(Q)}let $=this.open();if(E1($))return f$(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return f$(new V("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as F_,and as h$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(__).where(h$(F_(__.project,_),F_(__.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(__).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[__.project,__.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(__).where(F_(__.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(__).where(h$(F_(__.project,_),F_(__.filePath,$))).run()}}import{eq as $_,and as B_,sql as i_,count as n1}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i$=50;class O${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(n).where(B_($_(n.project,_),$_(n.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),Y=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<Y.length;Z+=i$)this.db.drizzleDb.insert(n).values(Y.slice(Z,Z+i$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(n).where(B_($_(n.project,_),$_(n.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(n).where(B_(i_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,$_(n.project,_),J.kind?$_(n.kind,J.kind):void 0)).orderBy(n.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(n).where(B_($_(n.project,_),$_(n.kind,$))).orderBy(n.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:n1(),fileCount:i_`COUNT(DISTINCT ${n.filePath})`}).from(n).where($_(n.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(n).where(B_($_(n.project,_),$_(n.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(n).where(B_($_(n.project,_),$_(n.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(n).where(B_(_.ftsQuery?i_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?$_(n.name,_.exactName):void 0,_.project!==void 0?$_(n.project,_.project):void 0,_.kind?$_(n.kind,_.kind):void 0,_.filePath!==void 0?$_(n.filePath,_.filePath):void 0,_.isExported!==void 0?$_(n.isExported,_.isExported?1:0):void 0,_.decorator?i_`${n.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${_.decorator})`:void 0,_.resolvedType!==void 0?$_(n.resolvedType,_.resolvedType):void 0)).orderBy(n.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new V("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((Y)=>J.test(Y.name));let Q=[];for(let z of[5,20,100]){let Y=_.limit*z,Z=$.limit(Y).all();if(Q=Z.filter((W)=>J.test(W.name)),Q.length>=_.limit||Z.length<Y)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as c,and as V_,isNull as p$,or as m1}from"drizzle-orm";var G_={project:G.project,type:G.type,srcFilePath:G.srcFilePath,srcSymbolName:G.srcSymbolName,dstProject:G.dstProject,dstFilePath:G.dstFilePath,dstSymbolName:G.dstSymbolName,metaJson:G.metaJson,specifier:G.specifier,isExternal:G.isExternal};class V${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(G).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$),m1(c(G.srcSymbolName,J),p$(G.srcSymbolName)))).all();return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.dstProject,$),c(G.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.dstProject,_),c(G.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(G_).from(G).where(V_(_.project!==void 0?c(G.project,_.project):void 0,_.srcFilePath!==void 0?c(G.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?c(G.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?c(G.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?c(G.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?c(G.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?c(G.type,_.type):void 0,_.specifier!==void 0?c(G.specifier,_.specifier):void 0,_.isExternal!==void 0?c(G.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:Y,newDstProject:Z}=_,W=Q===null?V_(c(G.dstProject,$),c(G.dstFilePath,J),p$(G.dstSymbolName)):V_(c(G.dstProject,$),c(G.dstFilePath,J),c(G.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:Y};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(G).set(X).where(W).run()}}import{err as l$}from"@zipbul/result";import{subscribe as x1}from"@parcel/watcher";import U$ from"path";import d$ from"path";function Z_(_){return _.replaceAll("\\","/")}function j_(_,$){return Z_(d$.relative(_,$))}function q_(_,$){return Z_(d$.resolve(_,$))}var h1=["**/.git/**",`**/${L_}/**`,"**/dist/**","**/node_modules/**"],i1=new Set(["package.json","tsconfig.json"]);function p1(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class H${#_;#$;#J;#z;#Q;#Y;constructor(_,$=x1,J=console){this.#$=_.projectRoot,this.#J=[...h1,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#Q=$,this.#Y=J}async start(_){try{this.#_=await this.#Q(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=Z_(U$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let Y=U$.basename(z),Z=U$.extname(z).toLowerCase();if(!i1.has(Y)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:p1(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return l$(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return l$(new V("watcher","Failed to close watcher",{cause:_}))}}}import M$ from"path";import{promises as d1}from"fs";var l1=["**/node_modules/**","**/.git/**",`**/${L_}/**`,"**/dist/**"];async function p_(_){let $=[];for await(let J of d1.glob("**/package.json",{cwd:_,exclude:l1})){let Q=Z_(M$.dirname(J)),z=M$.join(_,J),Y=await Bun.file(z).json(),Z=typeof Y?.name==="string"&&Y.name.length>0?Y.name:M$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function o(_,$,J="default"){let Q=Z_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import E_ from"path";var w_=new Map;async function c1(_){let $=Bun.file(_);if(!await $.exists())return null;try{let J=await $.text(),Q=Bun.JSONC.parse(J);return typeof Q==="object"&&Q!==null?Q:null}catch{return null}}function a1(_,$){if($.startsWith(".")){let J=E_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return E_.resolve(_,"node_modules",$)}async function c$(_,$=5){if($<=0)return null;let J=await c1(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=a1(E_.dirname(_),Q),Y=await c$(z,$-1);if(!Y)return J;let Z=typeof Y.compilerOptions==="object"&&Y.compilerOptions!==null?Y.compilerOptions:{},W=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...Y,...J,compilerOptions:{...Z,...W}}}async function v_(_){if(w_.has(_))return w_.get(_)??null;let $=E_.join(_,"tsconfig.json"),J=await c$($);if(!J)return w_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return w_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,Y=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!Y)return w_.set(_,null),null;let Z=z?E_.resolve(_,z):_,W=new Map;if(Y)for(let[H,O]of Object.entries(Y)){if(!Array.isArray(O))continue;let U=O.filter((K)=>typeof K==="string");W.set(H,U)}let X={baseUrl:Z,paths:W};return w_.set(_,X),X}function d_(_){if(_){w_.delete(_);return}w_.clear()}function O_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Q0}from"@zipbul/result";import{err as s1}from"@zipbul/result";import{parseSync as r1}from"oxc-parser";function b_(_,$,J,Q=r1){try{let z={preserveParens:!1,...J},Y=Q(_,$,z);return{filePath:_,program:Y.program,errors:Y.errors,comments:Y.comments,sourceText:$,module:Y.module}}catch(z){return s1(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{promises as o1}from"fs";import{join as t1}from"path";async function a$(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z}=_,Y=z.getFilesMap(),Z=new Set,W=[],X=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of o1.glob("**/*",{cwd:$})){let K=Z_(U);if(!J.some((P)=>K.endsWith(P)))continue;if(K.startsWith("node_modules/")||K.includes("/node_modules/"))continue;if(H.some((P)=>P.match(K)))continue;Z.add(K);let u=t1($,K),L=Bun.file(u),{size:B,lastModified:T}=L,F=Y.get(K);if(!F){let P=await L.text(),r=O_(P);W.push({filePath:K,contentHash:r,mtimeMs:T,size:B});continue}if(F.mtimeMs===T&&F.size===B){X.push({filePath:K,contentHash:F.contentHash,mtimeMs:T,size:B});continue}let m=await L.text(),j=O_(m);if(j===F.contentHash)X.push({filePath:K,contentHash:j,mtimeMs:T,size:B});else W.push({filePath:K,contentHash:j,mtimeMs:T,size:B})}let O=[];for(let U of Y.keys())if(!Z.has(U))O.push(U);return{changed:W,unchanged:X,deleted:O}}function y_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
3
+ `)$.push(J+1);return $}function X_(_,$){let J=0,Q=_.length-1;while(J<Q){let z=J+Q+1>>1;if(_[z]<=$)J=z;else Q=z-1}return{line:J+1,column:$-_[J]}}import{err as e1}from"@zipbul/result";import{parse as _J}from"comment-parser";function l_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=_J(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((z)=>({tag:z.tag??"",name:z.name??"",type:z.type??"",description:z.description??"",optional:z.optional??!1,...z.default!==void 0?{default:z.default}:{}}))}}catch($){return e1(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as $J}from"@zipbul/result";function c_(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _&&typeof _.value==="string")return _.value;return"unknown"}function S_(_){if(_.type==="Identifier")return[_.name];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J))}return $}if(_.type==="AssignmentPattern")return S_(_.left);return[]}function T_(_){let{program:$,sourceText:J,comments:Q}=_,z=y_(J),Y=Q.filter((w)=>w.type==="Block"&&w.value.startsWith("*")).sort((w,A)=>w.end-A.end),Z=$.body.map((w)=>w.start).sort((w,A)=>w-A);function W(w,A){return{start:X_(z,w),end:X_(z,A)}}function X(w){let A=0,D=Y.length-1,C=-1;while(A<=D){let g=A+D>>>1;if(Y[g].end<=w)C=g,A=g+1;else D=g-1}if(C<0)return;let N=Y[C];A=0,D=Z.length-1;while(A<=D){let g=A+D>>>1,R=Z[g];if(R<=N.end)A=g+1;else if(R>=w)D=g-1;else return}return`/*${N.value}*/`}function H(w){if(!w)return;let A="typeAnnotation"in w&&w.typeAnnotation?w.typeAnnotation:w;return J.slice(A.start,A.end)}function O(w){if(!w||w.length===0)return[];return w.map((A)=>{let D=A.expression;if(D.type==="CallExpression"){let C=D,N=C.callee,g="name"in N&&typeof N.name==="string"?N.name:("property"in N)&&N.property&&typeof N.property.name==="string"?N.property.name:"unknown",R=C.arguments.map((E)=>J.slice(E.start,E.end));return{name:g,arguments:R.length>0?R:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function U(w){if(w.type==="TSParameterProperty"){let D=w;return K(D.parameter,D.parameter.decorators)}if(w.type==="RestElement"){let D=w,C=D.argument,g=`...${"name"in C&&typeof C.name==="string"?C.name:"unknown"}`,R=D.typeAnnotation,E=R?H(R):void 0,i={name:g,isOptional:!1};if(E)i.type=E;return i}let A=w;return K(A,A.decorators)}function K(w,A){if(w.type==="AssignmentPattern"){let{left:i,right:d}=w,a="name"in i&&typeof i.name==="string"?i.name:"unknown",M="typeAnnotation"in i?i.typeAnnotation:null,q=M?H(M):void 0,S=J.slice(d.start,d.end),k="decorators"in i&&Array.isArray(i.decorators)?i.decorators:[],f=O(k),I={name:a,isOptional:!0,defaultValue:S};if(q)I.type=q;if(f.length>0)I.decorators=f;return I}let D="name"in w&&typeof w.name==="string"?w.name:("pattern"in w)&&w.pattern&&typeof w.pattern.name==="string"?w.pattern.name:"unknown",C=!!(("optional"in w)&&w.optional),N="typeAnnotation"in w?w.typeAnnotation:null,g=N?H(N):void 0,R=O(A??[]),E={name:D,isOptional:C};if(g)E.type=g;if(R.length>0)E.decorators=R;return E}function u(w,A){let D=[];if(A?.async)D.push("async");if(w.static)D.push("static");if(w.abstract)D.push("abstract");if(w.readonly)D.push("readonly");if(w.override)D.push("override");if(w.declare)D.push("declare");if(w.const)D.push("const");let C=w.accessibility;if(C==="private")D.push("private");else if(C==="protected")D.push("protected");else if(C==="public")D.push("public");return D}function L(w){if(!w)return;let A=w.params.flatMap((D)=>{let C=D.name.name;return C?[C]:[]});return A.length>0?A:void 0}function B(w){let A=[];if(w.superClass){let C=J.slice(w.superClass.start,w.superClass.end);A.push({kind:"extends",name:C})}let D=w.implements??[];for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"implements",name:g})}return A}function T(w){let A=[],D=w.extends;for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"extends",name:g})}return A}function F(w){let A=[];for(let D of w)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let C=D,N=c_(C.key),g=C.value,R=C.kind,E=R==="constructor"?"constructor":R==="get"?"getter":R==="set"?"setter":"method",i=u(C,g);if(D.type==="TSAbstractMethodDefinition"&&!i.includes("abstract"))i.push("abstract");let d=g.params.map(U),a=H(g.returnType),M={kind:"method",name:N,span:W(D.start,D.end),isExported:!1,methodKind:E,modifiers:i,parameters:d.length>0?d:void 0,returnType:a};A.push(M)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let C=D,N=c_(C.key),g=u(C);if(D.type==="TSAbstractPropertyDefinition"&&!g.includes("abstract"))g.push("abstract");let R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:g};A.push(R)}return A}function m(w){let A=[];for(let D of w)if(D.type==="TSMethodSignature"){let C=D,N=c_(C.key),g=C.params.map(U),R=H(C.returnType);A.push({kind:"method",name:N,span:W(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:g.length>0?g:void 0,returnType:R})}else if(D.type==="TSPropertySignature"){let C=D,N=c_(C.key),g=H(C.typeAnnotation),R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:C.readonly?["readonly"]:[],returnType:g};A.push(R)}return A}function j(w,A){let D=w.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let C=w,N=C.id?.name??"default",g=C.params.map(U),R=H(C.returnType),E=u(C,C),i=O(C.decorators??[]),d=L(C.typeParameters),a={kind:"function",name:N,span:W(w.start,w.end),isExported:A,modifiers:E,parameters:g.length>0?g:void 0,returnType:R,decorators:i.length>0?i:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="ClassDeclaration"||D==="ClassExpression"){let C=w,N=C.id?.name??"default",g=B(C),R=F(C.body.body),E=O(C.decorators),i=u(C),d=L(C.typeParameters),a={kind:"class",name:N,span:W(w.start,w.end),isExported:A,modifiers:i,heritage:g.length>0?g:void 0,members:R.length>0?R:void 0,decorators:E.length>0?E:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="VariableDeclaration"){let C=w,N=[];for(let g of C.declarations){let{id:R,init:E}=g;if(R.type==="ObjectPattern"||R.type==="ArrayPattern"){let S=S_(R);for(let k of S)N.push({kind:"variable",name:k,span:W(R.start,R.end),isExported:A,modifiers:[]});continue}let i="name"in R&&typeof R.name==="string"?R.name:"unknown",d="variable",a,M;if(E){if(E.type==="FunctionExpression"||E.type==="ArrowFunctionExpression"){d="function";let S=E;a=S.params.map(U),M=H(S.returnType)}}let q=[];N.push({kind:d,name:i,span:W(g.start,g.end),isExported:A,modifiers:q,parameters:a,returnType:M})}if(N.length===0)return null;if(N.length===1)return N[0];return N}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:w.id.name,span:W(w.start,w.end),isExported:A,modifiers:[]};if(D==="TSInterfaceDeclaration"){let C=w,N=C.id.name,g=T(C),R=m(C.body.body),E=L(C.typeParameters),i={kind:"interface",name:N,span:W(w.start,w.end),isExported:A,modifiers:[],heritage:g.length>0?g:void 0,members:R.length>0?R:void 0};if(E&&E.length>0)i.typeParameters=E;return i}if(D==="TSEnumDeclaration"){let C=w,N=C.id.name,g=u(C),E=C.body.members.map((i)=>{let d=i.id;return{kind:"property",name:"name"in d&&typeof d.name==="string"?d.name:("value"in d)&&typeof d.value==="string"?d.value:"unknown",span:W(i.start,i.end),isExported:!1,modifiers:[]}});return{kind:"enum",name:N,span:W(w.start,w.end),isExported:A,modifiers:g,members:E.length>0?E:void 0}}if(D==="TSModuleDeclaration"){let C=w,N=C.id.name??C.id.value??"unknown",g=u(C);return{kind:"namespace",name:N,span:W(w.start,w.end),isExported:A,modifiers:g}}return null}let P=[],r=new Set;for(let w of $.body){let A=null,D=w;if(D.type==="ExportNamedDeclaration"){let N=D;if(N.declaration){if(A=j(N.declaration,!0),A&&!Array.isArray(A))A.span=W(N.start,N.end);else if(Array.isArray(A))for(let g of A)g.span=W(N.start,N.end)}else if(!N.source&&N.specifiers)for(let g of N.specifiers){let R=g.local,E="name"in R?R.name:R.value;if(E)r.add(E)}}else if(D.type==="ExportDefaultDeclaration"){let N=D,g=N.declaration;if(g){if(A=j(g,!0),A&&!Array.isArray(A))A.name="id"in g&&g.id&&typeof g.id.name==="string"?g.id.name:"default",A.isExported=!0,A.span=W(N.start,N.end);else if(!A&&"type"in g&&g.type==="Identifier"){let R=g.name;if(R)r.add(R)}}}else{let N=D.type;if(N==="FunctionDeclaration"||N==="TSDeclareFunction"||N==="ClassDeclaration"||N==="VariableDeclaration"||N==="TSTypeAliasDeclaration"||N==="TSInterfaceDeclaration"||N==="TSEnumDeclaration"||N==="TSModuleDeclaration")A=j(D,!1)}let C=Array.isArray(A)?A:A?[A]:[];for(let N of C){let g=w.start,R=X(g);if(R){let E=l_(R);if(!$J(E))N.jsDoc=E}P.push(N)}}if(r.size>0){for(let w of P)if(!w.isExported&&r.has(w.name))w.isExported=!0}return P}function JJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function QJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((z)=>z==="private"||z==="protected"||z==="public");return{name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0}});return Object.keys($).length>0?JSON.stringify($):null}function zJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${O_(J)}`)}return O_($.join("|"))}function s$(_,$,J,Q,z){let Y=JJ(_),Z=O_(`${$}|${_.kind}|${Y??""}`),W=zJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:Y,fingerprint:Z,detailJson:QJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:W}}function K$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:Y}=_,Z=T_($),W=[];for(let X of Z){W.push(s$(X,X.name,J,Q,z));for(let H of X.members??[])W.push(s$(H,`${X.name}.${H.name}`,J,Q,z))}Y.replaceFileSymbols(J,Q,z,W)}import{resolve as L$,dirname as WJ,extname as YJ}from"path";function D_(_,$,J){let Q=(z)=>{let Y=YJ(z);if(Y==="")return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"];if(Y===".js")return[z.slice(0,-3)+".ts"];if(Y===".mjs")return[z.slice(0,-4)+".mts"];if(Y===".cjs")return[z.slice(0,-4)+".cts"];return[z]};if($.startsWith(".")){let z=Z_(L$(WJ(_),$));return Q(z)}if(J)for(let[z,Y]of J.paths){if(Y.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let W=[];for(let X of Y)W.push(...Q(Z_(L$(J.baseUrl,X))));return W}}else{let W=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(W)&&(X===""||$.endsWith(X))){let H=$.slice(W.length,X===""?void 0:$.length-X.length),O=[];for(let U of Y)O.push(...Q(Z_(L$(J.baseUrl,U.replace("*",H)))));return O}}}return[]}function r$(_,$,J,Q=D_){let z=new Map,Y=_.body??[];for(let Z of Y){if(Z.type!=="ImportDeclaration")continue;let W=Z.source?.value??"",X=Q($,W,J);if(X.length===0)continue;let H=X[0],O=Z.specifiers??[];for(let U of O)switch(U.type){case"ImportSpecifier":z.set(U.local.name,{path:H,importedName:U.imported.name});break;case"ImportDefaultSpecifier":z.set(U.local.name,{path:H,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(U.local.name,{path:H,importedName:"*"});break}}return z}import{Visitor as ZJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function XJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function u_(_,$,J,Q){let z=Q(_,$,J),Y=z.length>0?z[0]:null,Z=Y===null&&XJ($);return{resolved:Y,isExternal:Z}}function OJ(_,$,J,Q,z){for(let Y of _.staticImports){let Z=Y.moduleRequest.value,{resolved:W,isExternal:X}=u_($,Z,J,Q),H=W===null?{dstFilePath:null,specifier:Z}:{dstFilePath:W};if(Y.entries.length===0){let O={};if(X)O.isExternal=!0;if(W===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of Y.entries){let U=O.isType,K={};if(U)K.isType=!0;if(X)K.isExternal=!0;if(W===null&&!X)K.isUnresolved=!0;let u,L,B=O.importName.kind;if(B==="Default")u="default",L=O.localName.value;else if(B==="NamespaceObject")u="*",L=O.localName.value,K.importKind="namespace";else u=O.importName.name??"unknown",L=O.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:L,...H,dstSymbolName:u,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}}}function VJ(_,$,J,Q,z){let Y=new Map;for(let Z of _.staticImports)for(let W of Z.entries)Y.set(W.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let W of Z.entries){let X=null;if(W.moduleRequest)X=W.moduleRequest.value;else if(W.localName.name)X=Y.get(W.localName.name)??null;if(!X)continue;let{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportName.name??"default",K=W.exportName.kind,u=W.localName.name??W.importName.name??U,L=W.isType,B={isReExport:!0};if(K==="None");else B.specifiers=[{local:u,exported:U}];if(L)B.isType=!0;if(O)B.isExternal=!0;if(H===null&&!O)B.isUnresolved=!0;let T=null,F=W.importName.kind;if(F==="All"||F==="AllButDefault"){if(K==="Name"&&U)T=U,B.namespaceAlias=U}z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:T,metaJson:JSON.stringify(B),...H===null?{specifier:X}:{}})}}function UJ(_,$,J,Q,z){for(let Y of _.body){let Z=Y;if(Z.type==="ImportDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.importKind==="type",K=W.specifiers,u=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(K.length===0){let L={};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...u,dstSymbolName:null,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}else for(let L of K){let B=L.type,T=U||B==="ImportSpecifier"&&L.importKind==="type",F={};if(T)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;let m,j;if(B==="ImportDefaultSpecifier")m="default",j=L.local.name;else if(B==="ImportNamespaceSpecifier")m="*",j=L.local.name,F.importKind="namespace";else m=a_(L.imported),j=L.local.name;z.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:j,...u,dstSymbolName:m,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.exported,u=K?a_(K):null,L={isReExport:!0};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;if(u)L.namespaceAlias=u;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:u,metaJson:JSON.stringify(L),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let W=Z;if(!W.source)continue;let X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.specifiers??[];for(let u of K){let L=U||u.exportKind==="type",B=a_(u.local),T=a_(u.exported),F={isReExport:!0,specifiers:[{local:B,exported:T}]};if(L)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(F),...H===null?{specifier:X}:{}})}}}}function HJ(_,$,J,Q,z){new ZJ({ImportExpression(Z){let W=Z.source;if(W.type!=="Literal"||typeof W.value!=="string")return;let X=W.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U={isDynamic:!0};if(O)U.isExternal=!0;if(H===null&&!O)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(U),...H===null?{specifier:X}:{}})},CallExpression(Z){let W=Z.callee,X=!1;if(W.type==="Identifier"&&W.name==="require");else if(W.type==="MemberExpression"&&!W.computed){let B=W,T=B.object,F=B.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let O=H[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let U=O.value,{resolved:K,isExternal:u}=u_($,U,J,Q),L={isRequire:!0};if(X)L.isRequireResolve=!0;if(u)L.isExternal=!0;if(K===null&&!u)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,metaJson:JSON.stringify(L),...K===null?{specifier:U}:{}})}}).visit(_)}function o$(_,$,J,Q=D_,z){let Y=[];if(z)OJ(z,$,J,Q,Y),VJ(z,$,J,Q,Y);else UJ(_,$,J,Q,Y);return HJ(_,$,J,Q,Y),Y}import{walk as MJ}from"oxc-walker";function R_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let Y=[z,...J].join(".");return{root:z,parts:J,full:Y}}return null}function t$(_,$,J){let Q=[],z=[],Y=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function W(O){if(!O)return null;let U=J.get(O.root);if(O.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let K=O.parts[O.parts.length-1];return{dstFilePath:U.path,dstSymbolName:K,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,U){let K=R_(O.callee),u=W(K);if(u){let L=Z(),B={};if(U)B.isNew=!0;if(L===null)B.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:L,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}}function H(O,U){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let L=U.id,B=L.type==="Identifier"?L.name:"anonymous";z.push(B);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let L=U.key,B=Y[Y.length-1]??"",T="name"in L?L.name:"anonymous",F=B?`${B}.${T}`:T;z.push(F);return}let K=Z(),u=K?`${K}.<anonymous>`:"<anonymous>";z.push(u)}}return MJ(_,{enter(O,U){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){H(O,U);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as KJ}from"oxc-parser";function e$(_,$,J){let Q=[];function z(Z){let W=Z.id?.name??"AnonymousClass";if(Z.superClass){let H=R_(Z.superClass);if(H){let O=w$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...O})}}let X=Z.implements??[];for(let H of X){let O=R_(H.expression);if(!O)continue;let U=w$(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:W,...U})}}return new KJ({TSInterfaceDeclaration(Z){let W=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let O=R_(H.expression);if(!O)continue;let U=w$(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...U})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function w$(_,$,J){let Q=J.get(_.root);if(Q){if(Q.importedName==="*"){let z=_.parts[_.parts.length-1]??_.root;return{dstFilePath:Q.path,dstSymbolName:z,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:Q.path,dstSymbolName:_.parts.length>0?_.full:Q.importedName}}return{dstFilePath:$,dstSymbolName:_.full,metaJson:JSON.stringify({isLocal:!0})}}function s_(_,$,J,Q=D_,z){let Y=r$(_,$,J,Q),Z=o$(_,$,J,Q,z),W=t$(_,$,Y),X=e$(_,$,Y);return[...Z,...W,...X]}function B$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:Y,tsconfigPaths:Z,knownFiles:W,boundaries:X,module:H}=_,O=q_(Y,Q),K=s_($,O,Z,W?(L,B,T)=>{let F=D_(L,B,T);for(let m of F){let j=j_(Y,m);if(X){let P=o(j,X);if(W.has(`${P}::${j}`))return[m]}else if(W.has(`${J}::${j}`))return[m]}return[]}:void 0,H),u=[];for(let L of K){if(L.dstFilePath===null){let m=j_(Y,L.srcFilePath),j;if(L.metaJson)try{j=JSON.parse(L.metaJson)}catch{}let P=j?.isExternal===!0;u.push({project:J,type:L.type,srcFilePath:m,srcSymbolName:L.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:P?1:0});continue}let B=j_(Y,L.dstFilePath);if(B.startsWith(".."))continue;let T=j_(Y,L.srcFilePath),F=X?o(B,X):J;u.push({project:J,type:L.type,srcFilePath:T,srcSymbolName:L.srcSymbolName??null,dstProject:F,dstFilePath:B,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,u),u.length}import{isErr as LJ}from"@zipbul/result";var _0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function wJ(_){let $=T_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function D$(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let Y=Q+z>>1;if(_[Y].startLine<=$)Q=Y+1;else z=Y-1}if(Q<_.length){let Y=_[Q];if(Y.startLine-$<=J)return Y.name}return null}function r_(_,$,J){let Q=X_(_,$),z=X_(_,J);return{start:Q,end:z}}function $0(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=y_(J),z=wJ(_),Y=[],Z=[...$].sort((X,H)=>X.start-H.start),W=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){W=null;let H=`/*${X.value}*/`,O=l_(H);if(LJ(O))continue;let U=O;if(!U.tags?.length)continue;let K=X_(Q,X.end),u=D$(z,K.line,3),L=J.slice(X.start,X.end);for(let B of U.tags){let T=[B.name,B.description].filter(Boolean).join(" "),F=`@${B.tag}`,m=L.indexOf(F),j;if(m>=0){let P=X.start+m,r=J.indexOf(`
4
+ `,P),w=r>=0?Math.min(r,X.end):X.end;j=r_(Q,P,w)}else j=r_(Q,X.start,X.end);Y.push({tag:B.tag,value:T,source:"jsdoc",span:j,symbolName:u})}}else if(X.type==="Block"){W=null;let H=X.value.split(`
5
+ `),O=0;for(let U of H){let K=U.replace(/^\s*\*?\s?/,""),u=_0.exec(K);if(u){let L=u[1],B=u[2]?.trim()??"",T=`@${L}`,F=U.indexOf(T),m=X.start+2+O+(F>=0?F:0),j=X.start+2+O+U.length,P=r_(Q,m,j),r=X_(Q,X.end),w=D$(z,r.line,3);Y.push({tag:L,value:B,source:"block",span:P,symbolName:w})}O+=U.length+1}}else{let H=X.value,O=_0.exec(H),U=X_(Q,X.start),K=X_(Q,X.end);if(O){let u=O[1],L=O[2]?.trim()??"",B=`@${u}`,T=H.indexOf(B),F=X.start+2+(T>=0?T:0),m=r_(Q,F,X.end),j=D$(z,K.line,3),P={tag:u,value:L,source:"line",span:m,symbolName:j};Y.push(P),W={annotation:P,endLine:K.line}}else if(W&&U.line===W.endLine+1){let u=H.trim();if(u)W.annotation.value+=" "+u,W.annotation.span.end=X_(Q,X.end),W.endLine=K.line}else W=null}return Y}function u$(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,Y=$0($);if(z.deleteFileAnnotations(J,Q),!Y.length)return 0;let Z=new Date().toISOString(),W=Y.map((X)=>({project:J,filePath:Q,tag:X.tag,value:X.value,source:X.source,symbolName:X.symbolName,startLine:X.span.start.line,startColumn:X.span.start.column,endLine:X.span.end.line,endColumn:X.span.end.column,indexedAt:Z}));return z.insertBatch(J,Q,W),Y.length}function J0(_,$){let J=[],Q=[],z=[];for(let[O,U]of $)if(!_.has(O))J.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[O,U]of _)if(!$.has(O))Q.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let Y=new Map,Z=new Map;for(let O of J){let U=Y.get(O.filePath)??[];U.push(O),Y.set(O.filePath,U)}for(let O of Q){let U=Z.get(O.filePath)??[];U.push(O),Z.set(O.filePath,U)}let W=new Set,X=new Set;for(let[O,U]of Y){let K=Z.get(O);if(!K)continue;for(let u of new Set(U.map((L)=>L.kind))){let L=U.filter((j)=>j.kind===u&&!W.has(j)),B=K.filter((j)=>j.kind===u&&!X.has(j));if(!L.length||!B.length)continue;let T=(j,P)=>{return P.get(`${j.filePath}::${j.name}`)?.structuralFingerprint??null},F=(j,P)=>{return P.get(`${j.filePath}::${j.name}`)?.startLine??0},m=new Map;for(let j of B){let P=T(j,_);if(!P)continue;let r=m.get(P)??[];r.push(j),m.set(P,r)}for(let j of L){if(W.has(j))continue;let P=T(j,$);if(!P)continue;let r=m.get(P);if(!r)continue;let w=r.filter((D)=>!X.has(D));if(!w.length)continue;let A=w[0];if(w.length>1){let D=F(j,$),C=Math.abs(F(A,_)-D);for(let N=1;N<w.length;N++){let g=Math.abs(F(w[N],_)-D);if(g<C)C=g,A=w[N]}}z.push({oldName:A.name,newName:j.name,filePath:O,kind:u}),W.add(j),X.add(A)}}}let H=z.filter((O)=>!O.oldName.includes("."));for(let O of H){let U=`${O.oldName}.`,K=`${O.newName}.`,u=Q.filter((B)=>B.filePath===O.filePath&&B.name.startsWith(U)&&!X.has(B)),L=J.filter((B)=>B.filePath===O.filePath&&B.name.startsWith(K)&&!W.has(B));for(let B of u){let T=B.name.slice(U.length),F=L.find((m)=>m.name.slice(K.length)===T);if(F)z.push({oldName:B.name,newName:F.name,filePath:O.filePath,kind:B.kind}),W.add(F),X.add(B)}}return{renamed:z,added:J.filter((O)=>!W.has(O)),removed:Q.filter((O)=>!X.has(O))}}var BJ=100,z0=50;class I${opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(_){this.opts=_,this.logger=_.logger??console,this.tsconfigPathsRaw=v_(_.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(_){return this.startIndex(_,!1)}onIndexed(_){return this.callbacks.add(_),()=>this.callbacks.delete(_)}handleWatcherEvent(_){if(_.filePath.endsWith("tsconfig.json")){d_(this.opts.projectRoot),this.tsconfigPathsRaw=v_(this.opts.projectRoot),this.fullIndex().catch(($)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",$)});return}if(_.filePath.endsWith("package.json")){let $=this.opts.discoverProjectsFn??p_;this.boundariesRefresh=$(this.opts.projectRoot).then((J)=>{this.opts.boundaries=J})}if(this.pendingEvents.push(_),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},BJ)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(_,$){if(this.indexingLock){if($)return this.pendingFullIndex=!0,new Promise((Q,z)=>{this.pendingFullIndexWaiters.push({resolve:Q,reject:z})});return this.currentIndexing}this.indexingLock=!0;let J=this.doIndex(_,$).then((Q)=>{return this.fireCallbacks(Q),Q}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let Q=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((z)=>{for(let Y of Q)Y.resolve(z)}).catch((z)=>{for(let Y of Q)Y.reject(z)})}else if(this.pendingEvents.length>0){let Q=this.pendingEvents.splice(0);this.startIndex(Q,!1).catch((z)=>this.logger.error("[IndexCoordinator] incremental drain error",z))}});return this.currentIndexing=J,J}async doIndex(_,$){let J=Date.now(),{fileRepo:Q,symbolRepo:z,relationRepo:Y,dbConnection:Z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let W,X;if(_!==void 0)W=_.filter((M)=>M.eventType==="create"||M.eventType==="change").map((M)=>({filePath:M.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((M)=>M.eventType==="delete").map((M)=>M.filePath);else{let M=new Map;for(let S of this.opts.boundaries)for(let[k,f]of Q.getFilesMap(S.project))M.set(k,f);let q=await a$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>M}});W=q.changed,X=q.deleted}let H=await this.tsconfigPathsRaw??void 0,O=new Map;for(let M of X){let q=o(M,this.opts.boundaries),S=z.getFileSymbols(q,M);O.set(M,S)}let U=crypto.randomUUID(),K=new Map,u=new Map,L=(M)=>({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint,structuralFingerprint:M.structuralFingerprint??null,startLine:M.startLine,isExported:M.isExported??0});if($)for(let M of this.opts.boundaries)for(let q of Q.getAllFiles(M.project))for(let S of z.getFileSymbols(M.project,q.filePath))K.set(`${S.filePath}::${S.name}`,L(S));else{for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of z.getFileSymbols(q,M.filePath))K.set(`${S.filePath}::${S.name}`,L(S))}for(let[,M]of O)for(let q of M)K.set(`${q.filePath}::${q.name}`,L(q))}let B=(M)=>`${M.type}|${M.srcFilePath}|${M.dstFilePath??""}|${M.srcSymbolName??""}|${M.dstSymbolName??""}|${O_(M.metaJson??"")}`,T=new Map;if($)for(let M of this.opts.boundaries)for(let q of Q.getAllFiles(M.project))for(let S of Y.getOutgoing(M.project,q.filePath))T.set(B(S),S);else{for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of Y.getOutgoing(q,M.filePath))T.set(B(S),S)}for(let M of X){let q=o(M,this.opts.boundaries);for(let S of Y.getOutgoing(q,M))T.set(B(S),S)}}let{annotationRepo:F,changelogRepo:m}=this.opts,j=()=>{for(let M of X){let q=o(M,this.opts.boundaries);if(z.deleteFileSymbols(q,M),Y.deleteFileRelations(q,M),Y.deleteIncomingRelations(q,M),F)F.deleteFileAnnotations(q,M);Q.deleteFile(q,M)}},P=0,r=async()=>{let{projectRoot:M,boundaries:q}=this.opts,{parseCache:S}=this.opts,k=0,f=0,I=0,t=[],v=[];for(let y of W)try{let l=q_(M,y.filePath),K_=Bun.file(l),N_=await K_.text(),b$=y.contentHash||O_(N_),y$=o(y.filePath,q);Q.upsertFile({project:y$,filePath:y.filePath,mtimeMs:K_.lastModified,size:K_.size,contentHash:b$,updatedAt:new Date().toISOString(),lineCount:N_.split(`
6
+ `).length});let z$=(this.opts.parseSourceFn??b_)(l,N_);if(Q0(z$))throw z$.data;let A1=z$;v.push({filePath:y.filePath,text:N_,contentHash:b$,parsed:A1,project:y$})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${y.filePath}:`,l),t.push(y.filePath)}let x=new Set;for(let y of q)for(let[l]of Q.getFilesMap(y.project))x.add(`${y.project}::${l}`);return Z.transaction(()=>{for(let y of v){if(K$({parsed:y.parsed,project:y.project,filePath:y.filePath,contentHash:y.contentHash,symbolRepo:z}),f+=B$({ast:y.parsed.program,project:y.project,filePath:y.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:x,boundaries:q,module:y.parsed.module}),F)I+=u$({parsed:y.parsed,project:y.project,filePath:y.filePath,annotationRepo:F});S.set(y.filePath,y.parsed),k+=z.getFileSymbols(y.project,y.filePath).length}}),{symbols:k,relations:f,annotations:I,failedFiles:t}},w=0,A=0,D=[];if($){let{projectRoot:M,boundaries:q}=this.opts,{parseCache:S}=this.opts,k=[];for(let I=0;I<W.length;I+=z0){let t=W.slice(I,I+z0),v=await Promise.allSettled(t.map(async(x)=>{let y=q_(M,x.filePath),l=Bun.file(y),K_=await l.text(),N_=x.contentHash||O_(K_);return{filePath:x.filePath,text:K_,contentHash:N_,mtimeMs:l.lastModified,size:l.size}}));for(let x=0;x<v.length;x++){let y=v[x];if(y.status==="fulfilled")k.push(y.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",y.reason),D.push(t[x].filePath)}}let f=[];Z.transaction(()=>{for(let v of k){let x=o(v.filePath,q);Q.deleteFile(x,v.filePath)}for(let v of X){let x=o(v,q);if(z.deleteFileSymbols(x,v),Y.deleteFileRelations(x,v),Y.deleteIncomingRelations(x,v),F)F.deleteFileAnnotations(x,v);Q.deleteFile(x,v)}for(let v of k){let x=o(v.filePath,q);Q.upsertFile({project:x,filePath:v.filePath,mtimeMs:v.mtimeMs,size:v.size,contentHash:v.contentHash,updatedAt:new Date().toISOString(),lineCount:v.text.split(`
7
+ `).length})}let I=new Set;for(let v of q)for(let[x]of Q.getFilesMap(v.project))I.add(`${v.project}::${x}`);let t=this.opts.parseSourceFn??b_;for(let v of k){let x=o(v.filePath,q),y=t(q_(M,v.filePath),v.text);if(Q0(y))throw y.data;let l=y;if(f.push({filePath:v.filePath,parsed:l}),K$({parsed:l,project:x,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:z}),F)P+=u$({parsed:l,project:x,filePath:v.filePath,annotationRepo:F});A+=B$({ast:l.program,project:x,filePath:v.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:I,boundaries:q,module:l.module}),w+=z.getFileSymbols(x,v.filePath).length}});for(let I of f)S.set(I.filePath,I.parsed)}else{j();let M=await r();w=M.symbols,A=M.relations,P=M.annotations,D=M.failedFiles}for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of z.getFileSymbols(q,M.filePath))u.set(`${S.filePath}::${S.name}`,L(S))}let C=new Map;for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of Y.getOutgoing(q,M.filePath))C.set(B(S),S)}let N=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),g={added:[...C.entries()].filter(([M])=>!T.has(M)).map(([,M])=>N(M)),removed:[...T.entries()].filter(([M])=>!C.has(M)).map(([,M])=>N(M))},R={added:[],modified:[],removed:[]};for(let[M,q]of u){let S=K.get(M);if(!S)R.added.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});else{let k=S.fingerprint!==q.fingerprint,f=S.isExported!==q.isExported,I=S.structuralFingerprint!==null&&q.structuralFingerprint!==null&&S.structuralFingerprint!==q.structuralFingerprint;if(k||f||I)R.modified.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)})}}for(let[M,q]of K)if(!u.has(M))R.removed.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});let E=J0(K,u),i=new Set(E.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),d=new Set(E.renamed.map((M)=>`${M.filePath}::${M.newName}`));R.added=R.added.filter((M)=>!d.has(`${M.filePath}::${M.name}`)),R.removed=R.removed.filter((M)=>!i.has(`${M.filePath}::${M.name}`));let a=[];if(!$){for(let[M,q]of O)for(let S of q){if(!S.fingerprint)continue;let k=o(M,this.opts.boundaries),f=z.getByFingerprint(k,S.fingerprint);if(f.length===1){let I=f[0];Y.retargetRelations({dstProject:k,oldFile:M,oldSymbol:S.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M,isExported:I.isExported??0})}}for(let M of E.removed){let S=K.get(`${M.filePath}::${M.name}`)?.fingerprint;if(!S)continue;let k=o(M.filePath,this.opts.boundaries),f=z.getByFingerprint(k,S);if(f.length===1){let I=f[0];if(I.filePath!==M.filePath||I.name!==M.name)Y.retargetRelations({dstProject:k,oldFile:M.filePath,oldSymbol:M.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M.filePath,isExported:I.isExported??0})}}}if(a.length){let M=new Set(a.map((S)=>`${S.filePath}::${S.name}`)),q=new Set(a.map((S)=>`${S.oldFilePath}::${S.name}`));R.added=R.added.filter((S)=>!M.has(`${S.filePath}::${S.name}`)),R.removed=R.removed.filter((S)=>!q.has(`${S.filePath}::${S.name}`))}if(m){let M=new Date().toISOString(),q=$?1:0,S=[];for(let k of R.added){let f=`${k.filePath}::${k.name}`,I=u.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.modified){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"modified",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.removed){let f=`${k.filePath}::${k.name}`,I=K.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of E.renamed){let f=u.get(`${k.filePath}::${k.newName}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"renamed",symbolName:k.newName,symbolKind:k.kind,filePath:k.filePath,oldName:k.oldName,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of a){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"moved",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:k.oldFilePath,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}if(S.length)try{Z.transaction(()=>{m.insertBatch(S)})}catch(k){this.logger.error("[IndexCoordinator] changelog insert failed:",k)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let k=new Date(Date.now()-2592000000).toISOString();try{for(let f of this.opts.boundaries)m.pruneOlderThan(f.project,k)}catch(f){this.logger.error("[IndexCoordinator] changelog pruning failed:",f)}}}return{indexedFiles:W.length,removedFiles:X.length,totalSymbols:w,totalRelations:A,totalAnnotations:P,durationMs:Date.now()-J,changedFiles:W.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:D,changedSymbols:R,renamedSymbols:E.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(u.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:a.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:g}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function DJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function uJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function W0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??DJ,Y=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let W=_.selectOwner();if(!W)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-uJ(W.heartbeat_at))/1000),H=z(W.pid);if(H&&Z&&W.instance_id&&W.instance_id!==Z&&W.pid!==$)return _.replaceOwner($,Z),"owner";if(H&&X<Y)return"reader";return _.replaceOwner($,Z),"owner"})}function Y0(_,$){_.deleteOwner($)}function Z0(_,$){_.touchOwner($)}class P_{#_;#$=new Map;constructor(_){this.#_=Math.max(1,_)}get size(){return this.#$.size}has(_){return this.#$.has(_)}get(_){if(!this.#$.has(_))return;let $=this.#$.get(_);return this.#$.delete(_),this.#$.set(_,$),$}set(_,$){if(this.#$.has(_))this.#$.delete(_);if(this.#$.set(_,$),this.#$.size>this.#_){let J=this.#$.keys().next().value;if(J!==void 0)this.#$.delete(J)}}delete(_){return this.#$.delete(_)}clear(){this.#$.clear()}}class C${lru;constructor(_=500){this.lru=new P_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function N$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,Y={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)Y.exactName=Q.text;else{let W=g_(Q.text);if(W)Y.ftsQuery=W}if(Q.decorator)Y.decorator=Q.decorator;if(Q.regex)Y.regex=Q.regex;return $.searchByQuery(Y).map((W)=>{let X=W.name.indexOf(".");return{id:W.id,filePath:W.filePath,kind:W.kind,name:W.name,memberName:X>=0?W.name.slice(X+1):null,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}},isExported:W.isExported===1,signature:W.signature,fingerprint:W.fingerprint,detail:W.detailJson?(()=>{try{return JSON.parse(W.detailJson)}catch{return{}}})():{}}})}function A$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,Y=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),W=Z?void 0:Y,H=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:W}).map((O)=>{let U;if(O.metaJson)try{U=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,metaJson:O.metaJson??void 0,meta:U,...O.specifier!=null?{specifier:O.specifier}:{}}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((K)=>(!O||O.match(K.srcFilePath))&&(!U||K.dstFilePath===null||U.match(K.dstFilePath)))}if(Z&&Y!==void 0&&H.length>Y)H=H.slice(0,Y);return H}import{findInFiles as IJ,Lang as CJ}from"@ast-grep/napi";async function g$(_){if(_.filePaths.length===0)return[];let $=[];return await IJ(CJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,Q)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let z of Q){let Y=z.range();$.push({filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,matchedText:z.text()})}}),$}import J_ from"typescript";import{isErr as bJ}from"@zipbul/result";import U_ from"typescript";import NJ from"path";import{err as q$}from"@zipbul/result";function AJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}function gJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}class o_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??AJ,Q=$.resolveNonTrackedFile??gJ,z=NJ.dirname(_),Y=J(_);if(Y===void 0)return q$(new V("semantic",`tsconfig not found: ${_}`));let Z=U_.parseJsonText(_,Y),W=Z.parseDiagnostics;if(W&&W.length>0){let U=W.map((K)=>U_.flattenDiagnosticMessageText(K.messageText,`
8
+ `)).join("; ");return q$(new V("semantic",`tsconfig parse error: ${U}`))}let X=U_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>J(U)!==void 0||Q(U)!==void 0,readFile:(U)=>J(U)??Q(U)},z);if(X.errors.length>0){let U=X.errors.filter((K)=>K.category===U_.DiagnosticCategory.Error&&K.code!==18003);if(U.length>0){let K=U.map((u)=>U_.flattenDiagnosticMessageText(u.messageText,`
9
+ `)).join("; ");return q$(new V("semantic",`tsconfig compile error: ${K}`))}}let H=new X0(X.fileNames,X.options,z,Q),O=U_.createLanguageService(H);return new o_(O,H)}get isDisposed(){return this.#J}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#z(){if(this.#J)throw Error("TscProgram is disposed")}}class X0{#_;#$;#J;#z;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#Q.get(_);if(J)J.version+=1,J.content=$;else this.#Q.set(_,{version:1,content:$})}removeFile(_){this.#Q.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#Q.keys()];return[...[...this.#_].filter((J)=>!this.#Q.has(J)),..._]}getScriptVersion(_){let $=this.#Q.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#Q.get(_);if($)return U_.ScriptSnapshot.fromString($.content);let J=this.#z(_);if(J!==void 0)return U_.ScriptSnapshot.fromString(J);return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return U_.getDefaultLibFilePath(_)}fileExists(_){if(this.#Q.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#Q.get(_);if($)return $.content;return this.#z(_)}}import s from"typescript";import qJ from"typescript";function W_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),Y=Q.getEnd();if($<z||$>=Y)return;let Z;return qJ.forEachChild(Q,(W)=>{if(!Z)Z=J(W)}),Z??Q}return J(_)}var t_=8;function SJ(_){return!!(_.flags&s.TypeFlags.Object)&&!!(_.objectFlags&s.ObjectFlags.Reference)}function H_(_,$,J=0){let Q=_.typeToString($),z=$.flags,Y=!!(z&s.TypeFlags.Union),Z=!!(z&s.TypeFlags.Intersection),W;if(J<t_&&SJ($)){let K=_.getTypeArguments($);if(K.length>0)W=K}let X=!!(z&s.TypeFlags.TypeParameter)||W!==void 0&&W.length>0,H;if(Y&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));else if(Z&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));let O;if(W&&W.length>0)O=W.map((K)=>H_(_,K,J+1));let U;if(J<t_&&!!(z&s.TypeFlags.Object)&&!Y&&!Z){let K=_.getPropertiesOfType($);if(K.length>0&&K.length<=50){let u=$.symbol?.declarations?.[0];U=[];for(let L of K){let B=L.declarations?.[0]??u;if(!B)continue;try{let T=_.getTypeOfSymbolAtLocation(L,B);U.push({name:L.getName(),type:H_(_,T,J+1)})}catch{}}if(U.length===0)U=void 0}}return{text:Q,flags:z,isUnion:Y,isIntersection:Z,isGeneric:X,members:H,typeArguments:O,properties:U}}function TJ(_){return s.isFunctionDeclaration(_)||s.isVariableDeclaration(_)||s.isClassDeclaration(_)||s.isInterfaceDeclaration(_)||s.isTypeAliasDeclaration(_)||s.isEnumDeclaration(_)||s.isMethodDeclaration(_)||s.isPropertyDeclaration(_)||s.isPropertySignature(_)||s.isMethodSignature(_)}class S${program;constructor(_){this.program=_}collectAt(_,$){let J=this.program.getProgram(),Q=this.program.getChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let Y=W_(z,$);if(!Y)return null;if(!s.isIdentifier(Y)&&!s.isTypeNode(Y))return null;try{let Z=Q.getTypeAtLocation(Y);return H_(Q,Z)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getChecker(),Y=this.program.getProgram(),Z=Y.getSourceFile(_);if(!Z)return null;let W=W_(Z,$);if(!W||!s.isIdentifier(W))return null;let X=Y.getSourceFile(J);if(!X)return null;let H=W_(X,Q);if(!H||!s.isIdentifier(H))return null;try{let O=z.getTypeAtLocation(W),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(O,U)}catch{return null}}isAssignableToType(_,$,J,Q){let z=this.program.getChecker(),Z=this.program.getProgram().getSourceFile(_);if(!Z)return null;let W=W_(Z,$);if(!W||!s.isIdentifier(W)&&!s.isTypeNode(W))return null;let X=`${_}.__gildash_probe__.ts`,H=`declare const __gildash_probe__: ${J};`;this.program.notifyFileChanged(X,H);try{let O=z.getTypeAtLocation(W),K=this.program.getProgram().getSourceFile(X);if(!K)return null;let u=this.program.getChecker(),L=K.statements[0];if(!L||!s.isVariableStatement(L))return null;let B=L.declarationList.declarations[0];if(!B)return null;let T=u.getTypeAtLocation(B.name);if(Q?.anyConstituent&&O.isUnion())return O.types.some((F)=>u.isTypeAssignableTo(F,T));return u.isTypeAssignableTo(O,T)}catch{return null}finally{this.program.removeFile(X)}}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=this.program.getChecker(),z=J.getSourceFile(_);if(!z)return $;function Y(Z){if(TJ(Z)&&Z.name&&s.isIdentifier(Z.name)){let W=Z.name;try{let X=Q.getTypeAtLocation(W),H=W.getStart(z);$.set(H,H_(Q,X))}catch{}}s.forEachChild(Z,Y)}return Y(z),$}}import M_ from"typescript";var RJ=1000,kJ=1;function FJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?M_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function e_(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),Y=Q?M_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",W=Y?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:W},H=_;if(H.parent)X.parent=FJ(H.parent);let O=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<kJ){let U=O.flags,K=!!(U&M_.SymbolFlags.Enum),u=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),L=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(K&&O.exports&&O.exports.size>0){let B=[];O.exports.forEach((T)=>{B.push(e_(T,$+1,J))}),X.members=B}else if(L&&O.members&&O.members.size>0){let B=[];O.members.forEach((T)=>{B.push(e_(T,$+1,J))}),X.members=B}if(u&&O.exports&&O.exports.size>0){let B=[];O.exports.forEach((T)=>{B.push(e_(T,$+1,J))}),X.exports=B}}return X}class T${#_;#$;#J=new Map;constructor(_,$=RJ){this.#_=_,this.#$=new P_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let Y=this.#_.getProgram().getSourceFile(_);if(!Y)return null;let Z=W_(Y,$);if(!Z||!M_.isIdentifier(Z))return null;let W=this.#_.getChecker(),X=W.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,W);this.#$.set(J,H);let O=this.#J.get(_);if(!O)O=new Set,this.#J.set(_,O);return O.add(J),H}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import GJ from"typescript";class R${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=W_(Q,$);if(!z||!GJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z)for(let H of X.references){let O=J.getSourceFile(H.fileName);if(!O)continue;let{line:U,character:K}=O.getLineAndCharacterOfPosition(H.textSpan.start);W.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:K,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return W}}import p from"typescript";function jJ(_,$){let J=W_(_,$);if(!J)return;if(O0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(O0(Q))return Q;Q=Q.parent}return J}function O0(_){return p.isClassDeclaration(_)||p.isClassExpression(_)||p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_)||p.isVariableDeclaration(_)||p.isObjectLiteralExpression(_)}function V0(_){if(p.isClassDeclaration(_)||p.isClassExpression(_))return"class";if(p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_))return"function";if(p.isObjectLiteralExpression(_))return"object";if(p.isVariableDeclaration(_)&&_.initializer)return V0(_.initializer);return"class"}function EJ(_,$){if(p.isClassDeclaration(_)||p.isFunctionDeclaration(_))return _.name?.getText($)??"";if(p.isClassExpression(_))return _.name?.getText($)??"";if(p.isVariableDeclaration(_)&&p.isIdentifier(_.name))return _.name.getText($);if(p.isFunctionExpression(_))return _.name?.getText($)??"";if(p.isArrowFunction(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(p.isObjectLiteralExpression(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function vJ(_){if(!p.isClassDeclaration(_)&&!p.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===p.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=W_(Q,$);if(!z||!p.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z){if(X.kind===p.ScriptElementKind.interfaceElement||X.kind===p.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let O=jJ(H,X.textSpan.start);if(!O)continue;let U=V0(O),K=EJ(O,H),u=vJ(O);W.push({filePath:X.fileName,symbolName:K,position:X.textSpan.start,kind:U,isExplicit:u})}return W}}function yJ(_){if(J_.isFunctionDeclaration(_))return"function";if(J_.isClassDeclaration(_))return"class";if(J_.isInterfaceDeclaration(_))return"interface";if(J_.isTypeAliasDeclaration(_))return"type";if(J_.isEnumDeclaration(_))return"enum";if(J_.isVariableDeclaration(_))return"const";if(J_.isVariableStatement(_))return"const";return"unknown"}function U0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class _${#_;#$;#J;#z;#Q;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#Q=z}static create(_,$={}){let J=o_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(bJ(J))return J;let Q=J,z=$.typeCollector??new S$(Q),Y=$.symbolGraph??new T$(Q),Z=$.referenceResolver??new R$(Q),W=$.implementationFinder??new k$(Q);return new _$(Q,z,Y,Z,W)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#W(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#W(),this.#$.collectFile(_)}findReferences(_,$){return this.#W(),this.#z.findAt(_,$)}findImplementations(_,$){return this.#W(),this.#Q.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#W(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#W(),this.#$.isAssignableToType(_,$,J,Q)}getSymbolNode(_,$){return this.#W(),this.#J.get(_,$)}getBaseTypes(_,$){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=W_(Q,$);if(!z)return null;let Y=this.#_.getChecker(),Z=Y.getTypeAtLocation(z);if(!(Z.flags&J_.TypeFlags.Object)||!(Z.objectFlags&J_.ObjectFlags.ClassOrInterface))return null;let W=Y.getBaseTypes(Z);if(!W||W.length===0)return[];return W.map((X)=>H_(Y,X))}getModuleInterface(_){this.#W();let $=[],Q=this.#_.getProgram().getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=this.#_.getChecker(),Y=z.getSymbolAtLocation(Q);if(Y){let Z=z.getExportsOfModule(Y);for(let W of Z){let X=W.getName(),H=W.declarations?.[0],O="unknown";if(H){if(O=yJ(H),O==="unknown"&&J_.isExportAssignment(H))O="const"}let U=null;try{let K=z.getTypeOfSymbolAtLocation(W,H??Q);U=H_(z,K)}catch{}$.push({name:X,kind:O,resolvedType:U})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return J_.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),Y=$;while(Y<z.length){let Z=z.indexOf(J,Y);if(Z<0)return null;let W=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!U0(W)&&!U0(X))return Z;Y=Z+1}return null}getDiagnostics(_,$){this.#W();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[J_.DiagnosticCategory.Error]:"error",[J_.DiagnosticCategory.Warning]:"warning",[J_.DiagnosticCategory.Suggestion]:"suggestion",[J_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?J_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let W=1,X=0;if(Z.file&&Z.start!==void 0){let H=J_.getLineAndCharacterOfPosition(Z.file,Z.start);W=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:W,column:X,message:J_.flattenDiagnosticMessageText(Z.messageText,`
10
+ `),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#_.dispose(),this.#J.clear()}#W(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as I_,and as H0,sql as PJ}from"drizzle-orm";var M0=80;class F${db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((z)=>({project:_,filePath:$,tag:z.tag,value:z.value,source:z.source,symbolName:z.symbolName,startLine:z.startLine,startColumn:z.startColumn,endLine:z.endLine,endColumn:z.endColumn,indexedAt:z.indexedAt}));for(let z=0;z<Q.length;z+=M0)this.db.drizzleDb.insert(Y_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Y_).where(H0(I_(Y_.project,_),I_(Y_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Y_).where(H0(_.project?I_(Y_.project,_.project):void 0,_.tag?I_(Y_.tag,_.tag):void 0,_.filePath?I_(Y_.filePath,_.filePath):void 0,_.symbolName?I_(Y_.symbolName,_.symbolName):void 0,_.source?I_(Y_.source,_.source):void 0,_.ftsQuery?PJ`${Y_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as k_,and as K0,sql as f_,gt as fJ,gte as nJ}from"drizzle-orm";var L0=80;class G${db;constructor(_){this.db=_}insertBatch(_){if(!_.length)return;let $=_.map((J)=>({project:J.project,changeType:J.changeType,symbolName:J.symbolName,symbolKind:J.symbolKind,filePath:J.filePath,oldName:J.oldName,oldFilePath:J.oldFilePath,fingerprint:J.fingerprint,changedAt:J.changedAt,isFullIndex:J.isFullIndex,indexRunId:J.indexRunId}));for(let J=0;J<$.length;J+=L0)this.db.drizzleDb.insert(Q_).values($.slice(J,J+L0)).run()}getSince(_){return this.db.drizzleDb.select().from(Q_).where(K0(k_(Q_.project,_.project),nJ(Q_.changedAt,_.since),_.symbolName?k_(Q_.symbolName,_.symbolName):void 0,_.changeTypes?.length?f_`${Q_.changeType} IN (${f_.join(_.changeTypes.map(($)=>f_`${$}`),f_`, `)})`:void 0,_.filePath?k_(Q_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:k_(Q_.isFullIndex,0),_.indexRunId?k_(Q_.indexRunId,_.indexRunId):void 0,_.afterId?fJ(Q_.id,_.afterId):void 0)).orderBy(Q_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(Q_).where(K0(k_(Q_.project,_),f_`${Q_.changedAt} < ${$}`)).run().changes}}function w0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,Y;if(Q.text){let W=g_(Q.text);if(W)Y=W}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:Y,limit:Q.limit}).map((W)=>({tag:W.tag,value:W.value,source:W.source,filePath:W.filePath,symbolName:W.symbolName,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}}}))}class $${options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let Y=this.adjacencyList.get(z);if(Y){for(let W of Y)this.reverseAdjacencyList.get(W)?.delete(z);Y.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let W of Z)this.adjacencyList.get(W)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let Y=J(z);for(let Z of Y){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let Y of this.adjacencyList.get(z.node)??[]){if($.has(Y))return!0;if(!_.has(Y))Q.push({node:Y,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return pJ(J,$)}}var mJ=(_,$)=>_.localeCompare($);function xJ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let J=$;for(let Q=1;Q<$.length;Q++){let z=$.slice(Q).concat($.slice(0,Q));if(z.join("::")<J.join("::"))J=z}return[...J]}function j$(_,$,J){let Q=xJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function hJ(_){let $=0,J=[],Q=new Set,z=new Map,Y=new Map,Z=[],W=(X)=>{z.set(X,$),Y.set(X,$),$+=1,J.push(X),Q.add(X);for(let H of _.get(X)??[])if(!z.has(H))W(H),Y.set(X,Math.min(Y.get(X)??0,Y.get(H)??0));else if(Q.has(H))Y.set(X,Math.min(Y.get(X)??0,z.get(H)??0));if(Y.get(X)===z.get(X)){let H=[],O="";do O=J.pop()??"",Q.delete(O),H.push(O);while(O!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))W(X);return{components:Z}}function iJ(_,$,J){let Q=[],z=new Set,Y=[..._].sort(mJ),Z=(W,X,H)=>{X.delete(W);let O=H.get(W);if(!O)return;for(let U of O)if(X.has(U))Z(U,X,H);O.clear()};for(let W=0;W<Y.length&&Q.length<J;W++){let X=Y[W]??"",H=new Set(Y.slice(W)),O=new Set,U=new Map,K=[],u=(B)=>($.get(B)??[]).filter((T)=>H.has(T)),L=(B)=>{if(Q.length>=J)return!0;let T=!1;K.push(B),O.add(B);for(let F of u(B)){if(Q.length>=J)break;if(F===X)j$(z,Q,K.concat(X)),T=!0;else if(!O.has(F)){if(L(F))T=!0}}if(T)Z(B,O,U);else for(let F of u(B)){let m=U.get(F)??new Set;m.add(B),U.set(F,m)}return K.pop(),T};L(X)}return Q}function pJ(_,$){let{components:J}=hJ(_),Q=[],z=new Set;for(let Y of J){if(Q.length>=$)break;if(Y.length===0)continue;if(Y.length===1){let X=Y[0]??"";if((_.get(X)??[]).includes(X))j$(z,Q,[X,X]);continue}let Z=$-Q.length,W=iJ(Y,_,Z);for(let X of W){if(Q.length>=$)break;j$(z,Q,X)}}return Q}var dJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function C_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>dJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new $$({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function B0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependencies failed",{cause:z})}}function D0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependents failed",{cause:z})}}async function u0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function I0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function C0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function N0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function A0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function q0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=C_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getFanMetrics failed",{cause:Q})}}var aJ=30000,S0=15000,sJ=10;function rJ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let Y of _.onErrorCallbacks)try{Y(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function oJ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=m_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function T0(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new I$({projectRoot:_.projectRoot,boundaries:_.boundaries,extensions:_.extensions,ignorePatterns:_.ignorePatterns,dbConnection:_.db,parseCache:_.parseCache,fileRepo:_.fileRepo,symbolRepo:_.symbolRepo,relationRepo:_.relationRepo,annotationRepo:_.annotationRepo??void 0,changelogRepo:_.changelogRepo??void 0,logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let Y=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>Y.getByType(X,"imports").concat(Y.getByType(X,"type-references")).concat(Y.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else J$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new H$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(rJ(_,J)).then((z)=>{if(n_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},aJ)}await J.fullIndex(),await oJ(_)}function tJ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((Y)=>_.logger.error("[Gildash] close error during signal",Q,Y))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function R0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:Y=console,existsSyncFn:Z=cJ,dbConnectionFactory:W,watcherFactory:X,coordinatorFactory:H,repositoryFactory:O,acquireWatcherRoleFn:U=W0,releaseWatcherRoleFn:K=Y0,updateHeartbeatFn:u=Z0,discoverProjectsFn:L=p_,parseSourceFn:B=b_,extractSymbolsFn:T=T_,extractRelationsFn:F=s_,symbolSearchFn:m=N$,relationSearchFn:j=A$,patternSearchFn:P=g$,loadTsconfigPathsFn:r=v_,readFileFn:w=async(E)=>Bun.file(E).text(),unlinkFn:A=async(E)=>{await Bun.file(E).unlink()},watchMode:D,semantic:C,semanticLayerFactory:N}=_;if(!m_.isAbsolute($))throw new V("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new V("validation",`Gildash: projectRoot does not exist: "${$}"`);let g=W?W():new Z$({projectRoot:$}),R=g.open();if(n_(R))throw R.data;try{let E=await L($),i=E[0]?.project??m_.basename($),d=O?O():(()=>{let t=g;return{fileRepo:new X$(t),symbolRepo:new O$(t),relationRepo:new V$(t),parseCache:new C$(z)}})(),a=O?null:g,M=a?new F$(a):null,q=a?new G$(a):null,S=D??!0,k=crypto.randomUUID(),f;if(S)f=await Promise.resolve(U(g,process.pid,{instanceId:k}));else f="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:Y,defaultProject:i,role:f,db:g,symbolRepo:d.symbolRepo,relationRepo:d.relationRepo,fileRepo:d.fileRepo,parseCache:d.parseCache,annotationRepo:M,changelogRepo:q,annotationSearchFn:w0,releaseWatcherRoleFn:K,parseSourceFn:B,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:m,relationSearchFn:j,patternSearchFn:P,readFileFn:w,unlinkFn:A,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:u,watcherFactory:X,coordinatorFactory:H,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:E,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),I.tsconfigPaths=await r($),C){let t=m_.join($,"tsconfig.json");try{if(N)I.semanticLayer=N(t);else{let v=_$.create(t);if(n_(v))throw v.data;I.semanticLayer=v}}catch(v){if(v instanceof V)throw v;throw new V("semantic","Gildash: semantic layer creation failed",{cause:v})}}if(f==="owner")await T0(I,{isWatchMode:S});else{let t=0,v=async()=>{try{let x=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(t=0,x==="owner"){I.role="owner";for(let y of I.onRoleChangedCallbacks)try{y("owner")}catch(l){I.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(I.timer),I.timer=null;try{await T0(I,{isWatchMode:!0})}catch(y){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",y),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let l=await I.watcher.close();if(n_(l))I.logger.error("[Gildash] watcher close error during promotion rollback",l.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((l)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(l){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}I.timer=setInterval(v,S0)}}}catch(x){t++;let y=x instanceof V?x:new V("watcher","Gildash: healthcheck error",{cause:x});for(let l of I.onErrorCallbacks)try{l(y)}catch(K_){I.logger.error("[Gildash] onError callback threw:",K_)}if(I.logger.error("[Gildash] healthcheck error",x),t>=sJ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,Q$(I).catch((l)=>I.logger.error("[Gildash] close error during healthcheck shutdown",l))}};I.timer=setInterval(v,S0)}if(S)tJ(I,()=>Q$(I));return I}catch(E){if(g.close(),E instanceof V)throw E;throw new V("store","Gildash: initialization failed",{cause:E})}}async function Q$(_,$){if(_.closed)return;_.closed=!0;let J=[];for(let[Q,z]of _.signalHandlers)if(Q==="beforeExit")process.off("beforeExit",z);else process.off(Q,z);if(_.signalHandlers=[],_.semanticLayer){try{_.semanticLayer.dispose()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}_.semanticLayer=null}if(_.coordinator)try{await _.coordinator.shutdown()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if(_.watcher){let Q=await _.watcher.close();if(n_(Q))J.push(Q.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}try{_.db.close()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if($?.cleanup)for(let Q of["","-wal","-shm"])try{await _.unlinkFn(m_.join(_.projectRoot,L_,h_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function F0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(k0(z))throw z.data;return _.parseCache.set($,z),z}async function G0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(Y)=>{try{let Z=await _.readFileFn(Y),W=_.parseSourceFn(Y,Z,J);if(!k0(W))Q.set(Y,W);else z.push({filePath:Y,error:W.data})}catch(Z){z.push({filePath:Y,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function j0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function E0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function v0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import b0 from"path";function y0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: getStats failed",{cause:J})}}function E$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchSymbols failed",{cause:J})}}function P0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchRelations failed",{cause:J})}}function f0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllSymbols failed",{cause:J})}}function n0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllRelations failed",{cause:J})}}function m0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: listIndexedFiles failed",{cause:J})}}function x0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getInternalRelations failed",{cause:Q})}}function h0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(Y.length===0)return null;let Z=Y[0],W=Z.detail,X={...Z,members:W.members,jsDoc:W.jsDoc,parameters:W.parameters,returnType:W.returnType,heritage:W.heritage,decorators:W.decorators,typeParameters:W.typeParameters};if(_.semanticLayer)try{let H=b0.isAbsolute(J)?J:b0.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(O!==null){let U=_.semanticLayer.findNamePosition(H,O,Z.name)??O,K=_.semanticLayer.collectTypeAt(H,U);if(K)X.resolvedType=K}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function i0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let Y=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:Y.length,exportedSymbolCount:Y.filter((W)=>W.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function p0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileInfo failed",{cause:Q})}}function d0(_,$,J){return E$(_,{filePath:$,project:J??void 0,limit:1e4})}function l0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((Y)=>({name:Y.name,kind:Y.kind,parameters:Y.detail.parameters?`(${Y.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:Y.detail.returnType??void 0,jsDoc:Y.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import h from"path";function x_(_,$,J,Q){let z=Q??_.defaultProject,Y=h.isAbsolute(J)?h.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:Y,limit:1}});if(Z.length===0)return null;let W=Z[0],X=h.isAbsolute(J)?J:h.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,W.span.start.line,W.span.start.column);if(H===null)return null;let O=_.semanticLayer.findNamePosition(X,H,W.name)??H;return{sym:W,position:O,absPath:X}}function c0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getResolvedType failed",{cause:z})}}function a0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getSemanticReferences failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getImplementations failed",{cause:z})}}function r0(_,$,J,Q,z,Y){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=x_(_,$,J,Y);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let W=x_(_,Q,z,Y);if(!W)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,W.absPath,W.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function o0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function t0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Y=_.semanticLayer.lineColumnToPosition(z,J,Q);if(Y===null)return null;return _.semanticLayer.collectTypeAt(z,Y)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function e0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($.source.filePath)?$.source.filePath:h.resolve(_.projectRoot,$.source.filePath),Q=h.isAbsolute($.target.filePath)?$.target.filePath:h.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let Y=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(Y===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,Y)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function _1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function $1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function J1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function W1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Z=h.isAbsolute(Q)?Q:h.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(Y,J,Z,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:Y})}}function Y1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(Y,J,Q,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:Y})}}function Z1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function X1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: findNamePosition failed",{cause:z})}}function O1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function V1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function U1(_,$){let J=new Map(_.map((W)=>[`${W.name}::${W.filePath}`,W])),Q=new Map($.map((W)=>[`${W.name}::${W.filePath}`,W])),z=[],Y=[],Z=[];for(let[W,X]of Q){let H=J.get(W);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,after:X})}for(let[W,X]of J)if(!Q.has(W))Y.push(X);return{added:z,removed:Y,modified:Z}}function H1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function M1(_){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.coordinator)throw new V("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return J$(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function K1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,Y=new Set,Z=[],W=$,X=J;for(;;){let H=`${X}::${W}`;if(Y.has(H))return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!0};Y.add(H);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,K;for(let u of O){let L;if(u.metaJson)try{let T=JSON.parse(u.metaJson);if(Array.isArray(T.specifiers))L=T.specifiers}catch{}if(!L)continue;let B=L.find((T)=>T.exported===W);if(!B)continue;U=u.dstFilePath??void 0,K=B.local;break}if(!U||!K)return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:W}),X=U,W=K}}function L1(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function w1(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function B1(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function D1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((Y)=>Y.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function u1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=new Set,Z=(W,X,H)=>{let O=`${W}::${X}`;if(Y.has(O))return{symbolName:W,filePath:X,kind:H,children:[]};Y.add(O);let u=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:W,limit:1000}}).filter((L)=>L.type==="extends"||L.type==="implements").filter((L)=>L.dstSymbolName!=null&&L.dstFilePath!=null).map((L)=>Z(L.dstSymbolName,L.dstFilePath,L.type));return{symbolName:W,filePath:X,kind:H,children:u}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function I1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function C1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,Y=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:Y}).map((W)=>({changeType:W.changeType,symbolName:W.symbolName,symbolKind:W.symbolKind,filePath:W.filePath,oldName:W.oldName,oldFilePath:W.oldFilePath,fingerprint:W.fingerprint,changedAt:W.changedAt,isFullIndex:W.isFullIndex===1,indexRunId:W.indexRunId}))}function N1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],Y=[...new Set(z)];for(let Z of Y)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class v${_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(_){this._ctx=_}static async open(_){let $=await R0(_);return new v$($)}async close(_){return Q$(this._ctx,_)}parseSource(_,$,J){return F0(this._ctx,_,$,J)}async batchParse(_,$){return G0(this._ctx,_,$)}getParsedAst(_){return j0(this._ctx,_)}extractSymbols(_){return E0(this._ctx,_)}extractRelations(_){return v0(this._ctx,_)}getStats(_){return y0(this._ctx,_)}searchSymbols(_){return E$(this._ctx,_)}searchRelations(_){return P0(this._ctx,_)}searchAllSymbols(_){return f0(this._ctx,_)}searchAllRelations(_){return n0(this._ctx,_)}listIndexedFiles(_){return m0(this._ctx,_)}getInternalRelations(_,$){return x0(this._ctx,_,$)}getFullSymbol(_,$,J){return h0(this._ctx,_,$,J)}getFileStats(_,$){return i0(this._ctx,_,$)}getFileInfo(_,$){return p0(this._ctx,_,$)}getSymbolsByFile(_,$){return d0(this._ctx,_,$)}getModuleInterface(_,$){return l0(this._ctx,_,$)}getDependencies(_,$,J=1e4){return B0(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return D0(this._ctx,_,$,J)}async getAffected(_,$){return u0(this._ctx,_,$)}async hasCycle(_){return I0(this._ctx,_)}async getImportGraph(_){return C0(this._ctx,_)}async getTransitiveDependencies(_,$){return N0(this._ctx,_,$)}async getTransitiveDependents(_,$){return A0(this._ctx,_,$)}async getCyclePaths(_,$){return g0(this._ctx,_,$)}async getFanMetrics(_,$){return q0(this._ctx,_,$)}getResolvedType(_,$,J){return c0(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return a0(this._ctx,_,$,J)}getImplementations(_,$,J){return s0(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return r0(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return _1(this._ctx,_)}getFileTypes(_){return o0(this._ctx,_)}getResolvedTypeAt(_,$,J){return t0(this._ctx,_,$,J)}isTypeAssignableToAt(_){return e0(this._ctx,_)}getResolvedTypeAtPosition(_,$){return J1(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return Q1(this._ctx,_,$)}getImplementationsAtPosition(_,$){return z1(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return W1(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return Y1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return Z1(this._ctx,_,$,J)}findNamePosition(_,$,J){return X1(this._ctx,_,$,J)}getSymbolNode(_,$){return O1(this._ctx,_,$)}getBaseTypes(_,$){return $1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return V1(this._ctx,_,$)}diffSymbols(_,$){return U1(_,$)}onIndexed(_){return H1(this._ctx,_)}async reindex(){return M1(this._ctx)}resolveSymbol(_,$,J){return K1(this._ctx,_,$,J)}async findPattern(_,$){return D1(this._ctx,_,$)}async getHeritageChain(_,$,J){return u1(this._ctx,_,$,J)}onFileChanged(_){return L1(this._ctx,_)}onError(_){return w1(this._ctx,_)}onRoleChanged(_){return B1(this._ctx,_)}searchAnnotations(_){return I1(this._ctx,_)}getSymbolChanges(_,$){return C1(this._ctx,_,$)}pruneChangelog(_){return N1(this._ctx,_)}}import{Visitor as e4,visitorKeys as _3}from"oxc-parser";export{_3 as visitorKeys,N$ as symbolSearch,A$ as relationSearch,g$ as patternSearch,X_ as getLineColumn,y_ as buildLineOffsets,e4 as Visitor,V as GildashError,v$ as Gildash,$$ as DependencyGraph};