@zipbul/gildash 0.8.2 → 0.9.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,7 +1,9 @@
1
1
  // @bun
2
- var Ig=Object.defineProperty;var kg=(n)=>n;function Cg(n,u){this[n]=kg.bind(null,u)}var Tg=(n,u)=>{for(var g in u)Ig(n,g,{get:u[g],enumerable:!0,configurable:!0,set:Cg.bind(u,g)})};var Ju=import.meta.require;import{isErr as Kn}from"@zipbul/result";import Vn from"path";import{existsSync as qm}from"fs";import{err as Au,isErr as bg}from"@zipbul/result";import{Database as qg}from"bun:sqlite";import{mkdirSync as pg,unlinkSync as fu,existsSync as Nu}from"fs";import{dirname as vg,join as Mu}from"path";import{drizzle as Gg}from"drizzle-orm/bun-sqlite";import{migrate as Eg}from"drizzle-orm/bun-sqlite/migrator";class J extends Error{type;constructor(n,u,g){super(u,g);this.type=n;this.name="GildashError"}}function p(n,u,g){return new J(n,u,g!==void 0?{cause:g}:void 0)}var nn=".gildash",Wn="gildash.db";var an={};Tg(an,{watcherOwner:()=>ag,symbols:()=>k,relations:()=>K,files:()=>F});import{sql as yg}from"drizzle-orm";import{sqliteTable as Hn,text as y,integer as j,real as sg,index as un,primaryKey as Rg,foreignKey as Fn,check as Fg}from"drizzle-orm/sqlite-core";var F=Hn("files",{project:y("project").notNull(),filePath:y("file_path").notNull(),mtimeMs:sg("mtime_ms").notNull(),size:j("size").notNull(),contentHash:y("content_hash").notNull(),updatedAt:y("updated_at").notNull(),lineCount:j("line_count")},(n)=>[Rg({columns:[n.project,n.filePath]})]),k=Hn("symbols",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),filePath:y("file_path").notNull(),kind:y("kind").notNull(),name:y("name").notNull(),startLine:j("start_line").notNull(),startColumn:j("start_column").notNull(),endLine:j("end_line").notNull(),endColumn:j("end_column").notNull(),isExported:j("is_exported").notNull().default(0),signature:y("signature"),fingerprint:y("fingerprint"),detailJson:y("detail_json"),contentHash:y("content_hash").notNull(),indexedAt:y("indexed_at").notNull(),resolvedType:y("resolved_type")},(n)=>[un("idx_symbols_project_file").on(n.project,n.filePath),un("idx_symbols_project_kind").on(n.project,n.kind),un("idx_symbols_project_name").on(n.project,n.name),un("idx_symbols_fingerprint").on(n.project,n.fingerprint),Fn({columns:[n.project,n.filePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),K=Hn("relations",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),type:y("type").notNull(),srcFilePath:y("src_file_path").notNull(),srcSymbolName:y("src_symbol_name"),dstProject:y("dst_project").notNull(),dstFilePath:y("dst_file_path").notNull(),dstSymbolName:y("dst_symbol_name"),metaJson:y("meta_json")},(n)=>[un("idx_relations_src").on(n.project,n.srcFilePath),un("idx_relations_dst").on(n.dstProject,n.dstFilePath),un("idx_relations_type").on(n.project,n.type),un("idx_relations_project_type_src").on(n.project,n.type,n.srcFilePath),Fn({columns:[n.project,n.srcFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade"),Fn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),ag=Hn("watcher_owner",{id:j("id").primaryKey(),pid:j("pid").notNull(),startedAt:y("started_at").notNull(),heartbeatAt:y("heartbeat_at").notNull(),instanceId:y("instance_id")},(n)=>[Fg("watcher_owner_singleton",yg`${n.id} = 1`)]);class bn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Mu(n.projectRoot,nn,Wn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{pg(vg(this.dbPath),{recursive:!0}),this.client=new qg(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=Gg(this.client,{schema:an}),Eg(this.drizzle,{migrationsFolder:Mu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(g,m)=>{try{return new RegExp(g).test(m)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Nu(this.dbPath)){this.closeClient(),fu(this.dbPath);for(let g of["-wal","-shm"]){let m=this.dbPath+g;if(Nu(m))fu(m)}let u=this.open();if(bg(u))return Au(p("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return Au(p("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let g=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${g}"`);try{let m=n(this);return u.run(`RELEASE SAVEPOINT "${g}"`),m}catch(m){throw u.run(`ROLLBACK TO SAVEPOINT "${g}"`),u.run(`RELEASE SAVEPOINT "${g}"`),m}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let g=n();return u.run("COMMIT"),g}catch(g){throw u.run("ROLLBACK"),g}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n,u){let g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,u??null)}replaceOwner(n,u){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,u??null)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}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(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as Nn,and as $u}from"drizzle-orm";class qn{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(F).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[F.project,F.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(F).where(Nn(F.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),g=new Map;for(let m of u)g.set(m.filePath,m);return g}deleteFile(n,u){this.db.drizzleDb.delete(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).run()}}import{eq as a,and as wn,sql as Un,count as jg}from"drizzle-orm";function Qn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class pn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,g,m){if(this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run(),!m.length)return;let i=new Date().toISOString();for(let t of m)this.db.drizzleDb.insert(k).values({project:n,filePath:u,kind:t.kind??"unknown",name:t.name??"",startLine:t.startLine??0,startColumn:t.startColumn??0,endLine:t.endLine??0,endColumn:t.endColumn??0,isExported:t.isExported??0,signature:t.signature??null,fingerprint:t.fingerprint??null,detailJson:t.detailJson??null,contentHash:g,indexedAt:t.indexedAt??i,resolvedType:t.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.filePath,u))).all()}searchByName(n,u,g={}){let m=g.limit??50,i=Qn(u);if(!i)return[];return this.db.drizzleDb.select().from(k).where(wn(Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${i})`,a(k.project,n),g.kind?a(k.kind,g.kind):void 0)).orderBy(k.name).limit(m).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.kind,u))).orderBy(k.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:jg(),fileCount:Un`COUNT(DISTINCT ${k.filePath})`}).from(k).where(a(k.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(k).where(wn(n.ftsQuery?Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?a(k.name,n.exactName):void 0,n.project!==void 0?a(k.project,n.project):void 0,n.kind?a(k.kind,n.kind):void 0,n.filePath!==void 0?a(k.filePath,n.filePath):void 0,n.isExported!==void 0?a(k.isExported,n.isExported?1:0):void 0,n.decorator?Un`${k.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?a(k.resolvedType,n.resolvedType):void 0)).orderBy(k.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let g=new RegExp(n.regex);return u.filter((m)=>g.test(m.name)).slice(0,n.limit)}catch{return[]}}}import{eq as s,and as o,isNull as zu,or as Pg}from"drizzle-orm";class vn{db;constructor(n){this.db=n}replaceFileRelations(n,u,g){this.db.transaction((m)=>{if(m.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run(),!g.length)return;for(let i of g)m.drizzleDb.insert(K).values({project:n,type:i.type??"unknown",srcFilePath:i.srcFilePath??u,srcSymbolName:i.srcSymbolName??null,dstProject:i.dstProject??n,dstFilePath:i.dstFilePath??"",dstSymbolName:i.dstSymbolName??null,metaJson:i.metaJson??null}).run()})}getOutgoing(n,u,g){if(g!==void 0)return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u),Pg(s(K.srcSymbolName,g),zu(K.srcSymbolName)))).all();return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:g}=n;return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.dstProject,u),s(K.dstFilePath,g))).all()}getByType(n,u){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(n.project!==void 0?s(K.project,n.project):void 0,n.srcFilePath!==void 0?s(K.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?s(K.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?s(K.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?s(K.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?s(K.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?s(K.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:g,oldSymbol:m,newFile:i,newSymbol:t,newDstProject:S}=n,w=m===null?o(s(K.dstProject,u),s(K.dstFilePath,g),zu(K.dstSymbolName)):o(s(K.dstProject,u),s(K.dstFilePath,g),s(K.dstSymbolName,m)),O={dstFilePath:i,dstSymbolName:t};if(S!==void 0)O.dstProject=S;this.db.drizzleDb.update(K).set(O).where(w).run()}}import{err as Du}from"@zipbul/result";import{subscribe as hg}from"@parcel/watcher";import Gn from"path";var dg=["**/.git/**",`**/${nn}/**`,"**/dist/**","**/node_modules/**"],xg=new Set(["package.json","tsconfig.json"]);function og(n){return n.replaceAll("\\","/")}function lg(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class En{#n;#u;#g;#i;#m;#t;constructor(n,u=hg,g=console){this.#u=n.projectRoot,this.#g=[...dg,...n.ignorePatterns??[]],this.#i=new Set((n.extensions??[".ts",".mts",".cts"]).map((m)=>m.toLowerCase())),this.#m=u,this.#t=g}async start(n){try{this.#n=await this.#m(this.#u,(u,g)=>{if(u){this.#t.error(p("watcher","Callback error",u));return}try{for(let m of g){let i=og(Gn.relative(this.#u,m.path));if(i.startsWith(".."))continue;let t=Gn.basename(i),S=Gn.extname(i).toLowerCase();if(!xg.has(t)&&!this.#i.has(S))continue;if(i.endsWith(".d.ts"))continue;n({eventType:lg(m.type),filePath:i})}}catch(m){this.#t.error(p("watcher","Callback error",m))}},{ignore:this.#g})}catch(u){return Du(p("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Du(p("watcher","Failed to close watcher",n))}}}import jn from"path";import{promises as cg}from"fs";var eg=["**/node_modules/**","**/.git/**",`**/${nn}/**`,"**/dist/**"];async function Bn(n){let u=[];for await(let g of cg.glob("**/package.json",{cwd:n,exclude:eg})){let m=jn.dirname(g).replaceAll("\\","/"),i=jn.join(n,g),t=await Bun.file(i).json(),S=typeof t?.name==="string"&&t.name.length>0?t.name:jn.basename(m==="."?n:m);u.push({dir:m,project:S})}return u.sort((g,m)=>m.dir.length-g.dir.length),u}function G(n,u,g="default"){let m=n.replaceAll("\\","/");for(let i of u){if(i.dir===".")return i.project;if(m===i.dir||m.startsWith(`${i.dir}/`))return i.project}return g}import Ku from"path";var gn=new Map;async function nm(n){let u=Bun.file(n);if(!await u.exists())return null;try{let g=await u.text(),m=Bun.JSONC.parse(g);return typeof m==="object"&&m!==null?m:null}catch{return null}}async function Mn(n){if(gn.has(n))return gn.get(n)??null;let u=Ku.join(n,"tsconfig.json"),g=await nm(u);if(!g)return gn.set(n,null),null;let m=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!m)return gn.set(n,null),null;let i=typeof m.baseUrl==="string"?m.baseUrl:null,t=typeof m.paths==="object"&&m.paths!==null?m.paths:null;if(!i&&!t)return gn.set(n,null),null;let S=i?Ku.resolve(n,i):n,w=new Map;if(t)for(let[_,A]of Object.entries(t)){if(!Array.isArray(A))continue;let f=A.filter((z)=>typeof z==="string");w.set(_,f)}let O={baseUrl:S,paths:w};return gn.set(n,O),O}function Yn(n){if(n){gn.delete(n);return}gn.clear()}import Vu from"path";function Zn(n,u){return Vu.relative(n,u).replaceAll("\\","/")}function _n(n,u){return Vu.resolve(n,u)}function mn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Iu}from"@zipbul/result";import{err as um}from"@zipbul/result";import{parseSync as gm}from"oxc-parser";function $n(n,u,g,m=gm){try{let{program:i,errors:t,comments:S}=m(n,u,g);return{filePath:n,program:i,errors:t,comments:S,sourceText:u}}catch(i){return um(p("parse",`Failed to parse file: ${n}`,i))}}import{promises as mm}from"fs";import{join as im}from"path";async function Wu(n){let{projectRoot:u,extensions:g,ignorePatterns:m,fileRepo:i}=n,t=i.getFilesMap(),S=new Set,w=[],O=[],_=m.map((f)=>new Bun.Glob(f));for await(let f of mm.glob("**/*",{cwd:u})){if(!g.some((r)=>f.endsWith(r)))continue;if(f.startsWith("node_modules/")||f.includes("/node_modules/"))continue;if(_.some((r)=>r.match(f)))continue;S.add(f);let z=im(u,f),V=Bun.file(z),{size:Q,lastModified:B}=V,Y=t.get(f);if(!Y){let r=await V.text(),M=mn(r);w.push({filePath:f,contentHash:M,mtimeMs:B,size:Q});continue}if(Y.mtimeMs===B&&Y.size===Q){O.push({filePath:f,contentHash:Y.contentHash,mtimeMs:B,size:Q});continue}let N=await V.text(),$=mn(N);if($===Y.contentHash)O.push({filePath:f,contentHash:$,mtimeMs:B,size:Q});else w.push({filePath:f,contentHash:$,mtimeMs:B,size:Q})}let A=[];for(let f of t.keys())if(!S.has(f))A.push(f);return{changed:w,unchanged:O,deleted:A}}function Hu(n){let u=[0];for(let g=0;g<n.length;g++)if(n[g]===`
3
- `)u.push(g+1);return u}function Pn(n,u){let g=0,m=n.length-1;while(g<m){let i=g+m+1>>1;if(n[i]<=u)g=i;else m=i-1}return{line:g+1,column:u-n[g]}}import{err as tm}from"@zipbul/result";import{parse as wm}from"comment-parser";function Qu(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let m=wm(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(m.description??"").trim(),tags:(m.tags??[]).map((i)=>({tag:i.tag??"",name:i.name??"",type:i.type??"",description:i.description??"",optional:i.optional??!1,...i.default!==void 0?{default:i.default}:{}}))}}catch(u){return tm(p("parse","Failed to parse JSDoc comment",u))}}import{isErr as Om}from"@zipbul/result";function Ln(n){let{program:u,sourceText:g,comments:m}=n,i=Hu(g);function t(N,$){return{start:Pn(i,N),end:Pn(i,$)}}function S(N){let $=null;for(let r of m){if(r.type!=="Block")continue;if(r.end>N)continue;if(!r.value.startsWith("*"))continue;if(!$||r.end>$.end)$={value:`/*${r.value}*/`,end:r.end}}if(!$)return;for(let r of u.body){let M=r.start??0;if(M===N)continue;if(M>$.end&&M<N)return}return $.value}function w(N){if(!N)return;let $=N.typeAnnotation??N;return g.slice($.start,$.end)}function O(N){if(!N||N.length===0)return[];return N.map(($)=>{let r=$.expression;if(!r)return{name:"unknown"};if(r.type==="CallExpression"){let M=r.callee?.name??r.callee?.property?.name??"unknown",D=(r.arguments??[]).map((H)=>g.slice(H.start,H.end));return{name:M,arguments:D.length>0?D:void 0}}if(r.type==="Identifier")return{name:r.name??"unknown"};return{name:g.slice(r.start,r.end)}})}function _(N){let $=N.type==="TSParameterProperty"?N.parameter:N;if($?.type==="RestElement"){let U=`...${$.argument?.name??"unknown"}`,W=$.typeAnnotation,R=W?w(W):void 0,X={name:U,isOptional:!1};if(R)X.type=R;return X}if($?.type==="AssignmentPattern"){let{left:C,right:U}=$,W=C?.name??"unknown",R=C?.typeAnnotation,X=R?w(R):void 0,v=g.slice(U.start,U.end),E=O(C?.decorators??[]),P={name:W,isOptional:!0,defaultValue:v};if(X)P.type=X;if(E.length>0)P.decorators=E;return P}let r=$?.name??$?.pattern?.name??"unknown",M=!!$?.optional,D=$?.typeAnnotation,H=D?w(D):void 0,Z=O($?.decorators??[]),L={name:r,isOptional:M};if(H)L.type=H;if(Z.length>0)L.decorators=Z;return L}function A(N,$){let r=[];if($?.async)r.push("async");if(N.static)r.push("static");if(N.abstract)r.push("abstract");if(N.readonly)r.push("readonly");if(N.override)r.push("override");if(N.declare)r.push("declare");if(N.const)r.push("const");let M=N.accessibility;if(M==="private")r.push("private");else if(M==="protected")r.push("protected");else if(M==="public")r.push("public");return r}function f(N){let $=[];if(N.superClass){let M=g.slice(N.superClass.start,N.superClass.end);$.push({kind:"extends",name:M})}let r=N.implements??[];for(let M of r){let D=M.expression??M,H=g.slice(D.start,D.end);$.push({kind:"implements",name:H})}return $}function z(N){let $=[];for(let r of N.extends??[]){let M=r.expression??r,D=g.slice(M.start,M.end);$.push({kind:"extends",name:D})}return $}function V(N){let $=[];for(let r of N)if(r.type==="MethodDefinition"){let M=r.key?.name??"unknown",D=r.value,H=r.kind??"method",Z=H==="constructor"?"constructor":H==="get"?"getter":H==="set"?"setter":"method",L=A(r,D),C=(D?.params??[]).map(_),U=w(D?.returnType),W={kind:"method",name:M,span:t(r.start,r.end),isExported:!1,methodKind:Z,modifiers:L,parameters:C.length>0?C:void 0,returnType:U};$.push(W)}else if(r.type==="PropertyDefinition"){let M=r.key?.name??"unknown",D=A(r),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:D};$.push(H)}return $}function Q(N){let $=[];for(let r of N)if(r.type==="TSMethodSignature"){let M=r.key?.name??"unknown",D=(r.params??[]).map(_),H=w(r.returnType);$.push({kind:"method",name:M,span:t(r.start,r.end),isExported:!1,modifiers:[],methodKind:"method",parameters:D.length>0?D:void 0,returnType:H})}else if(r.type==="TSPropertySignature"){let M=r.key?.name??"unknown",D=w(r.typeAnnotation),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:r.readonly?["readonly"]:[],returnType:D};$.push(H)}return $}function B(N,$){let r=N.type??"";if(r==="FunctionDeclaration"){let M=N.id?.name??"default",D=(N.params??[]).map(_),H=w(N.returnType),Z=A(N,N),L=O(N.decorators??[]),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"function",name:M,span:t(N.start,N.end),isExported:$,modifiers:Z,parameters:D.length>0?D:void 0,returnType:H,decorators:L.length>0?L:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="ClassDeclaration"||r==="ClassExpression"){let M=N.id?.name??"default",D=f(N),H=V(N.body?.body??[]),Z=O(N.decorators??[]),L=A(N,N),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"class",name:M,span:t(N.start,N.end),isExported:$,modifiers:L,heritage:D.length>0?D:void 0,members:H.length>0?H:void 0,decorators:Z.length>0?Z:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="VariableDeclaration"){let M=[];for(let D of N.declarations??[]){let{id:H,init:Z}=D;if(H?.type==="ObjectPattern"){for(let X of H.properties??[]){let v=X.value?.name??X.key?.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}if(H?.type==="ArrayPattern"){for(let X of H.elements??[]){if(!X||X.type!=="Identifier")continue;let v=X.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}let L=H?.name??"unknown",C="variable",U,W;if(Z?.type==="FunctionExpression"||Z?.type==="ArrowFunctionExpression")C="function",U=(Z.params??[]).map(_),W=w(Z.returnType);let R=[];M.push({kind:C,name:L,span:t(D.start,D.end),isExported:$,modifiers:R,parameters:U,returnType:W})}if(M.length===0)return null;if(M.length===1)return M[0];return M}if(r==="TSTypeAliasDeclaration")return{kind:"type",name:N.id?.name??"unknown",span:t(N.start,N.end),isExported:$,modifiers:[]};if(r==="TSInterfaceDeclaration"){let M=N.id?.name??"unknown",D=z(N),H=Q(N.body?.body??[]),Z=N.typeParameters?.params?.map((C)=>C.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:M,span:t(N.start,N.end),isExported:$,modifiers:[],heritage:D.length>0?D:void 0,members:H.length>0?H:void 0};if(Z&&Z.length>0)L.typeParameters=Z;return L}if(r==="TSEnumDeclaration"){let M=N.id?.name??"unknown",D=A(N),Z=(N.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:t(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:M,span:t(N.start,N.end),isExported:$,modifiers:D,members:Z.length>0?Z:void 0}}return null}let Y=[];for(let N of u.body){let $=null,r=N,M=typeof r.type==="string"?r.type:"";if(M==="ExportNamedDeclaration"){let H=N;if(H.declaration){if($=B(H.declaration,!0),$&&!Array.isArray($))$.span=t(H.start,H.end);else if(Array.isArray($))for(let Z of $)Z.span=t(H.start,H.end)}}else if(M==="ExportDefaultDeclaration"){let H=N,Z=H.declaration;if(Z){if($=B(Z,!0),$&&!Array.isArray($))$.name=Z.id?.name??"default",$.isExported=!0,$.span=t(H.start,H.end)}}else $=B(N,!1);let D=Array.isArray($)?$:$?[$]:[];for(let H of D){let Z=N.start??0,L=S(Z);if(L){let C=Qu(L);if(!Om(C))H.jsDoc=C}Y.push(H)}}return Y}function Sm(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,g=n.modifiers.includes("async")?1:0;return`params:${u}|async:${g}`}return null}function rm(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((g)=>{let m=g.modifiers.find((i)=>i==="private"||i==="protected"||i==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:m,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function Uu(n,u,g,m,i){let t=Sm(n),S=mn(`${u}|${n.kind}|${t??""}`);return{project:g,filePath:m,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:t,fingerprint:S,detailJson:rm(n),contentHash:i,indexedAt:new Date().toISOString()}}function hn(n){let{parsed:u,project:g,filePath:m,contentHash:i,symbolRepo:t}=n,S=Ln(u),w=[];for(let O of S){w.push(Uu(O,O.name,g,m,i));for(let _ of O.members??[])w.push(Uu(_,`${O.name}.${_.name}`,g,m,i))}t.replaceFileSymbols(g,m,i,w)}import{resolve as dn,dirname as _m,extname as Jm}from"path";function On(n,u,g){let m=(i)=>{let t=Jm(i);if(t==="")return[i+".ts",i+".d.ts",i+"/index.ts",i+"/index.d.ts",i+".mts",i+"/index.mts",i+".cts",i+"/index.cts"];if(t===".js")return[i.slice(0,-3)+".ts"];if(t===".mjs")return[i.slice(0,-4)+".mts"];if(t===".cjs")return[i.slice(0,-4)+".cts"];return[i]};if(u.startsWith(".")){let i=dn(_m(n),u);return m(i)}if(g)for(let[i,t]of g.paths){if(t.length===0)continue;let S=i.indexOf("*");if(S===-1){if(u===i){let w=[];for(let O of t)w.push(...m(dn(g.baseUrl,O)));return w}}else{let w=i.slice(0,S),O=i.slice(S+1);if(u.startsWith(w)&&(O===""||u.endsWith(O))){let _=u.slice(w.length,O===""?void 0:u.length-O.length),A=[];for(let f of t)A.push(...m(dn(g.baseUrl,f.replace("*",_))));return A}}}return[]}function Bu(n,u,g,m=On){let i=new Map,t=n.body??[];for(let S of t){if(S.type!=="ImportDeclaration")continue;let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.specifiers??[];for(let f of A)switch(f.type){case"ImportSpecifier":i.set(f.local.name,{path:_,importedName:f.imported.name});break;case"ImportDefaultSpecifier":i.set(f.local.name,{path:_,importedName:"default"});break;case"ImportNamespaceSpecifier":i.set(f.local.name,{path:_,importedName:"*"});break}}return i}var Am=new Set(["loc","start","end","scope"]);function Jn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let m of n)Jn(m,u);return}let g=n;u(g);for(let m of Object.keys(g)){if(Am.has(m))continue;let i=g[m];if(i&&typeof i==="object")Jn(i,u)}}function Yu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function Sn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let g=u.name;return{root:g,parts:[],full:g}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let g=[],m=u;while(m.type==="MemberExpression"){let S=m.property;if(!S||typeof S.name!=="string")return null;g.unshift(S.name),m=m.object}let i;if(m.type==="Identifier")i=m.name;else if(m.type==="ThisExpression")i="this";else if(m.type==="Super")i="super";else return null;let t=[i,...g].join(".");return{root:i,parts:g,full:t}}return null}function Zu(n,u,g,m=On){let i=[],t=n.body??[];for(let S of t){if(S.type==="ImportDeclaration"){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.importKind==="type",f=S.specifiers??[];if(f.length===0){let z={};if(A)z.isType=!0;i.push({type:A?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,...Object.keys(z).length>0?{metaJson:JSON.stringify(z)}:{}})}else for(let z of f){let V=z.type,Q=A||z.importKind==="type",B={};if(Q)B.isType=!0;let Y,N;if(V==="ImportDefaultSpecifier")Y="default",N=z.local.name;else if(V==="ImportNamespaceSpecifier")Y="*",N=z.local.name,B.importKind="namespace";else Y=z.imported.name,N=z.local.name;i.push({type:Q?"type-references":"imports",srcFilePath:u,srcSymbolName:N,dstFilePath:_,dstSymbolName:Y,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}continue}if(S.type==="ExportAllDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",f={isReExport:!0};if(A)f.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(f)});continue}if(S.type==="ExportNamedDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",V={isReExport:!0,specifiers:(S.specifiers??[]).map((Q)=>({local:Q.local.name,exported:Q.exported.name}))};if(A)V.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(V)})}}return Jn(n,(S)=>{if(S.type!=="ImportExpression")return;let w=Yu(S.source);if(!w)return;let O=m(u,w,g);if(O.length===0)return;let _=O[0];i.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),i}function Lu(n,u,g){let m=[],i=[],t=[];function S(){if(i.length>0)return i[i.length-1]??null;return null}function w(_){if(!_)return null;let A=g.get(_.root);if(_.parts.length===0){if(A)return{dstFilePath:A.path,dstSymbolName:A.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:_.root,resolution:"local"}}else{if(A&&A.importedName==="*"){let f=_.parts[_.parts.length-1];return{dstFilePath:A.path,dstSymbolName:f,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:_.full,resolution:"local-member"}}}function O(_){if(!_||typeof _!=="object")return;if(Array.isArray(_)){for(let z of _)O(z);return}let A=_,f=typeof A.type==="string"?A.type:"";if(f==="ClassDeclaration"||f==="ClassExpression"){let z=A,V=z.id?.name??"AnonymousClass";t.push(V),O(z.body),t.pop();return}if(f==="FunctionDeclaration"){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.body),i.pop();return}if(f==="VariableDeclarator"&&A.init&&(A.init?.type==="FunctionExpression"||A.init?.type==="ArrowFunctionExpression")){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.init?.body??z.init),i.pop();return}if(f==="MethodDefinition"&&A.value){let z=A,V=t[t.length-1]??"",Q=z.key?.name??"anonymous",B=V?`${V}.${Q}`:Q;i.push(B),O(z.value?.body),i.pop();return}if(f==="FunctionExpression"||f==="ArrowFunctionExpression"){let z=S(),V=z?`${z}.<anonymous>`:"<anonymous>";i.push(V),O(A.body),i.pop();return}if(f==="CallExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,...Object.keys(Y).length>0?{metaJson:JSON.stringify(Y)}:{}})}O(z.callee);for(let B of z.arguments??[])O(B);return}if(f==="NewExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={isNew:!0};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,metaJson:JSON.stringify(Y)})}for(let B of z.arguments??[])O(B);return}for(let z of Object.keys(A)){if(z==="loc"||z==="start"||z==="end"||z==="scope")continue;let V=A[z];if(V&&typeof V==="object")O(V)}}return O(n),m}function Xu(n,u,g){let m=[];return Jn(n,(i)=>{if(i.type==="TSInterfaceDeclaration"){let w=i.id?.name??"AnonymousInterface",O=i.extends??[];for(let _ of O){let A=_.expression??_,f=Sn(A);if(!f)continue;let z=xn(f,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:w,...z})}return}if(i.type!=="ClassDeclaration"&&i.type!=="ClassExpression")return;let t=i.id?.name??"AnonymousClass";if(i.superClass){let w=Sn(i.superClass);if(w){let O=xn(w,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:t,...O})}}let S=i.implements??[];for(let w of S){let O=w.expression??w,_=Sn(O);if(!_)continue;let A=xn(_,u,g);m.push({type:"implements",srcFilePath:u,srcSymbolName:t,...A})}}),m}function xn(n,u,g){let m=g.get(n.root);if(m){if(m.importedName==="*"){let i=n.parts[n.parts.length-1]??n.root;return{dstFilePath:m.path,dstSymbolName:i,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:m.path,dstSymbolName:n.parts.length>0?n.full:m.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Xn(n,u,g,m=On){let i=Bu(n,u,g,m),t=Zu(n,u,g,m),S=Lu(n,u,i),w=Xu(n,u,i);return[...t,...S,...w]}function on(n){let{ast:u,project:g,filePath:m,relationRepo:i,projectRoot:t,tsconfigPaths:S,knownFiles:w,boundaries:O}=n,_=_n(t,m),f=Xn(u,_,S,w?(V,Q,B)=>{let Y=On(V,Q,B);for(let N of Y){let $=Zn(t,N);if(O){let r=G($,O);if(w.has(`${r}::${$}`))return[N]}else if(w.has(`${g}::${$}`))return[N]}return[]}:void 0),z=[];for(let V of f){let Q=Zn(t,V.dstFilePath);if(Q.startsWith(".."))continue;let B=Zn(t,V.srcFilePath),Y=O?G(Q,O):g;z.push({project:g,type:V.type,srcFilePath:B,srcSymbolName:V.srcSymbolName??null,dstProject:Y,dstFilePath:Q,dstSymbolName:V.dstSymbolName??null,metaJson:V.metaJson??null})}return i.replaceFileRelations(g,m,z),z.length}var fm=100,ku=50;class ln{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Mn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Yn(this.opts.projectRoot),this.tsconfigPathsRaw=Mn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??Bn;this.boundariesRefresh=u(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},fm)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((m,i)=>{this.pendingFullIndexWaiters.push({resolve:m,reject:i})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(n,u).then((m)=>{return this.fireCallbacks(m),m}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let m=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((i)=>{for(let t of m)t.resolve(i)}).catch((i)=>{for(let t of m)t.reject(i)})}else if(this.pendingEvents.length>0){let m=this.pendingEvents.splice(0);this.startIndex(m,!1).catch((i)=>this.logger.error("[IndexCoordinator] incremental drain error",i))}});return this.currentIndexing=g,g}async doIndex(n,u){let g=Date.now(),{fileRepo:m,symbolRepo:i,relationRepo:t,dbConnection:S}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let w,O;if(n!==void 0)w=n.filter((r)=>r.eventType==="create"||r.eventType==="change").map((r)=>({filePath:r.filePath,contentHash:"",mtimeMs:0,size:0})),O=n.filter((r)=>r.eventType==="delete").map((r)=>r.filePath);else{let r=new Map;for(let D of this.opts.boundaries)for(let[H,Z]of m.getFilesMap(D.project))r.set(H,Z);let M=await Wu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>r}});w=M.changed,O=M.deleted}let _=await this.tsconfigPathsRaw??void 0,A=new Map;for(let r of O){let M=G(r,this.opts.boundaries),D=i.getFileSymbols(M,r);A.set(r,D)}let f=new Map,z=new Map;if(u)for(let r of this.opts.boundaries)for(let M of m.getAllFiles(r.project))for(let D of i.getFileSymbols(r.project,M.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint});else{for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}for(let[,r]of A)for(let M of r)f.set(`${M.filePath}::${M.name}`,{name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint})}let V=()=>{for(let r of O){let M=G(r,this.opts.boundaries);i.deleteFileSymbols(M,r),t.deleteFileRelations(M,r),m.deleteFile(M,r)}},Q=async()=>{let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=0,Z=0,L=[],C=[];for(let W of w)try{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v),P=G(W.filePath,M);m.upsertFile({project:P,filePath:W.filePath,mtimeMs:X.lastModified,size:X.size,contentHash:E,updatedAt:new Date().toISOString(),lineCount:v.split(`
4
- `).length});let e=(this.opts.parseSourceFn??$n)(R,v);if(Iu(e))throw e.data;let I=e;C.push({filePath:W.filePath,text:v,contentHash:E,parsed:I,project:P})}catch(R){this.logger.error(`[IndexCoordinator] Failed to prepare ${W.filePath}:`,R),L.push(W.filePath)}let U=new Set;for(let W of M)for(let[R]of m.getFilesMap(W.project))U.add(`${W.project}::${R}`);return S.transaction(()=>{for(let W of C)hn({parsed:W.parsed,project:W.project,filePath:W.filePath,contentHash:W.contentHash,symbolRepo:i}),Z+=on({ast:W.parsed.program,project:W.project,filePath:W.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:U,boundaries:M}),D.set(W.filePath,W.parsed),H+=i.getFileSymbols(W.project,W.filePath).length}),{symbols:H,relations:Z,failedFiles:L}},B=0,Y=0,N=[];if(u){let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=[];for(let L=0;L<w.length;L+=ku){let C=w.slice(L,L+ku),U=await Promise.allSettled(C.map(async(W)=>{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v);return{filePath:W.filePath,text:v,contentHash:E,mtimeMs:X.lastModified,size:X.size}}));for(let W of U)if(W.status==="fulfilled")H.push(W.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",W.reason)}let Z=[];S.transaction(()=>{for(let U of H){let W=G(U.filePath,M);m.deleteFile(W,U.filePath)}for(let U of O){let W=G(U,M);i.deleteFileSymbols(W,U),t.deleteFileRelations(W,U),m.deleteFile(W,U)}for(let U of H){let W=G(U.filePath,M);m.upsertFile({project:W,filePath:U.filePath,mtimeMs:U.mtimeMs,size:U.size,contentHash:U.contentHash,updatedAt:new Date().toISOString(),lineCount:U.text.split(`
5
- `).length})}let L=new Set;for(let U of M)for(let[W]of m.getFilesMap(U.project))L.add(`${U.project}::${W}`);let C=this.opts.parseSourceFn??$n;for(let U of H){let W=G(U.filePath,M),R=C(_n(r,U.filePath),U.text);if(Iu(R))throw R.data;let X=R;Z.push({filePath:U.filePath,parsed:X}),hn({parsed:X,project:W,filePath:U.filePath,contentHash:U.contentHash,symbolRepo:i}),Y+=on({ast:X.program,project:W,filePath:U.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:L,boundaries:M}),B+=i.getFileSymbols(W,U.filePath).length}});for(let L of Z)D.set(L.filePath,L.parsed)}else{V();let r=await Q();B=r.symbols,Y=r.relations,N=r.failedFiles}for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))z.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}let $={added:[],modified:[],removed:[]};for(let[r,M]of z){let D=f.get(r);if(!D)$.added.push({name:M.name,filePath:M.filePath,kind:M.kind});else if(D.fingerprint!==M.fingerprint)$.modified.push({name:M.name,filePath:M.filePath,kind:M.kind})}for(let[r,M]of f)if(!z.has(r))$.removed.push({name:M.name,filePath:M.filePath,kind:M.kind});if(!u)for(let[r,M]of A)for(let D of M){if(!D.fingerprint)continue;let H=G(r,this.opts.boundaries),Z=i.getByFingerprint(H,D.fingerprint);if(Z.length===1){let L=Z[0];t.retargetRelations({dstProject:H,oldFile:r,oldSymbol:D.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:w.length,removedFiles:O.length,totalSymbols:B,totalRelations:Y,durationMs:Date.now()-g,changedFiles:w.map((r)=>r.filePath),deletedFiles:[...O],failedFiles:N,changedSymbols:$}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function Nm(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Mm(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Cu(n,u,g={}){let m=g.now??Date.now,i=g.isAlive??Nm,t=g.staleAfterSeconds??60,S=g.instanceId;return n.immediateTransaction(()=>{let w=n.selectOwner();if(!w)return n.insertOwner(u,S),"owner";let O=Math.floor((m()-Mm(w.heartbeat_at))/1000),_=i(w.pid);if(_&&S&&w.instance_id&&w.instance_id!==S&&w.pid!==u)return n.replaceOwner(u,S),"owner";if(_&&O<t)return"reader";return n.replaceOwner(u,S),"owner"})}function Tu(n,u){n.deleteOwner(u)}function yu(n,u){n.touchOwner(u)}class zn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let g=this.#u.keys().next().value;if(g!==void 0)this.#u.delete(g)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class cn{lru;constructor(n=500){this.lru=new zn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function en(n){let{symbolRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??100,S={kind:m.kind,filePath:m.filePath,isExported:m.isExported,project:i,limit:t,resolvedType:m.resolvedType};if(m.text)if(m.exact)S.exactName=m.text;else{let O=Qn(m.text);if(O)S.ftsQuery=O}if(m.decorator)S.decorator=m.decorator;if(m.regex)S.regex=m.regex;return u.searchByQuery(S).map((O)=>({id:O.id,filePath:O.filePath,kind:O.kind,name:O.name,span:{start:{line:O.startLine,column:O.startColumn},end:{line:O.endLine,column:O.endColumn}},isExported:O.isExported===1,signature:O.signature,fingerprint:O.fingerprint,detail:O.detailJson?(()=>{try{return JSON.parse(O.detailJson)}catch{return{}}})():{}}))}function nu(n){let{relationRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??500;return u.searchRelations({srcFilePath:m.srcFilePath,srcSymbolName:m.srcSymbolName,dstFilePath:m.dstFilePath,dstSymbolName:m.dstSymbolName,dstProject:m.dstProject,type:m.type,project:i,limit:t}).map((w)=>{let O;if(w.metaJson)try{O=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:O}})}import{findInFiles as $m,Lang as zm}from"@ast-grep/napi";async function uu(n){if(n.filePaths.length===0)return[];let u=[];return await $m(zm.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(g,m)=>{if(g)return;for(let i of m){let t=i.range();u.push({filePath:i.getRoot().filename(),startLine:t.start.line+1,endLine:t.end.line+1,matchedText:i.text()})}}),u}import b from"typescript";import{isErr as km}from"@zipbul/result";import l from"typescript";import Dm from"path";import{err as gu}from"@zipbul/result";function Km(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}function Vm(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}class In{#n;#u;#g=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let g=u.readConfigFile??Km,m=u.resolveNonTrackedFile??Vm,i=Dm.dirname(n),t=g(n);if(t===void 0)return gu(p("semantic",`tsconfig not found: ${n}`));let S=l.parseJsonText(n,t),w=S.parseDiagnostics;if(w&&w.length>0){let f=w.map((z)=>l.flattenDiagnosticMessageText(z.messageText,`
6
- `)).join("; ");return gu(p("semantic",`tsconfig parse error: ${f}`))}let O=l.parseJsonSourceFileConfigFileContent(S,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(f)=>g(f)!==void 0||m(f)!==void 0,readFile:(f)=>g(f)??m(f)},i);if(O.errors.length>0){let f=O.errors.filter((z)=>z.category===l.DiagnosticCategory.Error&&z.code!==18003);if(f.length>0){let z=f.map((V)=>l.flattenDiagnosticMessageText(V.messageText,`
7
- `)).join("; ");return gu(p("semantic",`tsconfig compile error: ${z}`))}}let _=new su(O.fileNames,O.options,i,m),A=l.createLanguageService(_);return new In(A,_)}get isDisposed(){return this.#g}getProgram(){this.#i();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#i(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#i(),this.#n}notifyFileChanged(n,u){if(this.#g)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#g)return;this.#u.removeFile(n)}dispose(){if(this.#g)return;this.#g=!0,this.#n.dispose()}#i(){if(this.#g)throw Error("TscProgram is disposed")}}class su{#n;#u;#g;#i;#m=new Map;constructor(n,u,g,m){this.#n=[...n],this.#u=u,this.#g=g,this.#i=m}updateFile(n,u){let g=this.#m.get(n);if(g)g.version+=1,g.content=u;else this.#m.set(n,{version:1,content:u})}removeFile(n){this.#m.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#m.keys()];return[...this.#n.filter((g)=>!this.#m.has(g)),...n]}getScriptVersion(n){let u=this.#m.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#m.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let g=this.#i(n);if(g!==void 0)return l.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#m.has(n))return!0;return this.#i(n)!==void 0}readFile(n){let u=this.#m.get(n);if(u)return u.content;return this.#i(n)}}import q from"typescript";import Wm from"typescript";function c(n,u){if(u<0||u>=n.getEnd())return;function g(m){let i=m.getStart(n,!1),t=m.getEnd();if(u<i||u>=t)return;let S;return Wm.forEachChild(m,(w)=>{if(!S)S=g(w)}),S??m}return g(n)}function Hm(n){return!!(n.flags&q.TypeFlags.Object)&&!!(n.objectFlags&q.ObjectFlags.Reference)}function Dn(n,u,g=0){let m=n.typeToString(u),i=u.flags,t=!!(i&q.TypeFlags.Union),S=!!(i&q.TypeFlags.Intersection),w;if(g<8&&Hm(u)){let f=n.getTypeArguments(u);if(f.length>0)w=f}let O=!!(i&q.TypeFlags.TypeParameter)||w!==void 0&&w.length>0,_;if(t&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));else if(S&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));let A;if(w&&w.length>0)A=w.map((f)=>Dn(n,f,g+1));return{text:m,flags:i,isUnion:t,isIntersection:S,isGeneric:O,members:_,typeArguments:A}}function Qm(n){return q.isFunctionDeclaration(n)||q.isVariableDeclaration(n)||q.isClassDeclaration(n)||q.isInterfaceDeclaration(n)||q.isTypeAliasDeclaration(n)||q.isEnumDeclaration(n)||q.isMethodDeclaration(n)||q.isPropertyDeclaration(n)||q.isPropertySignature(n)||q.isMethodSignature(n)}class mu{program;constructor(n){this.program=n}collectAt(n,u){let g=this.program.getProgram(),m=this.program.getChecker();if(u<0)return null;let i=g.getSourceFile(n);if(!i)return null;if(u>=i.getEnd())return null;let t=c(i,u);if(!t)return null;if(!q.isIdentifier(t))return null;try{let S=m.getTypeAtLocation(t);return Dn(m,S)}catch{return null}}collectFile(n){let u=new Map,g=this.program.getProgram(),m=this.program.getChecker(),i=g.getSourceFile(n);if(!i)return u;function t(S){if(Qm(S)&&S.name&&q.isIdentifier(S.name)){let w=S.name;try{let O=m.getTypeAtLocation(w),_=w.getStart(i);u.set(_,Dn(m,O))}catch{}}q.forEachChild(S,t)}return t(i),u}}import tn from"typescript";var Um=1000,Bm=1;function Ym(n){let u=n.declarations?.[0],g=u?.getSourceFile(),m=u?tn.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:g?.fileName??"",position:m?.getStart(g,!1)??u?.getStart(g,!1)??0}}function kn(n,u=0){let g=n.declarations?.[0],m=g?.getSourceFile(),i=g?tn.getNameOfDeclaration(g):void 0,t=m?.fileName??"",S=i?.getStart(m,!1)??g?.getStart(m,!1)??0,w={name:n.getName(),filePath:t,position:S},O=n;if(O.parent)w.parent=Ym(O.parent);if(u<Bm){let _=n.flags,A=!!(_&tn.SymbolFlags.Enum),f=!!(_&(tn.SymbolFlags.NamespaceModule|tn.SymbolFlags.ValueModule)),z=!!(_&(tn.SymbolFlags.Class|tn.SymbolFlags.Interface));if(A&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}else if(z&&n.members&&n.members.size>0){let V=[];n.members.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}if(f&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.exports=V}}return w}class iu{#n;#u;#g=new Map;constructor(n,u=Um){this.#n=n,this.#u=new zn(u)}get(n,u){if(this.#n.isDisposed)return null;let g=`${n}:${u}`,m=this.#u.get(g);if(m!==void 0)return m;let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;let S=c(t,u);if(!S||!tn.isIdentifier(S))return null;let O=this.#n.getChecker().getSymbolAtLocation(S);if(!O)return null;let _=kn(O);this.#u.set(g,_);let A=this.#g.get(n);if(!A)A=new Set,this.#g.set(n,A);return A.add(g),_}invalidate(n){let u=this.#g.get(n);if(u){for(let g of u)this.#u.delete(g);this.#g.delete(n)}}clear(){this.#u.clear(),this.#g.clear()}}import Zm from"typescript";class tu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!Zm.isIdentifier(i))return[];let S=this.#n.getLanguageService().findReferences(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S)for(let _ of O.references){let A=g.getSourceFile(_.fileName);if(!A)continue;let{line:f,character:z}=A.getLineAndCharacterOfPosition(_.textSpan.start);w.push({filePath:_.fileName,position:_.textSpan.start,line:f+1,column:z,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1})}return w}}import T from"typescript";function Lm(n,u){let g=c(n,u);if(!g)return;if(Ru(g))return g;let m=g.parent;for(let i=0;i<5&&m;i++){if(Ru(m))return m;m=m.parent}return g}function Ru(n){return T.isClassDeclaration(n)||T.isClassExpression(n)||T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)||T.isVariableDeclaration(n)||T.isObjectLiteralExpression(n)}function Fu(n){if(T.isClassDeclaration(n)||T.isClassExpression(n))return"class";if(T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n))return"function";if(T.isObjectLiteralExpression(n))return"object";if(T.isVariableDeclaration(n)&&n.initializer)return Fu(n.initializer);return"class"}function Xm(n,u){if(T.isClassDeclaration(n)||T.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(T.isClassExpression(n))return n.name?.getText(u)??"";if(T.isVariableDeclaration(n)&&T.isIdentifier(n.name))return n.name.getText(u);if(T.isFunctionExpression(n))return n.name?.getText(u)??"";if(T.isArrowFunction(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(T.isObjectLiteralExpression(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Im(n){if(!T.isClassDeclaration(n)&&!T.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((g)=>g.token===T.SyntaxKind.ImplementsKeyword)}class wu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!T.isIdentifier(i))return[];let S=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S){if(O.kind===T.ScriptElementKind.interfaceElement||O.kind===T.ScriptElementKind.typeElement)continue;let _=g.getSourceFile(O.fileName);if(!_)continue;let A=Lm(_,O.textSpan.start);if(!A)continue;let f=Fu(A),z=Xm(A,_),V=Im(A);w.push({filePath:O.fileName,symbolName:z,position:O.textSpan.start,kind:f,isExplicit:V})}return w}}function au(n){return b.canHaveModifiers(n)&&b.getModifiers(n)?.some((u)=>u.kind===b.SyntaxKind.ExportKeyword)===!0}function Cm(n){if(b.isFunctionDeclaration(n))return"function";if(b.isClassDeclaration(n))return"class";if(b.isInterfaceDeclaration(n))return"interface";if(b.isTypeAliasDeclaration(n))return"type";if(b.isEnumDeclaration(n))return"enum";if(b.isVariableDeclaration(n))return"const";if(b.isVariableStatement(n))return"const";return"unknown"}function bu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Cn{#n;#u;#g;#i;#m;#t=!1;constructor(n,u,g,m,i){this.#n=n,this.#u=u,this.#g=g,this.#i=m,this.#m=i}static create(n,u={}){let g=In.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(km(g))return g;let m=g,i=u.typeCollector??new mu(m),t=u.symbolGraph??new iu(m),S=u.referenceResolver??new tu(m),w=u.implementationFinder??new wu(m);return new Cn(m,i,t,S,w)}get isDisposed(){return this.#t}collectTypeAt(n,u){return this.#w(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#w(),this.#u.collectFile(n)}findReferences(n,u){return this.#w(),this.#i.findAt(n,u)}findImplementations(n,u){return this.#w(),this.#m.findAt(n,u)}getSymbolNode(n,u){return this.#w(),this.#g.get(n,u)}getModuleInterface(n){this.#w();let u=this.#u.collectFile(n),g=[],i=this.#n.getProgram().getSourceFile(n);if(!i)return{filePath:n,exports:g};function t(S){if(b.isVariableStatement(S)&&au(S)){for(let w of S.declarationList.declarations)if(b.isIdentifier(w.name)){let O=w.name.getStart(i),_=u.get(O)??null;g.push({name:w.name.text,kind:"const",resolvedType:_})}return}if((b.isFunctionDeclaration(S)||b.isClassDeclaration(S)||b.isInterfaceDeclaration(S)||b.isTypeAliasDeclaration(S)||b.isEnumDeclaration(S))&&au(S)&&S.name){let w=S.name,O=w.getStart(i),_=u.get(O)??null;g.push({name:w.text,kind:Cm(S),resolvedType:_});return}b.forEachChild(S,t)}return t(i),{filePath:n,exports:g}}notifyFileChanged(n,u){if(this.#t)return;this.#n.notifyFileChanged(n,u),this.#g.invalidate(n)}notifyFileDeleted(n){if(this.#t)return;this.#n.removeFile(n),this.#g.invalidate(n)}lineColumnToPosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;try{return b.getPositionOfLineAndCharacter(m,u-1,g)}catch{return null}}findNamePosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let i=m.getFullText(),t=u;while(t<i.length){let S=i.indexOf(g,t);if(S<0)return null;let w=S>0?i.charCodeAt(S-1):32,O=S+g.length<i.length?i.charCodeAt(S+g.length):32;if(!bu(w)&&!bu(O))return S;t=S+1}return null}dispose(){if(this.#t)return;this.#t=!0,this.#n.dispose(),this.#g.clear()}#w(){if(this.#t)throw Error("SemanticLayer is disposed")}}class Tn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of u){let{srcFilePath:m,dstFilePath:i}=g;if(!this.adjacencyList.has(m))this.adjacencyList.set(m,new Set);if(this.adjacencyList.get(m).add(i),!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(!this.reverseAdjacencyList.has(i))this.reverseAdjacencyList.set(i,new Set);this.reverseAdjacencyList.get(i).add(m)}}patchFiles(n,u,g){let m=new Set([...n,...u]);for(let i of m){let t=this.adjacencyList.get(i);if(t){for(let w of t)this.reverseAdjacencyList.get(w)?.delete(i);t.clear()}let S=this.reverseAdjacencyList.get(i);if(S){for(let w of S)this.adjacencyList.get(w)?.delete(i);S.clear()}}for(let i of u)this.adjacencyList.delete(i),this.reverseAdjacencyList.delete(i);for(let i of n){let t=g(i);for(let S of t){if(!this.adjacencyList.has(S.srcFilePath))this.adjacencyList.set(S.srcFilePath,new Set);if(this.adjacencyList.get(S.srcFilePath).add(S.dstFilePath),!this.adjacencyList.has(S.dstFilePath))this.adjacencyList.set(S.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(S.dstFilePath))this.reverseAdjacencyList.set(S.dstFilePath,new Set);this.reverseAdjacencyList.get(S.dstFilePath).add(S.srcFilePath)}}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,g=[n];while(g.length>0){let m=g.shift();for(let i of this.reverseAdjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let g of this.adjacencyList.keys()){if(n.has(g))continue;let m=[{node:g,entered:!1}];while(m.length>0){let i=m.pop();if(i.entered){u.delete(i.node);continue}if(u.has(i.node))return!0;if(n.has(i.node))continue;n.add(i.node),u.add(i.node),m.push({node:i.node,entered:!0});for(let t of this.adjacencyList.get(i.node)??[]){if(u.has(t))return!0;if(!n.has(t))m.push({node:t,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let g of n)for(let m of this.getTransitiveDependents(g))u.add(m);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,g]of this.adjacencyList)n.set(u,Array.from(g));return n}getTransitiveDependencies(n){let u=new Set,g=[n];while(g.length>0){let m=g.shift();for(let i of this.adjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let g=new Map;for(let[m,i]of this.adjacencyList)g.set(m,Array.from(i));return Fm(g,u)}}var Tm=(n,u)=>n.localeCompare(u);function ym(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let g=u;for(let m=1;m<u.length;m++){let i=u.slice(m).concat(u.slice(0,m));if(i.join("::")<g.join("::"))g=i}return[...g]}function Ou(n,u,g){let m=ym(g);if(m.length===0)return!1;let i=m.join("->");if(n.has(i))return!1;return n.add(i),u.push(m),!0}function sm(n){let u=0,g=[],m=new Set,i=new Map,t=new Map,S=[],w=(O)=>{i.set(O,u),t.set(O,u),u+=1,g.push(O),m.add(O);for(let _ of n.get(O)??[])if(!i.has(_))w(_),t.set(O,Math.min(t.get(O)??0,t.get(_)??0));else if(m.has(_))t.set(O,Math.min(t.get(O)??0,i.get(_)??0));if(t.get(O)===i.get(O)){let _=[],A="";do A=g.pop()??"",m.delete(A),_.push(A);while(A!==O&&g.length>0);S.push(_)}};for(let O of n.keys())if(!i.has(O))w(O);return{components:S}}function Rm(n,u,g){let m=[],i=new Set,t=[...n].sort(Tm),S=(w,O,_)=>{O.delete(w);let A=_.get(w);if(!A)return;for(let f of A)if(O.has(f))S(f,O,_);A.clear()};for(let w=0;w<t.length&&m.length<g;w++){let O=t[w]??"",_=new Set(t.slice(w)),A=new Set,f=new Map,z=[],V=(B)=>(u.get(B)??[]).filter((Y)=>_.has(Y)),Q=(B)=>{if(m.length>=g)return!0;let Y=!1;z.push(B),A.add(B);for(let N of V(B)){if(m.length>=g)break;if(N===O)Ou(i,m,z.concat(O)),Y=!0;else if(!A.has(N)){if(Q(N))Y=!0}}if(Y)S(B,A,f);else for(let N of V(B)){let $=f.get(N)??new Set;$.add(B),f.set(N,$)}return z.pop(),Y};Q(O)}return m}function Fm(n,u){let{components:g}=sm(n),m=[],i=new Set;for(let t of g){if(m.length>=u)break;if(t.length===0)continue;if(t.length===1){let O=t[0]??"";if((n.get(O)??[]).includes(O))Ou(i,m,[O,O]);continue}let S=u-m.length,w=Rm(t,n,S);for(let O of w){if(m.length>=u)break;Ou(i,m,O)}}return m}var am=15000;function yn(n){n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}function An(n,u){let g=u??"__cross__";if(n.graphCache&&n.graphCacheBuiltAt!==null){if(Date.now()-n.graphCacheBuiltAt>am)n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}if(n.graphCache&&n.graphCacheKey===g)return n.graphCache;let m=new Tn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((i)=>i.project)});return m.build(),n.graphCache=m,n.graphCacheKey=g,n.graphCacheBuiltAt=Date.now(),m}function qu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.dstFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependencies failed",{cause:i})}}function pu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{dstFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.srcFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependents failed",{cause:i})}}async function vu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getAffectedByChange(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getAffected failed",{cause:m})}}async function Gu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).hasCycle()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: hasCycle failed",{cause:g})}}async function Eu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getAdjacencyList()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getImportGraph failed",{cause:g})}}async function ju(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getTransitiveDependencies(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getTransitiveDependencies failed",{cause:m})}}async function Pu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getCyclePaths(g)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getCyclePaths failed",{cause:m})}}async function hu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=An(n,g);return{filePath:u,fanIn:m.getDependents(u).length,fanOut:m.getDependencies(u).length}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getFanMetrics failed",{cause:m})}}var pm=30000,du=15000,vm=10;function Gm(n,u){return(g)=>{for(let m of n.onFileChangedCallbacks)try{m(g)}catch(i){n.logger.error("[Gildash] onFileChanged callback threw:",i)}if(u.handleWatcherEvent?.(g),n.semanticLayer)if(g.eventType==="delete")try{n.semanticLayer.notifyFileDeleted(g.filePath)}catch(m){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",m);for(let i of n.onErrorCallbacks)try{i(m instanceof J?m:new J("semantic","semantic notifyFileDeleted failed",{cause:m}))}catch{}}else n.readFileFn(g.filePath).then((m)=>{try{n.semanticLayer?.notifyFileChanged(g.filePath,m)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",i);for(let t of n.onErrorCallbacks)try{t(i instanceof J?i:new J("semantic","semantic notifyFileChanged failed",{cause:i}))}catch{}}}).catch((m)=>{n.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,m);try{n.semanticLayer?.notifyFileDeleted(g.filePath)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",i)}})}}async function Em(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(g)=>{try{let m=Vn.resolve(n.projectRoot,g.filePath),i=await n.readFileFn(m);n.semanticLayer?.notifyFileChanged(m,i)}catch{}}))}async function xu(n,u){let g=n.coordinatorFactory?n.coordinatorFactory():new ln({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=g;for(let m of n.onIndexedCallbacks)g.onIndexed(m);if(g.onIndexed((m)=>{let i=m.changedFiles.length+m.deletedFiles.length;if(n.graphCache&&i>0&&i<100){let t=n.relationRepo;n.graphCache.patchFiles(m.changedFiles,m.deletedFiles,(S)=>{return[n.defaultProject,...n.boundaries.map((O)=>O.project)].flatMap((O)=>t.getByType(O,"imports").concat(t.getByType(O,"type-references")).concat(t.getByType(O,"re-exports"))).filter((O)=>O.srcFilePath===S||O.dstFilePath===S).map((O)=>({srcFilePath:O.srcFilePath,dstFilePath:O.dstFilePath}))}),n.graphCacheBuiltAt=Date.now()}else yn(n)}),u.isWatchMode){let m=n.watcherFactory?n.watcherFactory():new En({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await m.start(Gm(n,g)).then((i)=>{if(Kn(i))throw i.data}),n.watcher=m,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},pm)}await g.fullIndex(),await Em(n)}function jm(n,u){let g=["SIGTERM","SIGINT","beforeExit"];for(let m of g){let i=()=>{u().catch((t)=>n.logger.error("[Gildash] close error during signal",m,t))};if(m==="beforeExit")process.on("beforeExit",i);else process.on(m,i);n.signalHandlers.push([m,i])}}async function ou(n){let{projectRoot:u,extensions:g=[".ts",".mts",".cts"],ignorePatterns:m=["**/node_modules/**"],parseCacheCapacity:i=500,logger:t=console,existsSyncFn:S=qm,dbConnectionFactory:w,watcherFactory:O,coordinatorFactory:_,repositoryFactory:A,acquireWatcherRoleFn:f=Cu,releaseWatcherRoleFn:z=Tu,updateHeartbeatFn:V=yu,discoverProjectsFn:Q=Bn,parseSourceFn:B=$n,extractSymbolsFn:Y=Ln,extractRelationsFn:N=Xn,symbolSearchFn:$=en,relationSearchFn:r=nu,patternSearchFn:M=uu,loadTsconfigPathsFn:D=Mn,readFileFn:H=async(X)=>Bun.file(X).text(),unlinkFn:Z=async(X)=>{await Bun.file(X).unlink()},watchMode:L,semantic:C,semanticLayerFactory:U}=n;if(!Vn.isAbsolute(u))throw new J("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!S(u))throw new J("validation",`Gildash: projectRoot does not exist: "${u}"`);let W=w?w():new bn({projectRoot:u}),R=W.open();if(Kn(R))throw R.data;try{let X=await Q(u),v=X[0]?.project??Vn.basename(u),E=A?A():(()=>{let h=W;return{fileRepo:new qn(h),symbolRepo:new pn(h),relationRepo:new vn(h),parseCache:new cn(i)}})(),P=L??!0,Rn=crypto.randomUUID(),e;if(P)e=await Promise.resolve(f(W,process.pid,{instanceId:Rn}));else e="owner";let I={projectRoot:u,extensions:g,ignorePatterns:m,logger:t,defaultProject:v,role:e,db:W,symbolRepo:E.symbolRepo,relationRepo:E.relationRepo,fileRepo:E.fileRepo,parseCache:E.parseCache,releaseWatcherRoleFn:z,parseSourceFn:B,extractSymbolsFn:Y,extractRelationsFn:N,symbolSearchFn:$,relationSearchFn:r,patternSearchFn:M,readFileFn:H,unlinkFn:Z,existsSyncFn:S,acquireWatcherRoleFn:f,updateHeartbeatFn:V,watcherFactory:O,coordinatorFactory:_,instanceId:Rn,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:X,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(Yn(u),I.tsconfigPaths=await D(u),C){let h=Vn.join(u,"tsconfig.json");try{if(U)I.semanticLayer=U(h);else{let d=Cn.create(h);if(Kn(d))throw d.data;I.semanticLayer=d}}catch(d){if(d instanceof J)throw d;throw new J("semantic","Gildash: semantic layer creation failed",{cause:d})}}if(e==="owner")await xu(I,{isWatchMode:P});else{let h=0,d=async()=>{try{let rn=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(h=0,rn==="owner"){for(let fn of I.onRoleChangedCallbacks)try{fn("owner")}catch(x){I.logger.error("[Gildash] onRoleChanged callback threw:",x)}clearInterval(I.timer),I.timer=null;try{await xu(I,{isWatchMode:!0})}catch(fn){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",fn),I.watcher){let x=await I.watcher.close();if(Kn(x))I.logger.error("[Gildash] watcher close error during promotion rollback",x.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((x)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",x)),I.coordinator=null;if(I.timer===null)I.timer=setInterval(d,du)}}}catch(rn){h++;let fn=rn instanceof J?rn:new J("watcher","Gildash: healthcheck error",{cause:rn});for(let x of I.onErrorCallbacks)try{x(fn)}catch(Xg){I.logger.error("[Gildash] onError callback threw:",Xg)}if(I.logger.error("[Gildash] healthcheck error",rn),h>=vm)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,sn(I).catch((x)=>I.logger.error("[Gildash] close error during healthcheck shutdown",x))}};I.timer=setInterval(d,du)}if(P)jm(I,()=>sn(I));return I}catch(X){if(W.close(),X instanceof J)throw X;throw new J("store","Gildash: initialization failed",{cause:X})}}async function sn(n,u){if(n.closed)return;n.closed=!0;let g=[];for(let[m,i]of n.signalHandlers)if(m==="beforeExit")process.off("beforeExit",i);else process.off(m,i);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(n.watcher){let m=await n.watcher.close();if(Kn(m))g.push(m.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(m){g.push(m instanceof Error?m:Error(String(m)))}try{n.db.close()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(u?.cleanup)for(let m of["","-wal","-shm"])try{await n.unlinkFn(Vn.join(n.projectRoot,nn,Wn+m))}catch{}if(g.length>0)throw new J("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as lu}from"@zipbul/result";function cu(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=n.parseSourceFn(u,g,m);if(lu(i))throw i.data;return n.parseCache.set(u,i),i}async function eu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");let m=new Map,i=[];return await Promise.all(u.map(async(t)=>{try{let S=await n.readFileFn(t),w=n.parseSourceFn(t,S,g);if(!lu(w))m.set(t,w);else i.push({filePath:t,error:w.data})}catch(S){i.push({filePath:t,error:S instanceof Error?S:Error(String(S))})}})),{parsed:m,failures:i}}function ng(n,u){if(n.closed)return;return n.parseCache.get(u)}function ug(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function gg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import mg from"path";function ig(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: getStats failed",{cause:g})}}function Su(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchSymbols failed",{cause:g})}}function tg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchRelations failed",{cause:g})}}function wg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllSymbols failed",{cause:g})}}function Og(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllRelations failed",{cause:g})}}function Sg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: listIndexedFiles failed",{cause:g})}}function rg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getInternalRelations failed",{cause:m})}}function _g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=S.detail,O={...S,members:Array.isArray(w.members)?w.members:void 0,jsDoc:typeof w.jsDoc==="string"?w.jsDoc:void 0,parameters:typeof w.parameters==="string"?w.parameters:void 0,returnType:typeof w.returnType==="string"?w.returnType:void 0,heritage:Array.isArray(w.heritage)?w.heritage:void 0,decorators:Array.isArray(w.decorators)?w.decorators:void 0,typeParameters:typeof w.typeParameters==="string"?w.typeParameters:void 0};if(n.semanticLayer)try{let _=mg.isAbsolute(g)?g:mg.resolve(n.projectRoot,g),A=n.semanticLayer.lineColumnToPosition(_,S.span.start.line,S.span.start.column);if(A!==null){let f=n.semanticLayer.findNamePosition(_,A,S.name)??A,z=n.semanticLayer.collectTypeAt(_,f);if(z)O.resolvedType=z}}catch{}return O}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getFullSymbol failed",{cause:i})}}function Jg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g??n.defaultProject,i=n.fileRepo.getFile(m,u);if(!i)throw new J("search",`Gildash: file '${u}' is not in the index`);let t=n.symbolRepo.getFileSymbols(m,u),S=n.relationRepo.getOutgoing(m,u);return{filePath:i.filePath,lineCount:i.lineCount??0,size:i.size,symbolCount:t.length,exportedSymbolCount:t.filter((w)=>w.isExported).length,relationCount:S.length}}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileStats failed",{cause:m})}}function Ag(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(g??n.defaultProject,u)}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileInfo failed",{cause:m})}}function fg(n,u,g){return Su(n,{filePath:u,project:g??void 0,limit:1e4})}function Ng(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g??n.defaultProject,query:{filePath:u,isExported:!0}}).map((t)=>({name:t.name,kind:t.kind,parameters:t.detail.parameters??void 0,returnType:t.detail.returnType??void 0,jsDoc:t.detail.jsDoc??void 0}));return{filePath:u,exports:i}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getModuleInterface failed",{cause:m})}}import Mg from"path";function ru(n,u,g,m){let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=Mg.isAbsolute(g)?g:Mg.resolve(n.projectRoot,g),O=n.semanticLayer.lineColumnToPosition(w,S.span.start.line,S.span.start.column);if(O===null)return null;let _=n.semanticLayer.findNamePosition(w,O,S.name)??O;return{sym:S,position:_,absPath:w}}function $g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)return null;return n.semanticLayer.collectTypeAt(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getResolvedType failed",{cause:i})}}function zg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findReferences(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getSemanticReferences failed",{cause:i})}}function Dg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findImplementations(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getImplementations failed",{cause:i})}}function Kg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function Vg(n,u){let g=new Map(n.map((w)=>[`${w.name}::${w.filePath}`,w])),m=new Map(u.map((w)=>[`${w.name}::${w.filePath}`,w])),i=[],t=[],S=[];for(let[w,O]of m){let _=g.get(w);if(!_)i.push(O);else if(_.fingerprint!==O.fingerprint)S.push({before:_,after:O})}for(let[w,O]of g)if(!m.has(w))t.push(O);return{added:i,removed:t,modified:S}}function Wg(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let g=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),g()}}async function Hg(n){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.coordinator)throw new J("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return yn(n),u}catch(u){if(u instanceof J)throw u;throw new J("index","Gildash: reindex failed",{cause:u})}}function Qg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=m??n.defaultProject,t=new Set,S=[],w=u,O=g;for(;;){let _=`${O}::${w}`;if(t.has(_))return{originalName:w,originalFilePath:O,reExportChain:S,circular:!0};t.add(_);let A=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{type:"re-exports",srcFilePath:O,limit:500}}),f,z;for(let V of A){let Q;if(V.metaJson)try{let Y=JSON.parse(V.metaJson);if(Array.isArray(Y.specifiers))Q=Y.specifiers}catch{}if(!Q)continue;let B=Q.find((Y)=>Y.exported===w);if(!B)continue;f=V.dstFilePath,z=B.local;break}if(!f||!z)return{originalName:w,originalFilePath:O,reExportChain:S,circular:!1};S.push({filePath:O,exportedAs:w}),O=f,w=z}}function Ug(n,u){return n.onFileChangedCallbacks.add(u),()=>{n.onFileChangedCallbacks.delete(u)}}function Bg(n,u){return n.onErrorCallbacks.add(u),()=>{n.onErrorCallbacks.delete(u)}}function Yg(n,u){return n.onRoleChangedCallbacks.add(u),()=>{n.onRoleChangedCallbacks.delete(u)}}async function Zg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g?.project??n.defaultProject,i=g?.filePaths?g.filePaths:n.fileRepo.getAllFiles(m).map((t)=>t.filePath);return await n.patternSearchFn({pattern:u,filePaths:i})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: findPattern failed",{cause:m})}}async function Lg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=new Set,S=(w,O,_)=>{let A=`${w}::${O}`;if(t.has(A))return{symbolName:w,filePath:O,kind:_,children:[]};t.add(A);let V=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{srcFilePath:O,srcSymbolName:w,limit:1000}}).filter((Q)=>Q.type==="extends"||Q.type==="implements").filter((Q)=>Q.dstSymbolName!=null).map((Q)=>S(Q.dstSymbolName,Q.dstFilePath,Q.type));return{symbolName:w,filePath:O,kind:_,children:V}};return S(u,g)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getHeritageChain failed",{cause:i})}}class _u{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await ou(n);return new _u(u)}async close(n){return sn(this._ctx,n)}parseSource(n,u,g){return cu(this._ctx,n,u,g)}async batchParse(n,u){return eu(this._ctx,n,u)}getParsedAst(n){return ng(this._ctx,n)}extractSymbols(n){return ug(this._ctx,n)}extractRelations(n){return gg(this._ctx,n)}getStats(n){return ig(this._ctx,n)}searchSymbols(n){return Su(this._ctx,n)}searchRelations(n){return tg(this._ctx,n)}searchAllSymbols(n){return wg(this._ctx,n)}searchAllRelations(n){return Og(this._ctx,n)}listIndexedFiles(n){return Sg(this._ctx,n)}getInternalRelations(n,u){return rg(this._ctx,n,u)}getFullSymbol(n,u,g){return _g(this._ctx,n,u,g)}getFileStats(n,u){return Jg(this._ctx,n,u)}getFileInfo(n,u){return Ag(this._ctx,n,u)}getSymbolsByFile(n,u){return fg(this._ctx,n,u)}getModuleInterface(n,u){return Ng(this._ctx,n,u)}getDependencies(n,u,g=1e4){return qu(this._ctx,n,u,g)}getDependents(n,u,g=1e4){return pu(this._ctx,n,u,g)}async getAffected(n,u){return vu(this._ctx,n,u)}async hasCycle(n){return Gu(this._ctx,n)}async getImportGraph(n){return Eu(this._ctx,n)}async getTransitiveDependencies(n,u){return ju(this._ctx,n,u)}async getCyclePaths(n,u){return Pu(this._ctx,n,u)}async getFanMetrics(n,u){return hu(this._ctx,n,u)}getResolvedType(n,u,g){return $g(this._ctx,n,u,g)}getSemanticReferences(n,u,g){return zg(this._ctx,n,u,g)}getImplementations(n,u,g){return Dg(this._ctx,n,u,g)}getSemanticModuleInterface(n){return Kg(this._ctx,n)}diffSymbols(n,u){return Vg(n,u)}onIndexed(n){return Wg(this._ctx,n)}async reindex(){return Hg(this._ctx)}resolveSymbol(n,u,g){return Qg(this._ctx,n,u,g)}async findPattern(n,u){return Zg(this._ctx,n,u)}async getHeritageChain(n,u,g){return Lg(this._ctx,n,u,g)}onFileChanged(n){return Ug(this._ctx,n)}onError(n){return Bg(this._ctx,n)}onRoleChanged(n){return Yg(this._ctx,n)}}export{en as symbolSearch,nu as relationSearch,uu as patternSearch,p as gildashError,J as GildashError,_u as Gildash,Tn as DependencyGraph};
2
+ var ei=Object.defineProperty;var ng=(n)=>n;function ug(n,u){this[n]=ng.bind(null,u)}var ig=(n,u)=>{for(var i in u)ei(n,i,{get:u[i],enumerable:!0,configurable:!0,set:ug.bind(u,i)})};var Zu=import.meta.require;import{isErr as kn}from"@zipbul/result";import yn from"path";import{existsSync as Mt}from"fs";import{err as Xu,isErr as wg}from"@zipbul/result";import{Database as _g}from"bun:sqlite";import{mkdirSync as Ng,unlinkSync as Bu,existsSync as Cu}from"fs";import{dirname as Sg,join as Tu}from"path";import{drizzle as $g}from"drizzle-orm/bun-sqlite";import{migrate as Jg}from"drizzle-orm/bun-sqlite/migrator";class $ extends Error{type;constructor(n,u,i){super(u,i);this.type=n;this.name="GildashError"}}function c(n,u,i){return new $(n,u,i!==void 0?{cause:i}:void 0)}var $n=".gildash",Rn="gildash.db";var on={};ig(on,{watcherOwner:()=>Og,symbols:()=>y,symbolChangelog:()=>e,relations:()=>V,files:()=>v,annotations:()=>un});import{sql as gg}from"drizzle-orm";import{sqliteTable as Dn,text as T,integer as x,real as tg,index as nn,primaryKey as rg,foreignKey as Fn,check as mg}from"drizzle-orm/sqlite-core";var v=Dn("files",{project:T("project").notNull(),filePath:T("file_path").notNull(),mtimeMs:tg("mtime_ms").notNull(),size:x("size").notNull(),contentHash:T("content_hash").notNull(),updatedAt:T("updated_at").notNull(),lineCount:x("line_count")},(n)=>[rg({columns:[n.project,n.filePath]})]),y=Dn("symbols",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),kind:T("kind").notNull(),name:T("name").notNull(),startLine:x("start_line").notNull(),startColumn:x("start_column").notNull(),endLine:x("end_line").notNull(),endColumn:x("end_column").notNull(),isExported:x("is_exported").notNull().default(0),signature:T("signature"),fingerprint:T("fingerprint"),detailJson:T("detail_json"),contentHash:T("content_hash").notNull(),indexedAt:T("indexed_at").notNull(),resolvedType:T("resolved_type"),structuralFingerprint:T("structural_fingerprint")},(n)=>[nn("idx_symbols_project_file").on(n.project,n.filePath),nn("idx_symbols_project_kind").on(n.project,n.kind),nn("idx_symbols_project_name").on(n.project,n.name),nn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Fn({columns:[n.project,n.filePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),V=Dn("relations",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),type:T("type").notNull(),srcFilePath:T("src_file_path").notNull(),srcSymbolName:T("src_symbol_name"),dstProject:T("dst_project").notNull(),dstFilePath:T("dst_file_path").notNull(),dstSymbolName:T("dst_symbol_name"),metaJson:T("meta_json")},(n)=>[nn("idx_relations_src").on(n.project,n.srcFilePath),nn("idx_relations_dst").on(n.dstProject,n.dstFilePath),nn("idx_relations_type").on(n.project,n.type),nn("idx_relations_project_type_src").on(n.project,n.type,n.srcFilePath),Fn({columns:[n.project,n.srcFilePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade"),Fn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),un=Dn("annotations",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),tag:T("tag").notNull(),value:T("value").notNull().default(""),source:T("source").notNull(),symbolName:T("symbol_name"),startLine:x("start_line").notNull(),startColumn:x("start_column").notNull(),endLine:x("end_line").notNull(),endColumn:x("end_column").notNull(),indexedAt:T("indexed_at").notNull()},(n)=>[nn("idx_annotations_project_file").on(n.project,n.filePath),nn("idx_annotations_project_tag").on(n.project,n.tag),nn("idx_annotations_project_symbol").on(n.project,n.symbolName),Fn({columns:[n.project,n.filePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),e=Dn("symbol_changelog",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),changeType:T("change_type").notNull(),symbolName:T("symbol_name").notNull(),symbolKind:T("symbol_kind").notNull(),filePath:T("file_path").notNull(),oldName:T("old_name"),oldFilePath:T("old_file_path"),fingerprint:T("fingerprint"),changedAt:T("changed_at").notNull(),isFullIndex:x("is_full_index").notNull().default(0),indexRunId:T("index_run_id").notNull()},(n)=>[nn("idx_changelog_project_changed_at").on(n.project,n.changedAt),nn("idx_changelog_project_name").on(n.project,n.symbolName),nn("idx_changelog_project_run").on(n.project,n.indexRunId)]),Og=Dn("watcher_owner",{id:x("id").primaryKey(),pid:x("pid").notNull(),startedAt:T("started_at").notNull(),heartbeatAt:T("heartbeat_at").notNull(),instanceId:T("instance_id")},(n)=>[mg("watcher_owner_singleton",gg`${n.id} = 1`)]);class cn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Tu(n.projectRoot,$n,Rn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Ng(Sg(this.dbPath),{recursive:!0}),this.client=new _g(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=$g(this.client,{schema:on}),Jg(this.drizzle,{migrationsFolder:Tu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(i,g)=>{try{return new RegExp(i).test(g)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Cu(this.dbPath)){this.closeClient(),Bu(this.dbPath);for(let i of["-wal","-shm"]){let g=this.dbPath+i;if(Cu(g))Bu(g)}let u=this.open();if(wg(u))return Xu(c("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return Xu(c("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${i}"`);try{let g=n(this);return u.run(`RELEASE SAVEPOINT "${i}"`),g}catch(g){throw u.run(`ROLLBACK TO SAVEPOINT "${i}"`),u.run(`RELEASE SAVEPOINT "${i}"`),g}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let i=n();return u.run("COMMIT"),i}catch(i){throw u.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n,u){let i=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,i,i,u??null)}replaceOwner(n,u){let i=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,i,i,u??null)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}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(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as Zn,and as Lu}from"drizzle-orm";class en{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(v).where(Lu(Zn(v.project,n),Zn(v.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(v).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[v.project,v.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(v).where(Zn(v.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),i=new Map;for(let g of u)i.set(g.filePath,g);return i}deleteFile(n,u){this.db.drizzleDb.delete(v).where(Lu(Zn(v.project,n),Zn(v.filePath,u))).run()}}import{eq as a,and as Mn,sql as sn,count as Ag}from"drizzle-orm";function Kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class nu{db;constructor(n){this.db=n}replaceFileSymbols(n,u,i,g){if(this.db.drizzleDb.delete(y).where(Mn(a(y.project,n),a(y.filePath,u))).run(),!g.length)return;let t=new Date().toISOString();for(let m of g)this.db.drizzleDb.insert(y).values({project:n,filePath:u,kind:m.kind??"unknown",name:m.name??"",startLine:m.startLine??0,startColumn:m.startColumn??0,endLine:m.endLine??0,endColumn:m.endColumn??0,isExported:m.isExported??0,signature:m.signature??null,fingerprint:m.fingerprint??null,detailJson:m.detailJson??null,contentHash:i,indexedAt:m.indexedAt??t,resolvedType:m.resolvedType??null,structuralFingerprint:m.structuralFingerprint??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.filePath,u))).all()}searchByName(n,u,i={}){let g=i.limit??50,t=Kn(u);if(!t)return[];return this.db.drizzleDb.select().from(y).where(Mn(sn`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${t})`,a(y.project,n),i.kind?a(y.kind,i.kind):void 0)).orderBy(y.name).limit(g).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.kind,u))).orderBy(y.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:Ag(),fileCount:sn`COUNT(DISTINCT ${y.filePath})`}).from(y).where(a(y.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(y).where(Mn(a(y.project,n),a(y.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(y).where(Mn(n.ftsQuery?sn`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?a(y.name,n.exactName):void 0,n.project!==void 0?a(y.project,n.project):void 0,n.kind?a(y.kind,n.kind):void 0,n.filePath!==void 0?a(y.filePath,n.filePath):void 0,n.isExported!==void 0?a(y.isExported,n.isExported?1:0):void 0,n.decorator?sn`${y.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?a(y.resolvedType,n.resolvedType):void 0)).orderBy(y.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let i=new RegExp(n.regex);return u.filter((g)=>i.test(g.name)).slice(0,n.limit)}catch{return[]}}}import{eq as p,and as wn,isNull as ku,or as Mg}from"drizzle-orm";class uu{db;constructor(n){this.db=n}replaceFileRelations(n,u,i){this.db.transaction((g)=>{if(g.drizzleDb.delete(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).run(),!i.length)return;for(let t of i)g.drizzleDb.insert(V).values({project:n,type:t.type??"unknown",srcFilePath:t.srcFilePath??u,srcSymbolName:t.srcSymbolName??null,dstProject:t.dstProject??n,dstFilePath:t.dstFilePath??"",dstSymbolName:t.dstSymbolName??null,metaJson:t.metaJson??null}).run()})}getOutgoing(n,u,i){if(i!==void 0)return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.srcFilePath,u),Mg(p(V.srcSymbolName,i),ku(V.srcSymbolName)))).all();return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:i}=n;return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.dstProject,u),p(V.dstFilePath,i))).all()}getByType(n,u){return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(n.project!==void 0?p(V.project,n.project):void 0,n.srcFilePath!==void 0?p(V.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?p(V.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?p(V.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?p(V.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?p(V.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?p(V.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:i,oldSymbol:g,newFile:t,newSymbol:m,newDstProject:w}=n,O=g===null?wn(p(V.dstProject,u),p(V.dstFilePath,i),ku(V.dstSymbolName)):wn(p(V.dstProject,u),p(V.dstFilePath,i),p(V.dstSymbolName,g)),r={dstFilePath:t,dstSymbolName:m};if(w!==void 0)r.dstProject=w;this.db.drizzleDb.update(V).set(r).where(O).run()}}import{err as yu}from"@zipbul/result";import{subscribe as Qg}from"@parcel/watcher";import iu from"path";var zg=["**/.git/**",`**/${$n}/**`,"**/dist/**","**/node_modules/**"],fg=new Set(["package.json","tsconfig.json"]);function Dg(n){return n.replaceAll("\\","/")}function Kg(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class gu{#n;#u;#i;#t;#g;#r;constructor(n,u=Qg,i=console){this.#u=n.projectRoot,this.#i=[...zg,...n.ignorePatterns??[]],this.#t=new Set((n.extensions??[".ts",".mts",".cts"]).map((g)=>g.toLowerCase())),this.#g=u,this.#r=i}async start(n){try{this.#n=await this.#g(this.#u,(u,i)=>{if(u){this.#r.error(c("watcher","Callback error",u));return}try{for(let g of i){let t=Dg(iu.relative(this.#u,g.path));if(t.startsWith(".."))continue;let m=iu.basename(t),w=iu.extname(t).toLowerCase();if(!fg.has(m)&&!this.#t.has(w))continue;if(t.endsWith(".d.ts"))continue;n({eventType:Kg(g.type),filePath:t})}}catch(g){this.#r.error(c("watcher","Callback error",g))}},{ignore:this.#i})}catch(u){return yu(c("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return yu(c("watcher","Failed to close watcher",n))}}}import tu from"path";import{promises as Vg}from"fs";var Wg=["**/node_modules/**","**/.git/**",`**/${$n}/**`,"**/dist/**"];async function jn(n){let u=[];for await(let i of Vg.glob("**/package.json",{cwd:n,exclude:Wg})){let g=tu.dirname(i).replaceAll("\\","/"),t=tu.join(n,i),m=await Bun.file(t).json(),w=typeof m?.name==="string"&&m.name.length>0?m.name:tu.basename(g==="."?n:g);u.push({dir:g,project:w})}return u.sort((i,g)=>g.dir.length-i.dir.length),u}function P(n,u,i="default"){let g=n.replaceAll("\\","/");for(let t of u){if(t.dir===".")return t.project;if(g===t.dir||g.startsWith(`${t.dir}/`))return t.project}return i}import Ru from"path";var Jn=new Map;async function Hg(n){let u=Bun.file(n);if(!await u.exists())return null;try{let i=await u.text(),g=Bun.JSONC.parse(i);return typeof g==="object"&&g!==null?g:null}catch{return null}}async function Xn(n){if(Jn.has(n))return Jn.get(n)??null;let u=Ru.join(n,"tsconfig.json"),i=await Hg(u);if(!i)return Jn.set(n,null),null;let g=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!g)return Jn.set(n,null),null;let t=typeof g.baseUrl==="string"?g.baseUrl:null,m=typeof g.paths==="object"&&g.paths!==null?g.paths:null;if(!t&&!m)return Jn.set(n,null),null;let w=t?Ru.resolve(n,t):n,O=new Map;if(m)for(let[S,_]of Object.entries(m)){if(!Array.isArray(_))continue;let N=_.filter((M)=>typeof M==="string");O.set(S,N)}let r={baseUrl:w,paths:O};return Jn.set(n,r),r}function bn(n){if(n){Jn.delete(n);return}Jn.clear()}import Fu from"path";function qn(n,u){return Fu.relative(n,u).replaceAll("\\","/")}function Vn(n,u){return Fu.resolve(n,u)}function mn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as hu}from"@zipbul/result";import{err as Ug}from"@zipbul/result";import{parseSync as Yg}from"oxc-parser";function Bn(n,u,i,g=Yg){try{let{program:t,errors:m,comments:w}=g(n,u,i);return{filePath:n,program:t,errors:m,comments:w,sourceText:u}}catch(t){return Ug(c("parse",`Failed to parse file: ${n}`,t))}}import{promises as Ig}from"fs";import{join as Zg}from"path";async function su(n){let{projectRoot:u,extensions:i,ignorePatterns:g,fileRepo:t}=n,m=t.getFilesMap(),w=new Set,O=[],r=[],S=g.map((N)=>new Bun.Glob(N));for await(let N of Ig.glob("**/*",{cwd:u})){if(!i.some((J)=>N.endsWith(J)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(S.some((J)=>J.match(N)))continue;w.add(N);let M=Zg(u,N),f=Bun.file(M),{size:H,lastModified:K}=f,X=m.get(N);if(!X){let J=await f.text(),W=mn(J);O.push({filePath:N,contentHash:W,mtimeMs:K,size:H});continue}if(X.mtimeMs===K&&X.size===H){r.push({filePath:N,contentHash:X.contentHash,mtimeMs:K,size:H});continue}let A=await f.text(),z=mn(A);if(z===X.contentHash)r.push({filePath:N,contentHash:z,mtimeMs:K,size:H});else O.push({filePath:N,contentHash:z,mtimeMs:K,size:H})}let _=[];for(let N of m.keys())if(!w.has(N))_.push(N);return{changed:O,unchanged:r,deleted:_}}function Gn(n){let u=[0];for(let i=0;i<n.length;i++)if(n[i]===`
3
+ `)u.push(i+1);return u}function rn(n,u){let i=0,g=n.length-1;while(i<g){let t=i+g+1>>1;if(n[t]<=u)i=t;else g=t-1}return{line:i+1,column:u-n[i]}}import{err as Xg}from"@zipbul/result";import{parse as Bg}from"comment-parser";function En(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let g=Bg(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(g.description??"").trim(),tags:(g.tags??[]).map((t)=>({tag:t.tag??"",name:t.name??"",type:t.type??"",description:t.description??"",optional:t.optional??!1,...t.default!==void 0?{default:t.default}:{}}))}}catch(u){return Xg(c("parse","Failed to parse JSDoc comment",u))}}import{isErr as Cg}from"@zipbul/result";function Wn(n){let{program:u,sourceText:i,comments:g}=n,t=Gn(i);function m(A,z){return{start:rn(t,A),end:rn(t,z)}}function w(A){let z=null;for(let J of g){if(J.type!=="Block")continue;if(J.end>A)continue;if(!J.value.startsWith("*"))continue;if(!z||J.end>z.end)z={value:`/*${J.value}*/`,end:J.end}}if(!z)return;for(let J of u.body){let W=J.start??0;if(W===A)continue;if(W>z.end&&W<A)return}return z.value}function O(A){if(!A)return;let z=A.typeAnnotation??A;return i.slice(z.start,z.end)}function r(A){if(!A||A.length===0)return[];return A.map((z)=>{let J=z.expression;if(!J)return{name:"unknown"};if(J.type==="CallExpression"){let W=J.callee?.name??J.callee?.property?.name??"unknown",Y=(J.arguments??[]).map((I)=>i.slice(I.start,I.end));return{name:W,arguments:Y.length>0?Y:void 0}}if(J.type==="Identifier")return{name:J.name??"unknown"};return{name:i.slice(J.start,J.end)}})}function S(A){let z=A.type==="TSParameterProperty"?A.parameter:A;if(z?.type==="RestElement"){let E=`...${z.argument?.name??"unknown"}`,q=z.typeAnnotation,Q=q?O(q):void 0,D={name:E,isOptional:!1};if(Q)D.type=Q;return D}if(z?.type==="AssignmentPattern"){let{left:b,right:E}=z,q=b?.name??"unknown",Q=b?.typeAnnotation,D=Q?O(Q):void 0,Z=i.slice(E.start,E.end),U=r(b?.decorators??[]),R={name:q,isOptional:!0,defaultValue:Z};if(D)R.type=D;if(U.length>0)R.decorators=U;return R}let J=z?.name??z?.pattern?.name??"unknown",W=!!z?.optional,Y=z?.typeAnnotation,I=Y?O(Y):void 0,B=r(z?.decorators??[]),s={name:J,isOptional:W};if(I)s.type=I;if(B.length>0)s.decorators=B;return s}function _(A,z){let J=[];if(z?.async)J.push("async");if(A.static)J.push("static");if(A.abstract)J.push("abstract");if(A.readonly)J.push("readonly");if(A.override)J.push("override");if(A.declare)J.push("declare");if(A.const)J.push("const");let W=A.accessibility;if(W==="private")J.push("private");else if(W==="protected")J.push("protected");else if(W==="public")J.push("public");return J}function N(A){let z=[];if(A.superClass){let W=i.slice(A.superClass.start,A.superClass.end);z.push({kind:"extends",name:W})}let J=A.implements??[];for(let W of J){let Y=W.expression??W,I=i.slice(Y.start,Y.end);z.push({kind:"implements",name:I})}return z}function M(A){let z=[];for(let J of A.extends??[]){let W=J.expression??J,Y=i.slice(W.start,W.end);z.push({kind:"extends",name:Y})}return z}function f(A){let z=[];for(let J of A)if(J.type==="MethodDefinition"){let W=J.key?.name??"unknown",Y=J.value,I=J.kind??"method",B=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",s=_(J,Y),b=(Y?.params??[]).map(S),E=O(Y?.returnType),q={kind:"method",name:W,span:m(J.start,J.end),isExported:!1,methodKind:B,modifiers:s,parameters:b.length>0?b:void 0,returnType:E};z.push(q)}else if(J.type==="PropertyDefinition"){let W=J.key?.name??"unknown",Y=_(J),I={kind:"property",name:W,span:m(J.start,J.end),isExported:!1,modifiers:Y};z.push(I)}return z}function H(A){let z=[];for(let J of A)if(J.type==="TSMethodSignature"){let W=J.key?.name??"unknown",Y=(J.params??[]).map(S),I=O(J.returnType);z.push({kind:"method",name:W,span:m(J.start,J.end),isExported:!1,modifiers:[],methodKind:"method",parameters:Y.length>0?Y:void 0,returnType:I})}else if(J.type==="TSPropertySignature"){let W=J.key?.name??"unknown",Y=O(J.typeAnnotation),I={kind:"property",name:W,span:m(J.start,J.end),isExported:!1,modifiers:J.readonly?["readonly"]:[],returnType:Y};z.push(I)}return z}function K(A,z){let J=A.type??"";if(J==="FunctionDeclaration"){let W=A.id?.name??"default",Y=(A.params??[]).map(S),I=O(A.returnType),B=_(A,A),s=r(A.decorators??[]),b=A.typeParameters?.params?.map((q)=>q.name?.name).filter(Boolean)||void 0,E={kind:"function",name:W,span:m(A.start,A.end),isExported:z,modifiers:B,parameters:Y.length>0?Y:void 0,returnType:I,decorators:s.length>0?s:void 0};if(b&&b.length>0)E.typeParameters=b;return E}if(J==="ClassDeclaration"||J==="ClassExpression"){let W=A.id?.name??"default",Y=N(A),I=f(A.body?.body??[]),B=r(A.decorators??[]),s=_(A,A),b=A.typeParameters?.params?.map((q)=>q.name?.name).filter(Boolean)||void 0,E={kind:"class",name:W,span:m(A.start,A.end),isExported:z,modifiers:s,heritage:Y.length>0?Y:void 0,members:I.length>0?I:void 0,decorators:B.length>0?B:void 0};if(b&&b.length>0)E.typeParameters=b;return E}if(J==="VariableDeclaration"){let W=[];for(let Y of A.declarations??[]){let{id:I,init:B}=Y;if(I?.type==="ObjectPattern"){for(let D of I.properties??[]){let Z=D.value?.name??D.key?.name??"unknown";W.push({kind:"variable",name:Z,span:m(D.start??Y.start,D.end??Y.end),isExported:z,modifiers:[]})}continue}if(I?.type==="ArrayPattern"){for(let D of I.elements??[]){if(!D||D.type!=="Identifier")continue;let Z=D.name??"unknown";W.push({kind:"variable",name:Z,span:m(D.start??Y.start,D.end??Y.end),isExported:z,modifiers:[]})}continue}let s=I?.name??"unknown",b="variable",E,q;if(B?.type==="FunctionExpression"||B?.type==="ArrowFunctionExpression")b="function",E=(B.params??[]).map(S),q=O(B.returnType);let Q=[];W.push({kind:b,name:s,span:m(Y.start,Y.end),isExported:z,modifiers:Q,parameters:E,returnType:q})}if(W.length===0)return null;if(W.length===1)return W[0];return W}if(J==="TSTypeAliasDeclaration")return{kind:"type",name:A.id?.name??"unknown",span:m(A.start,A.end),isExported:z,modifiers:[]};if(J==="TSInterfaceDeclaration"){let W=A.id?.name??"unknown",Y=M(A),I=H(A.body?.body??[]),B=A.typeParameters?.params?.map((b)=>b.name?.name).filter(Boolean)||void 0,s={kind:"interface",name:W,span:m(A.start,A.end),isExported:z,modifiers:[],heritage:Y.length>0?Y:void 0,members:I.length>0?I:void 0};if(B&&B.length>0)s.typeParameters=B;return s}if(J==="TSEnumDeclaration"){let W=A.id?.name??"unknown",Y=_(A),B=(A.body?.members??[]).map((s)=>({kind:"property",name:s.id?.name??s.id?.value??"unknown",span:m(s.start,s.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:W,span:m(A.start,A.end),isExported:z,modifiers:Y,members:B.length>0?B:void 0}}return null}let X=[];for(let A of u.body){let z=null,J=A,W=typeof J.type==="string"?J.type:"";if(W==="ExportNamedDeclaration"){let I=A;if(I.declaration){if(z=K(I.declaration,!0),z&&!Array.isArray(z))z.span=m(I.start,I.end);else if(Array.isArray(z))for(let B of z)B.span=m(I.start,I.end)}}else if(W==="ExportDefaultDeclaration"){let I=A,B=I.declaration;if(B){if(z=K(B,!0),z&&!Array.isArray(z))z.name=B.id?.name??"default",z.isExported=!0,z.span=m(I.start,I.end)}}else z=K(A,!1);let Y=Array.isArray(z)?z:z?[z]:[];for(let I of Y){let B=A.start??0,s=w(B);if(s){let b=En(s);if(!Cg(b))I.jsDoc=b}X.push(I)}}return X}function Tg(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${u}|async:${i}`}return null}function Lg(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((i)=>{let g=i.modifiers.find((t)=>t==="private"||t==="protected"||t==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:g,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function kg(n){let u=[n.kind];if(n.modifiers.length)u.push(`mod:${[...n.modifiers].sort().join(",")}`);if(n.typeParameters?.length)u.push(`tp:${n.typeParameters.length}`);if(n.heritage?.length){let i=[...n.heritage].sort((g,t)=>g.name.localeCompare(t.name)).map((g)=>`${g.kind}:${g.name}`).join(",");u.push(`her:${i}`)}if(n.decorators?.length)u.push(`dec:${[...n.decorators].map((i)=>i.name).sort().join(",")}`);if(n.methodKind)u.push(`mk:${n.methodKind}`);if(n.parameters)u.push(`p:${n.parameters.length}`);if(n.returnType)u.push(`rt:${n.returnType}`);if(n.members?.length){let i=n.members.map((g)=>`${g.kind}:${g.modifiers.join(",")}:${g.parameters?.length??""}:${g.returnType??""}`).sort().join(";");u.push(`mem:${n.members.length}:${mn(i)}`)}return mn(u.join("|"))}function ju(n,u,i,g,t){let m=Tg(n),w=mn(`${u}|${n.kind}|${m??""}`),O=kg(n);return{project:i,filePath:g,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:m,fingerprint:w,detailJson:Lg(n),contentHash:t,indexedAt:new Date().toISOString(),structuralFingerprint:O}}function ru(n){let{parsed:u,project:i,filePath:g,contentHash:t,symbolRepo:m}=n,w=Wn(u),O=[];for(let r of w){O.push(ju(r,r.name,i,g,t));for(let S of r.members??[])O.push(ju(S,`${r.name}.${S.name}`,i,g,t))}m.replaceFileSymbols(i,g,t,O)}import{resolve as mu,dirname as yg,extname as Rg}from"path";function Qn(n,u,i){let g=(t)=>{let m=Rg(t);if(m==="")return[t+".ts",t+".d.ts",t+"/index.ts",t+"/index.d.ts",t+".mts",t+"/index.mts",t+".cts",t+"/index.cts"];if(m===".js")return[t.slice(0,-3)+".ts"];if(m===".mjs")return[t.slice(0,-4)+".mts"];if(m===".cjs")return[t.slice(0,-4)+".cts"];return[t]};if(u.startsWith(".")){let t=mu(yg(n),u);return g(t)}if(i)for(let[t,m]of i.paths){if(m.length===0)continue;let w=t.indexOf("*");if(w===-1){if(u===t){let O=[];for(let r of m)O.push(...g(mu(i.baseUrl,r)));return O}}else{let O=t.slice(0,w),r=t.slice(w+1);if(u.startsWith(O)&&(r===""||u.endsWith(r))){let S=u.slice(O.length,r===""?void 0:u.length-r.length),_=[];for(let N of m)_.push(...g(mu(i.baseUrl,N.replace("*",S))));return _}}}return[]}function bu(n,u,i,g=Qn){let t=new Map,m=n.body??[];for(let w of m){if(w.type!=="ImportDeclaration")continue;let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.specifiers??[];for(let N of _)switch(N.type){case"ImportSpecifier":t.set(N.local.name,{path:S,importedName:N.imported.name});break;case"ImportDefaultSpecifier":t.set(N.local.name,{path:S,importedName:"default"});break;case"ImportNamespaceSpecifier":t.set(N.local.name,{path:S,importedName:"*"});break}}return t}var Fg=new Set(["loc","start","end","scope"]);function Hn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let g of n)Hn(g,u);return}let i=n;u(i);for(let g of Object.keys(i)){if(Fg.has(g))continue;let t=i[g];if(t&&typeof t==="object")Hn(t,u)}}function qu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function zn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let i=u.name;return{root:i,parts:[],full:i}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let i=[],g=u;while(g.type==="MemberExpression"){let w=g.property;if(!w||typeof w.name!=="string")return null;i.unshift(w.name),g=g.object}let t;if(g.type==="Identifier")t=g.name;else if(g.type==="ThisExpression")t="this";else if(g.type==="Super")t="super";else return null;let m=[t,...i].join(".");return{root:t,parts:i,full:m}}return null}function Gu(n,u,i,g=Qn){let t=[],m=n.body??[];for(let w of m){if(w.type==="ImportDeclaration"){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.importKind==="type",N=w.specifiers??[];if(N.length===0){let M={};if(_)M.isType=!0;t.push({type:_?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of N){let f=M.type,H=_||M.importKind==="type",K={};if(H)K.isType=!0;let X,A;if(f==="ImportDefaultSpecifier")X="default",A=M.local.name;else if(f==="ImportNamespaceSpecifier")X="*",A=M.local.name,K.importKind="namespace";else X=M.imported.name,A=M.local.name;t.push({type:H?"type-references":"imports",srcFilePath:u,srcSymbolName:A,dstFilePath:S,dstSymbolName:X,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}continue}if(w.type==="ExportAllDeclaration"&&w.source){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.exportKind==="type",N={isReExport:!0};if(_)N.isType=!0;t.push({type:_?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify(N)});continue}if(w.type==="ExportNamedDeclaration"&&w.source){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.exportKind==="type",f={isReExport:!0,specifiers:(w.specifiers??[]).map((H)=>({local:H.local.name,exported:H.exported.name}))};if(_)f.isType=!0;t.push({type:_?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify(f)})}}return Hn(n,(w)=>{if(w.type!=="ImportExpression")return;let O=qu(w.source);if(!O)return;let r=g(u,O,i);if(r.length===0)return;let S=r[0];t.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),t}function Eu(n,u,i){let g=[],t=[],m=[];function w(){if(t.length>0)return t[t.length-1]??null;return null}function O(S){if(!S)return null;let _=i.get(S.root);if(S.parts.length===0){if(_)return{dstFilePath:_.path,dstSymbolName:_.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:S.root,resolution:"local"}}else{if(_&&_.importedName==="*"){let N=S.parts[S.parts.length-1];return{dstFilePath:_.path,dstSymbolName:N,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:S.full,resolution:"local-member"}}}function r(S){if(!S||typeof S!=="object")return;if(Array.isArray(S)){for(let M of S)r(M);return}let _=S,N=typeof _.type==="string"?_.type:"";if(N==="ClassDeclaration"||N==="ClassExpression"){let M=_,f=M.id?.name??"AnonymousClass";m.push(f),r(M.body),m.pop();return}if(N==="FunctionDeclaration"){let M=_,f=M.id?.name??"anonymous";t.push(f),r(M.body),t.pop();return}if(N==="VariableDeclarator"&&_.init&&(_.init?.type==="FunctionExpression"||_.init?.type==="ArrowFunctionExpression")){let M=_,f=M.id?.name??"anonymous";t.push(f),r(M.init?.body??M.init),t.pop();return}if(N==="MethodDefinition"&&_.value){let M=_,f=m[m.length-1]??"",H=M.key?.name??"anonymous",K=f?`${f}.${H}`:H;t.push(K),r(M.value?.body),t.pop();return}if(N==="FunctionExpression"||N==="ArrowFunctionExpression"){let M=w(),f=M?`${M}.<anonymous>`:"<anonymous>";t.push(f),r(_.body),t.pop();return}if(N==="CallExpression"){let M=_,f=zn(M.callee),H=O(f);if(H){let K=w(),X={};if(K===null)X.scope="module";g.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}r(M.callee);for(let K of M.arguments??[])r(K);return}if(N==="NewExpression"){let M=_,f=zn(M.callee),H=O(f);if(H){let K=w(),X={isNew:!0};if(K===null)X.scope="module";g.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,metaJson:JSON.stringify(X)})}for(let K of M.arguments??[])r(K);return}for(let M of Object.keys(_)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let f=_[M];if(f&&typeof f==="object")r(f)}}return r(n),g}function pu(n,u,i){let g=[];return Hn(n,(t)=>{if(t.type==="TSInterfaceDeclaration"){let O=t.id?.name??"AnonymousInterface",r=t.extends??[];for(let S of r){let _=S.expression??S,N=zn(_);if(!N)continue;let M=Ou(N,u,i);g.push({type:"extends",srcFilePath:u,srcSymbolName:O,...M})}return}if(t.type!=="ClassDeclaration"&&t.type!=="ClassExpression")return;let m=t.id?.name??"AnonymousClass";if(t.superClass){let O=zn(t.superClass);if(O){let r=Ou(O,u,i);g.push({type:"extends",srcFilePath:u,srcSymbolName:m,...r})}}let w=t.implements??[];for(let O of w){let r=O.expression??O,S=zn(r);if(!S)continue;let _=Ou(S,u,i);g.push({type:"implements",srcFilePath:u,srcSymbolName:m,..._})}}),g}function Ou(n,u,i){let g=i.get(n.root);if(g){if(g.importedName==="*"){let t=n.parts[n.parts.length-1]??n.root;return{dstFilePath:g.path,dstSymbolName:t,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:g.path,dstSymbolName:n.parts.length>0?n.full:g.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function pn(n,u,i,g=Qn){let t=bu(n,u,i,g),m=Gu(n,u,i,g),w=Eu(n,u,t),O=pu(n,u,t);return[...m,...w,...O]}function wu(n){let{ast:u,project:i,filePath:g,relationRepo:t,projectRoot:m,tsconfigPaths:w,knownFiles:O,boundaries:r}=n,S=Vn(m,g),N=pn(u,S,w,O?(f,H,K)=>{let X=Qn(f,H,K);for(let A of X){let z=qn(m,A);if(r){let J=P(z,r);if(O.has(`${J}::${z}`))return[A]}else if(O.has(`${i}::${z}`))return[A]}return[]}:void 0),M=[];for(let f of N){let H=qn(m,f.dstFilePath);if(H.startsWith(".."))continue;let K=qn(m,f.srcFilePath),X=r?P(H,r):i;M.push({project:i,type:f.type,srcFilePath:K,srcSymbolName:f.srcSymbolName??null,dstProject:X,dstFilePath:H,dstSymbolName:f.dstSymbolName??null,metaJson:f.metaJson??null})}return t.replaceFileRelations(i,g,M),M.length}import{isErr as sg}from"@zipbul/result";var vu=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function jg(n){let u=Wn(n),i=[];for(let g of u){i.push({name:g.name,startLine:g.span.start.line});for(let t of g.members??[])i.push({name:`${g.name}.${t.name}`,startLine:t.span.start.line})}return i.sort((g,t)=>g.startLine-t.startLine),i}function _u(n,u,i){let g=0,t=n.length-1;while(g<=t){let m=g+t>>1;if(n[m].startLine<=u)g=m+1;else t=m-1}if(g<n.length){let m=n[g];if(m.startLine-u<=i)return m.name}return null}function vn(n,u,i){let g=rn(n,u),t=rn(n,i);return{start:g,end:t}}function Pu(n){let{comments:u,sourceText:i}=n;if(!u.length)return[];let g=Gn(i),t=jg(n),m=[],w=[...u].sort((r,S)=>r.start-S.start),O=null;for(let r of w)if(r.type==="Block"&&r.value.startsWith("*")){O=null;let S=`/*${r.value}*/`,_=En(S);if(sg(_))continue;let N=_;if(!N.tags?.length)continue;let M=rn(g,r.end),f=_u(t,M.line,3),H=i.slice(r.start,r.end);for(let K of N.tags){let X=[K.name,K.description].filter(Boolean).join(" "),A=`@${K.tag}`,z=H.indexOf(A),J;if(z>=0){let W=r.start+z,Y=i.indexOf(`
4
+ `,W),I=Y>=0?Math.min(Y,r.end):r.end;J=vn(g,W,I)}else J=vn(g,r.start,r.end);m.push({tag:K.tag,value:X,source:"jsdoc",span:J,symbolName:f})}}else if(r.type==="Block"){O=null;let S=r.value.split(`
5
+ `),_=0;for(let N of S){let M=N.replace(/^\s*\*?\s?/,""),f=vu.exec(M);if(f){let H=f[1],K=f[2]?.trim()??"",X=`@${H}`,A=N.indexOf(X),z=r.start+2+_+(A>=0?A:0),J=r.start+2+_+N.length,W=vn(g,z,J),Y=rn(g,r.end),I=_u(t,Y.line,3);m.push({tag:H,value:K,source:"block",span:W,symbolName:I})}_+=N.length+1}}else{let S=r.value,_=vu.exec(S),N=rn(g,r.start),M=rn(g,r.end);if(_){let f=_[1],H=_[2]?.trim()??"",K=`@${f}`,X=S.indexOf(K),A=r.start+2+(X>=0?X:0),z=vn(g,A,r.end),J=_u(t,M.line,3),W={tag:f,value:H,source:"line",span:z,symbolName:J};m.push(W),O={annotation:W,endLine:M.line}}else if(O&&N.line===O.endLine+1){let f=S.trim();if(f)O.annotation.value+=" "+f,O.annotation.span.end=rn(g,r.end),O.endLine=M.line}else O=null}return m}function Nu(n){let{parsed:u,project:i,filePath:g,annotationRepo:t}=n,m=Pu(u);if(t.deleteFileAnnotations(i,g),!m.length)return 0;let w=new Date().toISOString(),O=m.map((r)=>({project:i,filePath:g,tag:r.tag,value:r.value,source:r.source,symbolName:r.symbolName,startLine:r.span.start.line,startColumn:r.span.start.column,endLine:r.span.end.line,endColumn:r.span.end.column,indexedAt:w}));return t.insertBatch(i,g,O),m.length}function au(n,u){let i=[],g=[],t=[];for(let[_,N]of u)if(!n.has(_))i.push({name:N.name,filePath:N.filePath,kind:N.kind,fingerprint:N.fingerprint});for(let[_,N]of n)if(!u.has(_))g.push({name:N.name,filePath:N.filePath,kind:N.kind,fingerprint:N.fingerprint});if(!i.length||!g.length)return{renamed:t,added:i,removed:g};let m=new Map,w=new Map;for(let _ of i){let N=m.get(_.filePath)??[];N.push(_),m.set(_.filePath,N)}for(let _ of g){let N=w.get(_.filePath)??[];N.push(_),w.set(_.filePath,N)}let O=new Set,r=new Set;for(let[_,N]of m){let M=w.get(_);if(!M)continue;for(let f of new Set(N.map((H)=>H.kind))){let H=N.filter((J)=>J.kind===f&&!O.has(J)),K=M.filter((J)=>J.kind===f&&!r.has(J));if(!H.length||!K.length)continue;let X=(J,W)=>{return W.get(`${J.filePath}::${J.name}`)?.structuralFingerprint??null},A=(J,W)=>{return W.get(`${J.filePath}::${J.name}`)?.startLine??0},z=new Map;for(let J of K){let W=X(J,n);if(!W)continue;let Y=z.get(W)??[];Y.push(J),z.set(W,Y)}for(let J of H){if(O.has(J))continue;let W=X(J,u);if(!W)continue;let Y=z.get(W);if(!Y)continue;let I=Y.filter((s)=>!r.has(s));if(!I.length)continue;let B=I[0];if(I.length>1){let s=A(J,u),b=Math.abs(A(B,n)-s);for(let E=1;E<I.length;E++){let q=Math.abs(A(I[E],n)-s);if(q<b)b=q,B=I[E]}}t.push({oldName:B.name,newName:J.name,filePath:_,kind:f}),O.add(J),r.add(B)}}}let S=t.filter((_)=>!_.oldName.includes("."));for(let _ of S){let N=`${_.oldName}.`,M=`${_.newName}.`,f=g.filter((K)=>K.filePath===_.filePath&&K.name.startsWith(N)&&!r.has(K)),H=i.filter((K)=>K.filePath===_.filePath&&K.name.startsWith(M)&&!O.has(K));for(let K of f){let X=K.name.slice(N.length),A=H.find((z)=>z.name.slice(M.length)===X);if(A)t.push({oldName:K.name,newName:A.name,filePath:_.filePath,kind:K.kind}),O.add(A),r.add(K)}}return{renamed:t,added:i.filter((_)=>!O.has(_)),removed:g.filter((_)=>!r.has(_))}}var bg=100,xu=50;class Su{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Xn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){bn(this.opts.projectRoot),this.tsconfigPathsRaw=Xn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??jn;this.boundariesRefresh=u(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},bg)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((g,t)=>{this.pendingFullIndexWaiters.push({resolve:g,reject:t})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,u).then((g)=>{return this.fireCallbacks(g),g}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let g=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((t)=>{for(let m of g)m.resolve(t)}).catch((t)=>{for(let m of g)m.reject(t)})}else if(this.pendingEvents.length>0){let g=this.pendingEvents.splice(0);this.startIndex(g,!1).catch((t)=>this.logger.error("[IndexCoordinator] incremental drain error",t))}});return this.currentIndexing=i,i}async doIndex(n,u){let i=Date.now(),{fileRepo:g,symbolRepo:t,relationRepo:m,dbConnection:w}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let O,r;if(n!==void 0)O=n.filter((Q)=>Q.eventType==="create"||Q.eventType==="change").map((Q)=>({filePath:Q.filePath,contentHash:"",mtimeMs:0,size:0})),r=n.filter((Q)=>Q.eventType==="delete").map((Q)=>Q.filePath);else{let Q=new Map;for(let Z of this.opts.boundaries)for(let[U,R]of g.getFilesMap(Z.project))Q.set(U,R);let D=await su({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Q}});O=D.changed,r=D.deleted}let S=await this.tsconfigPathsRaw??void 0,_=new Map;for(let Q of r){let D=P(Q,this.opts.boundaries),Z=t.getFileSymbols(D,Q);_.set(Q,Z)}let N=crypto.randomUUID(),M=new Map,f=new Map,H=(Q)=>({name:Q.name,filePath:Q.filePath,kind:Q.kind,fingerprint:Q.fingerprint,structuralFingerprint:Q.structuralFingerprint??null,startLine:Q.startLine});if(u)for(let Q of this.opts.boundaries)for(let D of g.getAllFiles(Q.project))for(let Z of t.getFileSymbols(Q.project,D.filePath))M.set(`${Z.filePath}::${Z.name}`,H(Z));else{for(let Q of O){let D=P(Q.filePath,this.opts.boundaries);for(let Z of t.getFileSymbols(D,Q.filePath))M.set(`${Z.filePath}::${Z.name}`,H(Z))}for(let[,Q]of _)for(let D of Q)M.set(`${D.filePath}::${D.name}`,H(D))}let{annotationRepo:K,changelogRepo:X}=this.opts,A=()=>{for(let Q of r){let D=P(Q,this.opts.boundaries);if(t.deleteFileSymbols(D,Q),m.deleteFileRelations(D,Q),K)K.deleteFileAnnotations(D,Q);g.deleteFile(D,Q)}},z=0,J=async()=>{let{projectRoot:Q,boundaries:D}=this.opts,{parseCache:Z}=this.opts,U=0,R=0,L=0,gn=[],k=[];for(let F of O)try{let C=Vn(Q,F.filePath),l=Bun.file(C),o=await l.text(),On=F.contentHash||mn(o),Sn=P(F.filePath,D);g.upsertFile({project:Sn,filePath:F.filePath,mtimeMs:l.lastModified,size:l.size,contentHash:On,updatedAt:new Date().toISOString(),lineCount:o.split(`
6
+ `).length});let In=(this.opts.parseSourceFn??Bn)(C,o);if(hu(In))throw In.data;let ci=In;k.push({filePath:F.filePath,text:o,contentHash:On,parsed:ci,project:Sn})}catch(C){this.logger.error(`[IndexCoordinator] Failed to prepare ${F.filePath}:`,C),gn.push(F.filePath)}let G=new Set;for(let F of D)for(let[C]of g.getFilesMap(F.project))G.add(`${F.project}::${C}`);return w.transaction(()=>{for(let F of k){if(ru({parsed:F.parsed,project:F.project,filePath:F.filePath,contentHash:F.contentHash,symbolRepo:t}),R+=wu({ast:F.parsed.program,project:F.project,filePath:F.filePath,relationRepo:m,projectRoot:Q,tsconfigPaths:S,knownFiles:G,boundaries:D}),K)L+=Nu({parsed:F.parsed,project:F.project,filePath:F.filePath,annotationRepo:K});Z.set(F.filePath,F.parsed),U+=t.getFileSymbols(F.project,F.filePath).length}}),{symbols:U,relations:R,annotations:L,failedFiles:gn}},W=0,Y=0,I=[];if(u){let{projectRoot:Q,boundaries:D}=this.opts,{parseCache:Z}=this.opts,U=[];for(let L=0;L<O.length;L+=xu){let gn=O.slice(L,L+xu),k=await Promise.allSettled(gn.map(async(G)=>{let F=Vn(Q,G.filePath),C=Bun.file(F),l=await C.text(),o=G.contentHash||mn(l);return{filePath:G.filePath,text:l,contentHash:o,mtimeMs:C.lastModified,size:C.size}}));for(let G of k)if(G.status==="fulfilled")U.push(G.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",G.reason)}let R=[];w.transaction(()=>{for(let k of U){let G=P(k.filePath,D);g.deleteFile(G,k.filePath)}for(let k of r){let G=P(k,D);if(t.deleteFileSymbols(G,k),m.deleteFileRelations(G,k),K)K.deleteFileAnnotations(G,k);g.deleteFile(G,k)}for(let k of U){let G=P(k.filePath,D);g.upsertFile({project:G,filePath:k.filePath,mtimeMs:k.mtimeMs,size:k.size,contentHash:k.contentHash,updatedAt:new Date().toISOString(),lineCount:k.text.split(`
7
+ `).length})}let L=new Set;for(let k of D)for(let[G]of g.getFilesMap(k.project))L.add(`${k.project}::${G}`);let gn=this.opts.parseSourceFn??Bn;for(let k of U){let G=P(k.filePath,D),F=gn(Vn(Q,k.filePath),k.text);if(hu(F))throw F.data;let C=F;if(R.push({filePath:k.filePath,parsed:C}),ru({parsed:C,project:G,filePath:k.filePath,contentHash:k.contentHash,symbolRepo:t}),K)z+=Nu({parsed:C,project:G,filePath:k.filePath,annotationRepo:K});Y+=wu({ast:C.program,project:G,filePath:k.filePath,relationRepo:m,projectRoot:Q,tsconfigPaths:S,knownFiles:L,boundaries:D}),W+=t.getFileSymbols(G,k.filePath).length}});for(let L of R)Z.set(L.filePath,L.parsed)}else{A();let Q=await J();W=Q.symbols,Y=Q.relations,z=Q.annotations,I=Q.failedFiles}for(let Q of O){let D=P(Q.filePath,this.opts.boundaries);for(let Z of t.getFileSymbols(D,Q.filePath))f.set(`${Z.filePath}::${Z.name}`,H(Z))}let B={added:[],modified:[],removed:[]};for(let[Q,D]of f){let Z=M.get(Q);if(!Z)B.added.push({name:D.name,filePath:D.filePath,kind:D.kind});else if(Z.fingerprint!==D.fingerprint)B.modified.push({name:D.name,filePath:D.filePath,kind:D.kind})}for(let[Q,D]of M)if(!f.has(Q))B.removed.push({name:D.name,filePath:D.filePath,kind:D.kind});let s=au(M,f),b=new Set(s.renamed.map((Q)=>`${Q.filePath}::${Q.oldName}`)),E=new Set(s.renamed.map((Q)=>`${Q.filePath}::${Q.newName}`));B.added=B.added.filter((Q)=>!E.has(`${Q.filePath}::${Q.name}`)),B.removed=B.removed.filter((Q)=>!b.has(`${Q.filePath}::${Q.name}`));let q=[];if(!u){for(let[Q,D]of _)for(let Z of D){if(!Z.fingerprint)continue;let U=P(Q,this.opts.boundaries),R=t.getByFingerprint(U,Z.fingerprint);if(R.length===1){let L=R[0];m.retargetRelations({dstProject:U,oldFile:Q,oldSymbol:Z.name,newFile:L.filePath,newSymbol:L.name}),q.push({name:L.name,filePath:L.filePath,kind:L.kind,oldFilePath:Q})}}for(let Q of s.removed){let Z=M.get(`${Q.filePath}::${Q.name}`)?.fingerprint;if(!Z)continue;let U=P(Q.filePath,this.opts.boundaries),R=t.getByFingerprint(U,Z);if(R.length===1){let L=R[0];if(L.filePath!==Q.filePath||L.name!==Q.name)m.retargetRelations({dstProject:U,oldFile:Q.filePath,oldSymbol:Q.name,newFile:L.filePath,newSymbol:L.name}),q.push({name:L.name,filePath:L.filePath,kind:L.kind,oldFilePath:Q.filePath})}}}if(q.length){let Q=new Set(q.map((Z)=>`${Z.filePath}::${Z.name}`)),D=new Set(q.map((Z)=>`${Z.oldFilePath}::${Z.name}`));B.added=B.added.filter((Z)=>!Q.has(`${Z.filePath}::${Z.name}`)),B.removed=B.removed.filter((Z)=>!D.has(`${Z.filePath}::${Z.name}`))}if(X){let Q=new Date().toISOString(),D=u?1:0,Z=[];for(let U of B.added){let R=`${U.filePath}::${U.name}`,L=f.get(R),gn=P(U.filePath,this.opts.boundaries);Z.push({project:gn,changeType:"added",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:L?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of B.modified){let R=f.get(`${U.filePath}::${U.name}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"modified",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of B.removed){let R=`${U.filePath}::${U.name}`,L=M.get(R),gn=P(U.filePath,this.opts.boundaries);Z.push({project:gn,changeType:"removed",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:L?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of s.renamed){let R=f.get(`${U.filePath}::${U.newName}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"renamed",symbolName:U.newName,symbolKind:U.kind,filePath:U.filePath,oldName:U.oldName,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of q){let R=f.get(`${U.filePath}::${U.name}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"moved",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:U.oldFilePath,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}if(Z.length)try{w.transaction(()=>{X.insertBatch(Z)})}catch(U){this.logger.error("[IndexCoordinator] changelog insert failed:",U)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let U=new Date(Date.now()-2592000000).toISOString();try{for(let R of this.opts.boundaries)X.pruneOlderThan(R.project,U)}catch(R){this.logger.error("[IndexCoordinator] changelog pruning failed:",R)}}}return{indexedFiles:O.length,removedFiles:r.length,totalSymbols:W,totalRelations:Y,totalAnnotations:z,durationMs:Date.now()-i,changedFiles:O.map((Q)=>Q.filePath),deletedFiles:[...r],failedFiles:I,changedSymbols:B}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function qg(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Gg(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function du(n,u,i={}){let g=i.now??Date.now,t=i.isAlive??qg,m=i.staleAfterSeconds??60,w=i.instanceId;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u,w),"owner";let r=Math.floor((g()-Gg(O.heartbeat_at))/1000),S=t(O.pid);if(S&&w&&O.instance_id&&O.instance_id!==w&&O.pid!==u)return n.replaceOwner(u,w),"owner";if(S&&r<m)return"reader";return n.replaceOwner(u,w),"owner"})}function lu(n,u){n.deleteOwner(u)}function ou(n,u){n.touchOwner(u)}class Cn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let i=this.#u.keys().next().value;if(i!==void 0)this.#u.delete(i)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class $u{lru;constructor(n=500){this.lru=new Cn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Ju(n){let{symbolRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??100,w={kind:g.kind,filePath:g.filePath,isExported:g.isExported,project:t,limit:m,resolvedType:g.resolvedType};if(g.text)if(g.exact)w.exactName=g.text;else{let r=Kn(g.text);if(r)w.ftsQuery=r}if(g.decorator)w.decorator=g.decorator;if(g.regex)w.regex=g.regex;return u.searchByQuery(w).map((r)=>({id:r.id,filePath:r.filePath,kind:r.kind,name:r.name,span:{start:{line:r.startLine,column:r.startColumn},end:{line:r.endLine,column:r.endColumn}},isExported:r.isExported===1,signature:r.signature,fingerprint:r.fingerprint,detail:r.detailJson?(()=>{try{return JSON.parse(r.detailJson)}catch{return{}}})():{}}))}function Au(n){let{relationRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??500;return u.searchRelations({srcFilePath:g.srcFilePath,srcSymbolName:g.srcSymbolName,dstFilePath:g.dstFilePath,dstSymbolName:g.dstSymbolName,dstProject:g.dstProject,type:g.type,project:t,limit:m}).map((O)=>{let r;if(O.metaJson)try{r=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,metaJson:O.metaJson??void 0,meta:r}})}import{findInFiles as Eg,Lang as pg}from"@ast-grep/napi";async function Mu(n){if(n.filePaths.length===0)return[];let u=[];return await Eg(pg.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,g)=>{if(i)return;for(let t of g){let m=t.range();u.push({filePath:t.getRoot().filename(),startLine:m.start.line+1,endLine:m.end.line+1,matchedText:t.text()})}}),u}import h from"typescript";import{isErr as gt}from"@zipbul/result";import _n from"typescript";import vg from"path";import{err as Qu}from"@zipbul/result";function Pg(n){try{return Zu("fs").readFileSync(n,"utf-8")}catch{return}}function ag(n){try{return Zu("fs").readFileSync(n,"utf-8")}catch{return}}class Pn{#n;#u;#i=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let i=u.readConfigFile??Pg,g=u.resolveNonTrackedFile??ag,t=vg.dirname(n),m=i(n);if(m===void 0)return Qu(c("semantic",`tsconfig not found: ${n}`));let w=_n.parseJsonText(n,m),O=w.parseDiagnostics;if(O&&O.length>0){let N=O.map((M)=>_n.flattenDiagnosticMessageText(M.messageText,`
8
+ `)).join("; ");return Qu(c("semantic",`tsconfig parse error: ${N}`))}let r=_n.parseJsonSourceFileConfigFileContent(w,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(N)=>i(N)!==void 0||g(N)!==void 0,readFile:(N)=>i(N)??g(N)},t);if(r.errors.length>0){let N=r.errors.filter((M)=>M.category===_n.DiagnosticCategory.Error&&M.code!==18003);if(N.length>0){let M=N.map((f)=>_n.flattenDiagnosticMessageText(f.messageText,`
9
+ `)).join("; ");return Qu(c("semantic",`tsconfig compile error: ${M}`))}}let S=new cu(r.fileNames,r.options,t,g),_=_n.createLanguageService(S);return new Pn(_,S)}get isDisposed(){return this.#i}getProgram(){this.#t();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#t(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#t(),this.#n}notifyFileChanged(n,u){if(this.#i)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#i)return;this.#u.removeFile(n)}dispose(){if(this.#i)return;this.#i=!0,this.#n.dispose()}#t(){if(this.#i)throw Error("TscProgram is disposed")}}class cu{#n;#u;#i;#t;#g=new Map;constructor(n,u,i,g){this.#n=[...n],this.#u=u,this.#i=i,this.#t=g}updateFile(n,u){let i=this.#g.get(n);if(i)i.version+=1,i.content=u;else this.#g.set(n,{version:1,content:u})}removeFile(n){this.#g.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#g.keys()];return[...this.#n.filter((i)=>!this.#g.has(i)),...n]}getScriptVersion(n){let u=this.#g.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#g.get(n);if(u)return _n.ScriptSnapshot.fromString(u.content);let i=this.#t(n);if(i!==void 0)return _n.ScriptSnapshot.fromString(i);return}getCurrentDirectory(){return this.#i}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return _n.getDefaultLibFilePath(n)}fileExists(n){if(this.#g.has(n))return!0;return this.#t(n)!==void 0}readFile(n){let u=this.#g.get(n);if(u)return u.content;return this.#t(n)}}import d from"typescript";import hg from"typescript";function Nn(n,u){if(u<0||u>=n.getEnd())return;function i(g){let t=g.getStart(n,!1),m=g.getEnd();if(u<t||u>=m)return;let w;return hg.forEachChild(g,(O)=>{if(!w)w=i(O)}),w??g}return i(n)}function xg(n){return!!(n.flags&d.TypeFlags.Object)&&!!(n.objectFlags&d.ObjectFlags.Reference)}function Tn(n,u,i=0){let g=n.typeToString(u),t=u.flags,m=!!(t&d.TypeFlags.Union),w=!!(t&d.TypeFlags.Intersection),O;if(i<8&&xg(u)){let N=n.getTypeArguments(u);if(N.length>0)O=N}let r=!!(t&d.TypeFlags.TypeParameter)||O!==void 0&&O.length>0,S;if(m&&i<8)S=u.types.map((N)=>Tn(n,N,i+1));else if(w&&i<8)S=u.types.map((N)=>Tn(n,N,i+1));let _;if(O&&O.length>0)_=O.map((N)=>Tn(n,N,i+1));return{text:g,flags:t,isUnion:m,isIntersection:w,isGeneric:r,members:S,typeArguments:_}}function dg(n){return d.isFunctionDeclaration(n)||d.isVariableDeclaration(n)||d.isClassDeclaration(n)||d.isInterfaceDeclaration(n)||d.isTypeAliasDeclaration(n)||d.isEnumDeclaration(n)||d.isMethodDeclaration(n)||d.isPropertyDeclaration(n)||d.isPropertySignature(n)||d.isMethodSignature(n)}class zu{program;constructor(n){this.program=n}collectAt(n,u){let i=this.program.getProgram(),g=this.program.getChecker();if(u<0)return null;let t=i.getSourceFile(n);if(!t)return null;if(u>=t.getEnd())return null;let m=Nn(t,u);if(!m)return null;if(!d.isIdentifier(m))return null;try{let w=g.getTypeAtLocation(m);return Tn(g,w)}catch{return null}}collectFile(n){let u=new Map,i=this.program.getProgram(),g=this.program.getChecker(),t=i.getSourceFile(n);if(!t)return u;function m(w){if(dg(w)&&w.name&&d.isIdentifier(w.name)){let O=w.name;try{let r=g.getTypeAtLocation(O),S=O.getStart(t);u.set(S,Tn(g,r))}catch{}}d.forEachChild(w,m)}return m(t),u}}import An from"typescript";var lg=1000,og=1;function cg(n){let u=n.declarations?.[0],i=u?.getSourceFile(),g=u?An.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:i?.fileName??"",position:g?.getStart(i,!1)??u?.getStart(i,!1)??0}}function an(n,u=0){let i=n.declarations?.[0],g=i?.getSourceFile(),t=i?An.getNameOfDeclaration(i):void 0,m=g?.fileName??"",w=t?.getStart(g,!1)??i?.getStart(g,!1)??0,O={name:n.getName(),filePath:m,position:w},r=n;if(r.parent)O.parent=cg(r.parent);if(u<og){let S=n.flags,_=!!(S&An.SymbolFlags.Enum),N=!!(S&(An.SymbolFlags.NamespaceModule|An.SymbolFlags.ValueModule)),M=!!(S&(An.SymbolFlags.Class|An.SymbolFlags.Interface));if(_&&n.exports&&n.exports.size>0){let f=[];n.exports.forEach((H)=>{f.push(an(H,u+1))}),O.members=f}else if(M&&n.members&&n.members.size>0){let f=[];n.members.forEach((H)=>{f.push(an(H,u+1))}),O.members=f}if(N&&n.exports&&n.exports.size>0){let f=[];n.exports.forEach((H)=>{f.push(an(H,u+1))}),O.exports=f}}return O}class fu{#n;#u;#i=new Map;constructor(n,u=lg){this.#n=n,this.#u=new Cn(u)}get(n,u){if(this.#n.isDisposed)return null;let i=`${n}:${u}`,g=this.#u.get(i);if(g!==void 0)return g;let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let w=Nn(m,u);if(!w||!An.isIdentifier(w))return null;let r=this.#n.getChecker().getSymbolAtLocation(w);if(!r)return null;let S=an(r);this.#u.set(i,S);let _=this.#i.get(n);if(!_)_=new Set,this.#i.set(n,_);return _.add(i),S}invalidate(n){let u=this.#i.get(n);if(u){for(let i of u)this.#u.delete(i);this.#i.delete(n)}}clear(){this.#u.clear(),this.#i.clear()}}import eg from"typescript";class Du{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),g=i.getSourceFile(n);if(!g)return[];let t=Nn(g,u);if(!t||!eg.isIdentifier(t))return[];let w=this.#n.getLanguageService().findReferences(n,u);if(!w||w.length===0)return[];let O=[];for(let r of w)for(let S of r.references){let _=i.getSourceFile(S.fileName);if(!_)continue;let{line:N,character:M}=_.getLineAndCharacterOfPosition(S.textSpan.start);O.push({filePath:S.fileName,position:S.textSpan.start,line:N+1,column:M,isDefinition:S.isDefinition??!1,isWrite:S.isWriteAccess??!1})}return O}}import j from"typescript";function nt(n,u){let i=Nn(n,u);if(!i)return;if(eu(i))return i;let g=i.parent;for(let t=0;t<5&&g;t++){if(eu(g))return g;g=g.parent}return i}function eu(n){return j.isClassDeclaration(n)||j.isClassExpression(n)||j.isFunctionDeclaration(n)||j.isFunctionExpression(n)||j.isArrowFunction(n)||j.isVariableDeclaration(n)||j.isObjectLiteralExpression(n)}function ni(n){if(j.isClassDeclaration(n)||j.isClassExpression(n))return"class";if(j.isFunctionDeclaration(n)||j.isFunctionExpression(n)||j.isArrowFunction(n))return"function";if(j.isObjectLiteralExpression(n))return"object";if(j.isVariableDeclaration(n)&&n.initializer)return ni(n.initializer);return"class"}function ut(n,u){if(j.isClassDeclaration(n)||j.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(j.isClassExpression(n))return n.name?.getText(u)??"";if(j.isVariableDeclaration(n)&&j.isIdentifier(n.name))return n.name.getText(u);if(j.isFunctionExpression(n))return n.name?.getText(u)??"";if(j.isArrowFunction(n)&&n.parent&&j.isVariableDeclaration(n.parent)){if(j.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(j.isObjectLiteralExpression(n)&&n.parent&&j.isVariableDeclaration(n.parent)){if(j.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function it(n){if(!j.isClassDeclaration(n)&&!j.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((i)=>i.token===j.SyntaxKind.ImplementsKeyword)}class Ku{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),g=i.getSourceFile(n);if(!g)return[];let t=Nn(g,u);if(!t||!j.isIdentifier(t))return[];let w=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!w||w.length===0)return[];let O=[];for(let r of w){if(r.kind===j.ScriptElementKind.interfaceElement||r.kind===j.ScriptElementKind.typeElement)continue;let S=i.getSourceFile(r.fileName);if(!S)continue;let _=nt(S,r.textSpan.start);if(!_)continue;let N=ni(_),M=ut(_,S),f=it(_);O.push({filePath:r.fileName,symbolName:M,position:r.textSpan.start,kind:N,isExplicit:f})}return O}}function ui(n){return h.canHaveModifiers(n)&&h.getModifiers(n)?.some((u)=>u.kind===h.SyntaxKind.ExportKeyword)===!0}function tt(n){if(h.isFunctionDeclaration(n))return"function";if(h.isClassDeclaration(n))return"class";if(h.isInterfaceDeclaration(n))return"interface";if(h.isTypeAliasDeclaration(n))return"type";if(h.isEnumDeclaration(n))return"enum";if(h.isVariableDeclaration(n))return"const";if(h.isVariableStatement(n))return"const";return"unknown"}function ii(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class hn{#n;#u;#i;#t;#g;#r=!1;constructor(n,u,i,g,t){this.#n=n,this.#u=u,this.#i=i,this.#t=g,this.#g=t}static create(n,u={}){let i=Pn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(gt(i))return i;let g=i,t=u.typeCollector??new zu(g),m=u.symbolGraph??new fu(g),w=u.referenceResolver??new Du(g),O=u.implementationFinder??new Ku(g);return new hn(g,t,m,w,O)}get isDisposed(){return this.#r}collectTypeAt(n,u){return this.#m(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#m(),this.#u.collectFile(n)}findReferences(n,u){return this.#m(),this.#t.findAt(n,u)}findImplementations(n,u){return this.#m(),this.#g.findAt(n,u)}getSymbolNode(n,u){return this.#m(),this.#i.get(n,u)}getModuleInterface(n){this.#m();let u=this.#u.collectFile(n),i=[],t=this.#n.getProgram().getSourceFile(n);if(!t)return{filePath:n,exports:i};function m(w){if(h.isVariableStatement(w)&&ui(w)){for(let O of w.declarationList.declarations)if(h.isIdentifier(O.name)){let r=O.name.getStart(t),S=u.get(r)??null;i.push({name:O.name.text,kind:"const",resolvedType:S})}return}if((h.isFunctionDeclaration(w)||h.isClassDeclaration(w)||h.isInterfaceDeclaration(w)||h.isTypeAliasDeclaration(w)||h.isEnumDeclaration(w))&&ui(w)&&w.name){let O=w.name,r=O.getStart(t),S=u.get(r)??null;i.push({name:O.text,kind:tt(w),resolvedType:S});return}h.forEachChild(w,m)}return m(t),{filePath:n,exports:i}}notifyFileChanged(n,u){if(this.#r)return;this.#n.notifyFileChanged(n,u),this.#i.invalidate(n)}notifyFileDeleted(n){if(this.#r)return;this.#n.removeFile(n),this.#i.invalidate(n)}lineColumnToPosition(n,u,i){this.#m();let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;try{return h.getPositionOfLineAndCharacter(g,u-1,i)}catch{return null}}findNamePosition(n,u,i){this.#m();let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;let t=g.getFullText(),m=u;while(m<t.length){let w=t.indexOf(i,m);if(w<0)return null;let O=w>0?t.charCodeAt(w-1):32,r=w+i.length<t.length?t.charCodeAt(w+i.length):32;if(!ii(O)&&!ii(r))return w;m=w+1}return null}dispose(){if(this.#r)return;this.#r=!0,this.#n.dispose(),this.#i.clear()}#m(){if(this.#r)throw Error("SemanticLayer is disposed")}}import{eq as fn,and as gi,sql as rt}from"drizzle-orm";class Vu{db;constructor(n){this.db=n}insertBatch(n,u,i){for(let g of i)this.db.drizzleDb.insert(un).values({project:n,filePath:u,tag:g.tag,value:g.value,source:g.source,symbolName:g.symbolName,startLine:g.startLine,startColumn:g.startColumn,endLine:g.endLine,endColumn:g.endColumn,indexedAt:g.indexedAt}).run()}deleteFileAnnotations(n,u){this.db.drizzleDb.delete(un).where(gi(fn(un.project,n),fn(un.filePath,u))).run()}search(n){return this.db.drizzleDb.select().from(un).where(gi(n.project?fn(un.project,n.project):void 0,n.tag?fn(un.tag,n.tag):void 0,n.filePath?fn(un.filePath,n.filePath):void 0,n.symbolName?fn(un.symbolName,n.symbolName):void 0,n.source?fn(un.source,n.source):void 0,n.ftsQuery?rt`${un.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${n.ftsQuery})`:void 0)).limit(n.limit).all()}}import{eq as Un,and as ti,sql as Ln,gt as mt,gte as Ot}from"drizzle-orm";class Wu{db;constructor(n){this.db=n}insertBatch(n){for(let u of n)this.db.drizzleDb.insert(e).values({project:u.project,changeType:u.changeType,symbolName:u.symbolName,symbolKind:u.symbolKind,filePath:u.filePath,oldName:u.oldName,oldFilePath:u.oldFilePath,fingerprint:u.fingerprint,changedAt:u.changedAt,isFullIndex:u.isFullIndex,indexRunId:u.indexRunId}).run()}getSince(n){return this.db.drizzleDb.select().from(e).where(ti(Un(e.project,n.project),Ot(e.changedAt,n.since),n.symbolName?Un(e.symbolName,n.symbolName):void 0,n.changeTypes?.length?Ln`${e.changeType} IN (${Ln.join(n.changeTypes.map((u)=>Ln`${u}`),Ln`, `)})`:void 0,n.filePath?Un(e.filePath,n.filePath):void 0,n.includeFullIndex?void 0:Un(e.isFullIndex,0),n.indexRunId?Un(e.indexRunId,n.indexRunId):void 0,n.afterId?mt(e.id,n.afterId):void 0)).orderBy(e.id).limit(n.limit).all()}pruneOlderThan(n,u){return this.db.drizzleDb.delete(e).where(ti(Un(e.project,n),Ln`${e.changedAt} < ${u}`)).run().changes}}function ri(n){let{annotationRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??100,w;if(g.text)w=Kn(g.text)??void 0;return u.search({project:t,tag:g.tag,filePath:g.filePath,symbolName:g.symbolName,source:g.source,ftsQuery:w,limit:m}).map((r)=>({tag:r.tag,value:r.value,source:r.source,filePath:r.filePath,symbolName:r.symbolName,span:{start:{line:r.startLine,column:r.startColumn},end:{line:r.endLine,column:r.endColumn}}}))}class xn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((i)=>[...this.options.relationRepo.getByType(i,"imports"),...this.options.relationRepo.getByType(i,"type-references"),...this.options.relationRepo.getByType(i,"re-exports")]);for(let i of u){let{srcFilePath:g,dstFilePath:t}=i;if(!this.adjacencyList.has(g))this.adjacencyList.set(g,new Set);if(this.adjacencyList.get(g).add(t),!this.adjacencyList.has(t))this.adjacencyList.set(t,new Set);if(!this.reverseAdjacencyList.has(t))this.reverseAdjacencyList.set(t,new Set);this.reverseAdjacencyList.get(t).add(g)}}patchFiles(n,u,i){let g=new Set([...n,...u]);for(let t of g){let m=this.adjacencyList.get(t);if(m){for(let O of m)this.reverseAdjacencyList.get(O)?.delete(t);m.clear()}let w=this.reverseAdjacencyList.get(t);if(w){for(let O of w)this.adjacencyList.get(O)?.delete(t);w.clear()}}for(let t of u)this.adjacencyList.delete(t),this.reverseAdjacencyList.delete(t);for(let t of n){let m=i(t);for(let w of m){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(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,i=[n];while(i.length>0){let g=i.shift();for(let t of this.reverseAdjacencyList.get(g)??[])if(!u.has(t))u.add(t),i.push(t)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let g=[{node:i,entered:!1}];while(g.length>0){let t=g.pop();if(t.entered){u.delete(t.node);continue}if(u.has(t.node))return!0;if(n.has(t.node))continue;n.add(t.node),u.add(t.node),g.push({node:t.node,entered:!0});for(let m of this.adjacencyList.get(t.node)??[]){if(u.has(m))return!0;if(!n.has(m))g.push({node:m,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let i of n)for(let g of this.getTransitiveDependents(i))u.add(g);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,i]of this.adjacencyList)n.set(u,Array.from(i));return n}getTransitiveDependencies(n){let u=new Set,i=[n];while(i.length>0){let g=i.shift();for(let t of this.adjacencyList.get(g)??[])if(!u.has(t))u.add(t),i.push(t)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let i=new Map;for(let[g,t]of this.adjacencyList)i.set(g,Array.from(t));return $t(i,u)}}var wt=(n,u)=>n.localeCompare(u);function _t(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let i=u;for(let g=1;g<u.length;g++){let t=u.slice(g).concat(u.slice(0,g));if(t.join("::")<i.join("::"))i=t}return[...i]}function Hu(n,u,i){let g=_t(i);if(g.length===0)return!1;let t=g.join("->");if(n.has(t))return!1;return n.add(t),u.push(g),!0}function Nt(n){let u=0,i=[],g=new Set,t=new Map,m=new Map,w=[],O=(r)=>{t.set(r,u),m.set(r,u),u+=1,i.push(r),g.add(r);for(let S of n.get(r)??[])if(!t.has(S))O(S),m.set(r,Math.min(m.get(r)??0,m.get(S)??0));else if(g.has(S))m.set(r,Math.min(m.get(r)??0,t.get(S)??0));if(m.get(r)===t.get(r)){let S=[],_="";do _=i.pop()??"",g.delete(_),S.push(_);while(_!==r&&i.length>0);w.push(S)}};for(let r of n.keys())if(!t.has(r))O(r);return{components:w}}function St(n,u,i){let g=[],t=new Set,m=[...n].sort(wt),w=(O,r,S)=>{r.delete(O);let _=S.get(O);if(!_)return;for(let N of _)if(r.has(N))w(N,r,S);_.clear()};for(let O=0;O<m.length&&g.length<i;O++){let r=m[O]??"",S=new Set(m.slice(O)),_=new Set,N=new Map,M=[],f=(K)=>(u.get(K)??[]).filter((X)=>S.has(X)),H=(K)=>{if(g.length>=i)return!0;let X=!1;M.push(K),_.add(K);for(let A of f(K)){if(g.length>=i)break;if(A===r)Hu(t,g,M.concat(r)),X=!0;else if(!_.has(A)){if(H(A))X=!0}}if(X)w(K,_,N);else for(let A of f(K)){let z=N.get(A)??new Set;z.add(K),N.set(A,z)}return M.pop(),X};H(r)}return g}function $t(n,u){let{components:i}=Nt(n),g=[],t=new Set;for(let m of i){if(g.length>=u)break;if(m.length===0)continue;if(m.length===1){let r=m[0]??"";if((n.get(r)??[]).includes(r))Hu(t,g,[r,r]);continue}let w=u-g.length,O=St(m,n,w);for(let r of O){if(g.length>=u)break;Hu(t,g,r)}}return g}var Jt=15000;function dn(n){n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}function Yn(n,u){let i=u??"__cross__";if(n.graphCache&&n.graphCacheBuiltAt!==null){if(Date.now()-n.graphCacheBuiltAt>Jt)n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}if(n.graphCache&&n.graphCacheKey===i)return n.graphCache;let g=new xn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((t)=>t.project)});return g.build(),n.graphCache=g,n.graphCacheKey=i,n.graphCacheBuiltAt=Date.now(),g}function mi(n,u,i,g=1e4){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,type:"imports",project:i??n.defaultProject,limit:g}}).map((t)=>t.dstFilePath)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getDependencies failed",{cause:t})}}function Oi(n,u,i,g=1e4){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{dstFilePath:u,type:"imports",project:i??n.defaultProject,limit:g}}).map((t)=>t.srcFilePath)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getDependents failed",{cause:t})}}async function wi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,i).getAffectedByChange(u)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getAffected failed",{cause:g})}}async function _i(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).hasCycle()}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: hasCycle failed",{cause:i})}}async function Ni(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).getAdjacencyList()}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: getImportGraph failed",{cause:i})}}async function Si(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,i).getTransitiveDependencies(u)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getTransitiveDependencies failed",{cause:g})}}async function $i(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).getCyclePaths(i)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getCyclePaths failed",{cause:g})}}async function Ji(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=Yn(n,i);return{filePath:u,fanIn:g.getDependents(u).length,fanOut:g.getDependencies(u).length}}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getFanMetrics failed",{cause:g})}}var Qt=30000,Ai=15000,zt=10;function ft(n,u){return(i)=>{for(let g of n.onFileChangedCallbacks)try{g(i)}catch(t){n.logger.error("[Gildash] onFileChanged callback threw:",t)}if(u.handleWatcherEvent?.(i),n.semanticLayer)if(i.eventType==="delete")try{n.semanticLayer.notifyFileDeleted(i.filePath)}catch(g){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",g);for(let t of n.onErrorCallbacks)try{t(g instanceof $?g:new $("semantic","semantic notifyFileDeleted failed",{cause:g}))}catch{}}else n.readFileFn(i.filePath).then((g)=>{try{n.semanticLayer?.notifyFileChanged(i.filePath,g)}catch(t){n.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",t);for(let m of n.onErrorCallbacks)try{m(t instanceof $?t:new $("semantic","semantic notifyFileChanged failed",{cause:t}))}catch{}}}).catch((g)=>{n.logger.error("[Gildash] failed to read file for semantic layer",i.filePath,g);try{n.semanticLayer?.notifyFileDeleted(i.filePath)}catch(t){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",t)}})}}async function Dt(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(i)=>{try{let g=yn.resolve(n.projectRoot,i.filePath),t=await n.readFileFn(g);n.semanticLayer?.notifyFileChanged(g,t)}catch{}}))}async function Mi(n,u){let i=n.coordinatorFactory?n.coordinatorFactory():new Su({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,annotationRepo:n.annotationRepo??void 0,changelogRepo:n.changelogRepo??void 0,logger:n.logger});n.coordinator=i;for(let g of n.onIndexedCallbacks)i.onIndexed(g);if(i.onIndexed((g)=>{let t=g.changedFiles.length+g.deletedFiles.length;if(n.graphCache&&t>0&&t<100){let m=n.relationRepo;n.graphCache.patchFiles(g.changedFiles,g.deletedFiles,(w)=>{return[n.defaultProject,...n.boundaries.map((r)=>r.project)].flatMap((r)=>m.getByType(r,"imports").concat(m.getByType(r,"type-references")).concat(m.getByType(r,"re-exports"))).filter((r)=>r.srcFilePath===w||r.dstFilePath===w).map((r)=>({srcFilePath:r.srcFilePath,dstFilePath:r.dstFilePath}))}),n.graphCacheBuiltAt=Date.now()}else dn(n)}),u.isWatchMode){let g=n.watcherFactory?n.watcherFactory():new gu({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await g.start(ft(n,i)).then((t)=>{if(kn(t))throw t.data}),n.watcher=g,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Qt)}await i.fullIndex(),await Dt(n)}function Kt(n,u){let i=["SIGTERM","SIGINT","beforeExit"];for(let g of i){let t=()=>{u().catch((m)=>n.logger.error("[Gildash] close error during signal",g,m))};if(g==="beforeExit")process.on("beforeExit",t);else process.on(g,t);n.signalHandlers.push([g,t])}}async function Qi(n){let{projectRoot:u,extensions:i=[".ts",".mts",".cts"],ignorePatterns:g=["**/node_modules/**"],parseCacheCapacity:t=500,logger:m=console,existsSyncFn:w=Mt,dbConnectionFactory:O,watcherFactory:r,coordinatorFactory:S,repositoryFactory:_,acquireWatcherRoleFn:N=du,releaseWatcherRoleFn:M=lu,updateHeartbeatFn:f=ou,discoverProjectsFn:H=jn,parseSourceFn:K=Bn,extractSymbolsFn:X=Wn,extractRelationsFn:A=pn,symbolSearchFn:z=Ju,relationSearchFn:J=Au,patternSearchFn:W=Mu,loadTsconfigPathsFn:Y=Xn,readFileFn:I=async(D)=>Bun.file(D).text(),unlinkFn:B=async(D)=>{await Bun.file(D).unlink()},watchMode:s,semantic:b,semanticLayerFactory:E}=n;if(!yn.isAbsolute(u))throw new $("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!w(u))throw new $("validation",`Gildash: projectRoot does not exist: "${u}"`);let q=O?O():new cn({projectRoot:u}),Q=q.open();if(kn(Q))throw Q.data;try{let D=await H(u),Z=D[0]?.project??yn.basename(u),U=_?_():(()=>{let l=q;return{fileRepo:new en(l),symbolRepo:new nu(l),relationRepo:new uu(l),parseCache:new $u(t)}})(),R=_?null:q,L=R?new Vu(R):null,gn=R?new Wu(R):null,k=s??!0,G=crypto.randomUUID(),F;if(k)F=await Promise.resolve(N(q,process.pid,{instanceId:G}));else F="owner";let C={projectRoot:u,extensions:i,ignorePatterns:g,logger:m,defaultProject:Z,role:F,db:q,symbolRepo:U.symbolRepo,relationRepo:U.relationRepo,fileRepo:U.fileRepo,parseCache:U.parseCache,annotationRepo:L,changelogRepo:gn,annotationSearchFn:ri,releaseWatcherRoleFn:M,parseSourceFn:K,extractSymbolsFn:X,extractRelationsFn:A,symbolSearchFn:z,relationSearchFn:J,patternSearchFn:W,readFileFn:I,unlinkFn:B,existsSyncFn:w,acquireWatcherRoleFn:N,updateHeartbeatFn:f,watcherFactory:r,coordinatorFactory:S,instanceId:G,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:D,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(bn(u),C.tsconfigPaths=await Y(u),b){let l=yn.join(u,"tsconfig.json");try{if(E)C.semanticLayer=E(l);else{let o=hn.create(l);if(kn(o))throw o.data;C.semanticLayer=o}}catch(o){if(o instanceof $)throw o;throw new $("semantic","Gildash: semantic layer creation failed",{cause:o})}}if(F==="owner")await Mi(C,{isWatchMode:k});else{let l=0,o=async()=>{try{let On=await Promise.resolve(C.acquireWatcherRoleFn(C.db,process.pid,{instanceId:C.instanceId}));if(l=0,On==="owner"){for(let Sn of C.onRoleChangedCallbacks)try{Sn("owner")}catch(tn){C.logger.error("[Gildash] onRoleChanged callback threw:",tn)}clearInterval(C.timer),C.timer=null;try{await Mi(C,{isWatchMode:!0})}catch(Sn){if(C.logger.error("[Gildash] owner promotion failed, reverting to reader",Sn),C.watcher){let tn=await C.watcher.close();if(kn(tn))C.logger.error("[Gildash] watcher close error during promotion rollback",tn.data);C.watcher=null}if(C.coordinator)await C.coordinator.shutdown().catch((tn)=>C.logger.error("[Gildash] coordinator shutdown error during promotion rollback",tn)),C.coordinator=null;if(C.timer===null)C.timer=setInterval(o,Ai)}}}catch(On){l++;let Sn=On instanceof $?On:new $("watcher","Gildash: healthcheck error",{cause:On});for(let tn of C.onErrorCallbacks)try{tn(Sn)}catch(In){C.logger.error("[Gildash] onError callback threw:",In)}if(C.logger.error("[Gildash] healthcheck error",On),l>=zt)C.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(C.timer),C.timer=null,ln(C).catch((tn)=>C.logger.error("[Gildash] close error during healthcheck shutdown",tn))}};C.timer=setInterval(o,Ai)}if(k)Kt(C,()=>ln(C));return C}catch(D){if(q.close(),D instanceof $)throw D;throw new $("store","Gildash: initialization failed",{cause:D})}}async function ln(n,u){if(n.closed)return;n.closed=!0;let i=[];for(let[g,t]of n.signalHandlers)if(g==="beforeExit")process.off("beforeExit",t);else process.off(g,t);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}if(n.watcher){let g=await n.watcher.close();if(kn(g))i.push(g.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(g){i.push(g instanceof Error?g:Error(String(g)))}try{n.db.close()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}if(u?.cleanup)for(let g of["","-wal","-shm"])try{await n.unlinkFn(yn.join(n.projectRoot,$n,Rn+g))}catch{}if(i.length>0)throw new $("close","Gildash: one or more errors occurred during close()",{cause:i})}import{isErr as zi}from"@zipbul/result";function fi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");let t=n.parseSourceFn(u,i,g);if(zi(t))throw t.data;return n.parseCache.set(u,t),t}async function Di(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");let g=new Map,t=[];return await Promise.all(u.map(async(m)=>{try{let w=await n.readFileFn(m),O=n.parseSourceFn(m,w,i);if(!zi(O))g.set(m,O);else t.push({filePath:m,error:O.data})}catch(w){t.push({filePath:m,error:w instanceof Error?w:Error(String(w))})}})),{parsed:g,failures:t}}function Ki(n,u){if(n.closed)return;return n.parseCache.get(u)}function Vi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function Wi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import Hi from"path";function Ui(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(i){if(i instanceof $)throw i;throw new $("store","Gildash: getStats failed",{cause:i})}}function Uu(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchSymbols failed",{cause:i})}}function Yi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchRelations failed",{cause:i})}}function Ii(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchAllSymbols failed",{cause:i})}}function Zi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchAllRelations failed",{cause:i})}}function Xi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(i){if(i instanceof $)throw i;throw new $("store","Gildash: listIndexedFiles failed",{cause:i})}}function Bi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getInternalRelations failed",{cause:g})}}function Ci(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=g??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t,query:{text:u,exact:!0,filePath:i,limit:1}});if(m.length===0)return null;let w=m[0],O=w.detail,r={...w,members:Array.isArray(O.members)?O.members:void 0,jsDoc:typeof O.jsDoc==="string"?O.jsDoc:void 0,parameters:typeof O.parameters==="string"?O.parameters:void 0,returnType:typeof O.returnType==="string"?O.returnType:void 0,heritage:Array.isArray(O.heritage)?O.heritage:void 0,decorators:Array.isArray(O.decorators)?O.decorators:void 0,typeParameters:typeof O.typeParameters==="string"?O.typeParameters:void 0};if(n.semanticLayer)try{let S=Hi.isAbsolute(i)?i:Hi.resolve(n.projectRoot,i),_=n.semanticLayer.lineColumnToPosition(S,w.span.start.line,w.span.start.column);if(_!==null){let N=n.semanticLayer.findNamePosition(S,_,w.name)??_,M=n.semanticLayer.collectTypeAt(S,N);if(M)r.resolvedType=M}}catch{}return r}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getFullSymbol failed",{cause:t})}}function Ti(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,t=n.fileRepo.getFile(g,u);if(!t)throw new $("search",`Gildash: file '${u}' is not in the index`);let m=n.symbolRepo.getFileSymbols(g,u),w=n.relationRepo.getOutgoing(g,u);return{filePath:t.filePath,lineCount:t.lineCount??0,size:t.size,symbolCount:m.length,exportedSymbolCount:m.filter((O)=>O.isExported).length,relationCount:w.length}}catch(g){if(g instanceof $)throw g;throw new $("store","Gildash: getFileStats failed",{cause:g})}}function Li(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(i??n.defaultProject,u)}catch(g){if(g instanceof $)throw g;throw new $("store","Gildash: getFileInfo failed",{cause:g})}}function ki(n,u,i){return Uu(n,{filePath:u,project:i??void 0,limit:1e4})}function yi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i??n.defaultProject,query:{filePath:u,isExported:!0}}).map((m)=>({name:m.name,kind:m.kind,parameters:m.detail.parameters??void 0,returnType:m.detail.returnType??void 0,jsDoc:m.detail.jsDoc??void 0}));return{filePath:u,exports:t}}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getModuleInterface failed",{cause:g})}}import Ri from"path";function Yu(n,u,i,g){let t=g??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t,query:{text:u,exact:!0,filePath:i,limit:1}});if(m.length===0)return null;let w=m[0],O=Ri.isAbsolute(i)?i:Ri.resolve(n.projectRoot,i),r=n.semanticLayer.lineColumnToPosition(O,w.span.start.line,w.span.start.column);if(r===null)return null;let S=n.semanticLayer.findNamePosition(O,r,w.name)??r;return{sym:w,position:S,absPath:O}}function Fi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)return null;return n.semanticLayer.collectTypeAt(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getResolvedType failed",{cause:t})}}function si(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)throw new $("search",`Gildash: symbol '${u}' not found in '${i}'`);return n.semanticLayer.findReferences(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getSemanticReferences failed",{cause:t})}}function ji(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)throw new $("search",`Gildash: symbol '${u}' not found in '${i}'`);return n.semanticLayer.findImplementations(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getImplementations failed",{cause:t})}}function bi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: getSemanticModuleInterface failed",{cause:i})}}function qi(n,u){let i=new Map(n.map((O)=>[`${O.name}::${O.filePath}`,O])),g=new Map(u.map((O)=>[`${O.name}::${O.filePath}`,O])),t=[],m=[],w=[];for(let[O,r]of g){let S=i.get(O);if(!S)t.push(r);else if(S.fingerprint!==r.fingerprint)w.push({before:S,after:r})}for(let[O,r]of i)if(!g.has(O))m.push(r);return{added:t,removed:m,modified:w}}function Gi(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let i=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),i()}}async function Ei(n){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.coordinator)throw new $("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return dn(n),u}catch(u){if(u instanceof $)throw u;throw new $("index","Gildash: reindex failed",{cause:u})}}function pi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");let t=g??n.defaultProject,m=new Set,w=[],O=u,r=i;for(;;){let S=`${r}::${O}`;if(m.has(S))return{originalName:O,originalFilePath:r,reExportChain:w,circular:!0};m.add(S);let _=n.relationSearchFn({relationRepo:n.relationRepo,project:t,query:{type:"re-exports",srcFilePath:r,limit:500}}),N,M;for(let f of _){let H;if(f.metaJson)try{let X=JSON.parse(f.metaJson);if(Array.isArray(X.specifiers))H=X.specifiers}catch{}if(!H)continue;let K=H.find((X)=>X.exported===O);if(!K)continue;N=f.dstFilePath,M=K.local;break}if(!N||!M)return{originalName:O,originalFilePath:r,reExportChain:w,circular:!1};w.push({filePath:r,exportedAs:O}),r=N,O=M}}function vi(n,u){return n.onFileChangedCallbacks.add(u),()=>{n.onFileChangedCallbacks.delete(u)}}function Pi(n,u){return n.onErrorCallbacks.add(u),()=>{n.onErrorCallbacks.delete(u)}}function ai(n,u){return n.onRoleChangedCallbacks.add(u),()=>{n.onRoleChangedCallbacks.delete(u)}}async function hi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=i?.project??n.defaultProject,t=i?.filePaths?i.filePaths:n.fileRepo.getAllFiles(g).map((m)=>m.filePath);return await n.patternSearchFn({pattern:u,filePaths:t})}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: findPattern failed",{cause:g})}}async function xi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=g??n.defaultProject,m=new Set,w=(O,r,S)=>{let _=`${O}::${r}`;if(m.has(_))return{symbolName:O,filePath:r,kind:S,children:[]};m.add(_);let f=n.relationSearchFn({relationRepo:n.relationRepo,project:t,query:{srcFilePath:r,srcSymbolName:O,limit:1000}}).filter((H)=>H.type==="extends"||H.type==="implements").filter((H)=>H.dstSymbolName!=null).map((H)=>w(H.dstSymbolName,H.dstFilePath,H.type));return{symbolName:O,filePath:r,kind:S,children:f}};return w(u,i)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getHeritageChain failed",{cause:t})}}function di(n,u){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.annotationRepo||!n.annotationSearchFn)return[];return n.annotationSearchFn({annotationRepo:n.annotationRepo,project:u.project??n.defaultProject,query:u})}function li(n,u,i){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.changelogRepo)return[];let g=u instanceof Date?u.toISOString():u,t=i?.project??n.defaultProject,m=i?.limit??1000;return n.changelogRepo.getSince({project:t,since:g,symbolName:i?.symbolName,changeTypes:i?.changeTypes,filePath:i?.filePath,includeFullIndex:i?.includeFullIndex,indexRunId:i?.indexRunId,afterId:i?.afterId,limit:m}).map((O)=>({changeType:O.changeType,symbolName:O.symbolName,symbolKind:O.symbolKind,filePath:O.filePath,oldName:O.oldName,oldFilePath:O.oldFilePath,fingerprint:O.fingerprint,changedAt:O.changedAt,isFullIndex:O.isFullIndex===1,indexRunId:O.indexRunId}))}function oi(n,u){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.changelogRepo)return 0;let i=u instanceof Date?u.toISOString():u,g=0,t=[n.defaultProject,...n.boundaries.map((w)=>w.project)],m=[...new Set(t)];for(let w of m)g+=n.changelogRepo.pruneOlderThan(w,i);return g}class Iu{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await Qi(n);return new Iu(u)}async close(n){return ln(this._ctx,n)}parseSource(n,u,i){return fi(this._ctx,n,u,i)}async batchParse(n,u){return Di(this._ctx,n,u)}getParsedAst(n){return Ki(this._ctx,n)}extractSymbols(n){return Vi(this._ctx,n)}extractRelations(n){return Wi(this._ctx,n)}getStats(n){return Ui(this._ctx,n)}searchSymbols(n){return Uu(this._ctx,n)}searchRelations(n){return Yi(this._ctx,n)}searchAllSymbols(n){return Ii(this._ctx,n)}searchAllRelations(n){return Zi(this._ctx,n)}listIndexedFiles(n){return Xi(this._ctx,n)}getInternalRelations(n,u){return Bi(this._ctx,n,u)}getFullSymbol(n,u,i){return Ci(this._ctx,n,u,i)}getFileStats(n,u){return Ti(this._ctx,n,u)}getFileInfo(n,u){return Li(this._ctx,n,u)}getSymbolsByFile(n,u){return ki(this._ctx,n,u)}getModuleInterface(n,u){return yi(this._ctx,n,u)}getDependencies(n,u,i=1e4){return mi(this._ctx,n,u,i)}getDependents(n,u,i=1e4){return Oi(this._ctx,n,u,i)}async getAffected(n,u){return wi(this._ctx,n,u)}async hasCycle(n){return _i(this._ctx,n)}async getImportGraph(n){return Ni(this._ctx,n)}async getTransitiveDependencies(n,u){return Si(this._ctx,n,u)}async getCyclePaths(n,u){return $i(this._ctx,n,u)}async getFanMetrics(n,u){return Ji(this._ctx,n,u)}getResolvedType(n,u,i){return Fi(this._ctx,n,u,i)}getSemanticReferences(n,u,i){return si(this._ctx,n,u,i)}getImplementations(n,u,i){return ji(this._ctx,n,u,i)}getSemanticModuleInterface(n){return bi(this._ctx,n)}diffSymbols(n,u){return qi(n,u)}onIndexed(n){return Gi(this._ctx,n)}async reindex(){return Ei(this._ctx)}resolveSymbol(n,u,i){return pi(this._ctx,n,u,i)}async findPattern(n,u){return hi(this._ctx,n,u)}async getHeritageChain(n,u,i){return xi(this._ctx,n,u,i)}onFileChanged(n){return vi(this._ctx,n)}onError(n){return Pi(this._ctx,n)}onRoleChanged(n){return ai(this._ctx,n)}searchAnnotations(n){return di(this._ctx,n)}getSymbolChanges(n,u){return li(this._ctx,n,u)}pruneChangelog(n){return oi(this._ctx,n)}}export{Ju as symbolSearch,Au as relationSearch,Mu as patternSearch,c as gildashError,$ as GildashError,Iu as Gildash,xn as DependencyGraph};
@@ -0,0 +1,36 @@
1
+ CREATE TABLE `annotations` (
2
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
3
+ `project` text NOT NULL,
4
+ `file_path` text NOT NULL,
5
+ `tag` text NOT NULL,
6
+ `value` text NOT NULL DEFAULT '',
7
+ `source` text NOT NULL,
8
+ `symbol_name` text,
9
+ `start_line` integer NOT NULL,
10
+ `start_column` integer NOT NULL,
11
+ `end_line` integer NOT NULL,
12
+ `end_column` integer NOT NULL,
13
+ `indexed_at` text NOT NULL,
14
+ FOREIGN KEY (`project`, `file_path`) REFERENCES `files`(`project`, `file_path`) ON DELETE CASCADE
15
+ );
16
+ --> statement-breakpoint
17
+ CREATE INDEX `idx_annotations_project_file` ON `annotations`(`project`, `file_path`);
18
+ --> statement-breakpoint
19
+ CREATE INDEX `idx_annotations_project_tag` ON `annotations`(`project`, `tag`);
20
+ --> statement-breakpoint
21
+ CREATE INDEX `idx_annotations_project_symbol` ON `annotations`(`project`, `symbol_name`);
22
+ --> statement-breakpoint
23
+ CREATE VIRTUAL TABLE `annotations_fts` USING fts5(`tag`, `value`, content=`annotations`, content_rowid=`id`);
24
+ --> statement-breakpoint
25
+ CREATE TRIGGER `annotations_ai` AFTER INSERT ON `annotations` BEGIN
26
+ INSERT INTO `annotations_fts`(`rowid`, `tag`, `value`) VALUES (new.`id`, new.`tag`, new.`value`);
27
+ END;
28
+ --> statement-breakpoint
29
+ CREATE TRIGGER `annotations_ad` AFTER DELETE ON `annotations` BEGIN
30
+ INSERT INTO `annotations_fts`(`annotations_fts`, `rowid`, `tag`, `value`) VALUES ('delete', old.`id`, old.`tag`, old.`value`);
31
+ END;
32
+ --> statement-breakpoint
33
+ CREATE TRIGGER `annotations_au` AFTER UPDATE ON `annotations` BEGIN
34
+ INSERT INTO `annotations_fts`(`annotations_fts`, `rowid`, `tag`, `value`) VALUES ('delete', old.`id`, old.`tag`, old.`value`);
35
+ INSERT INTO `annotations_fts`(`rowid`, `tag`, `value`) VALUES (new.`id`, new.`tag`, new.`value`);
36
+ END;
@@ -0,0 +1,22 @@
1
+ ALTER TABLE `symbols` ADD `structural_fingerprint` text;
2
+ --> statement-breakpoint
3
+ CREATE TABLE `symbol_changelog` (
4
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
5
+ `project` text NOT NULL,
6
+ `change_type` text NOT NULL,
7
+ `symbol_name` text NOT NULL,
8
+ `symbol_kind` text NOT NULL,
9
+ `file_path` text NOT NULL,
10
+ `old_name` text,
11
+ `old_file_path` text,
12
+ `fingerprint` text,
13
+ `changed_at` text NOT NULL,
14
+ `is_full_index` integer NOT NULL DEFAULT 0,
15
+ `index_run_id` text NOT NULL
16
+ );
17
+ --> statement-breakpoint
18
+ CREATE INDEX `idx_changelog_project_changed_at` ON `symbol_changelog`(`project`, `changed_at`);
19
+ --> statement-breakpoint
20
+ CREATE INDEX `idx_changelog_project_name` ON `symbol_changelog`(`project`, `symbol_name`);
21
+ --> statement-breakpoint
22
+ CREATE INDEX `idx_changelog_project_run` ON `symbol_changelog`(`project`, `index_run_id`);
@@ -43,6 +43,20 @@
43
43
  "when": 1772150400000,
44
44
  "tag": "0005_instance_id_covering_index",
45
45
  "breakpoints": true
46
+ },
47
+ {
48
+ "idx": 6,
49
+ "version": "6",
50
+ "when": 1773878400000,
51
+ "tag": "0006_annotations",
52
+ "breakpoints": true
53
+ },
54
+ {
55
+ "idx": 7,
56
+ "version": "6",
57
+ "when": 1773878400001,
58
+ "tag": "0007_symbol_changelog",
59
+ "breakpoints": true
46
60
  }
47
61
  ]
48
- }
62
+ }
@@ -0,0 +1,3 @@
1
+ import type { ParsedFile } from '../parser/types';
2
+ import type { ExtractedAnnotation } from './types';
3
+ export declare function extractAnnotations(parsed: ParsedFile): ExtractedAnnotation[];
@@ -1,7 +1,8 @@
1
1
  export { extractSymbols } from './symbol-extractor';
2
+ export { extractAnnotations } from './annotation-extractor';
2
3
  export { extractRelations } from './relation-extractor';
3
4
  export { extractImports } from './imports-extractor';
4
5
  export { extractCalls } from './calls-extractor';
5
6
  export { extractHeritage } from './heritage-extractor';
6
7
  export { resolveImport, buildImportMap } from './extractor-utils';
7
- export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, JsDocBlock, JsDocTag, ImportReference, QualifiedName, } from './types';
8
+ export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, JsDocBlock, JsDocTag, ImportReference, QualifiedName, AnnotationSource, ExtractedAnnotation, } from './types';