@zipbul/gildash 0.9.4 → 0.11.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.
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // @bun
2
- var _$=Object.defineProperty;var $$=(u)=>u;function N$(u,g){this[u]=$$.bind(null,g)}var J$=(u,g)=>{for(var _ in g)_$(u,_,{get:g[_],enumerable:!0,configurable:!0,set:N$.bind(g,_)})};var Rg=import.meta.require;import{isErr as Gu}from"@zipbul/result";import ju from"path";import{existsSync as M0}from"fs";import{err as kg,isErr as V$}from"@zipbul/result";import{Database as U$}from"bun:sqlite";import{mkdirSync as Y$,unlinkSync as Tg,existsSync as Fg}from"fs";import{dirname as Z$,join as qg}from"path";import{drizzle as X$}from"drizzle-orm/bun-sqlite";import{migrate as K$}from"drizzle-orm/bun-sqlite/migrator";class Y extends Error{type;constructor(u,g,_){super(g,_);this.type=u;this.name="GildashError"}}function e(u,g,_){return new Y(u,g,_!==void 0?{cause:_}:void 0)}var Vu=".gildash",Eu="gildash.db";var cu={};J$(cu,{watcherOwner:()=>W$,symbols:()=>f,symbolChangelog:()=>uu,relations:()=>L,files:()=>p,annotations:()=>$u});import{sql as Q$}from"drizzle-orm";import{sqliteTable as Mu,text as F,integer as t,real as w$,index as gu,primaryKey as z$,foreignKey as vu,check as O$}from"drizzle-orm/sqlite-core";var p=Mu("files",{project:F("project").notNull(),filePath:F("file_path").notNull(),mtimeMs:w$("mtime_ms").notNull(),size:t("size").notNull(),contentHash:F("content_hash").notNull(),updatedAt:F("updated_at").notNull(),lineCount:t("line_count")},(u)=>[z$({columns:[u.project,u.filePath]})]),f=Mu("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),kind:F("kind").notNull(),name:F("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:F("signature"),fingerprint:F("fingerprint"),detailJson:F("detail_json"),contentHash:F("content_hash").notNull(),indexedAt:F("indexed_at").notNull(),resolvedType:F("resolved_type"),structuralFingerprint:F("structural_fingerprint")},(u)=>[gu("idx_symbols_project_file").on(u.project,u.filePath),gu("idx_symbols_project_kind").on(u.project,u.kind),gu("idx_symbols_project_name").on(u.project,u.name),gu("idx_symbols_fingerprint").on(u.project,u.fingerprint),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),L=Mu("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),type:F("type").notNull(),srcFilePath:F("src_file_path").notNull(),srcSymbolName:F("src_symbol_name"),dstProject:F("dst_project").notNull(),dstFilePath:F("dst_file_path").notNull(),dstSymbolName:F("dst_symbol_name"),metaJson:F("meta_json")},(u)=>[gu("idx_relations_src").on(u.project,u.srcFilePath),gu("idx_relations_dst").on(u.dstProject,u.dstFilePath),gu("idx_relations_type").on(u.project,u.type),gu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),vu({columns:[u.project,u.srcFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade"),vu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),$u=Mu("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),tag:F("tag").notNull(),value:F("value").notNull().default(""),source:F("source").notNull(),symbolName:F("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:F("indexed_at").notNull()},(u)=>[gu("idx_annotations_project_file").on(u.project,u.filePath),gu("idx_annotations_project_tag").on(u.project,u.tag),gu("idx_annotations_project_symbol").on(u.project,u.symbolName),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),uu=Mu("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),changeType:F("change_type").notNull(),symbolName:F("symbol_name").notNull(),symbolKind:F("symbol_kind").notNull(),filePath:F("file_path").notNull(),oldName:F("old_name"),oldFilePath:F("old_file_path"),fingerprint:F("fingerprint"),changedAt:F("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:F("index_run_id").notNull()},(u)=>[gu("idx_changelog_project_changed_at").on(u.project,u.changedAt),gu("idx_changelog_project_name").on(u.project,u.symbolName),gu("idx_changelog_project_run").on(u.project,u.indexRunId)]),W$=Mu("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:F("started_at").notNull(),heartbeatAt:F("heartbeat_at").notNull(),instanceId:F("instance_id")},(u)=>[O$("watcher_owner_singleton",Q$`${u.id} = 1`)]);class su{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=qg(u.projectRoot,Vu,Eu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Y$(Z$(this.dbPath),{recursive:!0}),this.client=new U$(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=X$(this.client,{schema:cu}),K$(this.drizzle,{migrationsFolder:qg(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)&&Fg(this.dbPath)){this.closeClient(),Tg(this.dbPath);for(let _ of["-wal","-shm"]){let $=this.dbPath+_;if(Fg($))Tg($)}let g=this.open();if(V$(g))return kg(e("store",`Failed to recover database at ${this.dbPath}`,g.data));return g}return kg(e("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let g=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return g.transaction(()=>u(this))()}finally{this.txDepth--}}let _=`sp_${this.txDepth++}`;g.run(`SAVEPOINT "${_}"`);try{let $=u(this);return g.run(`RELEASE SAVEPOINT "${_}"`),$}catch($){throw g.run(`ROLLBACK TO SAVEPOINT "${_}"`),g.run(`RELEASE SAVEPOINT "${_}"`),$}finally{this.txDepth--}}immediateTransaction(u){let g=this.requireClient();this.txDepth++,g.run("BEGIN IMMEDIATE");try{let _=u();return g.run("COMMIT"),_}catch(_){throw g.run("ROLLBACK"),_}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((g)=>g.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}replaceOwner(u,g){let _=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??null)}touchOwner(u){let g=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(g,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let g=u;if(typeof g.function!=="function")return;g.function.call(u,"regexp",(_,$)=>{try{return new RegExp(_).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 g=u.message.toLowerCase();return g.includes("malformed")||g.includes("corrupt")||g.includes("not a database")||g.includes("disk i/o error")||g.includes("sqlite_corrupt")}}import{eq as Su,and as Gg}from"drizzle-orm";class ou{db;constructor(u){this.db=u}getFile(u,g){return this.db.drizzleDb.select().from(p).where(Gg(Su(p.project,u),Su(p.filePath,g))).get()??null}upsertFile(u){this.db.drizzleDb.insert(p).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:[p.project,p.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(p).where(Su(p.project,u)).all()}getFilesMap(u){let g=this.getAllFiles(u),_=new Map;for(let $ of g)_.set($.filePath,$);return _}deleteFile(u,g){this.db.drizzleDb.delete(p).where(Gg(Su(p.project,u),Su(p.filePath,g))).run()}}import{eq as r,and as Zu,sql as Pu,count as n$}from"drizzle-orm";function Bu(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((g)=>g.trim()).filter((g)=>g.length>0).map((g)=>`"${g.replaceAll('"','""')}"*`).join(" ")}var jg=50;class eu{db;constructor(u){this.db=u}replaceFileSymbols(u,g,_,$){if(this.db.drizzleDb.delete(f).where(Zu(r(f.project,u),r(f.filePath,g))).run(),!$.length)return;let N=new Date().toISOString(),z=$.map((w)=>({project:u,filePath:g,kind:w.kind??"unknown",name:w.name??"",startLine:w.startLine??0,startColumn:w.startColumn??0,endLine:w.endLine??0,endColumn:w.endColumn??0,isExported:w.isExported??0,signature:w.signature??null,fingerprint:w.fingerprint??null,detailJson:w.detailJson??null,contentHash:_,indexedAt:w.indexedAt??N,resolvedType:w.resolvedType??null,structuralFingerprint:w.structuralFingerprint??null}));for(let w=0;w<z.length;w+=jg)this.db.drizzleDb.insert(f).values(z.slice(w,w+jg)).run()}getFileSymbols(u,g){return this.db.drizzleDb.select().from(f).where(Zu(r(f.project,u),r(f.filePath,g))).all()}searchByName(u,g,_={}){let $=_.limit??50,N=Bu(g);if(!N)return[];return this.db.drizzleDb.select().from(f).where(Zu(Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${N})`,r(f.project,u),_.kind?r(f.kind,_.kind):void 0)).orderBy(f.name).limit($).all()}searchByKind(u,g){return this.db.drizzleDb.select().from(f).where(Zu(r(f.project,u),r(f.kind,g))).orderBy(f.name).all()}getStats(u){let g=this.db.drizzleDb.select({symbolCount:n$(),fileCount:Pu`COUNT(DISTINCT ${f.filePath})`}).from(f).where(r(f.project,u)).get();return{symbolCount:g?.symbolCount??0,fileCount:g?.fileCount??0}}getByFingerprint(u,g){return this.db.drizzleDb.select().from(f).where(Zu(r(f.project,u),r(f.fingerprint,g))).all()}deleteFileSymbols(u,g){this.db.drizzleDb.delete(f).where(Zu(r(f.project,u),r(f.filePath,g))).run()}searchByQuery(u){let g=this.db.drizzleDb.select().from(f).where(Zu(u.ftsQuery?Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?r(f.name,u.exactName):void 0,u.project!==void 0?r(f.project,u.project):void 0,u.kind?r(f.kind,u.kind):void 0,u.filePath!==void 0?r(f.filePath,u.filePath):void 0,u.isExported!==void 0?r(f.isExported,u.isExported?1:0):void 0,u.decorator?Pu`${f.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?r(f.resolvedType,u.resolvedType):void 0)).orderBy(f.name);if(!u.regex)return g.limit(u.limit).all();let _;try{_=new RegExp(u.regex)}catch{throw new Y("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let N of[5,20,100]){let z=u.limit*N,w=g.limit(z).all();if($=w.filter((Q)=>_.test(Q.name)),$.length>=u.limit||w.length<z)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as x,and as wu,isNull as Eg,or as M$}from"drizzle-orm";class ug{db;constructor(u){this.db=u}replaceFileRelations(u,g,_){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(wu(x(L.project,u),x(L.srcFilePath,g))).run(),!_.length)return;for(let N of _)$.drizzleDb.insert(L).values({project:u,type:N.type??"unknown",srcFilePath:N.srcFilePath??g,srcSymbolName:N.srcSymbolName??null,dstProject:N.dstProject??u,dstFilePath:N.dstFilePath??"",dstSymbolName:N.dstSymbolName??null,metaJson:N.metaJson??null}).run()})}getOutgoing(u,g,_){if(_!==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(x(L.project,u),x(L.srcFilePath,g),M$(x(L.srcSymbolName,_),Eg(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(x(L.project,u),x(L.srcFilePath,g))).all()}getIncoming(u){let{dstProject:g,dstFilePath:_}=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(x(L.dstProject,g),x(L.dstFilePath,_))).all()}getByType(u,g){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(x(L.project,u),x(L.type,g))).all()}deleteFileRelations(u,g){this.db.drizzleDb.delete(L).where(wu(x(L.project,u),x(L.srcFilePath,g))).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?x(L.project,u.project):void 0,u.srcFilePath!==void 0?x(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?x(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?x(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?x(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?x(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?x(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:g,oldFile:_,oldSymbol:$,newFile:N,newSymbol:z,newDstProject:w}=u,Q=$===null?wu(x(L.dstProject,g),x(L.dstFilePath,_),Eg(L.dstSymbolName)):wu(x(L.dstProject,g),x(L.dstFilePath,_),x(L.dstSymbolName,$)),J={dstFilePath:N,dstSymbolName:z};if(w!==void 0)J.dstProject=w;this.db.drizzleDb.update(L).set(J).where(Q).run()}}import{err as vg}from"@zipbul/result";import{subscribe as B$}from"@parcel/watcher";import gg from"path";var H$=["**/.git/**",`**/${Vu}/**`,"**/dist/**","**/node_modules/**"],L$=new Set(["package.json","tsconfig.json"]);function I$(u){return u.replaceAll("\\","/")}function D$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class _g{#u;#g;#_;#N;#$;#J;constructor(u,g=B$,_=console){this.#g=u.projectRoot,this.#_=[...H$,...u.ignorePatterns??[]],this.#N=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=g,this.#J=_}async start(u){try{this.#u=await this.#$(this.#g,(g,_)=>{if(g){this.#J.error(e("watcher","Callback error",g));return}try{for(let $ of _){let N=I$(gg.relative(this.#g,$.path));if(N.startsWith(".."))continue;let z=gg.basename(N),w=gg.extname(N).toLowerCase();if(!L$.has(z)&&!this.#N.has(w))continue;if(N.endsWith(".d.ts"))continue;u({eventType:D$($.type),filePath:N})}}catch($){this.#J.error(e("watcher","Callback error",$))}},{ignore:this.#_})}catch(g){return vg(e("watcher","Failed to subscribe watcher",g))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return vg(e("watcher","Failed to close watcher",u))}}}import $g from"path";import{promises as A$}from"fs";var C$=["**/node_modules/**","**/.git/**",`**/${Vu}/**`,"**/dist/**"];async function bu(u){let g=[];for await(let _ of A$.glob("**/package.json",{cwd:u,exclude:C$})){let $=$g.dirname(_).replaceAll("\\","/"),N=$g.join(u,_),z=await Bun.file(N).json(),w=typeof z?.name==="string"&&z.name.length>0?z.name:$g.basename($==="."?u:$);g.push({dir:$,project:w})}return g.sort((_,$)=>$.dir.length-_.dir.length),g}function l(u,g,_="default"){let $=u.replaceAll("\\","/");for(let N of g){if(N.dir===".")return N.project;if($===N.dir||$.startsWith(`${N.dir}/`))return N.project}return _}import Pg from"path";var Uu=new Map;async function S$(u){let g=Bun.file(u);if(!await g.exists())return null;try{let _=await g.text(),$=Bun.JSONC.parse(_);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function Ru(u){if(Uu.has(u))return Uu.get(u)??null;let g=Pg.join(u,"tsconfig.json"),_=await S$(g);if(!_)return Uu.set(u,null),null;let $=typeof _.compilerOptions==="object"&&_.compilerOptions!==null?_.compilerOptions:null;if(!$)return Uu.set(u,null),null;let N=typeof $.baseUrl==="string"?$.baseUrl:null,z=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!N&&!z)return Uu.set(u,null),null;let w=N?Pg.resolve(u,N):u,Q=new Map;if(z)for(let[V,O]of Object.entries(z)){if(!Array.isArray(O))continue;let W=O.filter((X)=>typeof X==="string");Q.set(V,W)}let J={baseUrl:w,paths:Q};return Uu.set(u,J),J}function fu(u){if(u){Uu.delete(u);return}Uu.clear()}import bg from"path";function yu(u,g){return bg.relative(u,g).replaceAll("\\","/")}function Hu(u,g){return bg.resolve(u,g)}function Ju(u){let g=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(g)).toString(16).padStart(16,"0")}import{isErr as tg}from"@zipbul/result";import{err as R$}from"@zipbul/result";import{parseSync as k$}from"oxc-parser";function ku(u,g,_,$=k$){try{let{program:N,errors:z,comments:w}=$(u,g,_);return{filePath:u,program:N,errors:z,comments:w,sourceText:g}}catch(N){return R$(e("parse",`Failed to parse file: ${u}`,N))}}import{promises as T$}from"fs";import{join as F$}from"path";async function fg(u){let{projectRoot:g,extensions:_,ignorePatterns:$,fileRepo:N}=u,z=N.getFilesMap(),w=new Set,Q=[],J=[],V=$.map((W)=>new Bun.Glob(W));for await(let W of T$.glob("**/*",{cwd:g})){if(!_.some((U)=>W.endsWith(U)))continue;if(W.startsWith("node_modules/")||W.includes("/node_modules/"))continue;if(V.some((U)=>U.match(W)))continue;w.add(W);let X=F$(g,W),M=Bun.file(X),{size:D,lastModified:I}=M,T=z.get(W);if(!T){let U=await M.text(),K=Ju(U);Q.push({filePath:W,contentHash:K,mtimeMs:I,size:D});continue}if(T.mtimeMs===I&&T.size===D){J.push({filePath:W,contentHash:T.contentHash,mtimeMs:I,size:D});continue}let G=await M.text(),i=Ju(G);if(i===T.contentHash)J.push({filePath:W,contentHash:i,mtimeMs:I,size:D});else Q.push({filePath:W,contentHash:i,mtimeMs:I,size:D})}let O=[];for(let W of z.keys())if(!w.has(W))O.push(W);return{changed:Q,unchanged:J,deleted:O}}function iu(u){let g=[0];for(let _=0;_<u.length;_++)if(u[_]===`
3
- `)g.push(_+1);return g}function Nu(u,g){let _=0,$=u.length-1;while(_<$){let N=_+$+1>>1;if(u[N]<=g)_=N;else $=N-1}return{line:_+1,column:g-u[_]}}import{err as q$}from"@zipbul/result";import{parse as G$}from"comment-parser";function mu(u){try{let g=u.trim();if(g.startsWith("/**"))g=g.slice(3);if(g.endsWith("*/"))g=g.slice(0,-2);let $=G$(`/** ${g} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((N)=>({tag:N.tag??"",name:N.name??"",type:N.type??"",description:N.description??"",optional:N.optional??!1,...N.default!==void 0?{default:N.default}:{}}))}}catch(g){return q$(e("parse","Failed to parse JSDoc comment",g))}}import{isErr as j$}from"@zipbul/result";function Lu(u){let{program:g,sourceText:_,comments:$}=u,N=iu(_),z=$.filter((U)=>U.type==="Block"&&U.value.startsWith("*")).sort((U,K)=>U.end-K.end),w=g.body.map((U)=>U.start??0).sort((U,K)=>U-K);function Q(U,K){return{start:Nu(N,U),end:Nu(N,K)}}function J(U){let K=0,n=z.length-1,R=-1;while(K<=n){let C=K+n>>>1;if(z[C].end<=U)R=C,K=C+1;else n=C-1}if(R<0)return;let A=z[R];K=0,n=w.length-1;while(K<=n){let C=K+n>>>1,v=w[C];if(v<=A.end)K=C+1;else if(v>=U)n=C-1;else return}return`/*${A.value}*/`}function V(U){if(!U)return;let K=U.typeAnnotation??U;return _.slice(K.start,K.end)}function O(U){if(!U||U.length===0)return[];return U.map((K)=>{let n=K.expression;if(!n)return{name:"unknown"};if(n.type==="CallExpression"){let R=n.callee?.name??n.callee?.property?.name??"unknown",A=(n.arguments??[]).map((C)=>_.slice(C.start,C.end));return{name:R,arguments:A.length>0?A:void 0}}if(n.type==="Identifier")return{name:n.name??"unknown"};return{name:_.slice(n.start,n.end)}})}function W(U){let K=U.type==="TSParameterProperty"?U.parameter:U;if(K?.type==="RestElement"){let Z=`...${K.argument?.name??"unknown"}`,H=K.typeAnnotation,S=H?V(H):void 0,B={name:Z,isOptional:!1};if(S)B.type=S;return B}if(K?.type==="AssignmentPattern"){let{left:j,right:Z}=K,H=j?.name??"unknown",S=j?.typeAnnotation,B=S?V(S):void 0,P=_.slice(Z.start,Z.end),q=O(j?.decorators??[]),c={name:H,isOptional:!0,defaultValue:P};if(B)c.type=B;if(q.length>0)c.decorators=q;return c}let n=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,A=K?.typeAnnotation,C=A?V(A):void 0,v=O(K?.decorators??[]),y={name:n,isOptional:R};if(C)y.type=C;if(v.length>0)y.decorators=v;return y}function X(U,K){let n=[];if(K?.async)n.push("async");if(U.static)n.push("static");if(U.abstract)n.push("abstract");if(U.readonly)n.push("readonly");if(U.override)n.push("override");if(U.declare)n.push("declare");if(U.const)n.push("const");let R=U.accessibility;if(R==="private")n.push("private");else if(R==="protected")n.push("protected");else if(R==="public")n.push("public");return n}function M(U){let K=[];if(U.superClass){let R=_.slice(U.superClass.start,U.superClass.end);K.push({kind:"extends",name:R})}let n=U.implements??[];for(let R of n){let A=R.expression??R,C=_.slice(A.start,A.end);K.push({kind:"implements",name:C})}return K}function D(U){let K=[];for(let n of U.extends??[]){let R=n.expression??n,A=_.slice(R.start,R.end);K.push({kind:"extends",name:A})}return K}function I(U){let K=[];for(let n of U)if(n.type==="MethodDefinition"){let R=n.key?.name??"unknown",A=n.value,C=n.kind??"method",v=C==="constructor"?"constructor":C==="get"?"getter":C==="set"?"setter":"method",y=X(n,A),j=(A?.params??[]).map(W),Z=V(A?.returnType),H={kind:"method",name:R,span:Q(n.start,n.end),isExported:!1,methodKind:v,modifiers:y,parameters:j.length>0?j:void 0,returnType:Z};K.push(H)}else if(n.type==="PropertyDefinition"){let R=n.key?.name??"unknown",A=X(n),C={kind:"property",name:R,span:Q(n.start,n.end),isExported:!1,modifiers:A};K.push(C)}return K}function T(U){let K=[];for(let n of U)if(n.type==="TSMethodSignature"){let R=n.key?.name??"unknown",A=(n.params??[]).map(W),C=V(n.returnType);K.push({kind:"method",name:R,span:Q(n.start,n.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:C})}else if(n.type==="TSPropertySignature"){let R=n.key?.name??"unknown",A=V(n.typeAnnotation),C={kind:"property",name:R,span:Q(n.start,n.end),isExported:!1,modifiers:n.readonly?["readonly"]:[],returnType:A};K.push(C)}return K}function G(U,K){let n=U.type??"";if(n==="FunctionDeclaration"){let R=U.id?.name??"default",A=(U.params??[]).map(W),C=V(U.returnType),v=X(U,U),y=O(U.decorators??[]),j=U.typeParameters?.params?.flatMap((H)=>{let S=H.name?.name;return S?[S]:[]})||void 0,Z={kind:"function",name:R,span:Q(U.start,U.end),isExported:K,modifiers:v,parameters:A.length>0?A:void 0,returnType:C,decorators:y.length>0?y:void 0};if(j&&j.length>0)Z.typeParameters=j;return Z}if(n==="ClassDeclaration"||n==="ClassExpression"){let R=U.id?.name??"default",A=M(U),C=I(U.body?.body??[]),v=O(U.decorators??[]),y=X(U,U),j=U.typeParameters?.params?.flatMap((H)=>{let S=H.name?.name;return S?[S]:[]})||void 0,Z={kind:"class",name:R,span:Q(U.start,U.end),isExported:K,modifiers:y,heritage:A.length>0?A:void 0,members:C.length>0?C:void 0,decorators:v.length>0?v:void 0};if(j&&j.length>0)Z.typeParameters=j;return Z}if(n==="VariableDeclaration"){let R=[];for(let A of U.declarations??[]){let{id:C,init:v}=A;if(C?.type==="ObjectPattern"){for(let B of C.properties??[]){let P=B.value?.name??B.key?.name??"unknown";R.push({kind:"variable",name:P,span:Q(B.start??A.start,B.end??A.end),isExported:K,modifiers:[]})}continue}if(C?.type==="ArrayPattern"){for(let B of C.elements??[]){if(!B||B.type!=="Identifier")continue;let P=B.name??"unknown";R.push({kind:"variable",name:P,span:Q(B.start??A.start,B.end??A.end),isExported:K,modifiers:[]})}continue}let y=C?.name??"unknown",j="variable",Z,H;if(v?.type==="FunctionExpression"||v?.type==="ArrowFunctionExpression")j="function",Z=(v.params??[]).map(W),H=V(v.returnType);let S=[];R.push({kind:j,name:y,span:Q(A.start,A.end),isExported:K,modifiers:S,parameters:Z,returnType:H})}if(R.length===0)return null;if(R.length===1)return R[0];return R}if(n==="TSTypeAliasDeclaration")return{kind:"type",name:U.id?.name??"unknown",span:Q(U.start,U.end),isExported:K,modifiers:[]};if(n==="TSInterfaceDeclaration"){let R=U.id?.name??"unknown",A=D(U),C=T(U.body?.body??[]),v=U.typeParameters?.params?.flatMap((j)=>{let Z=j.name?.name;return Z?[Z]:[]})||void 0,y={kind:"interface",name:R,span:Q(U.start,U.end),isExported:K,modifiers:[],heritage:A.length>0?A:void 0,members:C.length>0?C:void 0};if(v&&v.length>0)y.typeParameters=v;return y}if(n==="TSEnumDeclaration"){let R=U.id?.name??"unknown",A=X(U),v=(U.body?.members??[]).map((y)=>({kind:"property",name:y.id?.name??y.id?.value??"unknown",span:Q(y.start,y.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:Q(U.start,U.end),isExported:K,modifiers:A,members:v.length>0?v:void 0}}return null}let i=[];for(let U of g.body){let K=null,n=U,R=typeof n.type==="string"?n.type:"";if(R==="ExportNamedDeclaration"){let C=U;if(C.declaration){if(K=G(C.declaration,!0),K&&!Array.isArray(K))K.span=Q(C.start,C.end);else if(Array.isArray(K))for(let v of K)v.span=Q(C.start,C.end)}}else if(R==="ExportDefaultDeclaration"){let C=U,v=C.declaration;if(v){if(K=G(v,!0),K&&!Array.isArray(K))K.name=v.id?.name??"default",K.isExported=!0,K.span=Q(C.start,C.end)}}else K=G(U,!1);let A=Array.isArray(K)?K:K?[K]:[];for(let C of A){let v=U.start??0,y=J(v);if(y){let j=mu(y);if(!j$(j))C.jsDoc=j}i.push(C)}}return i}function E$(u){if(u.kind==="function"||u.kind==="method"){let g=u.parameters?.length??0,_=u.modifiers.includes("async")?1:0;return`params:${g}|async:${_}`}return null}function v$(u){let g={};if(u.jsDoc)g.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)g.parameters=u.parameters;if(u.returnType!==void 0)g.returnType=u.returnType}if(u.heritage?.length)g.heritage=u.heritage;if(u.decorators?.length)g.decorators=u.decorators;if(u.typeParameters?.length)g.typeParameters=u.typeParameters;if(u.modifiers?.length)g.modifiers=u.modifiers;if(u.members?.length)g.members=u.members.map((_)=>{let $=_.modifiers.find((N)=>N==="private"||N==="protected"||N==="public");return{name:_.name,kind:_.methodKind??_.kind,type:_.returnType,visibility:$,isStatic:_.modifiers.includes("static")||void 0,isReadonly:_.modifiers.includes("readonly")||void 0}});return Object.keys(g).length>0?JSON.stringify(g):null}function P$(u){let g=[u.kind];if(u.modifiers.length)g.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)g.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let _=[...u.heritage].sort(($,N)=>$.name.localeCompare(N.name)).map(($)=>`${$.kind}:${$.name}`).join(",");g.push(`her:${_}`)}if(u.decorators?.length)g.push(`dec:${[...u.decorators].map((_)=>_.name).sort().join(",")}`);if(u.methodKind)g.push(`mk:${u.methodKind}`);if(u.parameters)g.push(`p:${u.parameters.length}`);if(u.returnType)g.push(`rt:${u.returnType}`);if(u.members?.length){let _=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");g.push(`mem:${u.members.length}:${Ju(_)}`)}return Ju(g.join("|"))}function yg(u,g,_,$,N){let z=E$(u),w=Ju(`${g}|${u.kind}|${z??""}`),Q=P$(u);return{project:_,filePath:$,kind:u.kind,name:g,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:z,fingerprint:w,detailJson:v$(u),contentHash:N,indexedAt:new Date().toISOString(),structuralFingerprint:Q}}function Ng(u){let{parsed:g,project:_,filePath:$,contentHash:N,symbolRepo:z}=u,w=Lu(g),Q=[];for(let J of w){Q.push(yg(J,J.name,_,$,N));for(let V of J.members??[])Q.push(yg(V,`${J.name}.${V.name}`,_,$,N))}z.replaceFileSymbols(_,$,N,Q)}import{resolve as Jg,dirname as b$,extname as f$}from"path";function Xu(u,g,_){let $=(N)=>{let z=f$(N);if(z==="")return[N+".ts",N+".d.ts",N+"/index.ts",N+"/index.d.ts",N+".mts",N+"/index.mts",N+".cts",N+"/index.cts"];if(z===".js")return[N.slice(0,-3)+".ts"];if(z===".mjs")return[N.slice(0,-4)+".mts"];if(z===".cjs")return[N.slice(0,-4)+".cts"];return[N]};if(g.startsWith(".")){let N=Jg(b$(u),g);return $(N)}if(_)for(let[N,z]of _.paths){if(z.length===0)continue;let w=N.indexOf("*");if(w===-1){if(g===N){let Q=[];for(let J of z)Q.push(...$(Jg(_.baseUrl,J)));return Q}}else{let Q=N.slice(0,w),J=N.slice(w+1);if(g.startsWith(Q)&&(J===""||g.endsWith(J))){let V=g.slice(Q.length,J===""?void 0:g.length-J.length),O=[];for(let W of z)O.push(...$(Jg(_.baseUrl,W.replace("*",V))));return O}}}return[]}function ig(u,g,_,$=Xu){let N=new Map,z=u.body??[];for(let w of z){if(w.type!=="ImportDeclaration")continue;let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let V=J[0],O=w.specifiers??[];for(let W of O)switch(W.type){case"ImportSpecifier":N.set(W.local.name,{path:V,importedName:W.imported.name});break;case"ImportDefaultSpecifier":N.set(W.local.name,{path:V,importedName:"default"});break;case"ImportNamespaceSpecifier":N.set(W.local.name,{path:V,importedName:"*"});break}}return N}var y$=new Set(["loc","start","end","scope"]);function Iu(u,g){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Iu($,g);return}let _=u;g(_);for(let $ of Object.keys(_)){if(y$.has($))continue;let N=_[$];if(N&&typeof N==="object")Iu(N,g)}}function mg(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if((g.type==="StringLiteral"||g.type==="Literal")&&typeof g.value==="string")return g.value;return null}function Ku(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if(g.type==="Identifier"){let _=g.name;return{root:_,parts:[],full:_}}if(g.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(g.type==="Super")return{root:"super",parts:[],full:"super"};if(g.type==="MemberExpression"){let _=[],$=g;while($.type==="MemberExpression"){let w=$.property;if(!w||typeof w.name!=="string")return null;_.push(w.name),$=$.object}let N;if($.type==="Identifier")N=$.name;else if($.type==="ThisExpression")N="this";else if($.type==="Super")N="super";else return null;_.reverse();let z=[N,..._].join(".");return{root:N,parts:_,full:z}}return null}function hg(u,g,_,$=Xu){let N=[],z=u.body??[];for(let w of z){if(w.type==="ImportDeclaration"){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let V=J[0],O=w.importKind==="type",W=w.specifiers??[];if(W.length===0){let X={};if(O)X.isType=!0;N.push({type:O?"type-references":"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}else for(let X of W){let M=X.type,D=O||X.importKind==="type",I={};if(D)I.isType=!0;let T,G;if(M==="ImportDefaultSpecifier")T="default",G=X.local.name;else if(M==="ImportNamespaceSpecifier")T="*",G=X.local.name,I.importKind="namespace";else T=X.imported.name,G=X.local.name;N.push({type:D?"type-references":"imports",srcFilePath:g,srcSymbolName:G,dstFilePath:V,dstSymbolName:T,...Object.keys(I).length>0?{metaJson:JSON.stringify(I)}:{}})}continue}if(w.type==="ExportAllDeclaration"&&w.source){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let V=J[0],O=w.exportKind==="type",W={isReExport:!0};if(O)W.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(W)});continue}if(w.type==="ExportNamedDeclaration"&&w.source){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let V=J[0],O=w.exportKind==="type",M={isReExport:!0,specifiers:(w.specifiers??[]).map((D)=>({local:D.local.name,exported:D.exported.name}))};if(O)M.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(M)})}}return Iu(u,(w)=>{if(w.type!=="ImportExpression")return;let Q=mg(w.source);if(!Q)return;let J=$(g,Q,_);if(J.length===0)return;let V=J[0];N.push({type:"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),N}function xg(u,g,_){let $=[],N=[],z=[];function w(){if(N.length>0)return N[N.length-1]??null;return null}function Q(V){if(!V)return null;let O=_.get(V.root);if(V.parts.length===0){if(O)return{dstFilePath:O.path,dstSymbolName:O.importedName,resolution:"import"};return{dstFilePath:g,dstSymbolName:V.root,resolution:"local"}}else{if(O&&O.importedName==="*"){let W=V.parts[V.parts.length-1];return{dstFilePath:O.path,dstSymbolName:W,resolution:"namespace"}}return{dstFilePath:g,dstSymbolName:V.full,resolution:"local-member"}}}function J(V){if(!V||typeof V!=="object")return;if(Array.isArray(V)){for(let X of V)J(X);return}let O=V,W=typeof O.type==="string"?O.type:"";if(W==="ClassDeclaration"||W==="ClassExpression"){let X=O,M=X.id?.name??"AnonymousClass";z.push(M),J(X.body),z.pop();return}if(W==="FunctionDeclaration"){let X=O,M=X.id?.name??"anonymous";N.push(M),J(X.body),N.pop();return}if(W==="VariableDeclarator"&&O.init&&(O.init?.type==="FunctionExpression"||O.init?.type==="ArrowFunctionExpression")){let X=O,M=X.id?.name??"anonymous";N.push(M),J(X.init?.body??X.init),N.pop();return}if(W==="MethodDefinition"&&O.value){let X=O,M=z[z.length-1]??"",D=X.key?.name??"anonymous",I=M?`${M}.${D}`:D;N.push(I),J(X.value?.body),N.pop();return}if(W==="FunctionExpression"||W==="ArrowFunctionExpression"){let X=w(),M=X?`${X}.<anonymous>`:"<anonymous>";N.push(M),J(O.body),N.pop();return}if(W==="CallExpression"){let X=O,M=Ku(X.callee),D=Q(M);if(D){let I=w(),T={};if(I===null)T.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:I,dstFilePath:D.dstFilePath,dstSymbolName:D.dstSymbolName,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}J(X.callee);for(let I of X.arguments??[])J(I);return}if(W==="NewExpression"){let X=O,M=Ku(X.callee),D=Q(M);if(D){let I=w(),T={isNew:!0};if(I===null)T.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:I,dstFilePath:D.dstFilePath,dstSymbolName:D.dstSymbolName,metaJson:JSON.stringify(T)})}for(let I of X.arguments??[])J(I);return}for(let X of Object.keys(O)){if(X==="loc"||X==="start"||X==="end"||X==="scope")continue;let M=O[X];if(M&&typeof M==="object")J(M)}}return J(u),$}function pg(u,g,_){let $=[];return Iu(u,(N)=>{if(N.type==="TSInterfaceDeclaration"){let Q=N.id?.name??"AnonymousInterface",J=N.extends??[];for(let V of J){let O=V.expression??V,W=Ku(O);if(!W)continue;let X=Qg(W,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:Q,...X})}return}if(N.type!=="ClassDeclaration"&&N.type!=="ClassExpression")return;let z=N.id?.name??"AnonymousClass";if(N.superClass){let Q=Ku(N.superClass);if(Q){let J=Qg(Q,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:z,...J})}}let w=N.implements??[];for(let Q of w){let J=Q.expression??Q,V=Ku(J);if(!V)continue;let O=Qg(V,g,_);$.push({type:"implements",srcFilePath:g,srcSymbolName:z,...O})}}),$}function Qg(u,g,_){let $=_.get(u.root);if($){if($.importedName==="*"){let N=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:N,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:g,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function hu(u,g,_,$=Xu){let N=ig(u,g,_,$),z=hg(u,g,_,$),w=xg(u,g,N),Q=pg(u,g,N);return[...z,...w,...Q]}function wg(u){let{ast:g,project:_,filePath:$,relationRepo:N,projectRoot:z,tsconfigPaths:w,knownFiles:Q,boundaries:J}=u,V=Hu(z,$),W=hu(g,V,w,Q?(M,D,I)=>{let T=Xu(M,D,I);for(let G of T){let i=yu(z,G);if(J){let U=l(i,J);if(Q.has(`${U}::${i}`))return[G]}else if(Q.has(`${_}::${i}`))return[G]}return[]}:void 0),X=[];for(let M of W){let D=yu(z,M.dstFilePath);if(D.startsWith(".."))continue;let I=yu(z,M.srcFilePath),T=J?l(D,J):_;X.push({project:_,type:M.type,srcFilePath:I,srcSymbolName:M.srcSymbolName??null,dstProject:T,dstFilePath:D,dstSymbolName:M.dstSymbolName??null,metaJson:M.metaJson??null})}return N.replaceFileRelations(_,$,X),X.length}import{isErr as i$}from"@zipbul/result";var lg=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function m$(u){let g=Lu(u),_=[];for(let $ of g){_.push({name:$.name,startLine:$.span.start.line});for(let N of $.members??[])_.push({name:`${$.name}.${N.name}`,startLine:N.span.start.line})}return _.sort(($,N)=>$.startLine-N.startLine),_}function zg(u,g,_){let $=0,N=u.length-1;while($<=N){let z=$+N>>1;if(u[z].startLine<=g)$=z+1;else N=z-1}if($<u.length){let z=u[$];if(z.startLine-g<=_)return z.name}return null}function xu(u,g,_){let $=Nu(u,g),N=Nu(u,_);return{start:$,end:N}}function rg(u){let{comments:g,sourceText:_}=u;if(!g.length)return[];let $=iu(_),N=m$(u),z=[],w=[...g].sort((J,V)=>J.start-V.start),Q=null;for(let J of w)if(J.type==="Block"&&J.value.startsWith("*")){Q=null;let V=`/*${J.value}*/`,O=mu(V);if(i$(O))continue;let W=O;if(!W.tags?.length)continue;let X=Nu($,J.end),M=zg(N,X.line,3),D=_.slice(J.start,J.end);for(let I of W.tags){let T=[I.name,I.description].filter(Boolean).join(" "),G=`@${I.tag}`,i=D.indexOf(G),U;if(i>=0){let K=J.start+i,n=_.indexOf(`
4
- `,K),R=n>=0?Math.min(n,J.end):J.end;U=xu($,K,R)}else U=xu($,J.start,J.end);z.push({tag:I.tag,value:T,source:"jsdoc",span:U,symbolName:M})}}else if(J.type==="Block"){Q=null;let V=J.value.split(`
5
- `),O=0;for(let W of V){let X=W.replace(/^\s*\*?\s?/,""),M=lg.exec(X);if(M){let D=M[1],I=M[2]?.trim()??"",T=`@${D}`,G=W.indexOf(T),i=J.start+2+O+(G>=0?G:0),U=J.start+2+O+W.length,K=xu($,i,U),n=Nu($,J.end),R=zg(N,n.line,3);z.push({tag:D,value:I,source:"block",span:K,symbolName:R})}O+=W.length+1}}else{let V=J.value,O=lg.exec(V),W=Nu($,J.start),X=Nu($,J.end);if(O){let M=O[1],D=O[2]?.trim()??"",I=`@${M}`,T=V.indexOf(I),G=J.start+2+(T>=0?T:0),i=xu($,G,J.end),U=zg(N,X.line,3),K={tag:M,value:D,source:"line",span:i,symbolName:U};z.push(K),Q={annotation:K,endLine:X.line}}else if(Q&&W.line===Q.endLine+1){let M=V.trim();if(M)Q.annotation.value+=" "+M,Q.annotation.span.end=Nu($,J.end),Q.endLine=X.line}else Q=null}return z}function Og(u){let{parsed:g,project:_,filePath:$,annotationRepo:N}=u,z=rg(g);if(N.deleteFileAnnotations(_,$),!z.length)return 0;let w=new Date().toISOString(),Q=z.map((J)=>({project:_,filePath:$,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.span.start.line,startColumn:J.span.start.column,endLine:J.span.end.line,endColumn:J.span.end.column,indexedAt:w}));return N.insertBatch(_,$,Q),z.length}function dg(u,g){let _=[],$=[],N=[];for(let[O,W]of g)if(!u.has(O))_.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});for(let[O,W]of u)if(!g.has(O))$.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});if(!_.length||!$.length)return{renamed:N,added:_,removed:$};let z=new Map,w=new Map;for(let O of _){let W=z.get(O.filePath)??[];W.push(O),z.set(O.filePath,W)}for(let O of $){let W=w.get(O.filePath)??[];W.push(O),w.set(O.filePath,W)}let Q=new Set,J=new Set;for(let[O,W]of z){let X=w.get(O);if(!X)continue;for(let M of new Set(W.map((D)=>D.kind))){let D=W.filter((U)=>U.kind===M&&!Q.has(U)),I=X.filter((U)=>U.kind===M&&!J.has(U));if(!D.length||!I.length)continue;let T=(U,K)=>{return K.get(`${U.filePath}::${U.name}`)?.structuralFingerprint??null},G=(U,K)=>{return K.get(`${U.filePath}::${U.name}`)?.startLine??0},i=new Map;for(let U of I){let K=T(U,u);if(!K)continue;let n=i.get(K)??[];n.push(U),i.set(K,n)}for(let U of D){if(Q.has(U))continue;let K=T(U,g);if(!K)continue;let n=i.get(K);if(!n)continue;let R=n.filter((C)=>!J.has(C));if(!R.length)continue;let A=R[0];if(R.length>1){let C=G(U,g),v=Math.abs(G(A,u)-C);for(let y=1;y<R.length;y++){let j=Math.abs(G(R[y],u)-C);if(j<v)v=j,A=R[y]}}N.push({oldName:A.name,newName:U.name,filePath:O,kind:M}),Q.add(U),J.add(A)}}}let V=N.filter((O)=>!O.oldName.includes("."));for(let O of V){let W=`${O.oldName}.`,X=`${O.newName}.`,M=$.filter((I)=>I.filePath===O.filePath&&I.name.startsWith(W)&&!J.has(I)),D=_.filter((I)=>I.filePath===O.filePath&&I.name.startsWith(X)&&!Q.has(I));for(let I of M){let T=I.name.slice(W.length),G=D.find((i)=>i.name.slice(X.length)===T);if(G)N.push({oldName:I.name,newName:G.name,filePath:O.filePath,kind:I.kind}),Q.add(G),J.add(I)}}return{renamed:N,added:_.filter((O)=>!Q.has(O)),removed:$.filter((O)=>!J.has(O))}}var h$=100,ag=50;class Wg{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=Ru(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")){fu(this.opts.projectRoot),this.tsconfigPathsRaw=Ru(this.opts.projectRoot),this.fullIndex().catch((g)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",g)});return}if(u.filePath.endsWith("package.json")){let g=this.opts.discoverProjectsFn??bu;this.boundariesRefresh=g(this.opts.projectRoot).then((_)=>{this.opts.boundaries=_})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},h$)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,g){if(this.indexingLock){if(g)return this.pendingFullIndex=!0,new Promise(($,N)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:N})});return this.currentIndexing}this.indexingLock=!0;let _=this.doIndex(u,g).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((N)=>{for(let z of $)z.resolve(N)}).catch((N)=>{for(let z of $)z.reject(N)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((N)=>this.logger.error("[IndexCoordinator] incremental drain error",N))}});return this.currentIndexing=_,_}async doIndex(u,g){let _=Date.now(),{fileRepo:$,symbolRepo:N,relationRepo:z,dbConnection:w}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Q,J;if(u!==void 0)Q=u.filter((Z)=>Z.eventType==="create"||Z.eventType==="change").map((Z)=>({filePath:Z.filePath,contentHash:"",mtimeMs:0,size:0})),J=u.filter((Z)=>Z.eventType==="delete").map((Z)=>Z.filePath);else{let Z=new Map;for(let S of this.opts.boundaries)for(let[B,P]of $.getFilesMap(S.project))Z.set(B,P);let H=await fg({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Z}});Q=H.changed,J=H.deleted}let V=await this.tsconfigPathsRaw??void 0,O=new Map;for(let Z of J){let H=l(Z,this.opts.boundaries),S=N.getFileSymbols(H,Z);O.set(Z,S)}let W=crypto.randomUUID(),X=new Map,M=new Map,D=(Z)=>({name:Z.name,filePath:Z.filePath,kind:Z.kind,fingerprint:Z.fingerprint,structuralFingerprint:Z.structuralFingerprint??null,startLine:Z.startLine});if(g)for(let Z of this.opts.boundaries)for(let H of $.getAllFiles(Z.project))for(let S of N.getFileSymbols(Z.project,H.filePath))X.set(`${S.filePath}::${S.name}`,D(S));else{for(let Z of Q){let H=l(Z.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(H,Z.filePath))X.set(`${S.filePath}::${S.name}`,D(S))}for(let[,Z]of O)for(let H of Z)X.set(`${H.filePath}::${H.name}`,D(H))}let{annotationRepo:I,changelogRepo:T}=this.opts,G=()=>{for(let Z of J){let H=l(Z,this.opts.boundaries);if(N.deleteFileSymbols(H,Z),z.deleteFileRelations(H,Z),I)I.deleteFileAnnotations(H,Z);$.deleteFile(H,Z)}},i=0,U=async()=>{let{projectRoot:Z,boundaries:H}=this.opts,{parseCache:S}=this.opts,B=0,P=0,q=0,c=[],b=[];for(let E of Q)try{let k=Hu(Z,E.filePath),s=Bun.file(k),o=await s.text(),Qu=E.contentHash||Ju(o),Wu=l(E.filePath,H);$.upsertFile({project:Wu,filePath:E.filePath,mtimeMs:s.lastModified,size:s.size,contentHash:Qu,updatedAt:new Date().toISOString(),lineCount:o.split(`
6
- `).length});let Cu=(this.opts.parseSourceFn??ku)(k,o);if(tg(Cu))throw Cu.data;let g$=Cu;b.push({filePath:E.filePath,text:o,contentHash:Qu,parsed:g$,project:Wu})}catch(k){this.logger.error(`[IndexCoordinator] Failed to prepare ${E.filePath}:`,k),c.push(E.filePath)}let h=new Set;for(let E of H)for(let[k]of $.getFilesMap(E.project))h.add(`${E.project}::${k}`);return w.transaction(()=>{for(let E of b){if(Ng({parsed:E.parsed,project:E.project,filePath:E.filePath,contentHash:E.contentHash,symbolRepo:N}),P+=wg({ast:E.parsed.program,project:E.project,filePath:E.filePath,relationRepo:z,projectRoot:Z,tsconfigPaths:V,knownFiles:h,boundaries:H}),I)q+=Og({parsed:E.parsed,project:E.project,filePath:E.filePath,annotationRepo:I});S.set(E.filePath,E.parsed),B+=N.getFileSymbols(E.project,E.filePath).length}}),{symbols:B,relations:P,annotations:q,failedFiles:c}},K=0,n=0,R=[];if(g){let{projectRoot:Z,boundaries:H}=this.opts,{parseCache:S}=this.opts,B=[];for(let q=0;q<Q.length;q+=ag){let c=Q.slice(q,q+ag),b=await Promise.allSettled(c.map(async(h)=>{let E=Hu(Z,h.filePath),k=Bun.file(E),s=await k.text(),o=h.contentHash||Ju(s);return{filePath:h.filePath,text:s,contentHash:o,mtimeMs:k.lastModified,size:k.size}}));for(let h=0;h<b.length;h++){let E=b[h];if(E.status==="fulfilled")B.push(E.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",E.reason),R.push(c[h].filePath)}}let P=[];w.transaction(()=>{for(let b of B){let h=l(b.filePath,H);$.deleteFile(h,b.filePath)}for(let b of J){let h=l(b,H);if(N.deleteFileSymbols(h,b),z.deleteFileRelations(h,b),I)I.deleteFileAnnotations(h,b);$.deleteFile(h,b)}for(let b of B){let h=l(b.filePath,H);$.upsertFile({project:h,filePath:b.filePath,mtimeMs:b.mtimeMs,size:b.size,contentHash:b.contentHash,updatedAt:new Date().toISOString(),lineCount:b.text.split(`
7
- `).length})}let q=new Set;for(let b of H)for(let[h]of $.getFilesMap(b.project))q.add(`${b.project}::${h}`);let c=this.opts.parseSourceFn??ku;for(let b of B){let h=l(b.filePath,H),E=c(Hu(Z,b.filePath),b.text);if(tg(E))throw E.data;let k=E;if(P.push({filePath:b.filePath,parsed:k}),Ng({parsed:k,project:h,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:N}),I)i+=Og({parsed:k,project:h,filePath:b.filePath,annotationRepo:I});n+=wg({ast:k.program,project:h,filePath:b.filePath,relationRepo:z,projectRoot:Z,tsconfigPaths:V,knownFiles:q,boundaries:H}),K+=N.getFileSymbols(h,b.filePath).length}});for(let q of P)S.set(q.filePath,q.parsed)}else{G();let Z=await U();K=Z.symbols,n=Z.relations,i=Z.annotations,R=Z.failedFiles}for(let Z of Q){let H=l(Z.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(H,Z.filePath))M.set(`${S.filePath}::${S.name}`,D(S))}let A={added:[],modified:[],removed:[]};for(let[Z,H]of M){let S=X.get(Z);if(!S)A.added.push({name:H.name,filePath:H.filePath,kind:H.kind});else if(S.fingerprint!==H.fingerprint)A.modified.push({name:H.name,filePath:H.filePath,kind:H.kind})}for(let[Z,H]of X)if(!M.has(Z))A.removed.push({name:H.name,filePath:H.filePath,kind:H.kind});let C=dg(X,M),v=new Set(C.renamed.map((Z)=>`${Z.filePath}::${Z.oldName}`)),y=new Set(C.renamed.map((Z)=>`${Z.filePath}::${Z.newName}`));A.added=A.added.filter((Z)=>!y.has(`${Z.filePath}::${Z.name}`)),A.removed=A.removed.filter((Z)=>!v.has(`${Z.filePath}::${Z.name}`));let j=[];if(!g){for(let[Z,H]of O)for(let S of H){if(!S.fingerprint)continue;let B=l(Z,this.opts.boundaries),P=N.getByFingerprint(B,S.fingerprint);if(P.length===1){let q=P[0];z.retargetRelations({dstProject:B,oldFile:Z,oldSymbol:S.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:Z})}}for(let Z of C.removed){let S=X.get(`${Z.filePath}::${Z.name}`)?.fingerprint;if(!S)continue;let B=l(Z.filePath,this.opts.boundaries),P=N.getByFingerprint(B,S);if(P.length===1){let q=P[0];if(q.filePath!==Z.filePath||q.name!==Z.name)z.retargetRelations({dstProject:B,oldFile:Z.filePath,oldSymbol:Z.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:Z.filePath})}}}if(j.length){let Z=new Set(j.map((S)=>`${S.filePath}::${S.name}`)),H=new Set(j.map((S)=>`${S.oldFilePath}::${S.name}`));A.added=A.added.filter((S)=>!Z.has(`${S.filePath}::${S.name}`)),A.removed=A.removed.filter((S)=>!H.has(`${S.filePath}::${S.name}`))}if(T){let Z=new Date().toISOString(),H=g?1:0,S=[];for(let B of A.added){let P=`${B.filePath}::${B.name}`,q=M.get(P),c=l(B.filePath,this.opts.boundaries);S.push({project:c,changeType:"added",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:Z,isFullIndex:H,indexRunId:W})}for(let B of A.modified){let P=M.get(`${B.filePath}::${B.name}`),q=l(B.filePath,this.opts.boundaries);S.push({project:q,changeType:"modified",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Z,isFullIndex:H,indexRunId:W})}for(let B of A.removed){let P=`${B.filePath}::${B.name}`,q=X.get(P),c=l(B.filePath,this.opts.boundaries);S.push({project:c,changeType:"removed",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:Z,isFullIndex:H,indexRunId:W})}for(let B of C.renamed){let P=M.get(`${B.filePath}::${B.newName}`),q=l(B.filePath,this.opts.boundaries);S.push({project:q,changeType:"renamed",symbolName:B.newName,symbolKind:B.kind,filePath:B.filePath,oldName:B.oldName,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Z,isFullIndex:H,indexRunId:W})}for(let B of j){let P=M.get(`${B.filePath}::${B.name}`),q=l(B.filePath,this.opts.boundaries);S.push({project:q,changeType:"moved",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:B.oldFilePath,fingerprint:P?.fingerprint??null,changedAt:Z,isFullIndex:H,indexRunId:W})}if(S.length)try{w.transaction(()=>{T.insertBatch(S)})}catch(B){this.logger.error("[IndexCoordinator] changelog insert failed:",B)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let B=new Date(Date.now()-2592000000).toISOString();try{for(let P of this.opts.boundaries)T.pruneOlderThan(P.project,B)}catch(P){this.logger.error("[IndexCoordinator] changelog pruning failed:",P)}}}return{indexedFiles:Q.length,removedFiles:J.length,totalSymbols:K,totalRelations:n,totalAnnotations:i,durationMs:Date.now()-_,changedFiles:Q.map((Z)=>Z.filePath),deletedFiles:[...J],failedFiles:R,changedSymbols:A}}fireCallbacks(u){for(let g of this.callbacks)try{g(u)}catch(_){this.logger.error("[IndexCoordinator] onIndexed callback threw:",_)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((g)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",g))}}}function x$(u){try{return process.kill(u,0),!0}catch(g){if(typeof g==="object"&&g&&"code"in g)return g.code!=="ESRCH";return!0}}function p$(u){let g=new Date(u).getTime();return Number.isNaN(g)?0:g}function cg(u,g,_={}){let $=_.now??Date.now,N=_.isAlive??x$,z=_.staleAfterSeconds??60,w=_.instanceId;return u.immediateTransaction(()=>{let Q=u.selectOwner();if(!Q)return u.insertOwner(g,w),"owner";let J=Math.floor(($()-p$(Q.heartbeat_at))/1000),V=N(Q.pid);if(V&&w&&Q.instance_id&&Q.instance_id!==w&&Q.pid!==g)return u.replaceOwner(g,w),"owner";if(V&&J<z)return"reader";return u.replaceOwner(g,w),"owner"})}function sg(u,g){u.deleteOwner(g)}function og(u,g){u.touchOwner(g)}class Tu{#u;#g=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#g.size}has(u){return this.#g.has(u)}get(u){if(!this.#g.has(u))return;let g=this.#g.get(u);return this.#g.delete(u),this.#g.set(u,g),g}set(u,g){if(this.#g.has(u))this.#g.delete(u);if(this.#g.set(u,g),this.#g.size>this.#u){let _=this.#g.keys().next().value;if(_!==void 0)this.#g.delete(_)}}delete(u){return this.#g.delete(u)}clear(){this.#g.clear()}}class Vg{lru;constructor(u=500){this.lru=new Tu(u)}get(u){return this.lru.get(u)}set(u,g){this.lru.set(u,g)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Ug(u){let{symbolRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??100,w={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:N,limit:z,resolvedType:$.resolvedType};if($.text)if($.exact)w.exactName=$.text;else{let J=Bu($.text);if(J)w.ftsQuery=J}if($.decorator)w.decorator=$.decorator;if($.regex)w.regex=$.regex;return g.searchByQuery(w).map((J)=>({id:J.id,filePath:J.filePath,kind:J.kind,name:J.name,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}},isExported:J.isExported===1,signature:J.signature,fingerprint:J.fingerprint,detail:J.detailJson?(()=>{try{return JSON.parse(J.detailJson)}catch{return{}}})():{}}))}function Yg(u){let{relationRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??500;return g.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:N,limit:z}).map((Q)=>{let J;if(Q.metaJson)try{J=JSON.parse(Q.metaJson)}catch{}return{type:Q.type,srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,metaJson:Q.metaJson??void 0,meta:J}})}import{findInFiles as l$,Lang as r$}from"@ast-grep/napi";async function Zg(u){if(u.filePaths.length===0)return[];let g=[];return await l$(r$.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(_,$)=>{if(_){console.warn("[patternSearch] findInFiles callback error:",_);return}for(let N of $){let z=N.range();g.push({filePath:N.getRoot().filename(),startLine:z.start.line+1,endLine:z.end.line+1,matchedText:N.text()})}}),g}import d from"typescript";import{isErr as Q0}from"@zipbul/result";import zu from"typescript";import d$ from"path";import{err as Xg}from"@zipbul/result";function t$(u){try{return Rg("fs").readFileSync(u,"utf-8")}catch{return}}function a$(u){try{return Rg("fs").readFileSync(u,"utf-8")}catch{return}}class pu{#u;#g;#_=!1;__testing__;constructor(u,g){this.#u=u,this.#g=g,this.__testing__={host:g}}static create(u,g={}){let _=g.readConfigFile??t$,$=g.resolveNonTrackedFile??a$,N=d$.dirname(u),z=_(u);if(z===void 0)return Xg(e("semantic",`tsconfig not found: ${u}`));let w=zu.parseJsonText(u,z),Q=w.parseDiagnostics;if(Q&&Q.length>0){let W=Q.map((X)=>zu.flattenDiagnosticMessageText(X.messageText,`
8
- `)).join("; ");return Xg(e("semantic",`tsconfig parse error: ${W}`))}let J=zu.parseJsonSourceFileConfigFileContent(w,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(W)=>_(W)!==void 0||$(W)!==void 0,readFile:(W)=>_(W)??$(W)},N);if(J.errors.length>0){let W=J.errors.filter((X)=>X.category===zu.DiagnosticCategory.Error&&X.code!==18003);if(W.length>0){let X=W.map((M)=>zu.flattenDiagnosticMessageText(M.messageText,`
9
- `)).join("; ");return Xg(e("semantic",`tsconfig compile error: ${X}`))}}let V=new eg(J.fileNames,J.options,N,$),O=zu.createLanguageService(V);return new pu(O,V)}get isDisposed(){return this.#_}getProgram(){this.#N();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#N(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#N(),this.#u}notifyFileChanged(u,g){if(this.#_)return;this.#g.updateFile(u,g)}removeFile(u){if(this.#_)return;this.#g.removeFile(u)}dispose(){if(this.#_)return;this.#_=!0,this.#u.dispose()}#N(){if(this.#_)throw Error("TscProgram is disposed")}}class eg{#u;#g;#_;#N;#$=new Map;constructor(u,g,_,$){this.#u=new Set(u),this.#g=g,this.#_=_,this.#N=$}updateFile(u,g){let _=this.#$.get(u);if(_)_.version+=1,_.content=g;else this.#$.set(u,{version:1,content:g})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((_)=>!this.#$.has(_)),...u]}getScriptVersion(u){let g=this.#$.get(u);return g?String(g.version):"0"}getScriptSnapshot(u){let g=this.#$.get(u);if(g)return zu.ScriptSnapshot.fromString(g.content);let _=this.#N(u);if(_!==void 0)return zu.ScriptSnapshot.fromString(_);return}getCurrentDirectory(){return this.#_}getCompilationSettings(){return this.#g}getDefaultLibFileName(u){return zu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#N(u)!==void 0}readFile(u){let g=this.#$.get(u);if(g)return g.content;return this.#N(u)}}import a from"typescript";import c$ from"typescript";function Ou(u,g){if(g<0||g>=u.getEnd())return;function _($){let N=$.getStart(u,!1),z=$.getEnd();if(g<N||g>=z)return;let w;return c$.forEachChild($,(Q)=>{if(!w)w=_(Q)}),w??$}return _(u)}var Kg=8;function s$(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function Fu(u,g,_=0){let $=u.typeToString(g),N=g.flags,z=!!(N&a.TypeFlags.Union),w=!!(N&a.TypeFlags.Intersection),Q;if(_<Kg&&s$(g)){let W=u.getTypeArguments(g);if(W.length>0)Q=W}let J=!!(N&a.TypeFlags.TypeParameter)||Q!==void 0&&Q.length>0,V;if(z&&_<Kg)V=g.types.map((W)=>Fu(u,W,_+1));else if(w&&_<Kg)V=g.types.map((W)=>Fu(u,W,_+1));let O;if(Q&&Q.length>0)O=Q.map((W)=>Fu(u,W,_+1));return{text:$,flags:N,isUnion:z,isIntersection:w,isGeneric:J,members:V,typeArguments:O}}function o$(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 ng{program;constructor(u){this.program=u}collectAt(u,g){let _=this.program.getProgram(),$=this.program.getChecker();if(g<0)return null;let N=_.getSourceFile(u);if(!N)return null;if(g>=N.getEnd())return null;let z=Ou(N,g);if(!z)return null;if(!a.isIdentifier(z))return null;try{let w=$.getTypeAtLocation(z);return Fu($,w)}catch{return null}}collectFile(u){let g=new Map,_=this.program.getProgram(),$=this.program.getChecker(),N=_.getSourceFile(u);if(!N)return g;function z(w){if(o$(w)&&w.name&&a.isIdentifier(w.name)){let Q=w.name;try{let J=$.getTypeAtLocation(Q),V=Q.getStart(N);g.set(V,Fu($,J))}catch{}}a.forEachChild(w,z)}return z(N),g}}import Yu from"typescript";var e$=1000,u0=1;function g0(u){let g=u.declarations?.[0],_=g?.getSourceFile(),$=g?Yu.getNameOfDeclaration(g):void 0;return{name:u.getName(),filePath:_?.fileName??"",position:$?.getStart(_,!1)??g?.getStart(_,!1)??0}}function lu(u,g=0){let _=u.declarations?.[0],$=_?.getSourceFile(),N=_?Yu.getNameOfDeclaration(_):void 0,z=$?.fileName??"",w=N?.getStart($,!1)??_?.getStart($,!1)??0,Q={name:u.getName(),filePath:z,position:w},J=u;if(J.parent)Q.parent=g0(J.parent);if(g<u0){let V=u.flags,O=!!(V&Yu.SymbolFlags.Enum),W=!!(V&(Yu.SymbolFlags.NamespaceModule|Yu.SymbolFlags.ValueModule)),X=!!(V&(Yu.SymbolFlags.Class|Yu.SymbolFlags.Interface));if(O&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((D)=>{M.push(lu(D,g+1))}),Q.members=M}else if(X&&u.members&&u.members.size>0){let M=[];u.members.forEach((D)=>{M.push(lu(D,g+1))}),Q.members=M}if(W&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((D)=>{M.push(lu(D,g+1))}),Q.exports=M}}return Q}class Mg{#u;#g;#_=new Map;constructor(u,g=e$){this.#u=u,this.#g=new Tu(g)}get(u,g){if(this.#u.isDisposed)return null;let _=`${u}:${g}`,$=this.#g.get(_);if($!==void 0)return $;let z=this.#u.getProgram().getSourceFile(u);if(!z)return null;let w=Ou(z,g);if(!w||!Yu.isIdentifier(w))return null;let J=this.#u.getChecker().getSymbolAtLocation(w);if(!J)return null;let V=lu(J);this.#g.set(_,V);let O=this.#_.get(u);if(!O)O=new Set,this.#_.set(u,O);return O.add(_),V}invalidate(u){let g=this.#_.get(u);if(g){for(let _ of g)this.#g.delete(_);this.#_.delete(u)}}clear(){this.#g.clear(),this.#_.clear()}}import _0 from"typescript";class Bg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!_0.isIdentifier(N))return[];let w=this.#u.getLanguageService().findReferences(u,g);if(!w||w.length===0)return[];let Q=[];for(let J of w)for(let V of J.references){let O=_.getSourceFile(V.fileName);if(!O)continue;let{line:W,character:X}=O.getLineAndCharacterOfPosition(V.textSpan.start);Q.push({filePath:V.fileName,position:V.textSpan.start,line:W+1,column:X,isDefinition:V.isDefinition??!1,isWrite:V.isWriteAccess??!1})}return Q}}import m from"typescript";function $0(u,g){let _=Ou(u,g);if(!_)return;if(u_(_))return _;let $=_.parent;for(let N=0;N<5&&$;N++){if(u_($))return $;$=$.parent}return _}function u_(u){return m.isClassDeclaration(u)||m.isClassExpression(u)||m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u)||m.isVariableDeclaration(u)||m.isObjectLiteralExpression(u)}function g_(u){if(m.isClassDeclaration(u)||m.isClassExpression(u))return"class";if(m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u))return"function";if(m.isObjectLiteralExpression(u))return"object";if(m.isVariableDeclaration(u)&&u.initializer)return g_(u.initializer);return"class"}function N0(u,g){if(m.isClassDeclaration(u)||m.isFunctionDeclaration(u))return u.name?.getText(g)??"";if(m.isClassExpression(u))return u.name?.getText(g)??"";if(m.isVariableDeclaration(u)&&m.isIdentifier(u.name))return u.name.getText(g);if(m.isFunctionExpression(u))return u.name?.getText(g)??"";if(m.isArrowFunction(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}if(m.isObjectLiteralExpression(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}return""}function J0(u){if(!m.isClassDeclaration(u)&&!m.isClassExpression(u))return!1;let g=u.heritageClauses;if(!g)return!1;return g.some((_)=>_.token===m.SyntaxKind.ImplementsKeyword)}class Hg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!m.isIdentifier(N))return[];let w=this.#u.getLanguageService().getImplementationAtPosition(u,g);if(!w||w.length===0)return[];let Q=[];for(let J of w){if(J.kind===m.ScriptElementKind.interfaceElement||J.kind===m.ScriptElementKind.typeElement)continue;let V=_.getSourceFile(J.fileName);if(!V)continue;let O=$0(V,J.textSpan.start);if(!O)continue;let W=g_(O),X=N0(O,V),M=J0(O);Q.push({filePath:J.fileName,symbolName:X,position:J.textSpan.start,kind:W,isExplicit:M})}return Q}}function __(u){return d.canHaveModifiers(u)&&d.getModifiers(u)?.some((g)=>g.kind===d.SyntaxKind.ExportKeyword)===!0}function w0(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 $_(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 ru{#u;#g;#_;#N;#$;#J=!1;constructor(u,g,_,$,N){this.#u=u,this.#g=g,this.#_=_,this.#N=$,this.#$=N}static create(u,g={}){let _=pu.create(u,{readConfigFile:g.readConfigFile,resolveNonTrackedFile:g.resolveNonTrackedFile});if(Q0(_))return _;let $=_,N=g.typeCollector??new ng($),z=g.symbolGraph??new Mg($),w=g.referenceResolver??new Bg($),Q=g.implementationFinder??new Hg($);return new ru($,N,z,w,Q)}get isDisposed(){return this.#J}collectTypeAt(u,g){return this.#Q(),this.#g.collectAt(u,g)}collectFileTypes(u){return this.#Q(),this.#g.collectFile(u)}findReferences(u,g){return this.#Q(),this.#N.findAt(u,g)}findImplementations(u,g){return this.#Q(),this.#$.findAt(u,g)}getSymbolNode(u,g){return this.#Q(),this.#_.get(u,g)}getModuleInterface(u){this.#Q();let g=this.#g.collectFile(u),_=[],N=this.#u.getProgram().getSourceFile(u);if(!N)return{filePath:u,exports:_};function z(w){if(d.isVariableStatement(w)&&__(w)){for(let Q of w.declarationList.declarations)if(d.isIdentifier(Q.name)){let J=Q.name.getStart(N),V=g.get(J)??null;_.push({name:Q.name.text,kind:"const",resolvedType:V})}return}if((d.isFunctionDeclaration(w)||d.isClassDeclaration(w)||d.isInterfaceDeclaration(w)||d.isTypeAliasDeclaration(w)||d.isEnumDeclaration(w))&&__(w)&&w.name){let Q=w.name,J=Q.getStart(N),V=g.get(J)??null;_.push({name:Q.text,kind:w0(w),resolvedType:V});return}d.forEachChild(w,z)}return z(N),{filePath:u,exports:_}}notifyFileChanged(u,g){if(this.#J)return;this.#u.notifyFileChanged(u,g),this.#_.invalidate(u)}notifyFileDeleted(u){if(this.#J)return;this.#u.removeFile(u),this.#_.invalidate(u)}lineColumnToPosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return d.getPositionOfLineAndCharacter($,g-1,_)}catch{return null}}findNamePosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let N=$.getFullText(),z=g;while(z<N.length){let w=N.indexOf(_,z);if(w<0)return null;let Q=w>0?N.charCodeAt(w-1):32,J=w+_.length<N.length?N.charCodeAt(w+_.length):32;if(!$_(Q)&&!$_(J))return w;z=w+1}return null}dispose(){if(this.#J)return;this.#J=!0,this.#u.dispose(),this.#_.clear()}#Q(){if(this.#J)throw Error("SemanticLayer is disposed")}}import{eq as nu,and as N_,sql as z0}from"drizzle-orm";var J_=80;class Lg{db;constructor(u){this.db=u}insertBatch(u,g,_){if(!_.length)return;let $=_.map((N)=>({project:u,filePath:g,tag:N.tag,value:N.value,source:N.source,symbolName:N.symbolName,startLine:N.startLine,startColumn:N.startColumn,endLine:N.endLine,endColumn:N.endColumn,indexedAt:N.indexedAt}));for(let N=0;N<$.length;N+=J_)this.db.drizzleDb.insert($u).values($.slice(N,N+J_)).run()}deleteFileAnnotations(u,g){this.db.drizzleDb.delete($u).where(N_(nu($u.project,u),nu($u.filePath,g))).run()}search(u){return this.db.drizzleDb.select().from($u).where(N_(u.project?nu($u.project,u.project):void 0,u.tag?nu($u.tag,u.tag):void 0,u.filePath?nu($u.filePath,u.filePath):void 0,u.symbolName?nu($u.symbolName,u.symbolName):void 0,u.source?nu($u.source,u.source):void 0,u.ftsQuery?z0`${$u.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as Du,and as Q_,sql as qu,gt as O0,gte as W0}from"drizzle-orm";var w_=80;class Ig{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let g=u.map((_)=>({project:_.project,changeType:_.changeType,symbolName:_.symbolName,symbolKind:_.symbolKind,filePath:_.filePath,oldName:_.oldName,oldFilePath:_.oldFilePath,fingerprint:_.fingerprint,changedAt:_.changedAt,isFullIndex:_.isFullIndex,indexRunId:_.indexRunId}));for(let _=0;_<g.length;_+=w_)this.db.drizzleDb.insert(uu).values(g.slice(_,_+w_)).run()}getSince(u){return this.db.drizzleDb.select().from(uu).where(Q_(Du(uu.project,u.project),W0(uu.changedAt,u.since),u.symbolName?Du(uu.symbolName,u.symbolName):void 0,u.changeTypes?.length?qu`${uu.changeType} IN (${qu.join(u.changeTypes.map((g)=>qu`${g}`),qu`, `)})`:void 0,u.filePath?Du(uu.filePath,u.filePath):void 0,u.includeFullIndex?void 0:Du(uu.isFullIndex,0),u.indexRunId?Du(uu.indexRunId,u.indexRunId):void 0,u.afterId?O0(uu.id,u.afterId):void 0)).orderBy(uu.id).limit(u.limit).all()}pruneOlderThan(u,g){return this.db.drizzleDb.delete(uu).where(Q_(Du(uu.project,u),qu`${uu.changedAt} < ${g}`)).run().changes}}function z_(u){let{annotationRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??100,w;if($.text){let J=Bu($.text);if(J)w=J}return g.search({project:N,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:w,limit:z}).map((J)=>({tag:J.tag,value:J.value,source:J.source,filePath:J.filePath,symbolName:J.symbolName,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}}}))}class du{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let g=[this.options.project,...this.options.additionalProjects??[]].flatMap((_)=>[...this.options.relationRepo.getByType(_,"imports"),...this.options.relationRepo.getByType(_,"type-references"),...this.options.relationRepo.getByType(_,"re-exports")]);for(let _ of g){let{srcFilePath:$,dstFilePath:N}=_;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(N),!this.adjacencyList.has(N))this.adjacencyList.set(N,new Set);if(!this.reverseAdjacencyList.has(N))this.reverseAdjacencyList.set(N,new Set);this.reverseAdjacencyList.get(N).add($)}}patchFiles(u,g,_){let $=new Set([...u,...g]);for(let N of $){let z=this.adjacencyList.get(N);if(z){for(let Q of z)this.reverseAdjacencyList.get(Q)?.delete(N);z.clear()}let w=this.reverseAdjacencyList.get(N);if(w){for(let Q of w)this.adjacencyList.get(Q)?.delete(N);w.clear()}}for(let N of g)this.adjacencyList.delete(N),this.reverseAdjacencyList.delete(N);for(let N of u){let z=_(N);for(let w of z){if(!this.adjacencyList.has(w.srcFilePath))this.adjacencyList.set(w.srcFilePath,new Set);if(this.adjacencyList.get(w.srcFilePath).add(w.dstFilePath),!this.adjacencyList.has(w.dstFilePath))this.adjacencyList.set(w.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(w.dstFilePath))this.reverseAdjacencyList.set(w.dstFilePath,new Set);this.reverseAdjacencyList.get(w.dstFilePath).add(w.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.reverseAdjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}hasCycle(){let u=new Set,g=new Set;for(let _ of this.adjacencyList.keys()){if(u.has(_))continue;let $=[{node:_,entered:!1}];while($.length>0){let N=$.pop();if(N.entered){g.delete(N.node);continue}if(g.has(N.node))return!0;if(u.has(N.node))continue;u.add(N.node),g.add(N.node),$.push({node:N.node,entered:!0});for(let z of this.adjacencyList.get(N.node)??[]){if(g.has(z))return!0;if(!u.has(z))$.push({node:z,entered:!1})}}}return!1}getAffectedByChange(u){let g=new Set;for(let _ of u)for(let $ of this.getTransitiveDependents(_))g.add($);return Array.from(g)}getAdjacencyList(){let u=new Map;for(let[g,_]of this.adjacencyList)u.set(g,Array.from(_));return u}getTransitiveDependencies(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.adjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}getCyclePaths(u){let g=u?.maxCycles??1/0;if(g<=0)return[];let _=new Map;for(let[$,N]of this.adjacencyList)_.set($,Array.from(N));return X0(_,g)}}var V0=(u,g)=>u.localeCompare(g);function U0(u){let g=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(g.length===0)return[];let _=g;for(let $=1;$<g.length;$++){let N=g.slice($).concat(g.slice(0,$));if(N.join("::")<_.join("::"))_=N}return[..._]}function Dg(u,g,_){let $=U0(_);if($.length===0)return!1;let N=$.join("->");if(u.has(N))return!1;return u.add(N),g.push($),!0}function Y0(u){let g=0,_=[],$=new Set,N=new Map,z=new Map,w=[],Q=(J)=>{N.set(J,g),z.set(J,g),g+=1,_.push(J),$.add(J);for(let V of u.get(J)??[])if(!N.has(V))Q(V),z.set(J,Math.min(z.get(J)??0,z.get(V)??0));else if($.has(V))z.set(J,Math.min(z.get(J)??0,N.get(V)??0));if(z.get(J)===N.get(J)){let V=[],O="";do O=_.pop()??"",$.delete(O),V.push(O);while(O!==J&&_.length>0);w.push(V)}};for(let J of u.keys())if(!N.has(J))Q(J);return{components:w}}function Z0(u,g,_){let $=[],N=new Set,z=[...u].sort(V0),w=(Q,J,V)=>{J.delete(Q);let O=V.get(Q);if(!O)return;for(let W of O)if(J.has(W))w(W,J,V);O.clear()};for(let Q=0;Q<z.length&&$.length<_;Q++){let J=z[Q]??"",V=new Set(z.slice(Q)),O=new Set,W=new Map,X=[],M=(I)=>(g.get(I)??[]).filter((T)=>V.has(T)),D=(I)=>{if($.length>=_)return!0;let T=!1;X.push(I),O.add(I);for(let G of M(I)){if($.length>=_)break;if(G===J)Dg(N,$,X.concat(J)),T=!0;else if(!O.has(G)){if(D(G))T=!0}}if(T)w(I,O,W);else for(let G of M(I)){let i=W.get(G)??new Set;i.add(I),W.set(G,i)}return X.pop(),T};D(J)}return $}function X0(u,g){let{components:_}=Y0(u),$=[],N=new Set;for(let z of _){if($.length>=g)break;if(z.length===0)continue;if(z.length===1){let J=z[0]??"";if((u.get(J)??[]).includes(J))Dg(N,$,[J,J]);continue}let w=g-$.length,Q=Z0(z,u,w);for(let J of Q){if($.length>=g)break;Dg(N,$,J)}}return $}var K0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Au(u,g){let _=g??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>K0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===_)return u.graphCache;let $=new du({relationRepo:u.relationRepo,project:g??u.defaultProject,additionalProjects:g?void 0:u.boundaries?.map((N)=>N.project)});return $.build(),u.graphCache=$,u.graphCacheKey=_,u.graphCacheBuiltAt=Date.now(),$}function O_(u,g,_,$=1e4){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.dstFilePath)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getDependencies failed",{cause:N})}}function W_(u,g,_,$=1e4){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{dstFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.srcFilePath)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getDependents failed",{cause:N})}}async function V_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return Au(u,_).getAffectedByChange(g)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getAffected failed",{cause:$})}}async function U_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return Au(u,g).hasCycle()}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: hasCycle failed",{cause:_})}}async function Y_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return Au(u,g).getAdjacencyList()}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: getImportGraph failed",{cause:_})}}async function Z_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return Au(u,_).getTransitiveDependencies(g)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function X_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return Au(u,g).getCyclePaths(_)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getCyclePaths failed",{cause:$})}}async function K_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=Au(u,_);return{filePath:g,fanIn:$.getDependents(g).length,fanOut:$.getDependencies(g).length}}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getFanMetrics failed",{cause:$})}}var B0=30000,n_=15000,H0=10;function L0(u,g){return(_)=>{for(let $ of u.onFileChangedCallbacks)try{$(_)}catch(N){u.logger.error("[Gildash] onFileChanged callback threw:",N)}if(g.handleWatcherEvent?.(_),u.semanticLayer)if(_.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(_.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let N of u.onErrorCallbacks)try{N($ instanceof Y?$:new Y("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(_.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(_.filePath,$)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",N);for(let z of u.onErrorCallbacks)try{z(N instanceof Y?N:new Y("semantic","semantic notifyFileChanged failed",{cause:N}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",_.filePath,$);try{u.semanticLayer?.notifyFileDeleted(_.filePath)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",N)}})}}async function I0(u){if(!u.semanticLayer)return;let g=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(g.map(async(_)=>{try{let $=ju.resolve(u.projectRoot,_.filePath),N=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,N)}catch{}}))}async function M_(u,g){let _=u.coordinatorFactory?u.coordinatorFactory():new Wg({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=_;for(let $ of u.onIndexedCallbacks)_.onIndexed($);if(_.onIndexed(($)=>{let N=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&N>0&&N<100){let z=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(w)=>{return[u.defaultProject,...u.boundaries.map((J)=>J.project)].flatMap((J)=>z.getByType(J,"imports").concat(z.getByType(J,"type-references")).concat(z.getByType(J,"re-exports"))).filter((J)=>J.srcFilePath===w||J.dstFilePath===w).map((J)=>({srcFilePath:J.srcFilePath,dstFilePath:J.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),g.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new _g({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(L0(u,_)).then((N)=>{if(Gu(N))throw N.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},B0)}await _.fullIndex(),await I0(u)}function D0(u,g){let _=["SIGTERM","SIGINT","beforeExit"];for(let $ of _){let N=()=>{g().catch((z)=>u.logger.error("[Gildash] close error during signal",$,z))};if($==="beforeExit")process.on("beforeExit",N);else process.on($,N);u.signalHandlers.push([$,N])}}async function B_(u){let{projectRoot:g,extensions:_=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:N=500,logger:z=console,existsSyncFn:w=M0,dbConnectionFactory:Q,watcherFactory:J,coordinatorFactory:V,repositoryFactory:O,acquireWatcherRoleFn:W=cg,releaseWatcherRoleFn:X=sg,updateHeartbeatFn:M=og,discoverProjectsFn:D=bu,parseSourceFn:I=ku,extractSymbolsFn:T=Lu,extractRelationsFn:G=hu,symbolSearchFn:i=Ug,relationSearchFn:U=Yg,patternSearchFn:K=Zg,loadTsconfigPathsFn:n=Ru,readFileFn:R=async(H)=>Bun.file(H).text(),unlinkFn:A=async(H)=>{await Bun.file(H).unlink()},watchMode:C,semantic:v,semanticLayerFactory:y}=u;if(!ju.isAbsolute(g))throw new Y("validation",`Gildash: projectRoot must be an absolute path, got: "${g}"`);if(!w(g))throw new Y("validation",`Gildash: projectRoot does not exist: "${g}"`);let j=Q?Q():new su({projectRoot:g}),Z=j.open();if(Gu(Z))throw Z.data;try{let H=await D(g),S=H[0]?.project??ju.basename(g),B=O?O():(()=>{let s=j;return{fileRepo:new ou(s),symbolRepo:new eu(s),relationRepo:new ug(s),parseCache:new Vg(N)}})(),P=O?null:j,q=P?new Lg(P):null,c=P?new Ig(P):null,b=C??!0,h=crypto.randomUUID(),E;if(b)E=await Promise.resolve(W(j,process.pid,{instanceId:h}));else E="owner";let k={projectRoot:g,extensions:_,ignorePatterns:$,logger:z,defaultProject:S,role:E,db:j,symbolRepo:B.symbolRepo,relationRepo:B.relationRepo,fileRepo:B.fileRepo,parseCache:B.parseCache,annotationRepo:q,changelogRepo:c,annotationSearchFn:z_,releaseWatcherRoleFn:X,parseSourceFn:I,extractSymbolsFn:T,extractRelationsFn:G,symbolSearchFn:i,relationSearchFn:U,patternSearchFn:K,readFileFn:R,unlinkFn:A,existsSyncFn:w,acquireWatcherRoleFn:W,updateHeartbeatFn:M,watcherFactory:J,coordinatorFactory:V,instanceId:h,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:H,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(fu(g),k.tsconfigPaths=await n(g),v){let s=ju.join(g,"tsconfig.json");try{if(y)k.semanticLayer=y(s);else{let o=ru.create(s);if(Gu(o))throw o.data;k.semanticLayer=o}}catch(o){if(o instanceof Y)throw o;throw new Y("semantic","Gildash: semantic layer creation failed",{cause:o})}}if(E==="owner")await M_(k,{isWatchMode:b});else{let s=0,o=async()=>{try{let Qu=await Promise.resolve(k.acquireWatcherRoleFn(k.db,process.pid,{instanceId:k.instanceId}));if(s=0,Qu==="owner"){k.role="owner";for(let Wu of k.onRoleChangedCallbacks)try{Wu("owner")}catch(_u){k.logger.error("[Gildash] onRoleChanged callback threw:",_u)}clearInterval(k.timer),k.timer=null;try{await M_(k,{isWatchMode:!0})}catch(Wu){if(k.logger.error("[Gildash] owner promotion failed, reverting to reader",Wu),k.role="reader",k.timer!==null)clearInterval(k.timer),k.timer=null;if(k.watcher){let _u=await k.watcher.close();if(Gu(_u))k.logger.error("[Gildash] watcher close error during promotion rollback",_u.data);k.watcher=null}if(k.coordinator)await k.coordinator.shutdown().catch((_u)=>k.logger.error("[Gildash] coordinator shutdown error during promotion rollback",_u)),k.coordinator=null;try{k.releaseWatcherRoleFn(k.db,process.pid)}catch(_u){k.logger.error("[Gildash] failed to release watcher role during promotion rollback",_u)}k.timer=setInterval(o,n_)}}}catch(Qu){s++;let Wu=Qu instanceof Y?Qu:new Y("watcher","Gildash: healthcheck error",{cause:Qu});for(let _u of k.onErrorCallbacks)try{_u(Wu)}catch(Cu){k.logger.error("[Gildash] onError callback threw:",Cu)}if(k.logger.error("[Gildash] healthcheck error",Qu),s>=H0)k.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(k.timer),k.timer=null,au(k).catch((_u)=>k.logger.error("[Gildash] close error during healthcheck shutdown",_u))}};k.timer=setInterval(o,n_)}if(b)D0(k,()=>au(k));return k}catch(H){if(j.close(),H instanceof Y)throw H;throw new Y("store","Gildash: initialization failed",{cause:H})}}async function au(u,g){if(u.closed)return;u.closed=!0;let _=[];for(let[$,N]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",N);else process.off($,N);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){_.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(Gu($))_.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){_.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(g?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(ju.join(u.projectRoot,Vu,Eu+$))}catch{}if(_.length>0)throw new Y("close","Gildash: one or more errors occurred during close()",{cause:_})}import{isErr as H_}from"@zipbul/result";function L_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");let N=u.parseSourceFn(g,_,$);if(H_(N))throw N.data;return u.parseCache.set(g,N),N}async function I_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");let $=new Map,N=[];return await Promise.all(g.map(async(z)=>{try{let w=await u.readFileFn(z),Q=u.parseSourceFn(z,w,_);if(!H_(Q))$.set(z,Q);else N.push({filePath:z,error:Q.data})}catch(w){N.push({filePath:z,error:w instanceof Error?w:Error(String(w))})}})),{parsed:$,failures:N}}function D_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.parseCache.get(g)}function A_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.extractSymbolsFn(g)}function C_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.extractRelationsFn(g.program,g.filePath,u.tsconfigPaths??void 0)}import S_ from"path";function R_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(g??u.defaultProject)}catch(_){if(_ instanceof Y)throw _;throw new Y("store","Gildash: getStats failed",{cause:_})}}function Ag(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchSymbols failed",{cause:_})}}function k_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchRelations failed",{cause:_})}}function T_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchAllSymbols failed",{cause:_})}}function F_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchAllRelations failed",{cause:_})}}function q_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(g??u.defaultProject)}catch(_){if(_ instanceof Y)throw _;throw new Y("store","Gildash: listIndexedFiles failed",{cause:_})}}function G_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,dstFilePath:g,limit:1e4}})}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getInternalRelations failed",{cause:$})}}function j_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,z=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(z.length===0)return null;let w=z[0],Q=w.detail,J={...w,members:Array.isArray(Q.members)?Q.members:void 0,jsDoc:typeof Q.jsDoc==="string"?Q.jsDoc:void 0,parameters:typeof Q.parameters==="string"?Q.parameters:void 0,returnType:typeof Q.returnType==="string"?Q.returnType:void 0,heritage:Array.isArray(Q.heritage)?Q.heritage:void 0,decorators:Array.isArray(Q.decorators)?Q.decorators:void 0,typeParameters:typeof Q.typeParameters==="string"?Q.typeParameters:void 0};if(u.semanticLayer)try{let V=S_.isAbsolute(_)?_:S_.resolve(u.projectRoot,_),O=u.semanticLayer.lineColumnToPosition(V,w.span.start.line,w.span.start.column);if(O!==null){let W=u.semanticLayer.findNamePosition(V,O,w.name)??O,X=u.semanticLayer.collectTypeAt(V,W);if(X)J.resolvedType=X}}catch{}return J}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getFullSymbol failed",{cause:N})}}function E_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=_??u.defaultProject,N=u.fileRepo.getFile($,g);if(!N)throw new Y("search",`Gildash: file '${g}' is not in the index`);let z=u.symbolRepo.getFileSymbols($,g),w=u.relationRepo.getOutgoing($,g);return{filePath:N.filePath,lineCount:N.lineCount??0,size:N.size,symbolCount:z.length,exportedSymbolCount:z.filter((Q)=>Q.isExported).length,relationCount:w.length}}catch($){if($ instanceof Y)throw $;throw new Y("store","Gildash: getFileStats failed",{cause:$})}}function v_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(_??u.defaultProject,g)}catch($){if($ instanceof Y)throw $;throw new Y("store","Gildash: getFileInfo failed",{cause:$})}}function P_(u,g,_){return Ag(u,{filePath:g,project:_??void 0,limit:1e4})}function b_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let N=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:_??u.defaultProject,query:{filePath:g,isExported:!0}}).map((z)=>({name:z.name,kind:z.kind,parameters:z.detail.parameters??void 0,returnType:z.detail.returnType??void 0,jsDoc:z.detail.jsDoc??void 0}));return{filePath:g,exports:N}}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getModuleInterface failed",{cause:$})}}import f_ from"path";function Cg(u,g,_,$){let N=$??u.defaultProject,z=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(z.length===0)return null;let w=z[0],Q=f_.isAbsolute(_)?_:f_.resolve(u.projectRoot,_),J=u.semanticLayer.lineColumnToPosition(Q,w.span.start.line,w.span.start.column);if(J===null)return null;let V=u.semanticLayer.findNamePosition(Q,J,w.name)??J;return{sym:w,position:V,absPath:Q}}function y_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let N=Cg(u,g,_,$);if(!N)return null;return u.semanticLayer.collectTypeAt(N.absPath,N.position)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getResolvedType failed",{cause:N})}}function i_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let N=Cg(u,g,_,$);if(!N)throw new Y("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findReferences(N.absPath,N.position)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getSemanticReferences failed",{cause:N})}}function m_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let N=Cg(u,g,_,$);if(!N)throw new Y("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findImplementations(N.absPath,N.position)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getImplementations failed",{cause:N})}}function h_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(g)}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: getSemanticModuleInterface failed",{cause:_})}}function x_(u,g){let _=new Map(u.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),$=new Map(g.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),N=[],z=[],w=[];for(let[Q,J]of $){let V=_.get(Q);if(!V)N.push(J);else if(V.fingerprint!==J.fingerprint)w.push({before:V,after:J})}for(let[Q,J]of _)if(!$.has(Q))z.push(J);return{added:N,removed:z,modified:w}}function p_(u,g){if(u.onIndexedCallbacks.add(g),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(g)};let _=u.coordinator.onIndexed(g);return()=>{u.onIndexedCallbacks.delete(g),_()}}async function l_(u){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.coordinator)throw new Y("closed","Gildash: reindex() is not available for readers");try{let g=await u.coordinator.fullIndex();return tu(u),g}catch(g){if(g instanceof Y)throw g;throw new Y("index","Gildash: reindex failed",{cause:g})}}function r_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");let N=$??u.defaultProject,z=new Set,w=[],Q=g,J=_;for(;;){let V=`${J}::${Q}`;if(z.has(V))return{originalName:Q,originalFilePath:J,reExportChain:w,circular:!0};z.add(V);let O=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{type:"re-exports",srcFilePath:J,limit:500}}),W,X;for(let M of O){let D;if(M.metaJson)try{let T=JSON.parse(M.metaJson);if(Array.isArray(T.specifiers))D=T.specifiers}catch{}if(!D)continue;let I=D.find((T)=>T.exported===Q);if(!I)continue;W=M.dstFilePath,X=I.local;break}if(!W||!X)return{originalName:Q,originalFilePath:J,reExportChain:w,circular:!1};w.push({filePath:J,exportedAs:Q}),J=W,Q=X}}function d_(u,g){return u.onFileChangedCallbacks.add(g),()=>{u.onFileChangedCallbacks.delete(g)}}function t_(u,g){return u.onErrorCallbacks.add(g),()=>{u.onErrorCallbacks.delete(g)}}function a_(u,g){return u.onRoleChangedCallbacks.add(g),()=>{u.onRoleChangedCallbacks.delete(g)}}async function c_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=_?.project??u.defaultProject,N=_?.filePaths?_.filePaths:u.fileRepo.getAllFiles($).map((z)=>z.filePath);return await u.patternSearchFn({pattern:g,filePaths:N})}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: findPattern failed",{cause:$})}}async function s_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,z=new Set,w=(Q,J,V)=>{let O=`${Q}::${J}`;if(z.has(O))return{symbolName:Q,filePath:J,kind:V,children:[]};z.add(O);let M=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{srcFilePath:J,srcSymbolName:Q,limit:1000}}).filter((D)=>D.type==="extends"||D.type==="implements").filter((D)=>D.dstSymbolName!=null).map((D)=>w(D.dstSymbolName,D.dstFilePath,D.type));return{symbolName:Q,filePath:J,kind:V,children:M}};return w(g,_)}catch(N){if(N instanceof Y)throw N;throw new Y("search","Gildash: getHeritageChain failed",{cause:N})}}function o_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:g.project??u.defaultProject,query:g})}function e_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=g instanceof Date?g.toISOString():g,N=_?.project??u.defaultProject,z=_?.limit??1000;return u.changelogRepo.getSince({project:N,since:$,symbolName:_?.symbolName,changeTypes:_?.changeTypes,filePath:_?.filePath,includeFullIndex:_?.includeFullIndex,indexRunId:_?.indexRunId,afterId:_?.afterId,limit:z}).map((Q)=>({changeType:Q.changeType,symbolName:Q.symbolName,symbolKind:Q.symbolKind,filePath:Q.filePath,oldName:Q.oldName,oldFilePath:Q.oldFilePath,fingerprint:Q.fingerprint,changedAt:Q.changedAt,isFullIndex:Q.isFullIndex===1,indexRunId:Q.indexRunId}))}function u$(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let _=g instanceof Date?g.toISOString():g,$=0,N=[u.defaultProject,...u.boundaries.map((w)=>w.project)],z=[...new Set(N)];for(let w of z)$+=u.changelogRepo.pruneOlderThan(w,_);return $}class Sg{_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 g=await B_(u);return new Sg(g)}async close(u){return au(this._ctx,u)}parseSource(u,g,_){return L_(this._ctx,u,g,_)}async batchParse(u,g){return I_(this._ctx,u,g)}getParsedAst(u){return D_(this._ctx,u)}extractSymbols(u){return A_(this._ctx,u)}extractRelations(u){return C_(this._ctx,u)}getStats(u){return R_(this._ctx,u)}searchSymbols(u){return Ag(this._ctx,u)}searchRelations(u){return k_(this._ctx,u)}searchAllSymbols(u){return T_(this._ctx,u)}searchAllRelations(u){return F_(this._ctx,u)}listIndexedFiles(u){return q_(this._ctx,u)}getInternalRelations(u,g){return G_(this._ctx,u,g)}getFullSymbol(u,g,_){return j_(this._ctx,u,g,_)}getFileStats(u,g){return E_(this._ctx,u,g)}getFileInfo(u,g){return v_(this._ctx,u,g)}getSymbolsByFile(u,g){return P_(this._ctx,u,g)}getModuleInterface(u,g){return b_(this._ctx,u,g)}getDependencies(u,g,_=1e4){return O_(this._ctx,u,g,_)}getDependents(u,g,_=1e4){return W_(this._ctx,u,g,_)}async getAffected(u,g){return V_(this._ctx,u,g)}async hasCycle(u){return U_(this._ctx,u)}async getImportGraph(u){return Y_(this._ctx,u)}async getTransitiveDependencies(u,g){return Z_(this._ctx,u,g)}async getCyclePaths(u,g){return X_(this._ctx,u,g)}async getFanMetrics(u,g){return K_(this._ctx,u,g)}getResolvedType(u,g,_){return y_(this._ctx,u,g,_)}getSemanticReferences(u,g,_){return i_(this._ctx,u,g,_)}getImplementations(u,g,_){return m_(this._ctx,u,g,_)}getSemanticModuleInterface(u){return h_(this._ctx,u)}diffSymbols(u,g){return x_(u,g)}onIndexed(u){return p_(this._ctx,u)}async reindex(){return l_(this._ctx)}resolveSymbol(u,g,_){return r_(this._ctx,u,g,_)}async findPattern(u,g){return c_(this._ctx,u,g)}async getHeritageChain(u,g,_){return s_(this._ctx,u,g,_)}onFileChanged(u){return d_(this._ctx,u)}onError(u){return t_(this._ctx,u)}onRoleChanged(u){return a_(this._ctx,u)}searchAnnotations(u){return o_(this._ctx,u)}getSymbolChanges(u,g){return e_(this._ctx,u,g)}pruneChangelog(u){return u$(this._ctx,u)}}export{Ug as symbolSearch,Yg as relationSearch,Zg as patternSearch,e as gildashError,Y as GildashError,Sg as Gildash,du as DependencyGraph};
2
+ var H$=Object.defineProperty;var L$=(u)=>u;function I$(u,g){this[u]=L$.bind(null,g)}var D$=(u,g)=>{for(var _ in g)H$(u,_,{get:g[_],enumerable:!0,configurable:!0,set:I$.bind(g,_)})};var Fg=import.meta.require;import{isErr as vu}from"@zipbul/result";import Eu from"path";import{existsSync as E0}from"fs";import{err as Gg,isErr as T$}from"@zipbul/result";import{Database as q$}from"bun:sqlite";import{mkdirSync as n$,unlinkSync as vg,existsSync as Eg}from"fs";import{dirname as j$,join as bg}from"path";import{drizzle as F$}from"drizzle-orm/bun-sqlite";import{migrate as G$}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:_}:void 0)}var Yu=".gildash",yu="gildash.db";var ug={};D$(ug,{watcherOwner:()=>k$,symbols:()=>b,symbolChangelog:()=>Ju,relations:()=>L,files:()=>t,annotations:()=>Qu});import{sql as A$}from"drizzle-orm";import{sqliteTable as Du,text as F,integer as gu,real as C$,index as Nu,primaryKey as S$,foreignKey as fu,check as R$}from"drizzle-orm/sqlite-core";var t=Du("files",{project:F("project").notNull(),filePath:F("file_path").notNull(),mtimeMs:C$("mtime_ms").notNull(),size:gu("size").notNull(),contentHash:F("content_hash").notNull(),updatedAt:F("updated_at").notNull(),lineCount:gu("line_count")},(u)=>[S$({columns:[u.project,u.filePath]})]),b=Du("symbols",{id:gu("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),kind:F("kind").notNull(),name:F("name").notNull(),startLine:gu("start_line").notNull(),startColumn:gu("start_column").notNull(),endLine:gu("end_line").notNull(),endColumn:gu("end_column").notNull(),isExported:gu("is_exported").notNull().default(0),signature:F("signature"),fingerprint:F("fingerprint"),detailJson:F("detail_json"),contentHash:F("content_hash").notNull(),indexedAt:F("indexed_at").notNull(),resolvedType:F("resolved_type"),structuralFingerprint:F("structural_fingerprint")},(u)=>[Nu("idx_symbols_project_file").on(u.project,u.filePath),Nu("idx_symbols_project_kind").on(u.project,u.kind),Nu("idx_symbols_project_name").on(u.project,u.name),Nu("idx_symbols_fingerprint").on(u.project,u.fingerprint),fu({columns:[u.project,u.filePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),L=Du("relations",{id:gu("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),type:F("type").notNull(),srcFilePath:F("src_file_path").notNull(),srcSymbolName:F("src_symbol_name"),dstProject:F("dst_project").notNull(),dstFilePath:F("dst_file_path").notNull(),dstSymbolName:F("dst_symbol_name"),metaJson:F("meta_json")},(u)=>[Nu("idx_relations_src").on(u.project,u.srcFilePath),Nu("idx_relations_dst").on(u.dstProject,u.dstFilePath),Nu("idx_relations_type").on(u.project,u.type),Nu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),fu({columns:[u.project,u.srcFilePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade"),fu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),Qu=Du("annotations",{id:gu("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),tag:F("tag").notNull(),value:F("value").notNull().default(""),source:F("source").notNull(),symbolName:F("symbol_name"),startLine:gu("start_line").notNull(),startColumn:gu("start_column").notNull(),endLine:gu("end_line").notNull(),endColumn:gu("end_column").notNull(),indexedAt:F("indexed_at").notNull()},(u)=>[Nu("idx_annotations_project_file").on(u.project,u.filePath),Nu("idx_annotations_project_tag").on(u.project,u.tag),Nu("idx_annotations_project_symbol").on(u.project,u.symbolName),fu({columns:[u.project,u.filePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),Ju=Du("symbol_changelog",{id:gu("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),changeType:F("change_type").notNull(),symbolName:F("symbol_name").notNull(),symbolKind:F("symbol_kind").notNull(),filePath:F("file_path").notNull(),oldName:F("old_name"),oldFilePath:F("old_file_path"),fingerprint:F("fingerprint"),changedAt:F("changed_at").notNull(),isFullIndex:gu("is_full_index").notNull().default(0),indexRunId:F("index_run_id").notNull()},(u)=>[Nu("idx_changelog_project_changed_at").on(u.project,u.changedAt),Nu("idx_changelog_project_name").on(u.project,u.symbolName),Nu("idx_changelog_project_run").on(u.project,u.indexRunId)]),k$=Du("watcher_owner",{id:gu("id").primaryKey(),pid:gu("pid").notNull(),startedAt:F("started_at").notNull(),heartbeatAt:F("heartbeat_at").notNull(),instanceId:F("instance_id")},(u)=>[R$("watcher_owner_singleton",A$`${u.id} = 1`)]);class gg{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=bg(u.projectRoot,Yu,yu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{n$(j$(this.dbPath),{recursive:!0}),this.client=new q$(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=F$(this.client,{schema:ug}),G$(this.drizzle,{migrationsFolder:bg(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)&&Eg(this.dbPath)){this.closeClient(),vg(this.dbPath);for(let _ of["-wal","-shm"]){let $=this.dbPath+_;if(Eg($))vg($)}let g=this.open();if(T$(g))return Gg($u("store",`Failed to recover database at ${this.dbPath}`,g.data));return g}return Gg($u("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let g=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return g.transaction(()=>u(this))()}finally{this.txDepth--}}let _=`sp_${this.txDepth++}`;g.run(`SAVEPOINT "${_}"`);try{let $=u(this);return g.run(`RELEASE SAVEPOINT "${_}"`),$}catch($){throw g.run(`ROLLBACK TO SAVEPOINT "${_}"`),g.run(`RELEASE SAVEPOINT "${_}"`),$}finally{this.txDepth--}}immediateTransaction(u){let g=this.requireClient();this.txDepth++,g.run("BEGIN IMMEDIATE");try{let _=u();return g.run("COMMIT"),_}catch(_){throw g.run("ROLLBACK"),_}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((g)=>g.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}replaceOwner(u,g){let _=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??null)}touchOwner(u){let g=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(g,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let g=u;if(typeof g.function!=="function")return;g.function.call(u,"regexp",(_,$)=>{try{return new RegExp(_).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 g=u.message.toLowerCase();return g.includes("malformed")||g.includes("corrupt")||g.includes("not a database")||g.includes("disk i/o error")||g.includes("sqlite_corrupt")}}import{eq as Tu,and as yg}from"drizzle-orm";class _g{db;constructor(u){this.db=u}getFile(u,g){return this.db.drizzleDb.select().from(t).where(yg(Tu(t.project,u),Tu(t.filePath,g))).get()??null}upsertFile(u){this.db.drizzleDb.insert(t).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:[t.project,t.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(t).where(Tu(t.project,u)).all()}getFilesMap(u){let g=this.getAllFiles(u),_=new Map;for(let $ of g)_.set($.filePath,$);return _}deleteFile(u,g){this.db.drizzleDb.delete(t).where(yg(Tu(t.project,u),Tu(t.filePath,g))).run()}}import{eq as e,and as Ku,sql as Pu,count as v$}from"drizzle-orm";function Au(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((g)=>g.trim()).filter((g)=>g.length>0).map((g)=>`"${g.replaceAll('"','""')}"*`).join(" ")}var fg=50;class $g{db;constructor(u){this.db=u}replaceFileSymbols(u,g,_,$){if(this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,g))).run(),!$.length)return;let J=new Date().toISOString(),O=$.map((Q)=>({project:u,filePath:g,kind:Q.kind??"unknown",name:Q.name??"",startLine:Q.startLine??0,startColumn:Q.startColumn??0,endLine:Q.endLine??0,endColumn:Q.endColumn??0,isExported:Q.isExported??0,signature:Q.signature??null,fingerprint:Q.fingerprint??null,detailJson:Q.detailJson??null,contentHash:_,indexedAt:Q.indexedAt??J,resolvedType:Q.resolvedType??null,structuralFingerprint:Q.structuralFingerprint??null}));for(let Q=0;Q<O.length;Q+=fg)this.db.drizzleDb.insert(b).values(O.slice(Q,Q+fg)).run()}getFileSymbols(u,g){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.filePath,g))).all()}searchByName(u,g,_={}){let $=_.limit??50,J=Au(g);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),_.kind?e(b.kind,_.kind):void 0)).orderBy(b.name).limit($).all()}searchByKind(u,g){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.kind,g))).orderBy(b.name).all()}getStats(u){let g=this.db.drizzleDb.select({symbolCount:v$(),fileCount:Pu`COUNT(DISTINCT ${b.filePath})`}).from(b).where(e(b.project,u)).get();return{symbolCount:g?.symbolCount??0,fileCount:g?.fileCount??0}}getByFingerprint(u,g){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.fingerprint,g))).all()}deleteFileSymbols(u,g){this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,g))).run()}searchByQuery(u){let g=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 g.limit(u.limit).all();let _;try{_=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,Q=g.limit(O).all();if($=Q.filter((z)=>_.test(z.name)),$.length>=u.limit||Q.length<O)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as d,and as Wu,isNull as Pg,or as E$}from"drizzle-orm";class Jg{db;constructor(u){this.db=u}replaceFileRelations(u,g,_){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(Wu(d(L.project,u),d(L.srcFilePath,g))).run(),!_.length)return;for(let J of _)$.drizzleDb.insert(L).values({project:u,type:J.type??"unknown",srcFilePath:J.srcFilePath??g,srcSymbolName:J.srcSymbolName??null,dstProject:J.dstProject??u,dstFilePath:J.dstFilePath??"",dstSymbolName:J.dstSymbolName??null,metaJson:J.metaJson??null}).run()})}getOutgoing(u,g,_){if(_!==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(d(L.project,u),d(L.srcFilePath,g),E$(d(L.srcSymbolName,_),Pg(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(d(L.project,u),d(L.srcFilePath,g))).all()}getIncoming(u){let{dstProject:g,dstFilePath:_}=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(d(L.dstProject,g),d(L.dstFilePath,_))).all()}getByType(u,g){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(d(L.project,u),d(L.type,g))).all()}deleteFileRelations(u,g){this.db.drizzleDb.delete(L).where(Wu(d(L.project,u),d(L.srcFilePath,g))).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?d(L.project,u.project):void 0,u.srcFilePath!==void 0?d(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?d(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?d(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?d(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?d(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?d(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:g,oldFile:_,oldSymbol:$,newFile:J,newSymbol:O,newDstProject:Q}=u,z=$===null?Wu(d(L.dstProject,g),d(L.dstFilePath,_),Pg(L.dstSymbolName)):Wu(d(L.dstProject,g),d(L.dstFilePath,_),d(L.dstSymbolName,$)),N={dstFilePath:J,dstSymbolName:O};if(Q!==void 0)N.dstProject=Q;this.db.drizzleDb.update(L).set(N).where(z).run()}}import{err as mg}from"@zipbul/result";import{subscribe as b$}from"@parcel/watcher";import Ng from"path";var y$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],f$=new Set(["package.json","tsconfig.json"]);function P$(u){return u.replaceAll("\\","/")}function m$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class Qg{#u;#g;#_;#J;#$;#N;constructor(u,g=b$,_=console){this.#g=u.projectRoot,this.#_=[...y$,...u.ignorePatterns??[]],this.#J=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=g,this.#N=_}async start(u){try{this.#u=await this.#$(this.#g,(g,_)=>{if(g){this.#N.error($u("watcher","Callback error",g));return}try{for(let $ of _){let J=P$(Ng.relative(this.#g,$.path));if(J.startsWith(".."))continue;let O=Ng.basename(J),Q=Ng.extname(J).toLowerCase();if(!f$.has(O)&&!this.#J.has(Q))continue;if(J.endsWith(".d.ts"))continue;u({eventType:m$($.type),filePath:J})}}catch($){this.#N.error($u("watcher","Callback error",$))}},{ignore:this.#_})}catch(g){return mg($u("watcher","Failed to subscribe watcher",g))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return mg($u("watcher","Failed to close watcher",u))}}}import zg from"path";import{promises as h$}from"fs";var x$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function mu(u){let g=[];for await(let _ of h$.glob("**/package.json",{cwd:u,exclude:x$})){let $=zg.dirname(_).replaceAll("\\","/"),J=zg.join(u,_),O=await Bun.file(J).json(),Q=typeof O?.name==="string"&&O.name.length>0?O.name:zg.basename($==="."?u:$);g.push({dir:$,project:Q})}return g.sort((_,$)=>$.dir.length-_.dir.length),g}function s(u,g,_="default"){let $=u.replaceAll("\\","/");for(let J of g){if(J.dir===".")return J.project;if($===J.dir||$.startsWith(`${J.dir}/`))return J.project}return _}import hg from"path";var Zu=new Map;async function i$(u){let g=Bun.file(u);if(!await g.exists())return null;try{let _=await g.text(),$=Bun.JSONC.parse(_);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function qu(u){if(Zu.has(u))return Zu.get(u)??null;let g=hg.join(u,"tsconfig.json"),_=await i$(g);if(!_)return Zu.set(u,null),null;let $=typeof _.compilerOptions==="object"&&_.compilerOptions!==null?_.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 Q=J?hg.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 N={baseUrl:Q,paths:z};return Zu.set(u,N),N}function hu(u){if(u){Zu.delete(u);return}Zu.clear()}import xg from"path";function xu(u,g){return xg.relative(u,g).replaceAll("\\","/")}function Cu(u,g){return xg.resolve(u,g)}function zu(u){let g=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(g)).toString(16).padStart(16,"0")}import{isErr as eg}from"@zipbul/result";import{err as p$}from"@zipbul/result";import{parseSync as l$}from"oxc-parser";function nu(u,g,_,$=l$){try{let{program:J,errors:O,comments:Q}=$(u,g,_);return{filePath:u,program:J,errors:O,comments:Q,sourceText:g}}catch(J){return p$($u("parse",`Failed to parse file: ${u}`,J))}}import{promises as d$}from"fs";import{join as c$}from"path";async function ig(u){let{projectRoot:g,extensions:_,ignorePatterns:$,fileRepo:J}=u,O=J.getFilesMap(),Q=new Set,z=[],N=[],V=$.map((U)=>new Bun.Glob(U));for await(let U of d$.glob("**/*",{cwd:g})){if(!_.some((Z)=>U.endsWith(Z)))continue;if(U.startsWith("node_modules/")||U.includes("/node_modules/"))continue;if(V.some((Z)=>Z.match(U)))continue;Q.add(U);let X=c$(g,U),M=Bun.file(X),{size:I,lastModified:A}=M,q=O.get(U);if(!q){let Z=await M.text(),K=zu(Z);z.push({filePath:U,contentHash:K,mtimeMs:A,size:I});continue}if(q.mtimeMs===A&&q.size===I){N.push({filePath:U,contentHash:q.contentHash,mtimeMs:A,size:I});continue}let n=await M.text(),h=zu(n);if(h===q.contentHash)N.push({filePath:U,contentHash:h,mtimeMs:A,size:I});else z.push({filePath:U,contentHash:h,mtimeMs:A,size:I})}let W=[];for(let U of O.keys())if(!Q.has(U))W.push(U);return{changed:z,unchanged:N,deleted:W}}function iu(u){let g=[0];for(let _=0;_<u.length;_++)if(u[_]===`
3
+ `)g.push(_+1);return g}function Ou(u,g){let _=0,$=u.length-1;while(_<$){let J=_+$+1>>1;if(u[J]<=g)_=J;else $=J-1}return{line:_+1,column:g-u[_]}}import{err as r$}from"@zipbul/result";import{parse as s$}from"comment-parser";function pu(u){try{let g=u.trim();if(g.startsWith("/**"))g=g.slice(3);if(g.endsWith("*/"))g=g.slice(0,-2);let $=s$(`/** ${g} */`)[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(g){return r$($u("parse","Failed to parse JSDoc comment",g))}}import{isErr as a$}from"@zipbul/result";function Su(u){let{program:g,sourceText:_,comments:$}=u,J=iu(_),O=$.filter((Z)=>Z.type==="Block"&&Z.value.startsWith("*")).sort((Z,K)=>Z.end-K.end),Q=g.body.map((Z)=>Z.start??0).sort((Z,K)=>Z-K);function z(Z,K){return{start:Ou(J,Z),end:Ou(J,K)}}function N(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 T=O[R];K=0,B=Q.length-1;while(K<=B){let S=K+B>>>1,G=Q[S];if(G<=T.end)K=S+1;else if(G>=Z)B=S-1;else return}return`/*${T.value}*/`}function V(Z){if(!Z)return;let K=Z.typeAnnotation??Z;return _.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",T=(B.arguments??[]).map((S)=>_.slice(S.start,S.end));return{name:R,arguments:T.length>0?T:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:_.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"}`,i=K.typeAnnotation,_u=i?V(i):void 0,r={name:E,isOptional:!1};if(_u)r.type=_u;return r}if(K?.type==="AssignmentPattern"){let{left:y,right:E}=K,i=y?.name??"unknown",_u=y?.typeAnnotation,r=_u?V(_u):void 0,uu=_.slice(E.start,E.end),Y=W(y?.decorators??[]),D={name:i,isOptional:!0,defaultValue:uu};if(r)D.type=r;if(Y.length>0)D.decorators=Y;return D}let B=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,T=K?.typeAnnotation,S=T?V(T):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=_.slice(Z.superClass.start,Z.superClass.end);K.push({kind:"extends",name:R})}let B=Z.implements??[];for(let R of B){let T=R.expression??R,S=_.slice(T.start,T.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,T=_.slice(R.start,R.end);K.push({kind:"extends",name:T})}return K}function A(Z){let K=[];for(let B of Z)if(B.type==="MethodDefinition"){let R=B.key?.name??"unknown",T=B.value,S=B.kind??"method",G=S==="constructor"?"constructor":S==="get"?"getter":S==="set"?"setter":"method",f=X(B,T),y=(T?.params??[]).map(U),E=V(T?.returnType),i={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(i)}else if(B.type==="PropertyDefinition"){let R=B.key?.name??"unknown",T=X(B),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:T};K.push(S)}return K}function q(Z){let K=[];for(let B of Z)if(B.type==="TSMethodSignature"){let R=B.key?.name??"unknown",T=(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:T.length>0?T:void 0,returnType:S})}else if(B.type==="TSPropertySignature"){let R=B.key?.name??"unknown",T=V(B.typeAnnotation),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:B.readonly?["readonly"]:[],returnType:T};K.push(S)}return K}function n(Z,K){let B=Z.type??"";if(B==="FunctionDeclaration"){let R=Z.id?.name??"default",T=(Z.params??[]).map(U),S=V(Z.returnType),G=X(Z,Z),f=W(Z.decorators??[]),y=Z.typeParameters?.params?.flatMap((i)=>{let _u=i.name?.name;return _u?[_u]:[]})||void 0,E={kind:"function",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:G,parameters:T.length>0?T: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",T=M(Z),S=A(Z.body?.body??[]),G=W(Z.decorators??[]),f=X(Z,Z),y=Z.typeParameters?.params?.flatMap((i)=>{let _u=i.name?.name;return _u?[_u]:[]})||void 0,E={kind:"class",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:f,heritage:T.length>0?T: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 T of Z.declarations??[]){let{id:S,init:G}=T;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??T.start,r.end??T.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??T.start,r.end??T.end),isExported:K,modifiers:[]})}continue}let f=S?.name??"unknown",y="variable",E,i;if(G?.type==="FunctionExpression"||G?.type==="ArrowFunctionExpression")y="function",E=(G.params??[]).map(U),i=V(G.returnType);let _u=[];R.push({kind:y,name:f,span:z(T.start,T.end),isExported:K,modifiers:_u,parameters:E,returnType:i})}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",T=I(Z),S=q(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:T.length>0?T: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",T=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:T,members:G.length>0?G:void 0}}return null}let h=[];for(let Z of g.body){let K=null,B=Z,R=typeof B.type==="string"?B.type:"";if(R==="ExportNamedDeclaration"){let S=Z;if(S.declaration){if(K=n(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=n(G,!0),K&&!Array.isArray(K))K.name=G.id?.name??"default",K.isExported=!0,K.span=z(S.start,S.end)}}else K=n(Z,!1);let T=Array.isArray(K)?K:K?[K]:[];for(let S of T){let G=Z.start??0,f=N(G);if(f){let y=pu(f);if(!a$(y))S.jsDoc=y}h.push(S)}}return h}function t$(u){if(u.kind==="function"||u.kind==="method"){let g=u.parameters?.length??0,_=u.modifiers.includes("async")?1:0;return`params:${g}|async:${_}`}return null}function o$(u){let g={};if(u.jsDoc)g.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)g.parameters=u.parameters;if(u.returnType!==void 0)g.returnType=u.returnType}if(u.heritage?.length)g.heritage=u.heritage;if(u.decorators?.length)g.decorators=u.decorators;if(u.typeParameters?.length)g.typeParameters=u.typeParameters;if(u.modifiers?.length)g.modifiers=u.modifiers;if(u.members?.length)g.members=u.members.map((_)=>{let $=_.modifiers.find((J)=>J==="private"||J==="protected"||J==="public");return{name:_.name,kind:_.methodKind??_.kind,type:_.returnType,visibility:$,isStatic:_.modifiers.includes("static")||void 0,isReadonly:_.modifiers.includes("readonly")||void 0}});return Object.keys(g).length>0?JSON.stringify(g):null}function e$(u){let g=[u.kind];if(u.modifiers.length)g.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)g.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let _=[...u.heritage].sort(($,J)=>$.name.localeCompare(J.name)).map(($)=>`${$.kind}:${$.name}`).join(",");g.push(`her:${_}`)}if(u.decorators?.length)g.push(`dec:${[...u.decorators].map((_)=>_.name).sort().join(",")}`);if(u.methodKind)g.push(`mk:${u.methodKind}`);if(u.parameters)g.push(`p:${u.parameters.length}`);if(u.returnType)g.push(`rt:${u.returnType}`);if(u.members?.length){let _=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");g.push(`mem:${u.members.length}:${zu(_)}`)}return zu(g.join("|"))}function pg(u,g,_,$,J){let O=t$(u),Q=zu(`${g}|${u.kind}|${O??""}`),z=e$(u);return{project:_,filePath:$,kind:u.kind,name:g,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:Q,detailJson:o$(u),contentHash:J,indexedAt:new Date().toISOString(),structuralFingerprint:z}}function Og(u){let{parsed:g,project:_,filePath:$,contentHash:J,symbolRepo:O}=u,Q=Su(g),z=[];for(let N of Q){z.push(pg(N,N.name,_,$,J));for(let V of N.members??[])z.push(pg(V,`${N.name}.${V.name}`,_,$,J))}O.replaceFileSymbols(_,$,J,z)}import{resolve as wg,dirname as u0,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(g.startsWith(".")){let J=wg(u0(u),g);return $(J)}if(_)for(let[J,O]of _.paths){if(O.length===0)continue;let Q=J.indexOf("*");if(Q===-1){if(g===J){let z=[];for(let N of O)z.push(...$(wg(_.baseUrl,N)));return z}}else{let z=J.slice(0,Q),N=J.slice(Q+1);if(g.startsWith(z)&&(N===""||g.endsWith(N))){let V=g.slice(z.length,N===""?void 0:g.length-N.length),W=[];for(let U of O)W.push(...$(wg(_.baseUrl,U.replace("*",V))));return W}}}return[]}function lg(u,g,_,$=Mu){let J=new Map,O=u.body??[];for(let Q of O){if(Q.type!=="ImportDeclaration")continue;let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let V=N[0],W=Q.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,g){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Ru($,g);return}let _=u;g(_);for(let $ of Object.keys(_)){if(_0.has($))continue;let J=_[$];if(J&&typeof J==="object")Ru(J,g)}}function dg(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if((g.type==="StringLiteral"||g.type==="Literal")&&typeof g.value==="string")return g.value;return null}function Bu(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if(g.type==="Identifier"){let _=g.name;return{root:_,parts:[],full:_}}if(g.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(g.type==="Super")return{root:"super",parts:[],full:"super"};if(g.type==="MemberExpression"){let _=[],$=g;while($.type==="MemberExpression"){let Q=$.property;if(!Q||typeof Q.name!=="string")return null;_.push(Q.name),$=$.object}let J;if($.type==="Identifier")J=$.name;else if($.type==="ThisExpression")J="this";else if($.type==="Super")J="super";else return null;_.reverse();let O=[J,..._].join(".");return{root:J,parts:_,full:O}}return null}function cg(u,g,_,$=Mu){let J=[],O=u.body??[];for(let Q of O){if(Q.type==="ImportDeclaration"){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let V=N[0],W=Q.importKind==="type",U=Q.specifiers??[];if(U.length===0){let X={};if(W)X.isType=!0;J.push({type:W?"type-references":"imports",srcFilePath:g,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",A={};if(I)A.isType=!0;let q,n;if(M==="ImportDefaultSpecifier")q="default",n=X.local.name;else if(M==="ImportNamespaceSpecifier")q="*",n=X.local.name,A.importKind="namespace";else q=X.imported.name,n=X.local.name;J.push({type:I?"type-references":"imports",srcFilePath:g,srcSymbolName:n,dstFilePath:V,dstSymbolName:q,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}continue}if(Q.type==="ExportAllDeclaration"&&Q.source){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let V=N[0],W=Q.exportKind==="type",U={isReExport:!0};if(W)U.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(U)});continue}if(Q.type==="ExportNamedDeclaration"&&Q.source){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let V=N[0],W=Q.exportKind==="type",M={isReExport:!0,specifiers:(Q.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:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(M)})}}return Ru(u,(Q)=>{if(Q.type!=="ImportExpression")return;let z=dg(Q.source);if(!z)return;let N=$(g,z,_);if(N.length===0)return;let V=N[0];J.push({type:"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),J}function rg(u,g,_){let $=[],J=[],O=[];function Q(){if(J.length>0)return J[J.length-1]??null;return null}function z(V){if(!V)return null;let W=_.get(V.root);if(V.parts.length===0){if(W)return{dstFilePath:W.path,dstSymbolName:W.importedName,resolution:"import"};return{dstFilePath:g,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:g,dstSymbolName:V.full,resolution:"local-member"}}}function N(V){if(!V||typeof V!=="object")return;if(Array.isArray(V)){for(let X of V)N(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),N(X.body),O.pop();return}if(U==="FunctionDeclaration"){let X=W,M=X.id?.name??"anonymous";J.push(M),N(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),N(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",A=M?`${M}.${I}`:I;J.push(A),N(X.value?.body),J.pop();return}if(U==="FunctionExpression"||U==="ArrowFunctionExpression"){let X=Q(),M=X?`${X}.<anonymous>`:"<anonymous>";J.push(M),N(W.body),J.pop();return}if(U==="CallExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let A=Q(),q={};if(A===null)q.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:A,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(q).length>0?{metaJson:JSON.stringify(q)}:{}})}N(X.callee);for(let A of X.arguments??[])N(A);return}if(U==="NewExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let A=Q(),q={isNew:!0};if(A===null)q.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:A,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(q)})}for(let A of X.arguments??[])N(A);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")N(M)}}return N(u),$}function sg(u,g,_){let $=[];return Ru(u,(J)=>{if(J.type==="TSInterfaceDeclaration"){let z=J.id?.name??"AnonymousInterface",N=J.extends??[];for(let V of N){let W=V.expression??V,U=Bu(W);if(!U)continue;let X=Wg(U,g,_);$.push({type:"extends",srcFilePath:g,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 N=Wg(z,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:O,...N})}}let Q=J.implements??[];for(let z of Q){let N=z.expression??z,V=Bu(N);if(!V)continue;let W=Wg(V,g,_);$.push({type:"implements",srcFilePath:g,srcSymbolName:O,...W})}}),$}function Wg(u,g,_){let $=_.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:g,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function lu(u,g,_,$=Mu){let J=lg(u,g,_,$),O=cg(u,g,_,$),Q=rg(u,g,J),z=sg(u,g,J);return[...O,...Q,...z]}function Vg(u){let{ast:g,project:_,filePath:$,relationRepo:J,projectRoot:O,tsconfigPaths:Q,knownFiles:z,boundaries:N}=u,V=Cu(O,$),U=lu(g,V,Q,z?(M,I,A)=>{let q=Mu(M,I,A);for(let n of q){let h=xu(O,n);if(N){let Z=s(h,N);if(z.has(`${Z}::${h}`))return[n]}else if(z.has(`${_}::${h}`))return[n]}return[]}:void 0),X=[];for(let M of U){let I=xu(O,M.dstFilePath);if(I.startsWith(".."))continue;let A=xu(O,M.srcFilePath),q=N?s(I,N):_;X.push({project:_,type:M.type,srcFilePath:A,srcSymbolName:M.srcSymbolName??null,dstProject:q,dstFilePath:I,dstSymbolName:M.dstSymbolName??null,metaJson:M.metaJson??null})}return J.replaceFileRelations(_,$,X),X.length}import{isErr as $0}from"@zipbul/result";var ag=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function J0(u){let g=Su(u),_=[];for(let $ of g){_.push({name:$.name,startLine:$.span.start.line});for(let J of $.members??[])_.push({name:`${$.name}.${J.name}`,startLine:J.span.start.line})}return _.sort(($,J)=>$.startLine-J.startLine),_}function Ug(u,g,_){let $=0,J=u.length-1;while($<=J){let O=$+J>>1;if(u[O].startLine<=g)$=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 $=Ou(u,g),J=Ou(u,_);return{start:$,end:J}}function tg(u){let{comments:g,sourceText:_}=u;if(!g.length)return[];let $=iu(_),J=J0(u),O=[],Q=[...g].sort((N,V)=>N.start-V.start),z=null;for(let N of Q)if(N.type==="Block"&&N.value.startsWith("*")){z=null;let V=`/*${N.value}*/`,W=pu(V);if($0(W))continue;let U=W;if(!U.tags?.length)continue;let X=Ou($,N.end),M=Ug(J,X.line,3),I=_.slice(N.start,N.end);for(let A of U.tags){let q=[A.name,A.description].filter(Boolean).join(" "),n=`@${A.tag}`,h=I.indexOf(n),Z;if(h>=0){let K=N.start+h,B=_.indexOf(`
4
+ `,K),R=B>=0?Math.min(B,N.end):N.end;Z=du($,K,R)}else Z=du($,N.start,N.end);O.push({tag:A.tag,value:q,source:"jsdoc",span:Z,symbolName:M})}}else if(N.type==="Block"){z=null;let V=N.value.split(`
5
+ `),W=0;for(let U of V){let X=U.replace(/^\s*\*?\s?/,""),M=ag.exec(X);if(M){let I=M[1],A=M[2]?.trim()??"",q=`@${I}`,n=U.indexOf(q),h=N.start+2+W+(n>=0?n:0),Z=N.start+2+W+U.length,K=du($,h,Z),B=Ou($,N.end),R=Ug(J,B.line,3);O.push({tag:I,value:A,source:"block",span:K,symbolName:R})}W+=U.length+1}}else{let V=N.value,W=ag.exec(V),U=Ou($,N.start),X=Ou($,N.end);if(W){let M=W[1],I=W[2]?.trim()??"",A=`@${M}`,q=V.indexOf(A),n=N.start+2+(q>=0?q:0),h=du($,n,N.end),Z=Ug(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=Ou($,N.end),z.endLine=X.line}else z=null}return O}function Yg(u){let{parsed:g,project:_,filePath:$,annotationRepo:J}=u,O=tg(g);if(J.deleteFileAnnotations(_,$),!O.length)return 0;let Q=new Date().toISOString(),z=O.map((N)=>({project:_,filePath:$,tag:N.tag,value:N.value,source:N.source,symbolName:N.symbolName,startLine:N.span.start.line,startColumn:N.span.start.column,endLine:N.span.end.line,endColumn:N.span.end.column,indexedAt:Q}));return J.insertBatch(_,$,z),O.length}function og(u,g){let _=[],$=[],J=[];for(let[W,U]of g)if(!u.has(W))_.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[W,U]of u)if(!g.has(W))$.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!_.length||!$.length)return{renamed:J,added:_,removed:$};let O=new Map,Q=new Map;for(let W of _){let U=O.get(W.filePath)??[];U.push(W),O.set(W.filePath,U)}for(let W of $){let U=Q.get(W.filePath)??[];U.push(W),Q.set(W.filePath,U)}let z=new Set,N=new Set;for(let[W,U]of O){let X=Q.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)),A=X.filter((Z)=>Z.kind===M&&!N.has(Z));if(!I.length||!A.length)continue;let q=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.structuralFingerprint??null},n=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.startLine??0},h=new Map;for(let Z of A){let K=q(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=q(Z,g);if(!K)continue;let B=h.get(K);if(!B)continue;let R=B.filter((S)=>!N.has(S));if(!R.length)continue;let T=R[0];if(R.length>1){let S=n(Z,g),G=Math.abs(n(T,u)-S);for(let f=1;f<R.length;f++){let y=Math.abs(n(R[f],u)-S);if(y<G)G=y,T=R[f]}}J.push({oldName:T.name,newName:Z.name,filePath:W,kind:M}),z.add(Z),N.add(T)}}}let V=J.filter((W)=>!W.oldName.includes("."));for(let W of V){let U=`${W.oldName}.`,X=`${W.newName}.`,M=$.filter((A)=>A.filePath===W.filePath&&A.name.startsWith(U)&&!N.has(A)),I=_.filter((A)=>A.filePath===W.filePath&&A.name.startsWith(X)&&!z.has(A));for(let A of M){let q=A.name.slice(U.length),n=I.find((h)=>h.name.slice(X.length)===q);if(n)J.push({oldName:A.name,newName:n.name,filePath:W.filePath,kind:A.kind}),z.add(n),N.add(A)}}return{renamed:J,added:_.filter((W)=>!z.has(W)),removed:$.filter((W)=>!N.has(W))}}var N0=100,u_=50;class Zg{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((g)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",g)});return}if(u.filePath.endsWith("package.json")){let g=this.opts.discoverProjectsFn??mu;this.boundariesRefresh=g(this.opts.projectRoot).then((_)=>{this.opts.boundaries=_})}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,g){if(this.indexingLock){if(g)return this.pendingFullIndex=!0,new Promise(($,J)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:J})});return this.currentIndexing}this.indexingLock=!0;let _=this.doIndex(u,g).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=_,_}async doIndex(u,g){let _=Date.now(),{fileRepo:$,symbolRepo:J,relationRepo:O,dbConnection:Q}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let z,N;if(u!==void 0)z=u.filter((Y)=>Y.eventType==="create"||Y.eventType==="change").map((Y)=>({filePath:Y.filePath,contentHash:"",mtimeMs:0,size:0})),N=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 D=await ig({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Y}});z=D.changed,N=D.deleted}let V=await this.tsconfigPathsRaw??void 0,W=new Map;for(let Y of N){let D=s(Y,this.opts.boundaries),C=J.getFileSymbols(D,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(g)for(let Y of this.opts.boundaries)for(let D of $.getAllFiles(Y.project))for(let C of J.getFileSymbols(Y.project,D.filePath))X.set(`${C.filePath}::${C.name}`,I(C));else{for(let Y of z){let D=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(D,Y.filePath))X.set(`${C.filePath}::${C.name}`,I(C))}for(let[,Y]of W)for(let D of Y)X.set(`${D.filePath}::${D.name}`,I(D))}let A=(Y)=>`${Y.type}|${Y.srcFilePath}|${Y.dstFilePath}|${Y.srcSymbolName??""}|${Y.dstSymbolName??""}|${zu(Y.metaJson??"")}`,q=new Map;if(g)for(let Y of this.opts.boundaries)for(let D of $.getAllFiles(Y.project))for(let C of O.getOutgoing(Y.project,D.filePath))q.set(A(C),C);else{for(let Y of z){let D=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(D,Y.filePath))q.set(A(C),C)}for(let Y of N){let D=s(Y,this.opts.boundaries);for(let C of O.getOutgoing(D,Y))q.set(A(C),C)}}let{annotationRepo:n,changelogRepo:h}=this.opts,Z=()=>{for(let Y of N){let D=s(Y,this.opts.boundaries);if(J.deleteFileSymbols(D,Y),O.deleteFileRelations(D,Y),n)n.deleteFileAnnotations(D,Y);$.deleteFile(D,Y)}},K=0,B=async()=>{let{projectRoot:Y,boundaries:D}=this.opts,{parseCache:C}=this.opts,k=0,P=0,H=0,a=[],j=[];for(let v of z)try{let p=Cu(Y,v.filePath),Uu=Bun.file(p),Iu=await Uu.text(),ng=v.contentHash||zu(Iu),jg=s(v.filePath,D);$.upsertFile({project:jg,filePath:v.filePath,mtimeMs:Uu.lastModified,size:Uu.size,contentHash:ng,updatedAt:new Date().toISOString(),lineCount:Iu.split(`
6
+ `).length});let eu=(this.opts.parseSourceFn??nu)(p,Iu);if(eg(eu))throw eu.data;let B$=eu;j.push({filePath:v.filePath,text:Iu,contentHash:ng,parsed:B$,project:jg})}catch(p){this.logger.error(`[IndexCoordinator] Failed to prepare ${v.filePath}:`,p),a.push(v.filePath)}let m=new Set;for(let v of D)for(let[p]of $.getFilesMap(v.project))m.add(`${v.project}::${p}`);return Q.transaction(()=>{for(let v of j){if(Og({parsed:v.parsed,project:v.project,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:J}),P+=Vg({ast:v.parsed.program,project:v.project,filePath:v.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:m,boundaries:D}),n)H+=Yg({parsed:v.parsed,project:v.project,filePath:v.filePath,annotationRepo:n});C.set(v.filePath,v.parsed),k+=J.getFileSymbols(v.project,v.filePath).length}}),{symbols:k,relations:P,annotations:H,failedFiles:a}},R=0,T=0,S=[];if(g){let{projectRoot:Y,boundaries:D}=this.opts,{parseCache:C}=this.opts,k=[];for(let H=0;H<z.length;H+=u_){let a=z.slice(H,H+u_),j=await Promise.allSettled(a.map(async(m)=>{let v=Cu(Y,m.filePath),p=Bun.file(v),Uu=await p.text(),Iu=m.contentHash||zu(Uu);return{filePath:m.filePath,text:Uu,contentHash:Iu,mtimeMs:p.lastModified,size:p.size}}));for(let m=0;m<j.length;m++){let v=j[m];if(v.status==="fulfilled")k.push(v.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",v.reason),S.push(a[m].filePath)}}let P=[];Q.transaction(()=>{for(let j of k){let m=s(j.filePath,D);$.deleteFile(m,j.filePath)}for(let j of N){let m=s(j,D);if(J.deleteFileSymbols(m,j),O.deleteFileRelations(m,j),n)n.deleteFileAnnotations(m,j);$.deleteFile(m,j)}for(let j of k){let m=s(j.filePath,D);$.upsertFile({project:m,filePath:j.filePath,mtimeMs:j.mtimeMs,size:j.size,contentHash:j.contentHash,updatedAt:new Date().toISOString(),lineCount:j.text.split(`
7
+ `).length})}let H=new Set;for(let j of D)for(let[m]of $.getFilesMap(j.project))H.add(`${j.project}::${m}`);let a=this.opts.parseSourceFn??nu;for(let j of k){let m=s(j.filePath,D),v=a(Cu(Y,j.filePath),j.text);if(eg(v))throw v.data;let p=v;if(P.push({filePath:j.filePath,parsed:p}),Og({parsed:p,project:m,filePath:j.filePath,contentHash:j.contentHash,symbolRepo:J}),n)K+=Yg({parsed:p,project:m,filePath:j.filePath,annotationRepo:n});T+=Vg({ast:p.program,project:m,filePath:j.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:H,boundaries:D}),R+=J.getFileSymbols(m,j.filePath).length}});for(let H of P)C.set(H.filePath,H.parsed)}else{Z();let Y=await B();R=Y.symbols,T=Y.relations,K=Y.annotations,S=Y.failedFiles}for(let Y of z){let D=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(D,Y.filePath))M.set(`${C.filePath}::${C.name}`,I(C))}let G=new Map;for(let Y of z){let D=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(D,Y.filePath))G.set(A(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])=>!q.has(Y)).map(([,Y])=>f(Y)),removed:[...q.entries()].filter(([Y])=>!G.has(Y)).map(([,Y])=>f(Y))},E={added:[],modified:[],removed:[]};for(let[Y,D]of M){let C=X.get(Y);if(!C)E.added.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)});else{let k=C.fingerprint!==D.fingerprint,P=C.isExported!==D.isExported,H=C.structuralFingerprint!==null&&D.structuralFingerprint!==null&&C.structuralFingerprint!==D.structuralFingerprint;if(k||P||H)E.modified.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)})}}for(let[Y,D]of X)if(!M.has(Y))E.removed.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)});let i=og(X,M),_u=new Set(i.renamed.map((Y)=>`${Y.filePath}::${Y.oldName}`)),r=new Set(i.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)=>!_u.has(`${Y.filePath}::${Y.name}`));let uu=[];if(!g){for(let[Y,D]of W)for(let C of D){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 i.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}`)),D=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)=>!D.has(`${C.filePath}::${C.name}`))}if(h){let Y=new Date().toISOString(),D=g?1:0,C=[];for(let k of E.added){let P=`${k.filePath}::${k.name}`,H=M.get(P),a=s(k.filePath,this.opts.boundaries);C.push({project:a,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:D,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:D,indexRunId:U})}for(let k of E.removed){let P=`${k.filePath}::${k.name}`,H=X.get(P),a=s(k.filePath,this.opts.boundaries);C.push({project:a,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:D,indexRunId:U})}for(let k of i.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:D,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:D,indexRunId:U})}if(C.length)try{Q.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:N.length,totalSymbols:R,totalRelations:T,totalAnnotations:K,durationMs:Date.now()-_,changedFiles:z.map((Y)=>Y.filePath),deletedFiles:[...N],failedFiles:S,changedSymbols:E,renamedSymbols:i.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 g of this.callbacks)try{g(u)}catch(_){this.logger.error("[IndexCoordinator] onIndexed callback threw:",_)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((g)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",g))}}}function Q0(u){try{return process.kill(u,0),!0}catch(g){if(typeof g==="object"&&g&&"code"in g)return g.code!=="ESRCH";return!0}}function z0(u){let g=new Date(u).getTime();return Number.isNaN(g)?0:g}function g_(u,g,_={}){let $=_.now??Date.now,J=_.isAlive??Q0,O=_.staleAfterSeconds??60,Q=_.instanceId;return u.immediateTransaction(()=>{let z=u.selectOwner();if(!z)return u.insertOwner(g,Q),"owner";let N=Math.floor(($()-z0(z.heartbeat_at))/1000),V=J(z.pid);if(V&&Q&&z.instance_id&&z.instance_id!==Q&&z.pid!==g)return u.replaceOwner(g,Q),"owner";if(V&&N<O)return"reader";return u.replaceOwner(g,Q),"owner"})}function __(u,g){u.deleteOwner(g)}function $_(u,g){u.touchOwner(g)}class ju{#u;#g=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#g.size}has(u){return this.#g.has(u)}get(u){if(!this.#g.has(u))return;let g=this.#g.get(u);return this.#g.delete(u),this.#g.set(u,g),g}set(u,g){if(this.#g.has(u))this.#g.delete(u);if(this.#g.set(u,g),this.#g.size>this.#u){let _=this.#g.keys().next().value;if(_!==void 0)this.#g.delete(_)}}delete(u){return this.#g.delete(u)}clear(){this.#g.clear()}}class Xg{lru;constructor(u=500){this.lru=new ju(u)}get(u){return this.lru.get(u)}set(u,g){this.lru.set(u,g)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Kg(u){let{symbolRepo:g,project:_,query:$}=u,J=$.project??_,O=$.limit??100,Q={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:J,limit:O,resolvedType:$.resolvedType};if($.text)if($.exact)Q.exactName=$.text;else{let N=Au($.text);if(N)Q.ftsQuery=N}if($.decorator)Q.decorator=$.decorator;if($.regex)Q.regex=$.regex;return g.searchByQuery(Q).map((N)=>({id:N.id,filePath:N.filePath,kind:N.kind,name:N.name,span:{start:{line:N.startLine,column:N.startColumn},end:{line:N.endLine,column:N.endColumn}},isExported:N.isExported===1,signature:N.signature,fingerprint:N.fingerprint,detail:N.detailJson?(()=>{try{return JSON.parse(N.detailJson)}catch{return{}}})():{}}))}function Mg(u){let{relationRepo:g,project:_,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??_,O=$.limit??500,Q=!!($.srcFilePathPattern||$.dstFilePathPattern),z=Q?Number.MAX_SAFE_INTEGER:O,V=g.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(Q&&V.length>O)V=V.slice(0,O);return V}import{findInFiles as O0,Lang as w0}from"@ast-grep/napi";async function Bg(u){if(u.filePaths.length===0)return[];let g=[];return await O0(w0.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(_,$)=>{if(_){console.warn("[patternSearch] findInFiles callback error:",_);return}for(let J of $){let O=J.range();g.push({filePath:J.getRoot().filename(),startLine:O.start.line+1,endLine:O.end.line+1,matchedText:J.text()})}}),g}import c from"typescript";import{isErr as A0}from"@zipbul/result";import Vu from"typescript";import W0 from"path";import{err as Hg}from"@zipbul/result";function V0(u){try{return Fg("fs").readFileSync(u,"utf-8")}catch{return}}function U0(u){try{return Fg("fs").readFileSync(u,"utf-8")}catch{return}}class cu{#u;#g;#_=!1;__testing__;constructor(u,g){this.#u=u,this.#g=g,this.__testing__={host:g}}static create(u,g={}){let _=g.readConfigFile??V0,$=g.resolveNonTrackedFile??U0,J=W0.dirname(u),O=_(u);if(O===void 0)return Hg($u("semantic",`tsconfig not found: ${u}`));let Q=Vu.parseJsonText(u,O),z=Q.parseDiagnostics;if(z&&z.length>0){let U=z.map((X)=>Vu.flattenDiagnosticMessageText(X.messageText,`
8
+ `)).join("; ");return Hg($u("semantic",`tsconfig parse error: ${U}`))}let N=Vu.parseJsonSourceFileConfigFileContent(Q,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>_(U)!==void 0||$(U)!==void 0,readFile:(U)=>_(U)??$(U)},J);if(N.errors.length>0){let U=N.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 Hg($u("semantic",`tsconfig compile error: ${X}`))}}let V=new J_(N.fileNames,N.options,J,$),W=Vu.createLanguageService(V);return new cu(W,V)}get isDisposed(){return this.#_}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,g){if(this.#_)return;this.#g.updateFile(u,g)}removeFile(u){if(this.#_)return;this.#g.removeFile(u)}dispose(){if(this.#_)return;this.#_=!0,this.#u.dispose()}#J(){if(this.#_)throw Error("TscProgram is disposed")}}class J_{#u;#g;#_;#J;#$=new Map;constructor(u,g,_,$){this.#u=new Set(u),this.#g=g,this.#_=_,this.#J=$}updateFile(u,g){let _=this.#$.get(u);if(_)_.version+=1,_.content=g;else this.#$.set(u,{version:1,content:g})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((_)=>!this.#$.has(_)),...u]}getScriptVersion(u){let g=this.#$.get(u);return g?String(g.version):"0"}getScriptSnapshot(u){let g=this.#$.get(u);if(g)return Vu.ScriptSnapshot.fromString(g.content);let _=this.#J(u);if(_!==void 0)return Vu.ScriptSnapshot.fromString(_);return}getCurrentDirectory(){return this.#_}getCompilationSettings(){return this.#g}getDefaultLibFileName(u){return Vu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#J(u)!==void 0}readFile(u){let g=this.#$.get(u);if(g)return g.content;return this.#J(u)}}import o from"typescript";import Y0 from"typescript";function wu(u,g){if(g<0||g>=u.getEnd())return;function _($){let J=$.getStart(u,!1),O=$.getEnd();if(g<J||g>=O)return;let Q;return Y0.forEachChild($,(z)=>{if(!Q)Q=_(z)}),Q??$}return _(u)}var Lg=8;function Z0(u){return!!(u.flags&o.TypeFlags.Object)&&!!(u.objectFlags&o.ObjectFlags.Reference)}function Fu(u,g,_=0){let $=u.typeToString(g),J=g.flags,O=!!(J&o.TypeFlags.Union),Q=!!(J&o.TypeFlags.Intersection),z;if(_<Lg&&Z0(g)){let U=u.getTypeArguments(g);if(U.length>0)z=U}let N=!!(J&o.TypeFlags.TypeParameter)||z!==void 0&&z.length>0,V;if(O&&_<Lg)V=g.types.map((U)=>Fu(u,U,_+1));else if(Q&&_<Lg)V=g.types.map((U)=>Fu(u,U,_+1));let W;if(z&&z.length>0)W=z.map((U)=>Fu(u,U,_+1));return{text:$,flags:J,isUnion:O,isIntersection:Q,isGeneric:N,members:V,typeArguments:W}}function X0(u){return o.isFunctionDeclaration(u)||o.isVariableDeclaration(u)||o.isClassDeclaration(u)||o.isInterfaceDeclaration(u)||o.isTypeAliasDeclaration(u)||o.isEnumDeclaration(u)||o.isMethodDeclaration(u)||o.isPropertyDeclaration(u)||o.isPropertySignature(u)||o.isMethodSignature(u)}class Ig{program;constructor(u){this.program=u}collectAt(u,g){let _=this.program.getProgram(),$=this.program.getChecker();if(g<0)return null;let J=_.getSourceFile(u);if(!J)return null;if(g>=J.getEnd())return null;let O=wu(J,g);if(!O)return null;if(!o.isIdentifier(O))return null;try{let Q=$.getTypeAtLocation(O);return Fu($,Q)}catch{return null}}isAssignableTo(u,g,_,$){let J=this.program.getChecker(),O=this.program.getProgram(),Q=O.getSourceFile(u);if(!Q)return null;let z=wu(Q,g);if(!z||!o.isIdentifier(z))return null;let N=O.getSourceFile(_);if(!N)return null;let V=wu(N,$);if(!V||!o.isIdentifier(V))return null;try{let W=J.getTypeAtLocation(z),U=J.getTypeAtLocation(V);return J.isTypeAssignableTo(W,U)}catch{return null}}collectFile(u){let g=new Map,_=this.program.getProgram(),$=this.program.getChecker(),J=_.getSourceFile(u);if(!J)return g;function O(Q){if(X0(Q)&&Q.name&&o.isIdentifier(Q.name)){let z=Q.name;try{let N=$.getTypeAtLocation(z),V=z.getStart(J);g.set(V,Fu($,N))}catch{}}o.forEachChild(Q,O)}return O(J),g}}import Xu from"typescript";var K0=1000,M0=1;function B0(u){let g=u.declarations?.[0],_=g?.getSourceFile(),$=g?Xu.getNameOfDeclaration(g):void 0;return{name:u.getName(),filePath:_?.fileName??"",position:$?.getStart(_,!1)??g?.getStart(_,!1)??0}}function ru(u,g=0){let _=u.declarations?.[0],$=_?.getSourceFile(),J=_?Xu.getNameOfDeclaration(_):void 0,O=$?.fileName??"",Q=J?.getStart($,!1)??_?.getStart($,!1)??0,z={name:u.getName(),filePath:O,position:Q},N=u;if(N.parent)z.parent=B0(N.parent);if(g<M0){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,g+1))}),z.members=M}else if(X&&u.members&&u.members.size>0){let M=[];u.members.forEach((I)=>{M.push(ru(I,g+1))}),z.members=M}if(U&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(ru(I,g+1))}),z.exports=M}}return z}class Dg{#u;#g;#_=new Map;constructor(u,g=K0){this.#u=u,this.#g=new ju(g)}get(u,g){if(this.#u.isDisposed)return null;let _=`${u}:${g}`,$=this.#g.get(_);if($!==void 0)return $;let O=this.#u.getProgram().getSourceFile(u);if(!O)return null;let Q=wu(O,g);if(!Q||!Xu.isIdentifier(Q))return null;let N=this.#u.getChecker().getSymbolAtLocation(Q);if(!N)return null;let V=ru(N);this.#g.set(_,V);let W=this.#_.get(u);if(!W)W=new Set,this.#_.set(u,W);return W.add(_),V}invalidate(u){let g=this.#_.get(u);if(g){for(let _ of g)this.#g.delete(_);this.#_.delete(u)}}clear(){this.#g.clear(),this.#_.clear()}}import H0 from"typescript";class Ag{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let J=wu($,g);if(!J||!H0.isIdentifier(J))return[];let Q=this.#u.getLanguageService().findReferences(u,g);if(!Q||Q.length===0)return[];let z=[];for(let N of Q)for(let V of N.references){let W=_.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 L0(u,g){let _=wu(u,g);if(!_)return;if(N_(_))return _;let $=_.parent;for(let J=0;J<5&&$;J++){if(N_($))return $;$=$.parent}return _}function N_(u){return x.isClassDeclaration(u)||x.isClassExpression(u)||x.isFunctionDeclaration(u)||x.isFunctionExpression(u)||x.isArrowFunction(u)||x.isVariableDeclaration(u)||x.isObjectLiteralExpression(u)}function Q_(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 Q_(u.initializer);return"class"}function I0(u,g){if(x.isClassDeclaration(u)||x.isFunctionDeclaration(u))return u.name?.getText(g)??"";if(x.isClassExpression(u))return u.name?.getText(g)??"";if(x.isVariableDeclaration(u)&&x.isIdentifier(u.name))return u.name.getText(g);if(x.isFunctionExpression(u))return u.name?.getText(g)??"";if(x.isArrowFunction(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(g)}if(x.isObjectLiteralExpression(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(g)}return""}function D0(u){if(!x.isClassDeclaration(u)&&!x.isClassExpression(u))return!1;let g=u.heritageClauses;if(!g)return!1;return g.some((_)=>_.token===x.SyntaxKind.ImplementsKeyword)}class Cg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let J=wu($,g);if(!J||!x.isIdentifier(J))return[];let Q=this.#u.getLanguageService().getImplementationAtPosition(u,g);if(!Q||Q.length===0)return[];let z=[];for(let N of Q){if(N.kind===x.ScriptElementKind.interfaceElement||N.kind===x.ScriptElementKind.typeElement)continue;let V=_.getSourceFile(N.fileName);if(!V)continue;let W=L0(V,N.textSpan.start);if(!W)continue;let U=Q_(W),X=I0(W,V),M=D0(W);z.push({filePath:N.fileName,symbolName:X,position:N.textSpan.start,kind:U,isExplicit:M})}return z}}function z_(u){return c.canHaveModifiers(u)&&c.getModifiers(u)?.some((g)=>g.kind===c.SyntaxKind.ExportKeyword)===!0}function C0(u){if(c.isFunctionDeclaration(u))return"function";if(c.isClassDeclaration(u))return"class";if(c.isInterfaceDeclaration(u))return"interface";if(c.isTypeAliasDeclaration(u))return"type";if(c.isEnumDeclaration(u))return"enum";if(c.isVariableDeclaration(u))return"const";if(c.isVariableStatement(u))return"const";return"unknown"}function O_(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 su{#u;#g;#_;#J;#$;#N=!1;constructor(u,g,_,$,J){this.#u=u,this.#g=g,this.#_=_,this.#J=$,this.#$=J}static create(u,g={}){let _=cu.create(u,{readConfigFile:g.readConfigFile,resolveNonTrackedFile:g.resolveNonTrackedFile});if(A0(_))return _;let $=_,J=g.typeCollector??new Ig($),O=g.symbolGraph??new Dg($),Q=g.referenceResolver??new Ag($),z=g.implementationFinder??new Cg($);return new su($,J,O,Q,z)}get isDisposed(){return this.#N}collectTypeAt(u,g){return this.#Q(),this.#g.collectAt(u,g)}collectFileTypes(u){return this.#Q(),this.#g.collectFile(u)}findReferences(u,g){return this.#Q(),this.#J.findAt(u,g)}findImplementations(u,g){return this.#Q(),this.#$.findAt(u,g)}isTypeAssignableTo(u,g,_,$){return this.#Q(),this.#g.isAssignableTo(u,g,_,$)}getSymbolNode(u,g){return this.#Q(),this.#_.get(u,g)}getModuleInterface(u){this.#Q();let g=this.#g.collectFile(u),_=[],J=this.#u.getProgram().getSourceFile(u);if(!J)return{filePath:u,exports:_};function O(Q){if(c.isVariableStatement(Q)&&z_(Q)){for(let z of Q.declarationList.declarations)if(c.isIdentifier(z.name)){let N=z.name.getStart(J),V=g.get(N)??null;_.push({name:z.name.text,kind:"const",resolvedType:V})}return}if((c.isFunctionDeclaration(Q)||c.isClassDeclaration(Q)||c.isInterfaceDeclaration(Q)||c.isTypeAliasDeclaration(Q)||c.isEnumDeclaration(Q))&&z_(Q)&&Q.name){let z=Q.name,N=z.getStart(J),V=g.get(N)??null;_.push({name:z.text,kind:C0(Q),resolvedType:V});return}c.forEachChild(Q,O)}return O(J),{filePath:u,exports:_}}notifyFileChanged(u,g){if(this.#N)return;this.#u.notifyFileChanged(u,g),this.#_.invalidate(u)}notifyFileDeleted(u){if(this.#N)return;this.#u.removeFile(u),this.#_.invalidate(u)}lineColumnToPosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return c.getPositionOfLineAndCharacter($,g-1,_)}catch{return null}}findNamePosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let J=$.getFullText(),O=g;while(O<J.length){let Q=J.indexOf(_,O);if(Q<0)return null;let z=Q>0?J.charCodeAt(Q-1):32,N=Q+_.length<J.length?J.charCodeAt(Q+_.length):32;if(!O_(z)&&!O_(N))return Q;O=Q+1}return null}getDiagnostics(u){this.#Q();let g=this.#u.getProgram(),_=g.getSourceFile(u);if(!_)return[];let $={[c.DiagnosticCategory.Error]:"error",[c.DiagnosticCategory.Warning]:"warning",[c.DiagnosticCategory.Suggestion]:"suggestion",[c.DiagnosticCategory.Message]:"suggestion"};return g.getSemanticDiagnostics(_).map((J)=>{let O=1,Q=0;if(J.file&&J.start!==void 0){let z=c.getLineAndCharacterOfPosition(J.file,J.start);O=z.line+1,Q=z.character}return{filePath:J.file?.fileName??u,line:O,column:Q,message:c.flattenDiagnosticMessageText(J.messageText,`
10
+ `),code:J.code,category:$[J.category]??"error"}})}dispose(){if(this.#N)return;this.#N=!0,this.#u.dispose(),this.#_.clear()}#Q(){if(this.#N)throw Error("SemanticLayer is disposed")}}import{eq as Hu,and as w_,sql as S0}from"drizzle-orm";var W_=80;class Sg{db;constructor(u){this.db=u}insertBatch(u,g,_){if(!_.length)return;let $=_.map((J)=>({project:u,filePath:g,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+=W_)this.db.drizzleDb.insert(Qu).values($.slice(J,J+W_)).run()}deleteFileAnnotations(u,g){this.db.drizzleDb.delete(Qu).where(w_(Hu(Qu.project,u),Hu(Qu.filePath,g))).run()}search(u){return this.db.drizzleDb.select().from(Qu).where(w_(u.project?Hu(Qu.project,u.project):void 0,u.tag?Hu(Qu.tag,u.tag):void 0,u.filePath?Hu(Qu.filePath,u.filePath):void 0,u.symbolName?Hu(Qu.symbolName,u.symbolName):void 0,u.source?Hu(Qu.source,u.source):void 0,u.ftsQuery?S0`${Qu.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 V_,sql as Gu,gt as R0,gte as k0}from"drizzle-orm";var U_=80;class Rg{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let g=u.map((_)=>({project:_.project,changeType:_.changeType,symbolName:_.symbolName,symbolKind:_.symbolKind,filePath:_.filePath,oldName:_.oldName,oldFilePath:_.oldFilePath,fingerprint:_.fingerprint,changedAt:_.changedAt,isFullIndex:_.isFullIndex,indexRunId:_.indexRunId}));for(let _=0;_<g.length;_+=U_)this.db.drizzleDb.insert(Ju).values(g.slice(_,_+U_)).run()}getSince(u){return this.db.drizzleDb.select().from(Ju).where(V_(ku(Ju.project,u.project),k0(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((g)=>Gu`${g}`),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?R0(Ju.id,u.afterId):void 0)).orderBy(Ju.id).limit(u.limit).all()}pruneOlderThan(u,g){return this.db.drizzleDb.delete(Ju).where(V_(ku(Ju.project,u),Gu`${Ju.changedAt} < ${g}`)).run().changes}}function Y_(u){let{annotationRepo:g,project:_,query:$}=u,J=$.project??_,O=$.limit??100,Q;if($.text){let N=Au($.text);if(N)Q=N}return g.search({project:J,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:Q,limit:O}).map((N)=>({tag:N.tag,value:N.value,source:N.source,filePath:N.filePath,symbolName:N.symbolName,span:{start:{line:N.startLine,column:N.startColumn},end:{line:N.endLine,column:N.endColumn}}}))}class au{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let g=[this.options.project,...this.options.additionalProjects??[]].flatMap((_)=>[...this.options.relationRepo.getByType(_,"imports"),...this.options.relationRepo.getByType(_,"type-references"),...this.options.relationRepo.getByType(_,"re-exports")]);for(let _ of g){let{srcFilePath:$,dstFilePath:J}=_;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,...g]);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 Q=this.reverseAdjacencyList.get(J);if(Q){for(let z of Q)this.adjacencyList.get(z)?.delete(J);Q.clear()}}for(let J of g)this.adjacencyList.delete(J),this.reverseAdjacencyList.delete(J);for(let J of u){let O=_(J);for(let Q of O){if(!this.adjacencyList.has(Q.srcFilePath))this.adjacencyList.set(Q.srcFilePath,new Set);if(this.adjacencyList.get(Q.srcFilePath).add(Q.dstFilePath),!this.adjacencyList.has(Q.dstFilePath))this.adjacencyList.set(Q.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Q.dstFilePath))this.reverseAdjacencyList.set(Q.dstFilePath,new Set);this.reverseAdjacencyList.get(Q.dstFilePath).add(Q.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let J of this.reverseAdjacencyList.get($)??[])if(!g.has(J))g.add(J),_.push(J)}return Array.from(g)}hasCycle(){let u=new Set,g=new Set;for(let _ of this.adjacencyList.keys()){if(u.has(_))continue;let $=[{node:_,entered:!1}];while($.length>0){let J=$.pop();if(J.entered){g.delete(J.node);continue}if(g.has(J.node))return!0;if(u.has(J.node))continue;u.add(J.node),g.add(J.node),$.push({node:J.node,entered:!0});for(let O of this.adjacencyList.get(J.node)??[]){if(g.has(O))return!0;if(!u.has(O))$.push({node:O,entered:!1})}}}return!1}getAffectedByChange(u){let g=new Set;for(let _ of u)for(let $ of this.getTransitiveDependents(_))g.add($);return Array.from(g)}getAdjacencyList(){let u=new Map;for(let[g,_]of this.adjacencyList)u.set(g,Array.from(_));return u}getTransitiveDependencies(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let J of this.adjacencyList.get($)??[])if(!g.has(J))g.add(J),_.push(J)}return Array.from(g)}getCyclePaths(u){let g=u?.maxCycles??1/0;if(g<=0)return[];let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return F0(_,g)}}var T0=(u,g)=>u.localeCompare(g);function q0(u){let g=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(g.length===0)return[];let _=g;for(let $=1;$<g.length;$++){let J=g.slice($).concat(g.slice(0,$));if(J.join("::")<_.join("::"))_=J}return[..._]}function kg(u,g,_){let $=q0(_);if($.length===0)return!1;let J=$.join("->");if(u.has(J))return!1;return u.add(J),g.push($),!0}function n0(u){let g=0,_=[],$=new Set,J=new Map,O=new Map,Q=[],z=(N)=>{J.set(N,g),O.set(N,g),g+=1,_.push(N),$.add(N);for(let V of u.get(N)??[])if(!J.has(V))z(V),O.set(N,Math.min(O.get(N)??0,O.get(V)??0));else if($.has(V))O.set(N,Math.min(O.get(N)??0,J.get(V)??0));if(O.get(N)===J.get(N)){let V=[],W="";do W=_.pop()??"",$.delete(W),V.push(W);while(W!==N&&_.length>0);Q.push(V)}};for(let N of u.keys())if(!J.has(N))z(N);return{components:Q}}function j0(u,g,_){let $=[],J=new Set,O=[...u].sort(T0),Q=(z,N,V)=>{N.delete(z);let W=V.get(z);if(!W)return;for(let U of W)if(N.has(U))Q(U,N,V);W.clear()};for(let z=0;z<O.length&&$.length<_;z++){let N=O[z]??"",V=new Set(O.slice(z)),W=new Set,U=new Map,X=[],M=(A)=>(g.get(A)??[]).filter((q)=>V.has(q)),I=(A)=>{if($.length>=_)return!0;let q=!1;X.push(A),W.add(A);for(let n of M(A)){if($.length>=_)break;if(n===N)kg(J,$,X.concat(N)),q=!0;else if(!W.has(n)){if(I(n))q=!0}}if(q)Q(A,W,U);else for(let n of M(A)){let h=U.get(n)??new Set;h.add(A),U.set(n,h)}return X.pop(),q};I(N)}return $}function F0(u,g){let{components:_}=n0(u),$=[],J=new Set;for(let O of _){if($.length>=g)break;if(O.length===0)continue;if(O.length===1){let N=O[0]??"";if((u.get(N)??[]).includes(N))kg(J,$,[N,N]);continue}let Q=g-$.length,z=j0(O,u,Q);for(let N of z){if($.length>=g)break;kg(J,$,N)}}return $}var G0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Lu(u,g){let _=g??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>G0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===_)return u.graphCache;let $=new au({relationRepo:u.relationRepo,project:g??u.defaultProject,additionalProjects:g?void 0:u.boundaries?.map((J)=>J.project)});return $.build(),u.graphCache=$,u.graphCacheKey=_,u.graphCacheBuiltAt=Date.now(),$}function Z_(u,g,_,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,type:"imports",project:_??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 X_(u,g,_,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{dstFilePath:g,type:"imports",project:_??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 K_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getAffectedByChange(g)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getAffected failed",{cause:$})}}async function M_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).hasCycle()}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: hasCycle failed",{cause:_})}}async function B_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getAdjacencyList()}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: getImportGraph failed",{cause:_})}}async function H_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getTransitiveDependencies(g)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function L_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getTransitiveDependents(g)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependents failed",{cause:$})}}async function I_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getCyclePaths(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getCyclePaths failed",{cause:$})}}async function D_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=Lu(u,_);return{filePath:g,fanIn:$.getDependents(g).length,fanOut:$.getDependencies(g).length}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getFanMetrics failed",{cause:$})}}var b0=30000,A_=15000,y0=10;function f0(u,g){return(_)=>{for(let $ of u.onFileChangedCallbacks)try{$(_)}catch(J){u.logger.error("[Gildash] onFileChanged callback threw:",J)}if(g.handleWatcherEvent?.(_),u.semanticLayer)if(_.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(_.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(_.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(_.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",_.filePath,$);try{u.semanticLayer?.notifyFileDeleted(_.filePath)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",J)}})}}async function P0(u){if(!u.semanticLayer)return;let g=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(g.map(async(_)=>{try{let $=Eu.resolve(u.projectRoot,_.filePath),J=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,J)}catch{}}))}async function C_(u,g){let _=u.coordinatorFactory?u.coordinatorFactory():new Zg({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=_;for(let $ of u.onIndexedCallbacks)_.onIndexed($);if(_.onIndexed(($)=>{let J=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&J>0&&J<100){let O=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(Q)=>{return[u.defaultProject,...u.boundaries.map((N)=>N.project)].flatMap((N)=>O.getByType(N,"imports").concat(O.getByType(N,"type-references")).concat(O.getByType(N,"re-exports"))).filter((N)=>N.srcFilePath===Q||N.dstFilePath===Q).map((N)=>({srcFilePath:N.srcFilePath,dstFilePath:N.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),g.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new Qg({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(f0(u,_)).then((J)=>{if(vu(J))throw J.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},b0)}await _.fullIndex(),await P0(u)}function m0(u,g){let _=["SIGTERM","SIGINT","beforeExit"];for(let $ of _){let J=()=>{g().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 S_(u){let{projectRoot:g,extensions:_=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:J=500,logger:O=console,existsSyncFn:Q=E0,dbConnectionFactory:z,watcherFactory:N,coordinatorFactory:V,repositoryFactory:W,acquireWatcherRoleFn:U=g_,releaseWatcherRoleFn:X=__,updateHeartbeatFn:M=$_,discoverProjectsFn:I=mu,parseSourceFn:A=nu,extractSymbolsFn:q=Su,extractRelationsFn:n=lu,symbolSearchFn:h=Kg,relationSearchFn:Z=Mg,patternSearchFn:K=Bg,loadTsconfigPathsFn:B=qu,readFileFn:R=async(i)=>Bun.file(i).text(),unlinkFn:T=async(i)=>{await Bun.file(i).unlink()},watchMode:S,semantic:G,semanticLayerFactory:f}=u;if(!Eu.isAbsolute(g))throw new w("validation",`Gildash: projectRoot must be an absolute path, got: "${g}"`);if(!Q(g))throw new w("validation",`Gildash: projectRoot does not exist: "${g}"`);let y=z?z():new gg({projectRoot:g}),E=y.open();if(vu(E))throw E.data;try{let i=await I(g),_u=i[0]?.project??Eu.basename(g),r=W?W():(()=>{let a=y;return{fileRepo:new _g(a),symbolRepo:new $g(a),relationRepo:new Jg(a),parseCache:new Xg(J)}})(),uu=W?null:y,Y=uu?new Sg(uu):null,D=uu?new Rg(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:g,extensions:_,ignorePatterns:$,logger:O,defaultProject:_u,role:P,db:y,symbolRepo:r.symbolRepo,relationRepo:r.relationRepo,fileRepo:r.fileRepo,parseCache:r.parseCache,annotationRepo:Y,changelogRepo:D,annotationSearchFn:Y_,releaseWatcherRoleFn:X,parseSourceFn:A,extractSymbolsFn:q,extractRelationsFn:n,symbolSearchFn:h,relationSearchFn:Z,patternSearchFn:K,readFileFn:R,unlinkFn:T,existsSyncFn:Q,acquireWatcherRoleFn:U,updateHeartbeatFn:M,watcherFactory:N,coordinatorFactory:V,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:i,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(hu(g),H.tsconfigPaths=await B(g),G){let a=Eu.join(g,"tsconfig.json");try{if(f)H.semanticLayer=f(a);else{let j=su.create(a);if(vu(j))throw j.data;H.semanticLayer=j}}catch(j){if(j instanceof w)throw j;throw new w("semantic","Gildash: semantic layer creation failed",{cause:j})}}if(P==="owner")await C_(H,{isWatchMode:C});else{let a=0,j=async()=>{try{let m=await Promise.resolve(H.acquireWatcherRoleFn(H.db,process.pid,{instanceId:H.instanceId}));if(a=0,m==="owner"){H.role="owner";for(let v of H.onRoleChangedCallbacks)try{v("owner")}catch(p){H.logger.error("[Gildash] onRoleChanged callback threw:",p)}clearInterval(H.timer),H.timer=null;try{await C_(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 p=await H.watcher.close();if(vu(p))H.logger.error("[Gildash] watcher close error during promotion rollback",p.data);H.watcher=null}if(H.coordinator)await H.coordinator.shutdown().catch((p)=>H.logger.error("[Gildash] coordinator shutdown error during promotion rollback",p)),H.coordinator=null;try{H.releaseWatcherRoleFn(H.db,process.pid)}catch(p){H.logger.error("[Gildash] failed to release watcher role during promotion rollback",p)}H.timer=setInterval(j,A_)}}}catch(m){a++;let v=m instanceof w?m:new w("watcher","Gildash: healthcheck error",{cause:m});for(let p of H.onErrorCallbacks)try{p(v)}catch(Uu){H.logger.error("[Gildash] onError callback threw:",Uu)}if(H.logger.error("[Gildash] healthcheck error",m),a>=y0)H.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(H.timer),H.timer=null,ou(H).catch((p)=>H.logger.error("[Gildash] close error during healthcheck shutdown",p))}};H.timer=setInterval(j,A_)}if(C)m0(H,()=>ou(H));return H}catch(i){if(y.close(),i instanceof w)throw i;throw new w("store","Gildash: initialization failed",{cause:i})}}async function ou(u,g){if(u.closed)return;u.closed=!0;let _=[];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($){_.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(vu($))_.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){_.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(g?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(Eu.join(u.projectRoot,Yu,yu+$))}catch{}if(_.length>0)throw new w("close","Gildash: one or more errors occurred during close()",{cause:_})}import{isErr as R_}from"@zipbul/result";function k_(u,g,_,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=u.parseSourceFn(g,_,$);if(R_(J))throw J.data;return u.parseCache.set(g,J),J}async function T_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");let $=new Map,J=[];return await Promise.all(g.map(async(O)=>{try{let Q=await u.readFileFn(O),z=u.parseSourceFn(O,Q,_);if(!R_(z))$.set(O,z);else J.push({filePath:O,error:z.data})}catch(Q){J.push({filePath:O,error:Q instanceof Error?Q:Error(String(Q))})}})),{parsed:$,failures:J}}function q_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.parseCache.get(g)}function n_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractSymbolsFn(g)}function j_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractRelationsFn(g.program,g.filePath,u.tsconfigPaths??void 0)}import F_ from"path";function G_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(g??u.defaultProject)}catch(_){if(_ instanceof w)throw _;throw new w("store","Gildash: getStats failed",{cause:_})}}function Tg(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: searchSymbols failed",{cause:_})}}function v_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: searchRelations failed",{cause:_})}}function E_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:g})}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: searchAllSymbols failed",{cause:_})}}function b_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:g})}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: searchAllRelations failed",{cause:_})}}function y_(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(g??u.defaultProject)}catch(_){if(_ instanceof w)throw _;throw new w("store","Gildash: listIndexedFiles failed",{cause:_})}}function f_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,dstFilePath:g,limit:1e4}})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getInternalRelations failed",{cause:$})}}function P_(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:g,exact:!0,filePath:_,limit:1}});if(O.length===0)return null;let Q=O[0],z=Q.detail,N={...Q,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=F_.isAbsolute(_)?_:F_.resolve(u.projectRoot,_),W=u.semanticLayer.lineColumnToPosition(V,Q.span.start.line,Q.span.start.column);if(W!==null){let U=u.semanticLayer.findNamePosition(V,W,Q.name)??W,X=u.semanticLayer.collectTypeAt(V,U);if(X)N.resolvedType=X}}catch{}return N}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getFullSymbol failed",{cause:J})}}function m_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=_??u.defaultProject,J=u.fileRepo.getFile($,g);if(!J)throw new w("search",`Gildash: file '${g}' is not in the index`);let O=u.symbolRepo.getFileSymbols($,g),Q=u.relationRepo.getOutgoing($,g);return{filePath:J.filePath,lineCount:J.lineCount??0,size:J.size,symbolCount:O.length,exportedSymbolCount:O.filter((z)=>z.isExported).length,relationCount:Q.length}}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileStats failed",{cause:$})}}function h_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(_??u.defaultProject,g)}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileInfo failed",{cause:$})}}function x_(u,g,_){return Tg(u,{filePath:g,project:_??void 0,limit:1e4})}function i_(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:_??u.defaultProject,query:{filePath:g,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:g,exports:J}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getModuleInterface failed",{cause:$})}}import l from"path";function bu(u,g,_,$){let J=$??u.defaultProject,O=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:g,exact:!0,filePath:_,limit:1}});if(O.length===0)return null;let Q=O[0],z=l.isAbsolute(_)?_:l.resolve(u.projectRoot,_),N=u.semanticLayer.lineColumnToPosition(z,Q.span.start.line,Q.span.start.column);if(N===null)return null;let V=u.semanticLayer.findNamePosition(z,N,Q.name)??N;return{sym:Q,position:V,absPath:z}}function p_(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 l_(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 '${g}' not found in '${_}'`);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 d_(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 '${g}' not found in '${_}'`);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 c_(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 Q=bu(u,g,_,O);if(!Q)throw new w("search",`Gildash: source symbol '${g}' not found in '${_}'`);let z=bu(u,$,J,O);if(!z)throw new w("search",`Gildash: target symbol '${$}' not found in '${J}'`);return u.semanticLayer.isTypeAssignableTo(Q.absPath,Q.position,z.absPath,z.position)}catch(Q){if(Q instanceof w)throw Q;throw new w("semantic","Gildash: isTypeAssignableTo failed",{cause:Q})}}function r_(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 _=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.collectFileTypes(_)}catch(_){if(_ instanceof w)throw _;throw new w("semantic","Gildash: getFileTypes failed",{cause:_})}}function s_(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=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g),O=u.semanticLayer.lineColumnToPosition(J,_,$);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 a_(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 _=l.isAbsolute(g.source.filePath)?g.source.filePath:l.resolve(u.projectRoot,g.source.filePath),$=l.isAbsolute(g.target.filePath)?g.target.filePath:l.resolve(u.projectRoot,g.target.filePath),J=u.semanticLayer.lineColumnToPosition(_,g.source.line,g.source.column);if(J===null)return null;let O=u.semanticLayer.lineColumnToPosition($,g.target.line,g.target.column);if(O===null)return null;return u.semanticLayer.isTypeAssignableTo(_,J,$,O)}catch(_){if(_ instanceof w)throw _;throw new w("semantic","Gildash: isTypeAssignableToAt failed",{cause:_})}}function t_(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{return u.semanticLayer.getModuleInterface(g)}catch(_){if(_ instanceof w)throw _;throw new w("search","Gildash: getSemanticModuleInterface failed",{cause:_})}}function o_(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 $=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.collectTypeAt($,_)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:$})}}function e_(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 $=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.findReferences($,_)}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 $=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.findImplementations($,_)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getImplementationsAtPosition failed",{cause:$})}}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=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g),Q=l.isAbsolute($)?$:l.resolve(u.projectRoot,$);return u.semanticLayer.isTypeAssignableTo(O,_,Q,J)}catch(O){if(O instanceof w)throw O;throw new w("semantic","Gildash: isTypeAssignableToAtPosition 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=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.lineColumnToPosition(J,_,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: lineColumnToPosition failed",{cause:J})}}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=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.findNamePosition(J,_,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: findNamePosition 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 $=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.getSymbolNode($,_)}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 _=l.isAbsolute(g)?g:l.resolve(u.projectRoot,g);return u.semanticLayer.getDiagnostics(_)}catch(_){if(_ instanceof w)throw _;throw new w("semantic","Gildash: getSemanticDiagnostics failed",{cause:_})}}function Q$(u,g){let _=new Map(u.map((z)=>[`${z.name}::${z.filePath}`,z])),$=new Map(g.map((z)=>[`${z.name}::${z.filePath}`,z])),J=[],O=[],Q=[];for(let[z,N]of $){let V=_.get(z);if(!V)J.push(N);else if(V.fingerprint!==N.fingerprint)Q.push({before:V,after:N})}for(let[z,N]of _)if(!$.has(z))O.push(N);return{added:J,removed:O,modified:Q}}function z$(u,g){if(u.onIndexedCallbacks.add(g),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(g)};let _=u.coordinator.onIndexed(g);return()=>{u.onIndexedCallbacks.delete(g),_()}}async function O$(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 g=await u.coordinator.fullIndex();return tu(u),g}catch(g){if(g instanceof w)throw g;throw new w("index","Gildash: reindex failed",{cause:g})}}function w$(u,g,_,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=$??u.defaultProject,O=new Set,Q=[],z=g,N=_;for(;;){let V=`${N}::${z}`;if(O.has(V))return{originalName:z,originalFilePath:N,reExportChain:Q,circular:!0};O.add(V);let W=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{type:"re-exports",srcFilePath:N,limit:500}}),U,X;for(let M of W){let I;if(M.metaJson)try{let q=JSON.parse(M.metaJson);if(Array.isArray(q.specifiers))I=q.specifiers}catch{}if(!I)continue;let A=I.find((q)=>q.exported===z);if(!A)continue;U=M.dstFilePath,X=A.local;break}if(!U||!X)return{originalName:z,originalFilePath:N,reExportChain:Q,circular:!1};Q.push({filePath:N,exportedAs:z}),N=U,z=X}}function W$(u,g){return u.onFileChangedCallbacks.add(g),()=>{u.onFileChangedCallbacks.delete(g)}}function V$(u,g){return u.onErrorCallbacks.add(g),()=>{u.onErrorCallbacks.delete(g)}}function U$(u,g){return u.onRoleChangedCallbacks.add(g),()=>{u.onRoleChangedCallbacks.delete(g)}}async function Y$(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=_?.project??u.defaultProject,J=_?.filePaths?_.filePaths:u.fileRepo.getAllFiles($).map((O)=>O.filePath);return await u.patternSearchFn({pattern:g,filePaths:J})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: findPattern failed",{cause:$})}}async function Z$(u,g,_,$){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=new Set,Q=(z,N,V)=>{let W=`${z}::${N}`;if(O.has(W))return{symbolName:z,filePath:N,kind:V,children:[]};O.add(W);let M=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{srcFilePath:N,srcSymbolName:z,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>Q(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:z,filePath:N,kind:V,children:M}};return Q(g,_)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getHeritageChain failed",{cause:J})}}function X$(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:g.project??u.defaultProject,query:g})}function K$(u,g,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=g instanceof Date?g.toISOString():g,J=_?.project??u.defaultProject,O=_?.limit??1000;return u.changelogRepo.getSince({project:J,since:$,symbolName:_?.symbolName,changeTypes:_?.changeTypes,filePath:_?.filePath,includeFullIndex:_?.includeFullIndex,indexRunId:_?.indexRunId,afterId:_?.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 M$(u,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let _=g instanceof Date?g.toISOString():g,$=0,J=[u.defaultProject,...u.boundaries.map((Q)=>Q.project)],O=[...new Set(J)];for(let Q of O)$+=u.changelogRepo.pruneOlderThan(Q,_);return $}class qg{_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 g=await S_(u);return new qg(g)}async close(u){return ou(this._ctx,u)}parseSource(u,g,_){return k_(this._ctx,u,g,_)}async batchParse(u,g){return T_(this._ctx,u,g)}getParsedAst(u){return q_(this._ctx,u)}extractSymbols(u){return n_(this._ctx,u)}extractRelations(u){return j_(this._ctx,u)}getStats(u){return G_(this._ctx,u)}searchSymbols(u){return Tg(this._ctx,u)}searchRelations(u){return v_(this._ctx,u)}searchAllSymbols(u){return E_(this._ctx,u)}searchAllRelations(u){return b_(this._ctx,u)}listIndexedFiles(u){return y_(this._ctx,u)}getInternalRelations(u,g){return f_(this._ctx,u,g)}getFullSymbol(u,g,_){return P_(this._ctx,u,g,_)}getFileStats(u,g){return m_(this._ctx,u,g)}getFileInfo(u,g){return h_(this._ctx,u,g)}getSymbolsByFile(u,g){return x_(this._ctx,u,g)}getModuleInterface(u,g){return i_(this._ctx,u,g)}getDependencies(u,g,_=1e4){return Z_(this._ctx,u,g,_)}getDependents(u,g,_=1e4){return X_(this._ctx,u,g,_)}async getAffected(u,g){return K_(this._ctx,u,g)}async hasCycle(u){return M_(this._ctx,u)}async getImportGraph(u){return B_(this._ctx,u)}async getTransitiveDependencies(u,g){return H_(this._ctx,u,g)}async getTransitiveDependents(u,g){return L_(this._ctx,u,g)}async getCyclePaths(u,g){return I_(this._ctx,u,g)}async getFanMetrics(u,g){return D_(this._ctx,u,g)}getResolvedType(u,g,_){return p_(this._ctx,u,g,_)}getSemanticReferences(u,g,_){return l_(this._ctx,u,g,_)}getImplementations(u,g,_){return d_(this._ctx,u,g,_)}isTypeAssignableTo(u,g,_,$,J){return c_(this._ctx,u,g,_,$,J)}getSemanticModuleInterface(u){return t_(this._ctx,u)}getFileTypes(u){return r_(this._ctx,u)}getResolvedTypeAt(u,g,_){return s_(this._ctx,u,g,_)}isTypeAssignableToAt(u){return a_(this._ctx,u)}getResolvedTypeAtPosition(u,g){return o_(this._ctx,u,g)}getSemanticReferencesAtPosition(u,g){return e_(this._ctx,u,g)}getImplementationsAtPosition(u,g){return u$(this._ctx,u,g)}isTypeAssignableToAtPosition(u,g,_,$){return g$(this._ctx,u,g,_,$)}lineColumnToPosition(u,g,_){return _$(this._ctx,u,g,_)}findNamePosition(u,g,_){return $$(this._ctx,u,g,_)}getSymbolNode(u,g){return J$(this._ctx,u,g)}getSemanticDiagnostics(u){return N$(this._ctx,u)}diffSymbols(u,g){return Q$(u,g)}onIndexed(u){return z$(this._ctx,u)}async reindex(){return O$(this._ctx)}resolveSymbol(u,g,_){return w$(this._ctx,u,g,_)}async findPattern(u,g){return Y$(this._ctx,u,g)}async getHeritageChain(u,g,_){return Z$(this._ctx,u,g,_)}onFileChanged(u){return W$(this._ctx,u)}onError(u){return V$(this._ctx,u)}onRoleChanged(u){return U$(this._ctx,u)}searchAnnotations(u){return X$(this._ctx,u)}getSymbolChanges(u,g){return K$(this._ctx,u,g)}pruneChangelog(u){return M$(this._ctx,u)}}export{Kg as symbolSearch,Mg as relationSearch,Bg as patternSearch,$u as gildashError,w as GildashError,qg as Gildash,au as DependencyGraph};
@@ -2,6 +2,7 @@ import type { Result } from '@zipbul/result';
2
2
  import type { ParsedFile } from '../parser/types';
3
3
  import type { ParserOptions, Program } from 'oxc-parser';
4
4
  import type { ExtractedSymbol, CodeRelation } from '../extractor/types';
5
+ import type { StoredCodeRelation } from '../search/relation-search';
5
6
  import type { DbConnection } from '../store/connection';
6
7
  import type { FileRepository } from '../store/repositories/file.repository';
7
8
  import type { SymbolRepository } from '../store/repositories/symbol.repository';
@@ -35,7 +36,7 @@ export type RelationSearchFn = (options: {
35
36
  relationRepo: IRelationRepo;
36
37
  project?: string;
37
38
  query: RelationSearchQuery;
38
- }) => CodeRelation[];
39
+ }) => StoredCodeRelation[];
39
40
  export type PatternSearchFn = (opts: {
40
41
  pattern: string;
41
42
  filePaths: string[];
@@ -56,7 +57,7 @@ export type CoordinatorLike = Pick<IndexCoordinator, 'fullIndex' | 'shutdown' |
56
57
  handleWatcherEvent?(event: FileChangeEvent): void;
57
58
  };
58
59
  export type WatcherLike = Pick<ProjectWatcher, 'start' | 'close'>;
59
- export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'findReferences' | 'findImplementations' | 'getModuleInterface' | 'getSymbolNode' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
60
+ export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'findReferences' | 'findImplementations' | 'isTypeAssignableTo' | 'getModuleInterface' | 'getSymbolNode' | 'getDiagnostics' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
60
61
  /** Internal shared state for all Gildash API modules. */
61
62
  export interface GildashContext {
62
63
  readonly projectRoot: string;
@@ -23,6 +23,8 @@ export declare function hasCycle(ctx: GildashContext, project?: string): Promise
23
23
  export declare function getImportGraph(ctx: GildashContext, project?: string): Promise<Map<string, string[]>>;
24
24
  /** Return all files that `filePath` transitively imports (forward BFS). */
25
25
  export declare function getTransitiveDependencies(ctx: GildashContext, filePath: string, project?: string): Promise<string[]>;
26
+ /** Return all files that transitively depend on `filePath` (reverse BFS). */
27
+ export declare function getTransitiveDependents(ctx: GildashContext, filePath: string, project?: string): Promise<string[]>;
26
28
  /** Return all cycle paths in the import graph. */
27
29
  export declare function getCyclePaths(ctx: GildashContext, project?: string, options?: {
28
30
  maxCycles?: number;
@@ -1,6 +1,7 @@
1
1
  import type { ParsedFile } from '../parser/types';
2
2
  import type { ParserOptions } from 'oxc-parser';
3
3
  import type { ExtractedSymbol, CodeRelation } from '../extractor/types';
4
+ import type { StoredCodeRelation } from '../search/relation-search';
4
5
  import type { IndexResult } from '../indexer/index-coordinator';
5
6
  import type { ProjectBoundary } from '../common/project-discovery';
6
7
  import type { SymbolSearchQuery, SymbolSearchResult } from '../search/symbol-search';
@@ -8,7 +9,8 @@ import type { RelationSearchQuery } from '../search/relation-search';
8
9
  import type { SymbolStats } from '../store/repositories/symbol.repository';
9
10
  import type { FileRecord } from '../store/repositories/file.repository';
10
11
  import type { PatternMatch } from '../search/pattern-search';
11
- import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface } from '../semantic/types';
12
+ import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface, SemanticDiagnostic } from '../semantic/types';
13
+ import type { SymbolNode } from '../semantic/symbol-graph';
12
14
  import type { GildashContext } from './context';
13
15
  import type { FileChangeEvent } from '../watcher/types';
14
16
  import { GildashError } from '../errors';
@@ -57,13 +59,13 @@ export declare class Gildash {
57
59
  extractRelations(parsed: ParsedFile): CodeRelation[];
58
60
  getStats(project?: string): SymbolStats;
59
61
  searchSymbols(query: SymbolSearchQuery): SymbolSearchResult[];
60
- searchRelations(query: RelationSearchQuery): CodeRelation[];
62
+ searchRelations(query: RelationSearchQuery): StoredCodeRelation[];
61
63
  searchAllSymbols(query: Omit<SymbolSearchQuery, 'project'> & {
62
64
  project?: string;
63
65
  }): SymbolSearchResult[];
64
- searchAllRelations(query: RelationSearchQuery): CodeRelation[];
66
+ searchAllRelations(query: RelationSearchQuery): StoredCodeRelation[];
65
67
  listIndexedFiles(project?: string): FileRecord[];
66
- getInternalRelations(filePath: string, project?: string): CodeRelation[];
68
+ getInternalRelations(filePath: string, project?: string): StoredCodeRelation[];
67
69
  getFullSymbol(symbolName: string, filePath: string, project?: string): FullSymbol | null;
68
70
  getFileStats(filePath: string, project?: string): FileStats;
69
71
  getFileInfo(filePath: string, project?: string): FileRecord | null;
@@ -75,6 +77,7 @@ export declare class Gildash {
75
77
  hasCycle(project?: string): Promise<boolean>;
76
78
  getImportGraph(project?: string): Promise<Map<string, string[]>>;
77
79
  getTransitiveDependencies(filePath: string, project?: string): Promise<string[]>;
80
+ getTransitiveDependents(filePath: string, project?: string): Promise<string[]>;
78
81
  getCyclePaths(project?: string, options?: {
79
82
  maxCycles?: number;
80
83
  }): Promise<string[][]>;
@@ -89,7 +92,30 @@ export declare class Gildash {
89
92
  getResolvedType(symbolName: string, filePath: string, project?: string): ResolvedType | null;
90
93
  getSemanticReferences(symbolName: string, filePath: string, project?: string): SemanticReference[];
91
94
  getImplementations(symbolName: string, filePath: string, project?: string): Implementation[];
95
+ isTypeAssignableTo(sourceSymbol: string, sourceFilePath: string, targetSymbol: string, targetFilePath: string, project?: string): boolean | null;
92
96
  getSemanticModuleInterface(filePath: string): SemanticModuleInterface;
97
+ getFileTypes(filePath: string): Map<number, ResolvedType>;
98
+ getResolvedTypeAt(filePath: string, line: number, column: number): ResolvedType | null;
99
+ isTypeAssignableToAt(opts: {
100
+ source: {
101
+ filePath: string;
102
+ line: number;
103
+ column: number;
104
+ };
105
+ target: {
106
+ filePath: string;
107
+ line: number;
108
+ column: number;
109
+ };
110
+ }): boolean | null;
111
+ getResolvedTypeAtPosition(filePath: string, position: number): ResolvedType | null;
112
+ getSemanticReferencesAtPosition(filePath: string, position: number): SemanticReference[];
113
+ getImplementationsAtPosition(filePath: string, position: number): Implementation[];
114
+ isTypeAssignableToAtPosition(srcFilePath: string, srcPosition: number, dstFilePath: string, dstPosition: number): boolean | null;
115
+ lineColumnToPosition(filePath: string, line: number, column: number): number | null;
116
+ findNamePosition(filePath: string, declarationPos: number, name: string): number | null;
117
+ getSymbolNode(filePath: string, position: number): SymbolNode | null;
118
+ getSemanticDiagnostics(filePath: string): SemanticDiagnostic[];
93
119
  diffSymbols(before: SymbolSearchResult[], after: SymbolSearchResult[]): SymbolDiff;
94
120
  onIndexed(callback: (result: IndexResult) => void): () => void;
95
121
  reindex(): Promise<IndexResult>;
@@ -1,6 +1,5 @@
1
1
  import type { SymbolSearchQuery, SymbolSearchResult } from '../search/symbol-search';
2
- import type { RelationSearchQuery } from '../search/relation-search';
3
- import type { CodeRelation } from '../extractor/types';
2
+ import type { RelationSearchQuery, StoredCodeRelation } from '../search/relation-search';
4
3
  import type { FileRecord } from '../store/repositories/file.repository';
5
4
  import type { SymbolStats } from '../store/repositories/symbol.repository';
6
5
  import type { GildashContext } from './context';
@@ -10,17 +9,17 @@ export declare function getStats(ctx: GildashContext, project?: string): SymbolS
10
9
  /** Search indexed symbols by name, kind, file path, or export status. */
11
10
  export declare function searchSymbols(ctx: GildashContext, query: SymbolSearchQuery): SymbolSearchResult[];
12
11
  /** Search indexed code relationships (imports, calls, extends, implements). */
13
- export declare function searchRelations(ctx: GildashContext, query: RelationSearchQuery): CodeRelation[];
12
+ export declare function searchRelations(ctx: GildashContext, query: RelationSearchQuery): StoredCodeRelation[];
14
13
  /** Search symbols across all projects (no project filter). */
15
14
  export declare function searchAllSymbols(ctx: GildashContext, query: Omit<SymbolSearchQuery, 'project'> & {
16
15
  project?: string;
17
16
  }): SymbolSearchResult[];
18
17
  /** Search relations across all projects (no project filter). */
19
- export declare function searchAllRelations(ctx: GildashContext, query: RelationSearchQuery): CodeRelation[];
18
+ export declare function searchAllRelations(ctx: GildashContext, query: RelationSearchQuery): StoredCodeRelation[];
20
19
  /** List all files indexed for a given project. */
21
20
  export declare function listIndexedFiles(ctx: GildashContext, project?: string): FileRecord[];
22
21
  /** Get all intra-file relations for a given file. */
23
- export declare function getInternalRelations(ctx: GildashContext, filePath: string, project?: string): CodeRelation[];
22
+ export declare function getInternalRelations(ctx: GildashContext, filePath: string, project?: string): StoredCodeRelation[];
24
23
  /** Retrieve full details for a named symbol in a specific file. */
25
24
  export declare function getFullSymbol(ctx: GildashContext, symbolName: string, filePath: string, project?: string): FullSymbol | null;
26
25
  /** Retrieve statistics for an indexed file. */
@@ -1,5 +1,6 @@
1
1
  import type { SymbolSearchResult } from '../search/symbol-search';
2
- import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface } from '../semantic/types';
2
+ import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface, SemanticDiagnostic } from '../semantic/types';
3
+ import type { SymbolNode } from '../semantic/symbol-graph';
3
4
  import type { GildashContext } from './context';
4
5
  /**
5
6
  * Look up a symbol's position for semantic queries.
@@ -16,5 +17,40 @@ export declare function getResolvedType(ctx: GildashContext, symbolName: string,
16
17
  export declare function getSemanticReferences(ctx: GildashContext, symbolName: string, filePath: string, project?: string): SemanticReference[];
17
18
  /** Find implementations of an interface/abstract class. */
18
19
  export declare function getImplementations(ctx: GildashContext, symbolName: string, filePath: string, project?: string): Implementation[];
20
+ /** Check whether a source symbol's type is assignable to a target symbol's type. */
21
+ export declare function isTypeAssignableTo(ctx: GildashContext, sourceSymbol: string, sourceFilePath: string, targetSymbol: string, targetFilePath: string, project?: string): boolean | null;
22
+ /** Retrieve resolved types for all declarations in a file. */
23
+ export declare function getFileTypes(ctx: GildashContext, filePath: string): Map<number, ResolvedType>;
24
+ /** Retrieve the resolved type at a specific position (line:column) without DB lookup. */
25
+ export declare function getResolvedTypeAt(ctx: GildashContext, filePath: string, line: number, column: number): ResolvedType | null;
26
+ /** Check type assignability at specific positions without DB lookup. */
27
+ export declare function isTypeAssignableToAt(ctx: GildashContext, opts: {
28
+ source: {
29
+ filePath: string;
30
+ line: number;
31
+ column: number;
32
+ };
33
+ target: {
34
+ filePath: string;
35
+ line: number;
36
+ column: number;
37
+ };
38
+ }): boolean | null;
19
39
  /** Retrieve the semantic module interface — exported symbols with resolved types. */
20
40
  export declare function getSemanticModuleInterface(ctx: GildashContext, filePath: string): SemanticModuleInterface;
41
+ /** Retrieve the resolved type at a byte offset without line/column conversion. */
42
+ export declare function getResolvedTypeAtPosition(ctx: GildashContext, filePath: string, position: number): ResolvedType | null;
43
+ /** Find all semantic references at a byte offset. */
44
+ export declare function getSemanticReferencesAtPosition(ctx: GildashContext, filePath: string, position: number): SemanticReference[];
45
+ /** Find implementations at a byte offset. */
46
+ export declare function getImplementationsAtPosition(ctx: GildashContext, filePath: string, position: number): Implementation[];
47
+ /** Check type assignability at byte offsets. */
48
+ export declare function isTypeAssignableToAtPosition(ctx: GildashContext, srcFilePath: string, srcPosition: number, dstFilePath: string, dstPosition: number): boolean | null;
49
+ /** Convert 1-based line + 0-based column to a byte offset using tsc SourceFile. */
50
+ export declare function lineColumnToPosition(ctx: GildashContext, filePath: string, line: number, column: number): number | null;
51
+ /** Find the byte offset of a symbol name starting from its declaration position. */
52
+ export declare function findNamePosition(ctx: GildashContext, filePath: string, declarationPos: number, name: string): number | null;
53
+ /** Retrieve the tsc symbol graph node at a byte offset. */
54
+ export declare function getSymbolNode(ctx: GildashContext, filePath: string, position: number): SymbolNode | null;
55
+ /** Return tsc semantic diagnostics for an indexed file. */
56
+ export declare function getSemanticDiagnostics(ctx: GildashContext, filePath: string): SemanticDiagnostic[];
@@ -16,7 +16,8 @@ export type { SymbolStats } from "./store/repositories/symbol.repository";
16
16
  export type { WatcherRole } from "./watcher/types";
17
17
  export type { ParsedFile } from "./parser/types";
18
18
  export type { FileRecord } from "./store/repositories/file.repository";
19
- export type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface } from "./semantic/types";
19
+ export type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface, SemanticDiagnostic } from "./semantic/types";
20
+ export type { SymbolNode } from "./semantic/symbol-graph";
20
21
  export type { AnnotationSource, ExtractedAnnotation } from "./extractor/types";
21
22
  export type { AnnotationSearchQuery, AnnotationSearchResult } from "./search/annotation-search";
22
23
  export type { SymbolChange, SymbolChangeType, SymbolChangeQueryOptions } from "./gildash/types";
@@ -43,16 +43,56 @@ export interface IndexResult {
43
43
  name: string;
44
44
  filePath: string;
45
45
  kind: string;
46
+ isExported: boolean;
46
47
  }>;
47
48
  modified: Array<{
48
49
  name: string;
49
50
  filePath: string;
50
51
  kind: string;
52
+ isExported: boolean;
51
53
  }>;
52
54
  removed: Array<{
53
55
  name: string;
54
56
  filePath: string;
55
57
  kind: string;
58
+ isExported: boolean;
59
+ }>;
60
+ };
61
+ /** Symbols that were renamed (detected via structural fingerprint matching). */
62
+ renamedSymbols: Array<{
63
+ oldName: string;
64
+ newName: string;
65
+ filePath: string;
66
+ kind: string;
67
+ isExported: boolean;
68
+ }>;
69
+ /** Symbols that moved to a different file (detected via fingerprint matching). Incremental only. */
70
+ movedSymbols: Array<{
71
+ name: string;
72
+ oldFilePath: string;
73
+ newFilePath: string;
74
+ kind: string;
75
+ isExported: boolean;
76
+ }>;
77
+ /** Relation-level diff compared to the previous index state. */
78
+ changedRelations: {
79
+ added: Array<{
80
+ type: string;
81
+ srcFilePath: string;
82
+ dstFilePath: string;
83
+ srcSymbolName: string | null;
84
+ dstSymbolName: string | null;
85
+ dstProject: string;
86
+ metaJson: string | null;
87
+ }>;
88
+ removed: Array<{
89
+ type: string;
90
+ srcFilePath: string;
91
+ dstFilePath: string;
92
+ srcSymbolName: string | null;
93
+ dstSymbolName: string | null;
94
+ dstProject: string;
95
+ metaJson: string | null;
56
96
  }>;
57
97
  };
58
98
  }
@@ -92,6 +132,7 @@ export interface IndexCoordinatorOptions {
92
132
  newDstProject?: string;
93
133
  }): void;
94
134
  deleteFileRelations(project: string, filePath: string): void;
135
+ getOutgoing(project: string, srcFilePath: string): RelationRecord[];
95
136
  };
96
137
  annotationRepo?: {
97
138
  deleteFileAnnotations(project: string, filePath: string): void;
@@ -5,6 +5,7 @@ export interface SymbolSnap {
5
5
  fingerprint: string | null;
6
6
  structuralFingerprint: string | null;
7
7
  startLine: number;
8
+ isExported: number;
8
9
  }
9
10
  export interface RenamedEntry {
10
11
  oldName: string;
@@ -23,6 +23,10 @@ export interface RelationSearchQuery {
23
23
  dstSymbolName?: string;
24
24
  /** Destination project. */
25
25
  dstProject?: string;
26
+ /** Glob pattern for source file path filtering (app-level, via Bun.Glob). Mutually exclusive with srcFilePath. */
27
+ srcFilePathPattern?: string;
28
+ /** Glob pattern for destination file path filtering (app-level, via Bun.Glob). Mutually exclusive with dstFilePath. */
29
+ dstFilePathPattern?: string;
26
30
  /** Relationship type: `'imports'`, `'calls'`, `'extends'`, or `'implements'`. */
27
31
  type?: CodeRelation['type'];
28
32
  /** Limit results to this project. */
@@ -11,7 +11,7 @@ import { TypeCollector } from "./type-collector";
11
11
  import { SymbolGraph, type SymbolNode } from "./symbol-graph";
12
12
  import { ReferenceResolver } from "./reference-resolver";
13
13
  import { ImplementationFinder } from "./implementation-finder";
14
- import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface } from "./types";
14
+ import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface, SemanticDiagnostic } from "./types";
15
15
  export interface SemanticLayerOptions extends TscProgramOptions {
16
16
  /** Override TypeCollector (for testing). */
17
17
  typeCollector?: TypeCollector;
@@ -37,6 +37,7 @@ export declare class SemanticLayer {
37
37
  collectFileTypes(filePath: string): Map<number, ResolvedType>;
38
38
  findReferences(filePath: string, position: number): SemanticReference[];
39
39
  findImplementations(filePath: string, position: number): Implementation[];
40
+ isTypeAssignableTo(sourceFilePath: string, sourcePosition: number, targetFilePath: string, targetPosition: number): boolean | null;
40
41
  getSymbolNode(filePath: string, position: number): SymbolNode | null;
41
42
  getModuleInterface(filePath: string): SemanticModuleInterface;
42
43
  notifyFileChanged(filePath: string, content: string): void;
@@ -64,5 +65,12 @@ export declare class SemanticLayer {
64
65
  * Returns `null` when the file is not in the program or the name is not found.
65
66
  */
66
67
  findNamePosition(filePath: string, declarationPos: number, name: string): number | null;
68
+ /**
69
+ * Return tsc semantic diagnostics for an indexed file.
70
+ *
71
+ * Only files previously registered via `notifyFileChanged` produce
72
+ * meaningful results. Non-indexed files return an empty array.
73
+ */
74
+ getDiagnostics(filePath: string): SemanticDiagnostic[];
67
75
  dispose(): void;
68
76
  }
@@ -16,6 +16,16 @@ export declare class TypeCollector {
16
16
  * - `TscProgram이` disposed 상태이면 throw (getProgram이 throw)
17
17
  */
18
18
  collectAt(filePath: string, position: number): ResolvedType | null;
19
+ /**
20
+ * 두 위치의 타입 호환성을 검사한다.
21
+ *
22
+ * `sourceFilePath:sourcePosition`의 타입이 `targetFilePath:targetPosition`의 타입에
23
+ * 할당 가능한지 여부를 반환한다.
24
+ *
25
+ * - 파일이 없거나 위치에 식별자가 없으면 `null` 반환
26
+ * - `TscProgram`이 disposed 상태이면 throw (getProgram이 throw)
27
+ */
28
+ isAssignableTo(sourceFilePath: string, sourcePosition: number, targetFilePath: string, targetPosition: number): boolean | null;
19
29
  /**
20
30
  * `filePath`에서 모든 선언 이름 심볼의 타입을 수집한다.
21
31
  *
@@ -106,3 +106,23 @@ export interface SemanticExport {
106
106
  */
107
107
  resolvedType: ResolvedType | null;
108
108
  }
109
+ /**
110
+ * A single tsc semantic diagnostic for an indexed file.
111
+ *
112
+ * Only covers files known to the Semantic Layer (i.e. files that have been
113
+ * indexed via `notifyFileChanged`). This is **not** equivalent to `tsc --noEmit`.
114
+ */
115
+ export interface SemanticDiagnostic {
116
+ /** Absolute path of the file containing the diagnostic. */
117
+ filePath: string;
118
+ /** One-based line number. */
119
+ line: number;
120
+ /** Zero-based column offset. */
121
+ column: number;
122
+ /** Human-readable diagnostic message. */
123
+ message: string;
124
+ /** TypeScript diagnostic code (e.g. `2322` for type mismatch). */
125
+ code: number;
126
+ /** Severity category. */
127
+ category: 'error' | 'warning' | 'suggestion';
128
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zipbul/gildash",
3
- "version": "0.9.4",
3
+ "version": "0.11.0",
4
4
  "description": "TypeScript code indexing and dependency graph engine for Bun",
5
5
  "license": "MIT",
6
6
  "repository": {