@zipbul/gildash 0.14.0 → 0.15.1

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