@zipbul/gildash 0.34.0 → 0.34.2

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 t$=Object.defineProperty;var e$=(_)=>_;function _J(_,$){this[_]=e$.bind(null,$)}var $J=(_,$)=>{for(var J in $)t$(_,J,{get:$[J],enumerable:!0,configurable:!0,set:_J.bind($,J)})};var s0=import.meta.require;import{isErr as s_}from"@zipbul/result";import f_ from"path";import{existsSync as nQ}from"fs";import{err as r0,isErr as ZJ}from"@zipbul/result";import{Database as XJ}from"bun:sqlite";import{mkdirSync as UJ,unlinkSync as o0,existsSync as t0}from"fs";import{dirname as VJ,join as e0}from"path";import{drizzle as OJ}from"drizzle-orm/bun-sqlite";import{migrate as HJ}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var A_=".gildash",r_="gildash.db";var L0={};$J(L0,{watcherOwner:()=>YJ,symbols:()=>x,symbolChangelog:()=>$_,relations:()=>u,files:()=>o,annotations:()=>Z_});import{sql as JJ}from"drizzle-orm";import{sqliteTable as k_,text as f,integer as r,real as QJ,index as Q_,primaryKey as zJ,foreignKey as M0,check as WJ}from"drizzle-orm/sqlite-core";var o=k_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:QJ("mtime_ms").notNull(),size:r("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:r("line_count")},(_)=>[zJ({columns:[_.project,_.filePath]})]),x=k_("symbols",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind").notNull(),name:f("name").notNull(),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),isExported:r("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[Q_("idx_symbols_project_file").on(_.project,_.filePath),Q_("idx_symbols_project_kind").on(_.project,_.kind),Q_("idx_symbols_project_name").on(_.project,_.name),Q_("idx_symbols_fingerprint").on(_.project,_.fingerprint),M0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),u=k_("relations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type").notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:r("is_external").notNull().default(0)},(_)=>[Q_("idx_relations_src").on(_.project,_.srcFilePath),Q_("idx_relations_dst").on(_.dstProject,_.dstFilePath),Q_("idx_relations_type").on(_.project,_.type),Q_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),Q_("idx_relations_specifier").on(_.project,_.specifier),M0({columns:[_.project,_.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Z_=k_("annotations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source").notNull(),symbolName:f("symbol_name"),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),indexedAt:f("indexed_at").notNull()},(_)=>[Q_("idx_annotations_project_file").on(_.project,_.filePath),Q_("idx_annotations_project_tag").on(_.project,_.tag),Q_("idx_annotations_project_symbol").on(_.project,_.symbolName),M0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),$_=k_("symbol_changelog",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),changeType:f("change_type").notNull(),symbolName:f("symbol_name").notNull(),symbolKind:f("symbol_kind").notNull(),filePath:f("file_path").notNull(),oldName:f("old_name"),oldFilePath:f("old_file_path"),fingerprint:f("fingerprint"),changedAt:f("changed_at").notNull(),isFullIndex:r("is_full_index").notNull().default(0),indexRunId:f("index_run_id").notNull()},(_)=>[Q_("idx_changelog_project_changed_at").on(_.project,_.changedAt),Q_("idx_changelog_project_name").on(_.project,_.symbolName),Q_("idx_changelog_project_run").on(_.project,_.indexRunId)]),YJ=k_("watcher_owner",{id:r("id").primaryKey(),pid:r("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("instance_id")},(_)=>[WJ("watcher_owner_singleton",JJ`${_.id} = 1`)]);class B0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=e0(_.projectRoot,A_,r_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{UJ(VJ(this.dbPath),{recursive:!0}),this.client=new XJ(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=OJ(this.client,{schema:L0}),HJ(this.drizzle,{migrationsFolder:e0(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(_)&&t0(this.dbPath)){this.closeClient(),o0(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(t0(Q))o0(Q)}let $=this.open();if(ZJ($))return r0(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return r0(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 x_,and as _1}from"drizzle-orm";class I0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(o).where(_1(x_(o.project,_),x_(o.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(o).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(o).where(x_(o.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(o).where(_1(x_(o.project,_),x_(o.filePath,$))).run()}}import{eq as t,and as N_,sql as o_,count as KJ}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var $1=50;class w0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(x).where(N_(t(x.project,_),t(x.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),W=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<W.length;Z+=$1)this.db.drizzleDb.insert(x).values(W.slice(Z,Z+$1)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(x).where(N_(o_`${x.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,t(x.project,_),J.kind?t(x.kind,J.kind):void 0)).orderBy(x.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.kind,$))).orderBy(x.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:KJ(),fileCount:o_`COUNT(DISTINCT ${x.filePath})`}).from(x).where(t(x.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(x).where(N_(t(x.project,_),t(x.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(x).where(N_(_.ftsQuery?o_`${x.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?t(x.name,_.exactName):void 0,_.project!==void 0?t(x.project,_.project):void 0,_.kind?t(x.kind,_.kind):void 0,_.filePath!==void 0?t(x.filePath,_.filePath):void 0,_.isExported!==void 0?t(x.isExported,_.isExported?1:0):void 0,_.decorator?o_`${x.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?t(x.resolvedType,_.resolvedType):void 0)).orderBy(x.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((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Z=$.limit(W).all();if(Q=Z.filter((Y)=>J.test(Y.name)),Q.length>=_.limit||Z.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as n,and as L_,isNull as J1,or as MJ}from"drizzle-orm";var m_={project:u.project,type:u.type,srcFilePath:u.srcFilePath,srcSymbolName:u.srcSymbolName,dstProject:u.dstProject,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,metaJson:u.metaJson,specifier:u.specifier,isExternal:u.isExternal};class D0{db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(u).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(m_).from(u).where(L_(n(u.project,_),n(u.srcFilePath,$),MJ(n(u.srcSymbolName,J),J1(u.srcSymbolName)))).all();return this.db.drizzleDb.select(m_).from(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(m_).from(u).where(L_(n(u.dstProject,$),n(u.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(m_).from(u).where(L_(n(u.project,_),n(u.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(u).where(L_(n(u.dstProject,_),n(u.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(m_).from(u).where(L_(_.project!==void 0?n(u.project,_.project):void 0,_.srcFilePath!==void 0?n(u.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?n(u.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?n(u.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?n(u.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?n(u.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?n(u.type,_.type):void 0,_.specifier!==void 0?n(u.specifier,_.specifier):void 0,_.isExternal!==void 0?n(u.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:W,newDstProject:Z}=_,Y=Q===null?L_(n(u.dstProject,$),n(u.dstFilePath,J),J1(u.dstSymbolName)):L_(n(u.dstProject,$),n(u.dstFilePath,J),n(u.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(u).set(X).where(Y).run()}}import{err as z1}from"@zipbul/result";import{subscribe as LJ}from"@parcel/watcher";import C0 from"path";import Q1 from"path";function z_(_){return _.replaceAll("\\","/")}function R_(_,$){return z_(Q1.relative(_,$))}function v_(_,$){return z_(Q1.resolve(_,$))}var BJ=["**/.git/**",`**/${A_}/**`,"**/dist/**","**/node_modules/**"],IJ=new Set(["package.json","tsconfig.json"]);function wJ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class A0{#$;#_;#Q;#z;#W;#Y;constructor(_,$=LJ,J=console){this.#_=_.projectRoot,this.#Q=[...BJ,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#W=$,this.#Y=J}async start(_){try{this.#$=await this.#W(this.#_,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=z_(C0.relative(this.#_,Q.path));if(z.startsWith(".."))continue;let W=C0.basename(z),Z=C0.extname(z).toLowerCase();if(!IJ.has(W)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:wJ(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#Q})}catch($){return z1(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#$)return;try{await this.#$.unsubscribe(),this.#$=void 0}catch(_){return z1(new V("watcher","Failed to close watcher",{cause:_}))}}}import q0 from"path";var DJ=["**/node_modules/**","**/.git/**",`**/${A_}/**`,"**/dist/**"],CJ=DJ.map((_)=>new Bun.Glob(_));function AJ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function t_(_,$=AJ){let J=[];for await(let Q of $(_)){let z=z_(Q);if(CJ.some((M)=>M.match(z)))continue;let W=z_(q0.dirname(Q)),Z=q0.join(_,Q),Y=await Bun.file(Z).json(),X=typeof Y?.name==="string"&&Y.name.length>0?Y.name:q0.basename(W==="."?_:W);J.push({dir:W,project:X})}return J.sort((Q,z)=>z.dir.length-Q.dir.length),J}function a(_,$,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 h_ from"path";var q_=new Map;async function qJ(_){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 NJ(_,$){if($.startsWith(".")){let J=h_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return h_.resolve(_,"node_modules",$)}async function W1(_,$=5){if($<=0)return null;let J=await qJ(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=NJ(h_.dirname(_),Q),W=await W1(z,$-1);if(!W)return J;let Z=typeof W.compilerOptions==="object"&&W.compilerOptions!==null?W.compilerOptions:{},Y=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...W,...J,compilerOptions:{...Z,...Y}}}async function n_(_){if(q_.has(_))return q_.get(_)??null;let $=h_.join(_,"tsconfig.json"),J=await W1($);if(!J)return q_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return q_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,W=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!W)return q_.set(_,null),null;let Z=z?h_.resolve(_,z):_,Y=new Map;if(W)for(let[M,O]of Object.entries(W)){if(!Array.isArray(O))continue;let L=O.filter((C)=>typeof C==="string");Y.set(M,L)}let X={baseUrl:Z,paths:Y};return q_.set(_,X),X}function e_(_){if(_){q_.delete(_);return}q_.clear()}function K_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as B1}from"@zipbul/result";import{err as RJ}from"@zipbul/result";import{parseSync as SJ}from"oxc-parser";function E_(_,$,J,Q=SJ){try{let z={preserveParens:!1,...J},W=Q(_,$,z);return{filePath:_,program:W.program,errors:W.errors,comments:W.comments,sourceText:$,module:W.module}}catch(z){return RJ(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{join as TJ}from"path";function FJ(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function Y1(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z,scanFilesFn:W=FJ}=_,Z=z.getFilesMap(),Y=new Set,X=[],M=[],O=Q.map((C)=>new Bun.Glob(C));for await(let C of W($,J)){let R=z_(C);if(!J.some((l)=>R.endsWith(l)))continue;if(R.startsWith("node_modules/")||R.includes("/node_modules/"))continue;if(O.some((l)=>l.match(R)))continue;Y.add(R);let I=TJ($,R),q=Bun.file(I),{size:G,lastModified:F}=q,E=Z.get(R);if(!E){let l=await q.text(),i=K_(l);X.push({filePath:R,contentHash:i,mtimeMs:F,size:G});continue}if(E.mtimeMs===F&&E.size===G){M.push({filePath:R,contentHash:E.contentHash,mtimeMs:F,size:G});continue}let b=await q.text(),m=K_(b);if(m===E.contentHash)M.push({filePath:R,contentHash:m,mtimeMs:F,size:G});else X.push({filePath:R,contentHash:m,mtimeMs:F,size:G})}let L=[];for(let C of Z.keys())if(!Y.has(C))L.push(C);return{changed:X,unchanged:M,deleted:L}}function d_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
3
- `)$.push(J+1);return $}function O_(_,$){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 GJ}from"@zipbul/result";import{parse as jJ}from"comment-parser";function _0(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=jJ(`/** ${$} */`)[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 GJ(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as kJ}from"@zipbul/result";function gJ(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _){let $=_.value;if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return String($)}return"unknown"}function u_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...u_(J.argument));else $.push(...u_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...u_(J.argument));else $.push(...u_(J))}return $}if(_.type==="AssignmentPattern")return u_(_.left);return[]}function vJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let z of J.entries){let W=z.localName.value,Z=z.importName.kind==="Name"?z.importName.name:void 0,Y={specifier:Q};if(Z&&Z!==W)Y.originalName=Z;$.set(W,Y)}}return $}function S_(_){let{program:$,sourceText:J,comments:Q}=_,z=d_(J),W=vJ(_),Z=Q.filter((D)=>D.type==="Block"&&D.value.startsWith("*")).sort((D,N)=>D.end-N.end),Y=$.body.map((D)=>D.start).sort((D,N)=>D-N);function X(D,N){return F(D,N)}function M(D,N,U){if(D.type==="PrivateIdentifier")return{kind:"private"};if(!N&&D.type==="Identifier")return;return X(D,U)}function O(D,N){if(N)return J.slice(D.start,D.end);if(D.type==="PrivateIdentifier")return`#${D.name}`;return gJ(D)}function L(D,N,U){let H=D;if(!N&&H.type==="Identifier")return{kind:"string",value:H.name};return X(D,U)}function C(D,N){return{start:O_(z,D),end:O_(z,N)}}function R(D){let N=0,U=Z.length-1,H=-1;while(N<=U){let B=N+U>>>1;if(Z[B].end<=D)H=B,N=B+1;else U=B-1}if(H<0)return;let K=Z[H];N=0,U=Y.length-1;while(N<=U){let B=N+U>>>1,A=Y[B];if(A<=K.end)N=B+1;else if(A>=D)U=B-1;else return}return`/*${K.value}*/`}function I(D){if(!D)return;let N="typeAnnotation"in D&&D.typeAnnotation?D.typeAnnotation:D;return J.slice(N.start,N.end)}let q=8;function G(D){if(D.type==="Identifier")return W.get(D.name);if(D.type==="MemberExpression"){let N=D.object;if(N.type==="Identifier")return W.get(N.name)}return}function F(D,N=0){let U=D;if(N>=q)return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)};let H=U.type;if(H==="Literal"){let K=U.value;if(typeof K==="bigint")return{kind:"bigint",value:typeof U.bigint==="string"?U.bigint:K.toString()};if(typeof U.regex==="object"&&U.regex!==null)return{kind:"regex",value:J.slice(U.start,U.end)};if(K===null)return{kind:"null",value:null};if(typeof K==="string")return{kind:"string",value:K};if(typeof K==="number")return{kind:"number",value:K};if(typeof K==="boolean")return{kind:"boolean",value:K};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="Identifier"){let K=U.name;if(K==="undefined")return{kind:"undefined",value:null};let B=W.get(K),A={kind:"identifier",name:K};if(B){if(A.importSource=B.specifier,B.originalName)A.originalName=B.originalName}return A}if(H==="MemberExpression"){if(U.computed){let j=U.property;if(j.type==="Literal"&&typeof j.value==="string"){let g=U.object,P=J.slice(g.start,g.end),p=g.type==="Identifier"?g.name:void 0,J_=p?W.get(p):void 0,V_={kind:"member",object:P,property:j.value};if(J_)V_.importSource=J_.specifier;return V_}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}let K=U.object,B=J.slice(K.start,K.end),A=U.property.name??J.slice(U.property.start,U.property.end),w=K.type==="Identifier"?K.name:void 0,T=w?W.get(w):void 0,S={kind:"member",object:B,property:A};if(T)S.importSource=T.specifier;return S}if(H==="CallExpression"){let K=U.callee,B=J.slice(K.start,K.end),w=(U.arguments??[]).map((j)=>F(j,N+1)),T=G(K),S={kind:"call",callee:B,arguments:w};if(T)S.importSource=T.specifier;return S}if(H==="NewExpression"){let K=U.callee,B=J.slice(K.start,K.end),w=(U.arguments??[]).map((j)=>F(j,N+1)),T=G(K),S={kind:"new",callee:B,arguments:w};if(T)S.importSource=T.specifier;return S}if(H==="ObjectExpression"){let K=U.properties??[],B=[];for(let A of K){if(A.type==="SpreadElement"){let p=A.argument;B.push({kind:"spread",argument:F(p,N+1)});continue}let w=A.key,T=A.computed===!0,S=A.value,j=A.shorthand||void 0,P={kind:"property",key:L(w,T,N+1),value:F(S,N+1)};if(j)P.shorthand=!0;B.push(P)}return{kind:"object",properties:B}}if(H==="ArrayExpression")return{kind:"array",elements:(U.elements??[]).map((A)=>{if(!A)return{kind:"undefined",value:null};return F(A,N+1)})};if(H==="SpreadElement"){let K=U.argument;return{kind:"spread",argument:F(K,N+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let B=U.params.map(b),A={kind:"function",sourceText:J.slice(U.start,U.end)};if(B.length>0)A.parameters=B;return A}if(H==="TemplateLiteral"||H==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(U.start,U.end)};if(H==="UnaryExpression"){let{operator:K,argument:B}=U;if(K==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(K==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="TSAsExpression"||H==="TSSatisfiesExpression"||H==="TSNonNullExpression"||H==="TSTypeAssertion"||H==="TSInstantiationExpression"||H==="ParenthesizedExpression"||H==="ChainExpression"){let K=U.expression;if(K)return F(K,N)}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}function E(D){if(!D||D.length===0)return[];return D.map((N)=>{let U=N.expression;if(U.type==="CallExpression"){let H=U,K=H.callee,B="name"in K&&typeof K.name==="string"?K.name:("property"in K)&&K.property&&typeof K.property.name==="string"?K.property.name:"unknown",A=H.arguments.map((w)=>F(w));return{name:B,arguments:A.length>0?A:void 0}}if(U.type==="Identifier")return{name:U.name??"unknown"};return{name:J.slice(U.start,U.end)}})}function b(D){if(D.type==="TSParameterProperty"){let U=D;return l(U.parameter,U.decorators)}if(D.type==="RestElement"){let U=D,H=U.argument,B=`...${"name"in H&&typeof H.name==="string"?H.name:"unknown"}`,A=U.typeAnnotation,w=A?I(A):void 0,T={name:B,isOptional:!1};if(w)T.type=w;return T}let N=D;return l(N,N.decorators)}function m(D){if(!D)return;let N="typeAnnotation"in D&&D.typeAnnotation?D.typeAnnotation:null;if(!N)return;let H=N.typeName?.name;if(!H)return;return W.get(H)?.specifier}function l(D,N){if(D.type==="AssignmentPattern"){let{left:S,right:j}=D,g="name"in S&&typeof S.name==="string"?S.name:"unknown",P="typeAnnotation"in S?S.typeAnnotation:null,p=P?I(P):void 0,J_=m(P),V_=J.slice(j.start,j.end),B_="decorators"in S&&Array.isArray(S.decorators)?S.decorators:[],K0=E(B_),C_={name:g,isOptional:!0,defaultValue:V_};if(p)C_.type=p;if(J_)C_.typeImportSource=J_;if(K0.length>0)C_.decorators=K0;return C_}let U="name"in D&&typeof D.name==="string"?D.name:("pattern"in D)&&D.pattern&&typeof D.pattern.name==="string"?D.pattern.name:"unknown",H=!!(("optional"in D)&&D.optional),K="typeAnnotation"in D?D.typeAnnotation:null,B=K?I(K):void 0,A=m(K),w=E(N??[]),T={name:U,isOptional:H};if(B)T.type=B;if(A)T.typeImportSource=A;if(w.length>0)T.decorators=w;return T}function i(D,N){let U=[];if(N?.async)U.push("async");if(D.static)U.push("static");if(D.abstract)U.push("abstract");if(D.readonly)U.push("readonly");if(D.override)U.push("override");if(D.declare)U.push("declare");if(D.const)U.push("const");let H=D.accessibility;if(H==="private")U.push("private");else if(H==="protected")U.push("protected");else if(H==="public")U.push("public");return U}function W_(D){if(!D)return;let N=D.params.flatMap((U)=>{let H=U.name.name;return H?[H]:[]});return N.length>0?N:void 0}function X_(D){let N=[];if(D.superClass){let H=J.slice(D.superClass.start,D.superClass.end);N.push({kind:"extends",name:H})}let U=D.implements??[];for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);N.push({kind:"implements",name:B})}return N}function M_(D){let N=[],U=D.extends;for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);N.push({kind:"extends",name:B})}return N}function U_(D){let N=[];for(let U of D)if(U.type==="MethodDefinition"||U.type==="TSAbstractMethodDefinition"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.value,w=H.kind,T=w==="constructor"?"constructor":w==="get"?"getter":w==="set"?"setter":"method",S=i(H,A);if(U.type==="TSAbstractMethodDefinition"&&!S.includes("abstract"))S.push("abstract");let j=A.params.map(b),g=I(A.returnType),P=E(H.decorators??[]),p={kind:"method",name:K,span:C(U.start,U.end),isExported:!1,methodKind:T,modifiers:S,parameters:j.length>0?j:void 0,returnType:g};if(B)p.key=B;if(P.length>0)p.decorators=P;N.push(p)}else if(U.type==="PropertyDefinition"||U.type==="TSAbstractPropertyDefinition"||U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=i(H);if(U.type==="TSAbstractPropertyDefinition"||U.type==="TSAbstractAccessorProperty"){if(!A.includes("abstract"))A.push("abstract")}if(U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty")A.push("accessor");let w=I(H.typeAnnotation),T=H.value,S=T?F(T):void 0,j=E(H.decorators??[]),g={kind:"property",name:K,span:C(U.start,U.end),isExported:!1,modifiers:A,returnType:w,initializer:S};if(B)g.key=B;if(j.length>0)g.decorators=j;N.push(g)}return N}function Y_(D){let N=[];for(let U of D)if(U.type==="TSMethodSignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.params.map(b),w=I(H.returnType),T={kind:"method",name:K,span:C(U.start,U.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:w};if(B)T.key=B;N.push(T)}else if(U.type==="TSPropertySignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=I(H.typeAnnotation),w={kind:"property",name:K,span:C(U.start,U.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:A};if(B)w.key=B;N.push(w)}return N}function c(D,N){let U=D.type;if(U==="FunctionDeclaration"||U==="FunctionExpression"||U==="TSDeclareFunction"||U==="TSEmptyBodyFunctionExpression"){let H=D,K=H.id?.name??"default",B=H.params.map(b),A=I(H.returnType),w=i(H,H),T=E(H.decorators??[]),S=W_(H.typeParameters),j={kind:"function",name:K,span:C(D.start,D.end),isExported:N,modifiers:w,parameters:B.length>0?B:void 0,returnType:A,decorators:T.length>0?T:void 0};if(S&&S.length>0)j.typeParameters=S;return j}if(U==="ClassDeclaration"||U==="ClassExpression"){let H=D,K=H.id?.name??"default",B=X_(H),A=U_(H.body.body),w=E(H.decorators),T=i(H),S=W_(H.typeParameters),j={kind:"class",name:K,span:C(D.start,D.end),isExported:N,modifiers:T,heritage:B.length>0?B:void 0,members:A.length>0?A:void 0,decorators:w.length>0?w:void 0};if(S&&S.length>0)j.typeParameters=S;return j}if(U==="VariableDeclaration"){let H=D,K=[];for(let B of H.declarations){let{id:A,init:w}=B;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let V_=u_(A);for(let B_ of V_)K.push({kind:"variable",name:B_.name,span:C(B_.start,B_.end),isExported:N,modifiers:[]});continue}let T="name"in A&&typeof A.name==="string"?A.name:"unknown",S="variable",j,g,P;if(w)if(w.type==="FunctionExpression"||w.type==="ArrowFunctionExpression"){S="function";let V_=w;j=V_.params.map(b),g=I(V_.returnType)}else P=F(w);let p=[],J_={kind:S,name:T,span:C(B.start,B.end),isExported:N,modifiers:p,parameters:j,returnType:g};if(P)J_.initializer=P;K.push(J_)}if(K.length===0)return null;if(K.length===1)return K[0];return K}if(U==="TSTypeAliasDeclaration")return{kind:"type",name:D.id.name,span:C(D.start,D.end),isExported:N,modifiers:[]};if(U==="TSInterfaceDeclaration"){let H=D,K=H.id.name,B=M_(H),A=Y_(H.body.body),w=W_(H.typeParameters),T={kind:"interface",name:K,span:C(D.start,D.end),isExported:N,modifiers:[],heritage:B.length>0?B:void 0,members:A.length>0?A:void 0};if(w&&w.length>0)T.typeParameters=w;return T}if(U==="TSEnumDeclaration"){let H=D,K=H.id.name,B=i(H),w=H.body.members.map((T)=>{let S=T.id,j=S.type!=="Identifier",g="name"in S&&typeof S.name==="string"?S.name:("value"in S)&&typeof S.value==="string"?S.value:"unknown",P=T.initializer?F(T.initializer):void 0,p={kind:"property",name:g,span:C(T.start,T.end),isExported:!1,modifiers:[]};if(j)p.key=X(S,0);if(P)p.initializer=P;return p});return{kind:"enum",name:K,span:C(D.start,D.end),isExported:N,modifiers:B,members:w.length>0?w:void 0}}if(U==="TSModuleDeclaration"){let H=D,K=H.id.name??H.id.value??"unknown",B=i(H),A=[];if(H.body?.type==="TSModuleBlock")for(let w of H.body.body??[]){if(w.type!=="ExportNamedDeclaration")continue;let T=w.declaration;if(!T)continue;let S=c(T,!1);if(S)if(Array.isArray(S))A.push(...S);else A.push(S)}return{kind:"namespace",name:K,span:C(D.start,D.end),isExported:N,modifiers:B,members:A.length>0?A:void 0}}return null}let s=[],D_=new Set;for(let D of $.body){let N=null,U=D;if(U.type==="ExportNamedDeclaration"){let K=U;if(K.declaration){if(N=c(K.declaration,!0),N&&!Array.isArray(N))N.span=C(K.start,K.end)}else if(!K.source&&K.specifiers)for(let B of K.specifiers){let A=B.local,w="name"in A?A.name:A.value;if(w)D_.add(w)}}else if(U.type==="ExportDefaultDeclaration"){let K=U,B=K.declaration;if(B){if(N=c(B,!0),N&&!Array.isArray(N))N.name="id"in B&&B.id&&typeof B.id.name==="string"?B.id.name:"default",N.isExported=!0,N.span=C(K.start,K.end);else if(!N&&"type"in B&&B.type==="Identifier"){let A=B.name;if(A)D_.add(A)}}}else{let K=U.type;if(K==="FunctionDeclaration"||K==="TSDeclareFunction"||K==="ClassDeclaration"||K==="VariableDeclaration"||K==="TSTypeAliasDeclaration"||K==="TSInterfaceDeclaration"||K==="TSEnumDeclaration"||K==="TSModuleDeclaration")N=c(U,!1)}let H=Array.isArray(N)?N:N?[N]:[];for(let K of H){let B=D.start,A=R(B);if(A){let w=_0(A);if(!kJ(w))K.jsDoc=w}s.push(K)}}if(D_.size>0){for(let D of s)if(!D.isExported&&D_.has(D.name))D.isExported=!0}return s}function $0(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map($0).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${$0($[Q])}`).join(",")}}`}function EJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function uJ(_){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(_.initializer)$.initializer=_.initializer;if(_.key)$.key=_.key;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),z={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,isAccessor:J.modifiers.includes("accessor")||void 0};if(J.key)z.key=J.key;if(J.initializer)z.initializer=J.initializer;if(J.decorators?.length)z.decorators=J.decorators;return z});return Object.keys($).length>0?JSON.stringify($):null}function bJ(_){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(_.key)$.push(`k:${$0(_.key)}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}:${Q.key?$0(Q.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${K_(J)}`)}return K_($.join("|"))}function Z1(_,$,J,Q,z){let W=EJ(_),Z=K_(`${$}|${_.kind}|${W??""}`),Y=bJ(_);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:W,fingerprint:Z,detailJson:uJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function N0(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Z=S_($),Y=[];for(let X of Z){Y.push(Z1(X,X.name,J,Q,z));for(let M of X.members??[])Y.push(Z1(M,`${X.name}.${M.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as R0,dirname as PJ,extname as fJ}from"path";function T_(_,$,J){let Q=(z)=>{let W=fJ(z);if(W===".js")return[z.slice(0,-3)+".ts"];if(W===".mjs")return[z.slice(0,-4)+".mts"];if(W===".cjs")return[z.slice(0,-4)+".cts"];if(W===".ts"||W===".mts"||W===".cts"||W===".d.ts")return[z];return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"]};if($.startsWith(".")){let z=z_(R0(PJ(_),$));return Q(z)}if(J)for(let[z,W]of J.paths){if(W.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let Y=[];for(let X of W)Y.push(...Q(z_(R0(J.baseUrl,X))));return Y}}else{let Y=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(Y)&&(X===""||$.endsWith(X))){let M=$.slice(Y.length,X===""?void 0:$.length-X.length),O=[];for(let L of W)O.push(...Q(z_(R0(J.baseUrl,L.replace("*",M)))));return O}}}return[]}function X1(_,$,J,Q=T_){let z=new Map,W=_.body??[];for(let Z of W){if(Z.type!=="ImportDeclaration")continue;let Y=Z.source?.value??"",X=Q($,Y,J);if(X.length===0)continue;let M=X[0],O=Z.specifiers??[];for(let L of O)switch(L.type){case"ImportSpecifier":z.set(L.local.name,{path:M,importedName:L.imported.name});break;case"ImportDefaultSpecifier":z.set(L.local.name,{path:M,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(L.local.name,{path:M,importedName:"*"});break}}return z}import{Visitor as yJ}from"oxc-parser";function J0(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function xJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function F_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&xJ($);return{resolved:W,isExternal:Z}}function mJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=F_($,Z,J,Q),M={dstFilePath:Y,specifier:Z};if(W.entries.length===0){let O={};if(X)O.isExternal=!0;if(Y===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...M,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of W.entries){let L=O.isType,C={};if(L)C.isType=!0;if(X)C.isExternal=!0;if(Y===null&&!X)C.isUnresolved=!0;let R,I,q=O.importName.kind;if(q==="Default")R="default",I=O.localName.value;else if(q==="NamespaceObject")R="*",I=O.localName.value,C.importKind="namespace";else R=O.importName.name??"unknown",I=O.localName.value;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:I,...M,dstSymbolName:R,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}}function hJ(_,$,J,Q,z){let W=new Map;for(let Z of _.staticImports)for(let Y of Z.entries)W.set(Y.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let Y of Z.entries){let X=null;if(Y.moduleRequest)X=Y.moduleRequest.value;else if(Y.localName.name)X=W.get(Y.localName.name)??null;if(!X)continue;let{resolved:M,isExternal:O}=F_($,X,J,Q),L=Y.exportName.name??"default",C=Y.exportName.kind,R=Y.localName.name??Y.importName.name??L,I=Y.isType,q={isReExport:!0};if(C==="None");else q.specifiers=[{local:R,exported:L}];if(I)q.isType=!0;if(O)q.isExternal=!0;if(M===null&&!O)q.isUnresolved=!0;let G=null,F=null,E=Y.importName.kind;if(E==="All"||E==="AllButDefault"){if(C==="Name"&&L)F=L,q.namespaceAlias=L}else F=R,G=L;z.push({type:I?"type-references":"re-exports",srcFilePath:$,srcSymbolName:G,dstFilePath:M,dstSymbolName:F,specifier:X,metaJson:JSON.stringify(q)})}}function nJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=F_($,X,J,Q),L=Y.importKind==="type",C=Y.specifiers,R={dstFilePath:M,specifier:X};if(C.length===0){let I={};if(L)I.isType=!0;if(O)I.isExternal=!0;if(M===null&&!O)I.isUnresolved=!0;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...R,dstSymbolName:null,...Object.keys(I).length>0?{metaJson:JSON.stringify(I)}:{}})}else for(let I of C){let q=I.type,G=L||q==="ImportSpecifier"&&I.importKind==="type",F={};if(G)F.isType=!0;if(O)F.isExternal=!0;if(M===null&&!O)F.isUnresolved=!0;let E,b;if(q==="ImportDefaultSpecifier")E="default",b=I.local.name;else if(q==="ImportNamespaceSpecifier")E="*",b=I.local.name,F.importKind="namespace";else E=J0(I.imported),b=I.local.name;z.push({type:G?"type-references":"imports",srcFilePath:$,srcSymbolName:b,...R,dstSymbolName:E,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=F_($,X,J,Q),L=Y.exportKind==="type",C=Y.exported,R=C?J0(C):null,I={isReExport:!0};if(L)I.isType=!0;if(O)I.isExternal=!0;if(M===null&&!O)I.isUnresolved=!0;if(R)I.namespaceAlias=R;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:R,specifier:X,metaJson:JSON.stringify(I)});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:M,isExternal:O}=F_($,X,J,Q),L=Y.exportKind==="type",C=Y.specifiers??[];for(let R of C){let I=L||R.exportKind==="type",q=J0(R.local),G=J0(R.exported),F={isReExport:!0,specifiers:[{local:q,exported:G}]};if(I)F.isType=!0;if(O)F.isExternal=!0;if(M===null&&!O)F.isUnresolved=!0;z.push({type:I?"type-references":"re-exports",srcFilePath:$,srcSymbolName:G,dstFilePath:M,dstSymbolName:q,specifier:X,metaJson:JSON.stringify(F)})}}}}function dJ(_,$,J,Q,z){new yJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:M,isExternal:O}=F_($,X,J,Q),L={isDynamic:!0};if(O)L.isExternal=!0;if(M===null&&!O)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(L)})},CallExpression(Z){let Y=Z.callee,X=!1;if(Y.type==="Identifier"&&Y.name==="require");else if(Y.type==="MemberExpression"&&!Y.computed){let q=Y,G=q.object,F=q.property;if(G.type==="Identifier"&&G.name==="require"&&F.name==="resolve")X=!0;else return}else return;let M=Z.arguments;if(M.length===0)return;let O=M[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let L=O.value,{resolved:C,isExternal:R}=F_($,L,J,Q),I={isRequire:!0};if(X)I.isRequireResolve=!0;if(R)I.isExternal=!0;if(C===null&&!R)I.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:C,dstSymbolName:null,specifier:L,metaJson:JSON.stringify(I)})}}).visit(_)}function U1(_,$,J,Q=T_,z){let W=[];if(z)mJ(z,$,J,Q,W),hJ(z,$,J,Q,W);else nJ(_,$,J,Q,W);return dJ(_,$,J,Q,W),W}import{walk as $Q}from"oxc-walker";function pJ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function lJ(_){return _.type==="ArrowFunctionExpression"}function iJ(_){return _.type==="AssignmentExpression"}function cJ(_){return _.type==="CallExpression"}function aJ(_){return _.type==="FunctionDeclaration"}function sJ(_){return _.type==="FunctionExpression"}function rJ(_){return _.type==="Identifier"}function oJ(_){return _.type==="MemberExpression"}function tJ(_){return _.type==="TSQualifiedName"}function eJ(_){return _.type==="VariableDeclaration"}var V1=new Map,_Q=new Proxy({},{get(_,$,J){if(typeof $!=="string")return Reflect.get(_,$,J);let Q=$.charCodeAt(0);if(Q<65||Q>90)return Reflect.get(_,$,J);let z=V1.get($);if(z===void 0)z=(W)=>W!==null&&W!==void 0&&W.type===$,V1.set($,z);return z}});function b_(_){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 W=[z,...J].join(".");return{root:z,parts:J,full:W}}return null}function O1(_,$,J){let Q=[],z=[],W=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function Y(O){if(!O)return null;let L=J.get(O.root);if(O.parts.length===0){if(L)return{dstFilePath:L.path,dstSymbolName:L.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(L&&L.importedName==="*"){let C=O.parts[O.parts.length-1];return{dstFilePath:L.path,dstSymbolName:C,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,L){let C=b_(O.callee),R=Y(C);if(R){let I=Z(),q={};if(L)q.isNew=!0;if(I===null)q.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:I,dstFilePath:R.dstFilePath,dstSymbolName:R.dstSymbolName,...Object.keys(q).length>0?{metaJson:JSON.stringify(q)}:{}})}}function M(O,L){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(L?.type==="VariableDeclarator"){let I=L.id,q=I.type==="Identifier"?I.name:"anonymous";z.push(q);return}if(L?.type==="MethodDefinition"||L?.type==="TSAbstractMethodDefinition"){let I=L.key,q=W[W.length-1]??"",G="name"in I?I.name:"anonymous",F=q?`${q}.${G}`:G;z.push(F);return}let C=Z(),R=C?`${C}.<anonymous>`:"<anonymous>";z.push(R)}}return $Q(_,{enter(O,L){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){W.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){M(O,L);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"){W.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as JQ}from"oxc-parser";function H1(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let M=b_(Z.superClass);if(M){let O=S0(M,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...O})}}let X=Z.implements??[];for(let M of X){let O=b_(M.expression);if(!O)continue;let L=S0(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...L})}}return new JQ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let M of X){let O=b_(M.expression);if(!O)continue;let L=S0(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...L})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function S0(_,$,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 p_(_,$,J,Q=T_,z){let W=X1(_,$,J,Q),Z=U1(_,$,J,Q,z),Y=O1(_,$,W),X=H1(_,$,W);return[...Z,...Y,...X]}function T0(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Z,knownFiles:Y,boundaries:X,module:M}=_,O=v_(W,Q),C=p_($,O,Z,Y?(I,q,G)=>{let F=T_(I,q,G);for(let E of F){let b=R_(W,E);if(X){let m=a(b,X);if(Y.has(`${m}::${b}`))return[E]}else if(Y.has(`${J}::${b}`))return[E]}return[]}:void 0,M),R=[];for(let I of C){if(I.dstFilePath===null){let E=R_(W,I.srcFilePath),b;if(I.metaJson)try{b=JSON.parse(I.metaJson)}catch{}let m=b?.isExternal===!0;R.push({project:J,type:I.type,srcFilePath:E,srcSymbolName:I.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:I.dstSymbolName??null,metaJson:I.metaJson??null,specifier:I.specifier??null,isExternal:m?1:0});continue}let q=R_(W,I.dstFilePath);if(q.startsWith(".."))continue;let G=R_(W,I.srcFilePath),F=X?a(q,X):J;R.push({project:J,type:I.type,srcFilePath:G,srcSymbolName:I.srcSymbolName??null,dstProject:F,dstFilePath:q,dstSymbolName:I.dstSymbolName??null,metaJson:I.metaJson??null,specifier:I.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,R),R.length}import{isErr as QQ}from"@zipbul/result";var K1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function zQ(_){let $=S_(_),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 F0(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let W=Q+z>>1;if(_[W].startLine<=$)Q=W+1;else z=W-1}if(Q<_.length){let W=_[Q];if(W.startLine-$<=J)return W.name}return null}function Q0(_,$,J){let Q=O_(_,$),z=O_(_,J);return{start:Q,end:z}}function M1(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=d_(J),z=zQ(_),W=[],Z=[...$].sort((X,M)=>X.start-M.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let M=`/*${X.value}*/`,O=_0(M);if(QQ(O))continue;let L=O;if(!L.tags?.length)continue;let C=O_(Q,X.end),R=F0(z,C.line,3),I=J.slice(X.start,X.end);for(let q of L.tags){let G=[q.name,q.description].filter(Boolean).join(" "),F=`@${q.tag}`,E=I.indexOf(F),b;if(E>=0){let m=X.start+E,l=J.indexOf(`
4
- `,m),i=l>=0?Math.min(l,X.end):X.end;b=Q0(Q,m,i)}else b=Q0(Q,X.start,X.end);W.push({tag:q.tag,value:G,source:"jsdoc",span:b,symbolName:R})}}else if(X.type==="Block"){Y=null;let M=X.value.split(`
5
- `),O=0;for(let L of M){let C=L.replace(/^\s*\*?\s?/,""),R=K1.exec(C);if(R){let I=R[1],q=R[2]?.trim()??"",G=`@${I}`,F=L.indexOf(G),E=X.start+2+O+(F>=0?F:0),b=X.start+2+O+L.length,m=Q0(Q,E,b),l=O_(Q,X.end),i=F0(z,l.line,3);W.push({tag:I,value:q,source:"block",span:m,symbolName:i})}O+=L.length+1}}else{let M=X.value,O=K1.exec(M),L=O_(Q,X.start),C=O_(Q,X.end);if(O){let R=O[1],I=O[2]?.trim()??"",q=`@${R}`,G=M.indexOf(q),F=X.start+2+(G>=0?G:0),E=Q0(Q,F,X.end),b=F0(z,C.line,3),m={tag:R,value:I,source:"line",span:E,symbolName:b};W.push(m),Y={annotation:m,endLine:C.line}}else if(Y&&L.line===Y.endLine+1){let R=M.trim();if(R)Y.annotation.value+=" "+R,Y.annotation.span.end=O_(Q,X.end),Y.endLine=C.line}else Y=null}return W}function G0(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,W=M1($);if(z.deleteFileAnnotations(J,Q),!W.length)return 0;let Z=new Date().toISOString(),Y=W.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,Y),W.length}function L1(_,$){let J=[],Q=[],z=[];for(let[O,L]of $)if(!_.has(O))J.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});for(let[O,L]of _)if(!$.has(O))Q.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Z=new Map;for(let O of J){let L=W.get(O.filePath)??[];L.push(O),W.set(O.filePath,L)}for(let O of Q){let L=Z.get(O.filePath)??[];L.push(O),Z.set(O.filePath,L)}let Y=new Set,X=new Set;for(let[O,L]of W){let C=Z.get(O);if(!C)continue;for(let R of new Set(L.map((I)=>I.kind))){let I=L.filter((b)=>b.kind===R&&!Y.has(b)),q=C.filter((b)=>b.kind===R&&!X.has(b));if(!I.length||!q.length)continue;let G=(b,m)=>{return m.get(`${b.filePath}::${b.name}`)?.structuralFingerprint??null},F=(b,m)=>{return m.get(`${b.filePath}::${b.name}`)?.startLine??0},E=new Map;for(let b of q){let m=G(b,_);if(!m)continue;let l=E.get(m)??[];l.push(b),E.set(m,l)}for(let b of I){if(Y.has(b))continue;let m=G(b,$);if(!m)continue;let l=E.get(m);if(!l)continue;let i=l.filter((X_)=>!X.has(X_));if(!i.length)continue;let W_=i[0];if(i.length>1){let X_=F(b,$),M_=Math.abs(F(W_,_)-X_);for(let U_=1;U_<i.length;U_++){let Y_=Math.abs(F(i[U_],_)-X_);if(Y_<M_)M_=Y_,W_=i[U_]}}z.push({oldName:W_.name,newName:b.name,filePath:O,kind:R}),Y.add(b),X.add(W_)}}}let M=z.filter((O)=>!O.oldName.includes("."));for(let O of M){let L=`${O.oldName}.`,C=`${O.newName}.`,R=Q.filter((q)=>q.filePath===O.filePath&&q.name.startsWith(L)&&!X.has(q)),I=J.filter((q)=>q.filePath===O.filePath&&q.name.startsWith(C)&&!Y.has(q));for(let q of R){let G=q.name.slice(L.length),F=I.find((E)=>E.name.slice(C.length)===G);if(F)z.push({oldName:q.name,newName:F.name,filePath:O.filePath,kind:q.kind}),Y.add(F),X.add(q)}}return{renamed:z,added:J.filter((O)=>!Y.has(O)),removed:Q.filter((O)=>!X.has(O))}}var WQ=100,I1=50;class j0{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=n_(_.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")){e_(this.opts.projectRoot),this.tsconfigPathsRaw=n_(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??t_;this.boundariesRefresh=$(this.opts.projectRoot).then((J)=>{this.opts.boundaries=J,this.opts.onBoundariesChanged?.(J)}),this.fullIndex().catch((J)=>{this.logger.error("[IndexCoordinator] fullIndex failed after package.json change:",J)});return}if(this.pendingEvents.push(_),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},WQ)}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 W of Q)W.resolve(z)}).catch((z)=>{for(let W of Q)W.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:W,dbConnection:Z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Y,X;if(_!==void 0)Y=_.filter((U)=>U.eventType==="create"||U.eventType==="change").map((U)=>({filePath:U.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((U)=>U.eventType==="delete").map((U)=>U.filePath);else{let U=new Map;for(let K of this.opts.boundaries)for(let[B,A]of Q.getFilesMap(K.project))U.set(B,A);let H=await Y1({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});Y=H.changed,X=H.deleted}let M=await this.tsconfigPathsRaw??void 0,O=new Map;for(let U of X){let H=a(U,this.opts.boundaries),K=z.getFileSymbols(H,U);O.set(U,K)}let L=crypto.randomUUID(),C=new Map,R=new Map,I=(U)=>({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint,structuralFingerprint:U.structuralFingerprint??null,startLine:U.startLine,isExported:U.isExported??0});if($)for(let U of this.opts.boundaries)for(let H of Q.getAllFiles(U.project))for(let K of z.getFileSymbols(U.project,H.filePath))C.set(`${K.filePath}::${K.name}`,I(K));else{for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(H,U.filePath))C.set(`${K.filePath}::${K.name}`,I(K))}for(let[,U]of O)for(let H of U)C.set(`${H.filePath}::${H.name}`,I(H))}let q=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath??""}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${K_(U.metaJson??"")}`,G=new Map;if($)for(let U of this.opts.boundaries)for(let H of Q.getAllFiles(U.project))for(let K of W.getOutgoing(U.project,H.filePath))G.set(q(K),K);else{for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of W.getOutgoing(H,U.filePath))G.set(q(K),K)}for(let U of X){let H=a(U,this.opts.boundaries);for(let K of W.getOutgoing(H,U))G.set(q(K),K)}}let{annotationRepo:F,changelogRepo:E}=this.opts,b=()=>{for(let U of X){let H=a(U,this.opts.boundaries);if(z.deleteFileSymbols(H,U),W.deleteFileRelations(H,U),W.deleteIncomingRelations(H,U),F)F.deleteFileAnnotations(H,U);Q.deleteFile(H,U)}},m=0,l=async()=>{let{projectRoot:U,boundaries:H}=this.opts,{parseCache:K}=this.opts,B=0,A=0,w=0,T=[],S=[];for(let g of Y)try{let P=v_(U,g.filePath),p=Bun.file(P),J_=await p.text(),V_=g.contentHash||K_(J_),B_=a(g.filePath,H);Q.upsertFile({project:B_,filePath:g.filePath,mtimeMs:p.lastModified,size:p.size,contentHash:V_,updatedAt:new Date().toISOString(),lineCount:J_.split(`
6
- `).length});let C_=(this.opts.parseSourceFn??E_)(P,J_);if(B1(C_))throw C_.data;let o$=C_;S.push({filePath:g.filePath,text:J_,contentHash:V_,parsed:o$,project:B_})}catch(P){this.logger.error(`[IndexCoordinator] Failed to prepare ${g.filePath}:`,P),T.push(g.filePath)}let j=new Set;for(let g of H)for(let[P]of Q.getFilesMap(g.project))j.add(`${g.project}::${P}`);return Z.transaction(()=>{for(let g of S){if(N0({parsed:g.parsed,project:g.project,filePath:g.filePath,contentHash:g.contentHash,symbolRepo:z}),A+=T0({ast:g.parsed.program,project:g.project,filePath:g.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:M,knownFiles:j,boundaries:H,module:g.parsed.module}),F)w+=G0({parsed:g.parsed,project:g.project,filePath:g.filePath,annotationRepo:F});K.set(g.filePath,g.parsed),B+=z.getFileSymbols(g.project,g.filePath).length}}),{symbols:B,relations:A,annotations:w,failedFiles:T}},i=0,W_=0,X_=[];if($){let{projectRoot:U,boundaries:H}=this.opts,{parseCache:K}=this.opts,B=[];for(let w=0;w<Y.length;w+=I1){let T=Y.slice(w,w+I1),S=await Promise.allSettled(T.map(async(j)=>{let g=v_(U,j.filePath),P=Bun.file(g),p=await P.text(),J_=j.contentHash||K_(p);return{filePath:j.filePath,text:p,contentHash:J_,mtimeMs:P.lastModified,size:P.size}}));for(let j=0;j<S.length;j++){let g=S[j];if(g.status==="fulfilled")B.push(g.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",g.reason),X_.push(T[j].filePath)}}let A=[];Z.transaction(()=>{for(let S of B){let j=a(S.filePath,H);Q.deleteFile(j,S.filePath)}for(let S of X){let j=a(S,H);if(z.deleteFileSymbols(j,S),W.deleteFileRelations(j,S),W.deleteIncomingRelations(j,S),F)F.deleteFileAnnotations(j,S);Q.deleteFile(j,S)}for(let S of B){let j=a(S.filePath,H);Q.upsertFile({project:j,filePath:S.filePath,mtimeMs:S.mtimeMs,size:S.size,contentHash:S.contentHash,updatedAt:new Date().toISOString(),lineCount:S.text.split(`
7
- `).length})}let w=new Set;for(let S of H)for(let[j]of Q.getFilesMap(S.project))w.add(`${S.project}::${j}`);let T=this.opts.parseSourceFn??E_;for(let S of B){let j=a(S.filePath,H),g=T(v_(U,S.filePath),S.text);if(B1(g))throw g.data;let P=g;if(A.push({filePath:S.filePath,parsed:P}),N0({parsed:P,project:j,filePath:S.filePath,contentHash:S.contentHash,symbolRepo:z}),F)m+=G0({parsed:P,project:j,filePath:S.filePath,annotationRepo:F});W_+=T0({ast:P.program,project:j,filePath:S.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:M,knownFiles:w,boundaries:H,module:P.module}),i+=z.getFileSymbols(j,S.filePath).length}});for(let w of A)K.set(w.filePath,w.parsed)}else{b();let U=await l();i=U.symbols,W_=U.relations,m=U.annotations,X_=U.failedFiles}for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(H,U.filePath))R.set(`${K.filePath}::${K.name}`,I(K))}let M_=new Map;for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of W.getOutgoing(H,U.filePath))M_.set(q(K),K)}let U_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),Y_={added:[...M_.entries()].filter(([U])=>!G.has(U)).map(([,U])=>U_(U)),removed:[...G.entries()].filter(([U])=>!M_.has(U)).map(([,U])=>U_(U))},c={added:[],modified:[],removed:[]};for(let[U,H]of R){let K=C.get(U);if(!K)c.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let B=K.fingerprint!==H.fingerprint,A=K.isExported!==H.isExported,w=K.structuralFingerprint!==null&&H.structuralFingerprint!==null&&K.structuralFingerprint!==H.structuralFingerprint;if(B||A||w)c.modified.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)})}}for(let[U,H]of C)if(!R.has(U))c.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let s=L1(C,R),D_=new Set(s.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),D=new Set(s.renamed.map((U)=>`${U.filePath}::${U.newName}`));c.added=c.added.filter((U)=>!D.has(`${U.filePath}::${U.name}`)),c.removed=c.removed.filter((U)=>!D_.has(`${U.filePath}::${U.name}`));let N=[];if(!$){for(let[H,K]of O)for(let B of K){if(!B.fingerprint)continue;let A=a(H,this.opts.boundaries),w=z.getByFingerprint(A,B.fingerprint);if(w.length===1){let T=w[0];W.retargetRelations({dstProject:A,oldFile:H,oldSymbol:B.name,newFile:T.filePath,newSymbol:T.name}),N.push({name:T.name,filePath:T.filePath,kind:T.kind,oldFilePath:H,isExported:T.isExported??0})}}let U=new Set(N.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of s.removed){if(U.has(`${H.filePath}::${H.name}`))continue;let B=C.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!B)continue;let A=a(H.filePath,this.opts.boundaries),w=z.getByFingerprint(A,B);if(w.length===1){let T=w[0];if(T.filePath!==H.filePath||T.name!==H.name)W.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:T.filePath,newSymbol:T.name}),N.push({name:T.name,filePath:T.filePath,kind:T.kind,oldFilePath:H.filePath,isExported:T.isExported??0})}}}if(N.length){let U=new Set(N.map((K)=>`${K.filePath}::${K.name}`)),H=new Set(N.map((K)=>`${K.oldFilePath}::${K.name}`));c.added=c.added.filter((K)=>!U.has(`${K.filePath}::${K.name}`)),c.removed=c.removed.filter((K)=>!H.has(`${K.filePath}::${K.name}`))}if(E){let U=new Date().toISOString(),H=$?1:0,K=[];for(let B of c.added){let A=`${B.filePath}::${B.name}`,w=R.get(A),T=a(B.filePath,this.opts.boundaries);K.push({project:T,changeType:"added",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:w?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.modified){let A=R.get(`${B.filePath}::${B.name}`),w=a(B.filePath,this.opts.boundaries);K.push({project:w,changeType:"modified",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.removed){let A=`${B.filePath}::${B.name}`,w=C.get(A),T=a(B.filePath,this.opts.boundaries);K.push({project:T,changeType:"removed",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:w?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of s.renamed){let A=R.get(`${B.filePath}::${B.newName}`),w=a(B.filePath,this.opts.boundaries);K.push({project:w,changeType:"renamed",symbolName:B.newName,symbolKind:B.kind,filePath:B.filePath,oldName:B.oldName,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of N){let A=R.get(`${B.filePath}::${B.name}`),w=a(B.filePath,this.opts.boundaries);K.push({project:w,changeType:"moved",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:B.oldFilePath,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}if(K.length)try{Z.transaction(()=>{E.insertBatch(K)})}catch(B){this.logger.error("[IndexCoordinator] changelog insert failed:",B)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let B=new Date(Date.now()-2592000000).toISOString();try{for(let A of this.opts.boundaries)E.pruneOlderThan(A.project,B)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:i,totalRelations:W_,totalAnnotations:m,durationMs:Date.now()-J,changedFiles:Y.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:X_,changedSymbols:c,renamedSymbols:s.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(R.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:N.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:Y_}}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 YQ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function ZQ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function w1(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??YQ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-ZQ(Y.heartbeat_at))/1000),M=z(Y.pid);if(M&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(M&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function D1(_,$){_.deleteOwner($)}function C1(_,$){_.touchOwner($)}class l_{#$;#_=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 k0{lru;constructor(_=500){this.lru=new l_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function g0(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,W={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)W.exactName=Q.text;else{let Y=g_(Q.text);if(Y)W.ftsQuery=Y}if(Q.decorator)W.decorator=Q.decorator;if(Q.regex)W.regex=Q.regex;return $.searchByQuery(W).map((Y)=>{let X=Y.name.indexOf(".");return{id:Y.id,filePath:Y.filePath,kind:Y.kind,name:Y.name,memberName:X>=0?Y.name.slice(X+1):null,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}},isExported:Y.isExported===1,signature:Y.signature,fingerprint:Y.fingerprint,detail:Y.detailJson?(()=>{try{return JSON.parse(Y.detailJson)}catch{return{}}})():{}}})}function v0(_){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,W=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Y=Z?void 0:W,M=$.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:Y}).map((O)=>{let L;if(O.metaJson)try{L=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,isExternal:O.isExternal===1,specifier:O.specifier,metaJson:O.metaJson??void 0,meta:L}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,L=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;M=M.filter((C)=>(!O||O.match(C.srcFilePath))&&(!L||C.dstFilePath===null||L.match(C.dstFilePath)))}if(Z&&W!==void 0&&M.length>W)M=M.slice(0,W);return M}import{findInFiles as XQ,Lang as UQ}from"@ast-grep/napi";function VQ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function OQ(_){return _.replace(/^\$+/,"")}function HQ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=OQ(z),Z=_.getMatch(W);if(Z){let X=Z.range();J[z]={text:Z.text(),startLine:X.start.line+1,endLine:X.end.line+1,startColumn:X.start.column,endColumn:X.end.column,startOffset:X.start.index,endOffset:X.end.index},Q=!0;continue}let Y=_.getMultipleMatches(W);if(Y.length>0){let X=Y[0].range(),M=Y[Y.length-1].range();J[z]={text:Y.map((O)=>O.text()).join(", "),startLine:X.start.line+1,endLine:M.end.line+1,startColumn:X.start.column,endColumn:M.end.column,startOffset:X.start.index,endOffset:M.end.index},Q=!0}}return Q?J:void 0}async function E0(_){if(_.filePaths.length===0)return[];let $=VQ(_.pattern),J=[];return await XQ(UQ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,startColumn:Z.start.column,endColumn:Z.end.column,startOffset:Z.start.index,endOffset:Z.end.index,matchedText:W.text()},X=HQ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import __ from"typescript";import{isErr as kQ}from"@zipbul/result";import I_ from"typescript";import KQ from"path";import{err as u0}from"@zipbul/result";function MQ(_){try{return s0("fs").readFileSync(_,"utf-8")}catch{return}}function LQ(_){try{return s0("fs").readFileSync(_,"utf-8")}catch{return}}class z0{#$;#_;#Q=!1;__testing__;constructor(_,$){this.#$=_,this.#_=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??MQ,Q=$.resolveNonTrackedFile??LQ,z=KQ.dirname(_),W=J(_);if(W===void 0)return u0(new V("semantic",`tsconfig not found: ${_}`));let Z=I_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let L=Y.map((C)=>I_.flattenDiagnosticMessageText(C.messageText,`
8
- `)).join("; ");return u0(new V("semantic",`tsconfig parse error: ${L}`))}let X=I_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(L)=>J(L)!==void 0||Q(L)!==void 0,readFile:(L)=>J(L)??Q(L)},z);if(X.errors.length>0){let L=X.errors.filter((C)=>C.category===I_.DiagnosticCategory.Error&&C.code!==18003);if(L.length>0){let C=L.map((R)=>I_.flattenDiagnosticMessageText(R.messageText,`
9
- `)).join("; ");return u0(new V("semantic",`tsconfig compile error: ${C}`))}}let M=new A1(X.fileNames,X.options,z,Q),O=I_.createLanguageService(M);return new z0(O,M)}get isDisposed(){return this.#Q}getProgram(){this.#z();let _=this.#$.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getCompilerOptions(){return this.#z(),this.#_.getCompilationSettings()}getLanguageService(){return this.#z(),this.#$}notifyFileChanged(_,$){if(this.#Q)return;this.#_.updateFile(_,$)}removeFile(_){if(this.#Q)return;this.#_.removeFile(_)}dispose(){if(this.#Q)return;this.#Q=!0,this.#$.dispose()}#z(){if(this.#Q)throw Error("TscProgram is disposed")}}class A1{#$;#_;#Q;#z;#W=new Map;#Y=new Map;#J=new Map;constructor(_,$,J,Q){this.#$=new Set(_),this.#_=$,this.#Q=J,this.#z=Q}updateFile(_,$){let J=this.#W.get(_);if(J){if(J.content===$)return;this.#Y.delete(`${_}:${J.version}`),J.version+=1,J.content=$}else this.#W.set(_,{version:1,content:$})}removeFile(_){let $=this.#W.get(_);if($)this.#Y.delete(`${_}:${$.version}`);this.#W.delete(_),this.#$.delete(_)}getScriptFileNames(){let _=[...this.#W.keys()];return[...[...this.#$].filter((J)=>!this.#W.has(J)),..._]}getScriptVersion(_){let $=this.#W.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#W.get(_);if($){let z=`${_}:${$.version}`,W=this.#Y.get(z);if(!W)W=I_.ScriptSnapshot.fromString($.content),this.#Y.set(z,W);return W}let J=this.#J.get(_);if(J)return J;let Q=this.#z(_);if(Q!==void 0)return J=I_.ScriptSnapshot.fromString(Q),this.#J.set(_,J),J;return}getCurrentDirectory(){return this.#Q}getCompilationSettings(){return this.#_}getDefaultLibFileName(_){return I_.getDefaultLibFilePath(_)}fileExists(_){if(this.#W.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#W.get(_);if($)return $.content;return this.#z(_)}}import y from"typescript";import W0 from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let J,Q=(z)=>{if($<z.getStart(_,!1)||$>=z.getEnd())return;J=z,W0.forEachChild(z,Q)};return W0.forEachChild(_,Q),J}function i_(_,$,J){if($<0||J<=$||J>_.getEnd())return;let Q,z=(W)=>{let Z=W.getStart(_,!1),Y=W.getEnd();if($<Z||J>Y)return;if(Z===$&&Y===J)Q=W;W0.forEachChild(W,z)};return W0.forEachChild(_,z),Q}var Y0=8;function BQ(_){return!!(_.flags&y.TypeFlags.Object)&&!!(_.objectFlags&y.ObjectFlags.Reference)}function H_(_,$,J=0,Q){if(Q){let I=Q.get($);if(I)return I}let z=_.typeToString($),W=$.flags,Z=!!(W&y.TypeFlags.Union),Y=!!(W&y.TypeFlags.Intersection),X;if(J<Y0&&BQ($)){let I=_.getTypeArguments($);if(I.length>0)X=I}let M=!!(W&y.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,O;if(Z&&J<Y0)O=$.types.map((I)=>H_(_,I,J+1,Q));else if(Y&&J<Y0)O=$.types.map((I)=>H_(_,I,J+1,Q));let L;if(X&&X.length>0)L=X.map((I)=>H_(_,I,J+1,Q));let C;if(J<Y0&&!!(W&y.TypeFlags.Object)&&!Z&&!Y){let I=_.getPropertiesOfType($);if(I.length>0&&I.length<=50){let q=$.symbol?.declarations?.[0];C=[];for(let G of I){let F=G.declarations?.[0]??q;if(!F)continue;try{let E=_.getTypeOfSymbolAtLocation(G,F);C.push({name:G.getName(),type:H_(_,E,J+1,Q)})}catch{}}if(C.length===0)C=void 0}}let R={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:M,members:O,typeArguments:L,properties:C};if(Q)Q.set($,R);return R}function Z0(_,$,J){if($.flags&y.TypeFlags.Any)return!1;if($.isUnion()){let Z=$.types.filter((Y)=>!(Y.flags&(y.TypeFlags.Void|y.TypeFlags.Undefined|y.TypeFlags.Null)));return J?Z.some((Y)=>Z0(_,Y,J)):Z.length>0&&Z.every((Y)=>Z0(_,Y,J))}if($.isIntersection())return $.types.some((Z)=>Z0(_,Z,J));let Q=_.getPropertyOfType($,"then");if(!Q)return!1;let z=Q.declarations?.[0];if(!z)return!1;return _.getTypeOfSymbolAtLocation(Q,z).getCallSignatures().some((Z)=>Z.parameters.length>=1)}function IQ(_){return y.isFunctionDeclaration(_)||y.isVariableDeclaration(_)||y.isClassDeclaration(_)||y.isInterfaceDeclaration(_)||y.isTypeAliasDeclaration(_)||y.isEnumDeclaration(_)||y.isMethodDeclaration(_)||y.isPropertyDeclaration(_)||y.isPropertySignature(_)||y.isMethodSignature(_)}var b0="/__gildash_type_probe__.ts";class P0{program;#$=null;constructor(_){this.program=_}#_(_){if(this.#$===_)return;this.program.notifyFileChanged(b0,`declare const __gildash_probe__: ${_};`),this.#$=_}#Q(_,$){let J=_.getSourceFile(b0);if(!J)return null;let Q=J.statements[0];if(!Q||!y.isVariableStatement(Q))return null;let z=Q.declarationList.declarations[0];if(!z)return null;let W=$.getTypeAtLocation(z.name);if(!!(W.flags&y.TypeFlags.Any)&&W.intrinsicName==="error")return null;return W}clearProbe(){if(this.#$!==null)this.program.removeFile(b0),this.#$=null}collectAt(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let W=e(z,$);if(!W)return null;if(!y.isIdentifier(W)&&!y.isTypeNode(W))return null;try{let Z=Q.getTypeAtLocation(W);return H_(Q,Z,0,new Map)}catch{return null}}collectAtSpan(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return null;let W=i_(z,$.start,$.end);if(!W)return null;try{let Z=Q.getTypeAtLocation(W);return H_(Q,Z,0,new Map)}catch{return null}}isThenableAtSpan(_,$,J){let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return null;let Z=i_(W,$.start,$.end);if(!Z)return null;try{let Y=z.getTypeAtLocation(Z);return Z0(z,Y,J?.anyConstituent??!0)}catch{return null}}contextualCallReturnsAtSpan(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return null;let W=i_(z,$.start,$.end);if(!W||!y.isExpression(W))return null;try{let Z=Q.getContextualType(W);if(!Z)return null;let Y=Z.isUnion()?Z.types.filter((O)=>!(O.flags&(y.TypeFlags.Void|y.TypeFlags.Undefined|y.TypeFlags.Null))):[Z],X=new Map,M=[];for(let O of Y)for(let L of O.getCallSignatures()){let C=Q.getReturnTypeOfSignature(L);M.push(H_(Q,C,0,X))}return M}catch{return null}}isAssignableToTypeAtSpan(_,$,J,Q){this.#_(J);let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=i_(Z,$.start,$.end);if(!Y)return null;try{let X=this.#Q(z,W);if(!X)return null;let M=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&M.isUnion())return M.types.some((O)=>W.isTypeAssignableTo(O,X));return W.isTypeAssignableTo(M,X)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!y.isIdentifier(Y))return null;let X=z.getSourceFile(J);if(!X)return null;let M=e(X,Q);if(!M||!y.isIdentifier(M))return null;try{let O=W.getTypeAtLocation(Y),L=W.getTypeAtLocation(M);return W.isTypeAssignableTo(O,L)}catch{return null}}isAssignableToType(_,$,J,Q){this.#_(J);let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!y.isIdentifier(Y)&&!y.isTypeNode(Y))return null;try{let X=this.#Q(z,W);if(!X)return null;let M=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&M.isUnion())return M.types.some((O)=>W.isTypeAssignableTo(O,X));return W.isTypeAssignableTo(M,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#_(J);let W=this.program.getProgram(),Z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return z;try{let X=this.#Q(W,Z);if(!X)return z;let M=Y.getEnd();for(let O of $){if(O<0||O>=M)continue;let L=e(Y,O);if(!L||!y.isIdentifier(L)&&!y.isTypeNode(L))continue;try{let C=Z.getTypeAtLocation(L);if(Q?.anyConstituent&&C.isUnion())z.set(O,C.types.some((R)=>Z.isTypeAssignableTo(R,X)));else z.set(O,Z.isTypeAssignableTo(C,X))}catch{}}}catch{}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return J;let Z=W.getEnd(),Y=new Map;for(let X of $){if(X<0||X>=Z)continue;let M=e(W,X);if(!M)continue;if(!y.isIdentifier(M)&&!y.isTypeNode(M))continue;try{let O=z.getTypeAtLocation(M);J.set(X,H_(z,O,0,Y))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return $;let W=new Map;function Z(Y){if(IQ(Y)&&Y.name&&y.isIdentifier(Y.name)){let X=Y.name;try{let M=Q.getTypeAtLocation(X),O=X.getStart(z);$.set(O,H_(Q,M,0,W))}catch{}}y.forEachChild(Y,Z)}return Z(z),$}}import w_ from"typescript";var wQ=1000,DQ=1;function CQ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?w_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function X0(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),W=Q?w_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},M=_;if(M.parent)X.parent=CQ(M.parent);let O=J&&!!(_.flags&w_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<DQ){let L=O.flags,C=!!(L&w_.SymbolFlags.Enum),R=!!(L&(w_.SymbolFlags.NamespaceModule|w_.SymbolFlags.ValueModule)),I=!!(L&(w_.SymbolFlags.Class|w_.SymbolFlags.Interface));if(C&&O.exports&&O.exports.size>0){let q=[];O.exports.forEach((G)=>{q.push(X0(G,$+1,J))}),X.members=q}else if(I&&O.members&&O.members.size>0){let q=[];O.members.forEach((G)=>{q.push(X0(G,$+1,J))}),X.members=q}if(R&&O.exports&&O.exports.size>0){let q=[];O.exports.forEach((G)=>{q.push(X0(G,$+1,J))}),X.exports=q}}return X}class f0{#$;#_;constructor(_,$=wQ){this.#$=_,this.#_=new l_($)}get(_,$){if(this.#$.isDisposed)return null;let J=`${_}:${$}`,Q=this.#_.get(J);if(Q!==void 0)return Q;let z=this.#$.getProgram(),W=z.getSourceFile(_);if(!W)return null;let Z=e(W,$);if(!Z||!w_.isIdentifier(Z))return null;let Y=z.getTypeChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let M=X0(X,0,Y);return this.#_.set(J,M),M}clear(){this.#_.clear()}}import d from"typescript";import k from"typescript";function y0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(AQ($))return!0;return!1}function AQ(_){if(!k.canHaveModifiers(_))return!1;return k.getModifiers(_)?.some((J)=>J.kind===k.SyntaxKind.DeclareKeyword)??!1}function x0(_){let $=(Q,z)=>({kind:Q,pos:z.getStart(),end:z.getEnd()}),J=_.parent;while(J){if(k.isSourceFile(J)||k.isModuleDeclaration(J))return $("module",J);if(k.isFunctionLike(J))return $("function",J);if(k.isClassStaticBlockDeclaration(J))return $("function",J);if(k.isPropertyDeclaration(J))return $("function",J);if(k.isBlock(J)){let Q=J.parent;if(Q&&(k.isFunctionLike(Q)||k.isClassStaticBlockDeclaration(Q)))return $("function",Q);return $("block",J)}if(k.isForStatement(J)||k.isForInStatement(J)||k.isForOfStatement(J)||k.isCatchClause(J)||k.isCaseBlock(J)||k.isWithStatement(J))return $("block",J);J=J.parent}return $("module",_.getSourceFile())}function m0(_){let $=_.parent;if(!$)return;if(k.isVariableDeclaration($)&&$.name===_)return"declaration";if(k.isParameter($)&&$.name===_)return"declaration";if(k.isBindingElement($)&&$.name===_)return"declaration";if((k.isForOfStatement($)||k.isForInStatement($))&&$.initializer===_)return"assignment";if((k.isPrefixUnaryExpression($)||k.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===k.SyntaxKind.PlusPlusToken||$.operator===k.SyntaxKind.MinusMinusToken))return"update";let J=_;while(J.parent&&k.isParenthesizedExpression(J.parent))J=J.parent;let Q=J.parent;if(Q&&k.isBinaryExpression(Q)&&Q.left===J)return qQ(Q.operatorToken.kind);if(NQ(_))return"assignment";return}function qQ(_){switch(_){case k.SyntaxKind.EqualsToken:return"assignment";case k.SyntaxKind.PlusEqualsToken:case k.SyntaxKind.MinusEqualsToken:case k.SyntaxKind.AsteriskEqualsToken:case k.SyntaxKind.AsteriskAsteriskEqualsToken:case k.SyntaxKind.SlashEqualsToken:case k.SyntaxKind.PercentEqualsToken:case k.SyntaxKind.LessThanLessThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case k.SyntaxKind.AmpersandEqualsToken:case k.SyntaxKind.BarEqualsToken:case k.SyntaxKind.CaretEqualsToken:return"compound-assignment";case k.SyntaxKind.AmpersandAmpersandEqualsToken:case k.SyntaxKind.BarBarEqualsToken:case k.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function NQ(_){let $=_.parent;if(!$)return!1;if(!(k.isShorthandPropertyAssignment($)&&$.name===_||k.isPropertyAssignment($)&&$.initializer===_||k.isArrayLiteralExpression($)||k.isSpreadAssignment($)&&$.expression===_||k.isSpreadElement($)&&$.expression===_))return!1;let Q=$;while(Q.parent){let z=Q.parent;if(k.isBinaryExpression(z)&&z.left===Q&&z.operatorToken.kind===k.SyntaxKind.EqualsToken)return!0;if(k.isObjectLiteralExpression(z)||k.isArrayLiteralExpression(z)||k.isPropertyAssignment(z)||k.isShorthandPropertyAssignment(z)||k.isSpreadAssignment(z)||k.isSpreadElement(z)){Q=z;continue}return!1}return!1}class h0{#$;constructor(_){this.#$=_}findAt(_,$){let J=this.#_(_,$);if(!J)return[];let Q=this.#$.getProgram(),z=[];for(let W of J)for(let Z of W.references){let Y=Q.getSourceFile(Z.fileName);if(!Y)continue;z.push(q1(Z,Y))}return z}findEnrichedAt(_,$){let J=this.#_(_,$);if(!J)return[];let Q=this.#$.getProgram(),z=Q.getTypeChecker(),W=[];for(let Z of J){let Y=this.#Q(Z,Q,z);for(let X of Z.references){let M=Q.getSourceFile(X.fileName);if(!M)continue;let O=e(M,X.textSpan.start),L=O&&d.isIdentifier(O)?O:void 0;W.push({...q1(X,M),writeKind:L?m0(L):void 0,isAmbient:Y,enclosingScope:x0(L??M)})}}return W}findFileBindings(_){if(this.#$.isDisposed)return[];let $=this.#$.getProgram(),J=$.getSourceFile(_);if(!J)return[];return n0(J,$.getTypeChecker())}#_(_,$){if(this.#$.isDisposed)return null;let Q=this.#$.getProgram().getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z||!d.isIdentifier(z))return null;let W=this.#$.getLanguageService().findReferences(_,$);if(!W||W.length===0)return null;return W}#Q(_,$,J){let Q=_.definition,z=$.getSourceFile(Q.fileName);if(!z)return!1;let W=e(z,Q.textSpan.start);if(!W)return!1;let Y=J.getSymbolAtLocation(W)?.declarations;if(!Y||Y.length===0)return!1;return Y.every(y0)}}function n0(_,$){let J=new Map,Q=(W)=>{if(d.isIdentifier(W)&&!RQ(W)){let Z=TQ(W,$);if(Z){let Y=J.get(Z);if(Y)Y.push(W);else J.set(Z,[W])}}d.forEachChild(W,Q)};d.forEachChild(_,Q);let z=[];for(let[W,Z]of J){let Y=W.declarations;if(!Y||Y.length===0)continue;if(Y.every(SQ))continue;let X=Y.every(y0),M=new Set(Y.map((I)=>d.getNameOfDeclaration(I)).filter((I)=>I!==void 0)),O=Y[0],L=d.getNameOfDeclaration(O)??O,C=O.getSourceFile(),R=Z.map((I)=>{let q=I.getStart(_),{line:G,character:F}=_.getLineAndCharacterOfPosition(q),E=m0(I);return{filePath:_.fileName,position:q,line:G+1,column:F,isDefinition:M.has(I),isWrite:E!==void 0,writeKind:E,isAmbient:X,enclosingScope:x0(I)}});z.push({declaration:{filePath:C.fileName,position:L.getStart(C),name:W.getName(),isAmbient:X},references:R})}return z}function RQ(_){let $=_.parent;return d.isPropertyAccessExpression($)&&$.name===_||d.isQualifiedName($)&&$.right===_||d.isPropertyAssignment($)&&$.name===_||d.isBindingElement($)&&$.propertyName===_||d.isJsxAttribute($)&&$.name===_||d.isImportSpecifier($)&&$.propertyName===_||d.isModuleDeclaration($)&&$.name===_&&($.flags&d.NodeFlags.GlobalAugmentation)!==0}function SQ(_){return d.isPropertyDeclaration(_)||d.isPropertySignature(_)||d.isMethodDeclaration(_)||d.isMethodSignature(_)||d.isGetAccessorDeclaration(_)||d.isSetAccessorDeclaration(_)||d.isEnumMember(_)||d.isParameter(_)&&d.isIndexSignatureDeclaration(_.parent)}function TQ(_,$){let J=_.parent;if(d.isShorthandPropertyAssignment(J))return $.getShorthandAssignmentValueSymbol(J);if(d.isExportSpecifier(J)){let Q=J.parent.parent;if(d.isExportDeclaration(Q)&&Q.moduleSpecifier)return;return(J.propertyName??J.name)===_?$.getExportSpecifierLocalTargetSymbol(J):void 0}return $.getSymbolAtLocation(_)}function q1(_,$){let{line:J,character:Q}=$.getLineAndCharacterOfPosition(_.textSpan.start);return{filePath:_.fileName,position:_.textSpan.start,line:J+1,column:Q,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1}}import c_ from"typescript";function N1(_,$,J={}){let Q=c_.createSourceFile(_,$,J.target??c_.ScriptTarget.ESNext,!0),z={target:J.target,module:J.module,jsx:J.jsx??(_.endsWith(".tsx")?c_.JsxEmit.Preserve:void 0),jsxFactory:J.jsxFactory,jsxFragmentFactory:J.jsxFragmentFactory,jsxImportSource:J.jsxImportSource,experimentalDecorators:J.experimentalDecorators,useDefineForClassFields:J.useDefineForClassFields,noLib:!0,noResolve:!0,types:[]},W=c_.createCompilerHost(z,!0);W.getSourceFile=(X)=>X===_?Q:void 0;let Z=c_.createProgram([_],z,W),Y=Z.getSourceFile(_);if(!Y)return[];return n0(Y,Z.getTypeChecker())}import h from"typescript";function FQ(_,$){let J=e(_,$);if(!J)return;if(R1(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(R1(Q))return Q;Q=Q.parent}return J}function R1(_){return h.isClassDeclaration(_)||h.isClassExpression(_)||h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_)||h.isVariableDeclaration(_)||h.isObjectLiteralExpression(_)}function S1(_){if(h.isClassDeclaration(_)||h.isClassExpression(_))return"class";if(h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_))return"function";if(h.isObjectLiteralExpression(_))return"object";if(h.isVariableDeclaration(_)&&_.initializer)return S1(_.initializer);return"class"}function GQ(_,$){if(h.isClassDeclaration(_)||h.isFunctionDeclaration(_))return _.name?.getText($)??"";if(h.isClassExpression(_))return _.name?.getText($)??"";if(h.isVariableDeclaration(_)&&h.isIdentifier(_.name))return _.name.getText($);if(h.isFunctionExpression(_))return _.name?.getText($)??"";if(h.isArrowFunction(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(h.isObjectLiteralExpression(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function jQ(_){if(!h.isClassDeclaration(_)&&!h.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===h.SyntaxKind.ImplementsKeyword)}class d0{#$;constructor(_){this.#$=_}findAt(_,$){if(this.#$.isDisposed)return[];let J=this.#$.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=e(Q,$);if(!z||!h.isIdentifier(z))return[];let Z=this.#$.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===h.ScriptElementKind.interfaceElement||X.kind===h.ScriptElementKind.typeElement)continue;let M=J.getSourceFile(X.fileName);if(!M)continue;let O=FQ(M,X.textSpan.start);if(!O)continue;let L=S1(O),C=GQ(O,M),R=jQ(O);Y.push({filePath:X.fileName,symbolName:C,position:X.textSpan.start,kind:L,isExplicit:R})}return Y}}function gQ(_){if(__.isFunctionDeclaration(_))return"function";if(__.isClassDeclaration(_))return"class";if(__.isInterfaceDeclaration(_))return"interface";if(__.isTypeAliasDeclaration(_))return"type";if(__.isEnumDeclaration(_))return"enum";if(__.isVariableDeclaration(_))return"const";if(__.isVariableStatement(_))return"const";return"unknown"}function T1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class U0{#$;#_;#Q;#z;#W;#Y=!1;constructor(_,$,J,Q,z){this.#$=_,this.#_=$,this.#Q=J,this.#z=Q,this.#W=z}static create(_,$={}){let J=z0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(kQ(J))return J;let Q=J,z=$.typeCollector??new P0(Q),W=$.symbolGraph??new f0(Q),Z=$.referenceResolver??new h0(Q),Y=$.implementationFinder??new d0(Q);return new U0(Q,z,W,Z,Y)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#J(),this.#_.collectAt(_,$)}collectFileTypes(_){return this.#J(),this.#_.collectFile(_)}collectTypesAtPositions(_,$){return this.#J(),this.#_.collectAtPositions(_,$)}collectAtSpan(_,$){return this.#J(),this.#_.collectAtSpan(_,$)}isThenableAtSpan(_,$,J){return this.#J(),this.#_.isThenableAtSpan(_,$,J)}contextualCallReturnsAtSpan(_,$){return this.#J(),this.#_.contextualCallReturnsAtSpan(_,$)}isTypeAssignableToTypeAtSpan(_,$,J,Q){return this.#J(),this.#_.isAssignableToTypeAtSpan(_,$,J,Q)}findReferences(_,$){return this.#J(),this.#z.findAt(_,$)}findEnrichedReferences(_,$){return this.#J(),this.#z.findEnrichedAt(_,$)}getFileBindings(_){return this.#J(),this.#z.findFileBindings(_)}getStandaloneFileBindings(_,$){this.#J();let J=this.#$.getCompilerOptions();return N1(_,$,{target:J.target,module:J.module,jsx:J.jsx,jsxFactory:J.jsxFactory,jsxFragmentFactory:J.jsxFragmentFactory,jsxImportSource:J.jsxImportSource,experimentalDecorators:J.experimentalDecorators,useDefineForClassFields:J.useDefineForClassFields})}getFileBindingsBatch(_){this.#J();for(let J of _)this.notifyFileChanged(J.filePath,J.content);let $=new Map;for(let J of _)$.set(J.filePath,this.#z.findFileBindings(J.filePath));return $}findImplementations(_,$){return this.#J(),this.#W.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#J(),this.#_.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#J(),this.#_.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#J(),this.#_.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#J(),this.#Q.get(_,$)}getBaseTypes(_,$){this.#J();let J=this.#$.getProgram(),Q=J.getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z)return null;let W=J.getTypeChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&__.TypeFlags.Object)||!(Z.objectFlags&__.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((M)=>H_(W,M,0,X))}getModuleInterface(_){this.#J();let $=[],J=this.#$.getProgram(),Q=J.getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=J.getTypeChecker(),W=z.getSymbolAtLocation(Q);if(W){let Z=z.getExportsOfModule(W),Y=new Map;for(let X of Z){let M=X.getName(),O=X.declarations?.[0],L="unknown";if(O){if(L=gQ(O),L==="unknown"&&__.isExportAssignment(O))L="const"}let C=null;try{let R=z.getTypeOfSymbolAtLocation(X,O??Q);C=H_(z,R,0,Y)}catch{}$.push({name:M,kind:L,resolvedType:C})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#$.notifyFileChanged(_,$),this.#Q.clear()}notifyFileDeleted(_){if(this.#Y)return;this.#$.removeFile(_),this.#Q.clear()}lineColumnToPosition(_,$,J){this.#J();let Q=this.#$.getProgram().getSourceFile(_);if(!Q)return null;try{return __.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#J();let Q=this.#$.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),W=$;while(W<z.length){let Z=z.indexOf(J,W);if(Z<0)return null;let Y=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!T1(Y)&&!T1(X))return Z;W=Z+1}return null}getDiagnostics(_,$){this.#J();let J=this.#$.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[__.DiagnosticCategory.Error]:"error",[__.DiagnosticCategory.Warning]:"warning",[__.DiagnosticCategory.Suggestion]:"suggestion",[__.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?__.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let M=__.getLineAndCharacterOfPosition(Z.file,Z.start);Y=M.line+1,X=M.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:__.flattenDiagnosticMessageText(Z.messageText,`
10
- `),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#_.clearProbe(),this.#$.dispose(),this.#Q.clear()}#J(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as G_,and as F1,sql as vQ}from"drizzle-orm";var G1=80;class p0{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+=G1)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+G1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(F1(G_(Z_.project,_),G_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(F1(_.project?G_(Z_.project,_.project):void 0,_.tag?G_(Z_.tag,_.tag):void 0,_.filePath?G_(Z_.filePath,_.filePath):void 0,_.symbolName?G_(Z_.symbolName,_.symbolName):void 0,_.source?G_(Z_.source,_.source):void 0,_.ftsQuery?vQ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as P_,and as j1,sql as a_,gt as EQ,gte as uQ}from"drizzle-orm";var k1=80;class l0{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+=k1)this.db.drizzleDb.insert($_).values($.slice(J,J+k1)).run()}getSince(_){return this.db.drizzleDb.select().from($_).where(j1(P_($_.project,_.project),uQ($_.changedAt,_.since),_.symbolName?P_($_.symbolName,_.symbolName):void 0,_.changeTypes?.length?a_`${$_.changeType} IN (${a_.join(_.changeTypes.map(($)=>a_`${$}`),a_`, `)})`:void 0,_.filePath?P_($_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:P_($_.isFullIndex,0),_.indexRunId?P_($_.indexRunId,_.indexRunId):void 0,_.afterId?EQ($_.id,_.afterId):void 0)).orderBy($_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete($_).where(j1(P_($_.project,_),a_`${$_.changedAt} < ${$}`)).run().changes}}function g1(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Y=g_(Q.text);if(Y)W=Y}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:W,limit:Q.limit}).map((Y)=>({tag:Y.tag,value:Y.value,source:Y.source,filePath:Y.filePath,symbolName:Y.symbolName,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}}}))}class V0{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 W=this.adjacencyList.get(z);if(W){for(let Y of W)this.reverseAdjacencyList.get(Y)?.delete(z);W.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let Y of Z)this.adjacencyList.get(Y)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let W=J(z);for(let Z of W){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 W of this.adjacencyList.get(z.node)??[]){if($.has(W))return!0;if(!_.has(W))Q.push({node:W,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 xQ(J,$)}}var bQ=(_,$)=>_.localeCompare($);function PQ(_){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 i0(_,$,J){let Q=PQ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function fQ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Z=[],Y=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let M of _.get(X)??[])if(!z.has(M))Y(M),W.set(X,Math.min(W.get(X)??0,W.get(M)??0));else if(Q.has(M))W.set(X,Math.min(W.get(X)??0,z.get(M)??0));if(W.get(X)===z.get(X)){let M=[],O="";do O=J.pop()??"",Q.delete(O),M.push(O);while(O!==X&&J.length>0);Z.push(M)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function yQ(_,$,J){let Q=[],z=new Set,W=[..._].sort(bQ),Z=(Y,X,M)=>{X.delete(Y);let O=M.get(Y);if(!O)return;for(let L of O)if(X.has(L))Z(L,X,M);O.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",M=new Set(W.slice(Y)),O=new Set,L=new Map,C=[],R=(q)=>($.get(q)??[]).filter((G)=>M.has(G)),I=(q)=>{if(Q.length>=J)return!0;let G=!1;C.push(q),O.add(q);for(let F of R(q)){if(Q.length>=J)break;if(F===X)i0(z,Q,C.concat(X)),G=!0;else if(!O.has(F)){if(I(F))G=!0}}if(G)Z(q,O,L);else for(let F of R(q)){let E=L.get(F)??new Set;E.add(q),L.set(F,E)}return C.pop(),G};I(X)}return Q}function xQ(_,$){let{components:J}=fQ(_),Q=[],z=new Set;for(let W of J){if(Q.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))i0(z,Q,[X,X]);continue}let Z=$-Q.length,Y=yQ(W,_,Z);for(let X of Y){if(Q.length>=$)break;i0(z,Q,X)}}return Q}var mQ=15000;function O0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function j_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>mQ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new V0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function v1(_,$,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 E1(_,$,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 u1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function b1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function P1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function f1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function y1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function x1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return j_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function m1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=j_(_,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 dQ=30000,h1=15000,pQ=10;function lQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??f_.basename(_.projectRoot)}function iQ(_,$){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 W of _.onErrorCallbacks)try{W(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 cQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=f_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function n1(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new j0({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,onBoundariesChanged:(Q)=>lQ(_,Q),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 W=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>W.getByType(X,"imports").concat(W.getByType(X,"type-references")).concat(W.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 O0(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new A0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(iQ(_,J)).then((z)=>{if(s_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},dQ)}await J.fullIndex(),await cQ(_)}function aQ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((W)=>_.logger.error("[Gildash] close error during signal",Q,W))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function d1(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:W=console,existsSyncFn:Z=nQ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:M,repositoryFactory:O,acquireWatcherRoleFn:L=w1,releaseWatcherRoleFn:C=D1,updateHeartbeatFn:R=C1,discoverProjectsFn:I=t_,parseSourceFn:q=E_,extractSymbolsFn:G=S_,extractRelationsFn:F=p_,symbolSearchFn:E=g0,relationSearchFn:b=v0,patternSearchFn:m=E0,loadTsconfigPathsFn:l=n_,readFileFn:i=async(s)=>Bun.file(s).text(),unlinkFn:W_=async(s)=>{await Bun.file(s).unlink()},watchMode:X_,semantic:M_,semanticLayerFactory:U_}=_;if(!f_.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 Y_=Y?Y():new B0({projectRoot:$}),c=Y_.open();if(s_(c))throw c.data;try{let s=await I($),D_=s[0]?.project??f_.basename($),D=O?O():(()=>{let T=Y_;return{fileRepo:new I0(T),symbolRepo:new w0(T),relationRepo:new D0(T),parseCache:new k0(z)}})(),N=O?null:Y_,U=N?new p0(N):null,H=N?new l0(N):null,K=X_??!0,B=crypto.randomUUID(),A;if(K)A=await Promise.resolve(L(Y_,process.pid,{instanceId:B}));else A="owner";let w={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:D_,role:A,db:Y_,symbolRepo:D.symbolRepo,relationRepo:D.relationRepo,fileRepo:D.fileRepo,parseCache:D.parseCache,annotationRepo:U,changelogRepo:H,annotationSearchFn:g1,releaseWatcherRoleFn:C,parseSourceFn:q,extractSymbolsFn:G,extractRelationsFn:F,symbolSearchFn:E,relationSearchFn:b,patternSearchFn:m,readFileFn:i,unlinkFn:W_,existsSyncFn:Z,acquireWatcherRoleFn:L,updateHeartbeatFn:R,watcherFactory:X,coordinatorFactory:M,instanceId:B,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:s,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(e_($),w.tsconfigPaths=await l($),M_){let T=f_.join($,"tsconfig.json");try{if(U_)w.semanticLayer=U_(T);else{let S=U0.create(T);if(s_(S))throw S.data;w.semanticLayer=S}}catch(S){if(S instanceof V)throw S;throw new V("semantic","Gildash: semantic layer creation failed",{cause:S})}}if(A==="owner")await n1(w,{isWatchMode:K});else{let T=0,S=async()=>{try{let j=await Promise.resolve(w.acquireWatcherRoleFn(w.db,process.pid,{instanceId:w.instanceId}));if(T=0,j==="owner"){w.role="owner";for(let g of w.onRoleChangedCallbacks)try{g("owner")}catch(P){w.logger.error("[Gildash] onRoleChanged callback threw:",P)}clearInterval(w.timer),w.timer=null;try{await n1(w,{isWatchMode:!0})}catch(g){if(w.logger.error("[Gildash] owner promotion failed, reverting to reader",g),w.role="reader",w.timer!==null)clearInterval(w.timer),w.timer=null;if(w.watcher){let P=await w.watcher.close();if(s_(P))w.logger.error("[Gildash] watcher close error during promotion rollback",P.data);w.watcher=null}if(w.coordinator)await w.coordinator.shutdown().catch((P)=>w.logger.error("[Gildash] coordinator shutdown error during promotion rollback",P)),w.coordinator=null;try{w.releaseWatcherRoleFn(w.db,process.pid)}catch(P){w.logger.error("[Gildash] failed to release watcher role during promotion rollback",P)}w.timer=setInterval(S,h1)}}}catch(j){T++;let g=j instanceof V?j:new V("watcher","Gildash: healthcheck error",{cause:j});for(let P of w.onErrorCallbacks)try{P(g)}catch(p){w.logger.error("[Gildash] onError callback threw:",p)}if(w.logger.error("[Gildash] healthcheck error",j),T>=pQ)w.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(w.timer),w.timer=null,H0(w).catch((P)=>w.logger.error("[Gildash] close error during healthcheck shutdown",P))}};w.timer=setInterval(S,h1)}if(K)aQ(w,()=>H0(w));return w}catch(s){if(Y_.close(),s instanceof V)throw s;throw new V("store","Gildash: initialization failed",{cause:s})}}async function H0(_,$){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(s_(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(f_.join(_.projectRoot,A_,r_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as p1}from"@zipbul/result";function l1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(p1(z))throw z.data;return _.parseCache.set($,z),z}async function i1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Z=await _.readFileFn(W),Y=_.parseSourceFn(W,Z,J);if(!p1(Y))Q.set(W,Y);else z.push({filePath:W,error:Y.data})}catch(Z){z.push({filePath:W,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function c1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function a1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function s1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import r1 from"path";function o1(_,$){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 c0(_,$){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 t1(_,$){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 e1(_,$){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 _$(_,$){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 $$(_,$){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 J$(_,$,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 Q$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Z=W[0],Y=Z.detail,X={...Z,members:Y.members,jsDoc:Y.jsDoc,parameters:Y.parameters,returnType:Y.returnType,heritage:Y.heritage,decorators:Y.decorators,typeParameters:Y.typeParameters,initializer:Y.initializer};if(_.semanticLayer)try{let M=r1.isAbsolute(J)?J:r1.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(M,Z.span.start.line,Z.span.start.column);if(O!==null){let L=_.semanticLayer.findNamePosition(M,O,Z.name)??O,C=_.semanticLayer.collectTypeAt(M,L);if(C)X.resolvedType=C}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function z$(_,$,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 W=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Y)=>Y.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function W$(_,$,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 Y$(_,$,J){return c0(_,{filePath:$,project:J??void 0,limit:1e4})}function Z$(_,$,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((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.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 v from"path";function y_(_,$,J,Q){let z=Q??_.defaultProject,W=v.isAbsolute(J)?v.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:W,limit:1}});if(Z.length===0)return null;let Y=Z[0],X=v.isAbsolute(J)?J:v.resolve(_.projectRoot,J),M=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(M===null)return null;let O=_.semanticLayer.findNamePosition(X,M,Y.name)??M;return{sym:Y,position:O,absPath:X}}function X$(_,$,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=y_(_,$,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 U$(_,$,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=y_(_,$,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 V$(_,$,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=y_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findEnrichedReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getEnrichedReferences failed",{cause:z})}}function O$(_,$,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=y_(_,$,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 H$(_,$,J,Q,z,W){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=y_(_,$,J,W);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=y_(_,Q,z,W);if(!Y)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,Y.absPath,Y.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function K$(_,$){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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function M$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function L$(_,$){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=v.isAbsolute($.source.filePath)?$.source.filePath:v.resolve(_.projectRoot,$.source.filePath),Q=v.isAbsolute($.target.filePath)?$.target.filePath:v.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let W=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,W)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function B$(_,$){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 I$(_,$,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=v.isAbsolute($)?$:v.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 w$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function D$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.collectAtSpan(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getExpressionTypeAtSpan failed",{cause:Q})}}function C$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isThenableAtSpan(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: isThenableAtSpan failed",{cause:z})}}function A$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.contextualCallReturnsAtSpan(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getContextualCallReturnsAtSpan failed",{cause:Q})}}function q$(_,$,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 W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtSpan(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToTypeAtSpan failed",{cause:W})}}function N$(_,$,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=v.isAbsolute($)?$:v.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 R$(_,$,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=v.isAbsolute($)?$:v.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 S$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getEnrichedReferencesAtPosition failed",{cause:Q})}}function T$(_,$){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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindings failed",{cause:J})}}function F$(_,$){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=$.map((W)=>({orig:W.filePath,abs:v.isAbsolute(W.filePath)?W.filePath:v.resolve(_.projectRoot,W.filePath),content:W.content})),Q=_.semanticLayer.getFileBindingsBatch(J.map((W)=>({filePath:W.abs,content:W.content}))),z=new Map;for(let W of J)z.set(W.orig,Q.get(W.abs)??[]);return z}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindingsBatch failed",{cause:J})}}function G$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.getStandaloneFileBindings(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getStandaloneFileBindings failed",{cause:Q})}}function j$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);_.semanticLayer.notifyFileChanged(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: notifyFileChanged failed",{cause:Q})}}function k$(_,$){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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);_.semanticLayer.notifyFileDeleted(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: notifyFileDeleted failed",{cause:J})}}function g$(_,$,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=v.isAbsolute($)?$:v.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 v$(_,$,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 W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$),Z=v.isAbsolute(Q)?Q:v.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function E$(_,$,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 W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function u$(_,$,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 W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function b$(_,$,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=v.isAbsolute($)?$:v.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 P$(_,$,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=v.isAbsolute($)?$:v.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 f$(_,$,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=v.isAbsolute($)?$:v.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 y$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}import eQ from"path";function x$(_,$){let J=new Map(_.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),Q=new Map($.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),z=[],W=[],Z=[];for(let[Y,X]of Q){let M=J.get(Y);if(!M)z.push(X);else if(M.fingerprint!==X.fingerprint)Z.push({before:M,after:X})}for(let[Y,X]of J)if(!Q.has(Y))W.push(X);return{added:z,removed:W,modified:Z}}function m$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function h$(_){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 O0(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function n$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let M=`${X}::${Y}`;if(W.has(M))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(M);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),L,C;for(let R of O){let I;if(R.metaJson)try{let G=JSON.parse(R.metaJson);if(Array.isArray(G.specifiers))I=G.specifiers}catch{}if(!I)continue;let q=I.find((G)=>G.exported===Y);if(!q)continue;L=R.dstFilePath??void 0,C=q.local;break}if(!L||!C)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=L,Y=C}}function d$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function p$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function l$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function i$(_,$,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((W)=>W.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 c$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(X,M,O)=>{let L=`${X}::${M}`;if(W.has(L))return{symbolName:X,filePath:M,kind:O,children:[]};W.add(L);let I=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:M,srcSymbolName:X,limit:1000}}).filter((q)=>q.type==="extends"||q.type==="implements").filter((q)=>q.dstSymbolName!=null&&q.dstFilePath!=null).map((q)=>Z(q.dstSymbolName,q.dstFilePath,q.type));return{symbolName:X,filePath:M,kind:O,children:I}},Y=eQ.isAbsolute(J)?R_(_.projectRoot,J):J;return Z($,Y)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function a$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function s$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,W=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:W}).map((Y)=>({changeType:Y.changeType,symbolName:Y.symbolName,symbolKind:Y.symbolKind,filePath:Y.filePath,oldName:Y.oldName,oldFilePath:Y.oldFilePath,fingerprint:Y.fingerprint,changedAt:Y.changedAt,isFullIndex:Y.isFullIndex===1,indexRunId:Y.indexRunId}))}function r$(_,$){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)],W=[...new Set(z)];for(let Z of W)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class a0{_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 d1(_);return new a0($)}async close(_){return H0(this._ctx,_)}parseSource(_,$,J){return l1(this._ctx,_,$,J)}async batchParse(_,$){return i1(this._ctx,_,$)}getParsedAst(_){return c1(this._ctx,_)}extractSymbols(_){return a1(this._ctx,_)}extractRelations(_){return s1(this._ctx,_)}getStats(_){return o1(this._ctx,_)}searchSymbols(_){return c0(this._ctx,_)}searchRelations(_){return t1(this._ctx,_)}searchAllSymbols(_){return e1(this._ctx,_)}searchAllRelations(_){return _$(this._ctx,_)}listIndexedFiles(_){return $$(this._ctx,_)}getInternalRelations(_,$){return J$(this._ctx,_,$)}getFullSymbol(_,$,J){return Q$(this._ctx,_,$,J)}getFileStats(_,$){return z$(this._ctx,_,$)}getFileInfo(_,$){return W$(this._ctx,_,$)}getSymbolsByFile(_,$){return Y$(this._ctx,_,$)}getModuleInterface(_,$){return Z$(this._ctx,_,$)}getDependencies(_,$,J=1e4){return v1(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return E1(this._ctx,_,$,J)}async getAffected(_,$){return u1(this._ctx,_,$)}async hasCycle(_){return b1(this._ctx,_)}async getImportGraph(_){return P1(this._ctx,_)}async getTransitiveDependencies(_,$){return f1(this._ctx,_,$)}async getTransitiveDependents(_,$){return y1(this._ctx,_,$)}async getCyclePaths(_,$){return x1(this._ctx,_,$)}async getFanMetrics(_,$){return m1(this._ctx,_,$)}getResolvedType(_,$,J){return X$(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return U$(this._ctx,_,$,J)}getEnrichedReferences(_,$,J){return V$(this._ctx,_,$,J)}getImplementations(_,$,J){return O$(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return H$(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return B$(this._ctx,_)}getFileTypes(_){return K$(this._ctx,_)}getResolvedTypeAt(_,$,J){return M$(this._ctx,_,$,J)}isTypeAssignableToAt(_){return L$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return N$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return w$(this._ctx,_,$)}getExpressionTypeAtSpan(_,$){return D$(this._ctx,_,$)}isThenableAtSpan(_,$,J){return C$(this._ctx,_,$,J)}getContextualCallReturnsAtSpan(_,$){return A$(this._ctx,_,$)}isTypeAssignableToTypeAtSpan(_,$,J,Q){return q$(this._ctx,_,$,J,Q)}getSemanticReferencesAtPosition(_,$){return R$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return S$(this._ctx,_,$)}getFileBindings(_){return T$(this._ctx,_)}getFileBindingsBatch(_){return F$(this._ctx,_)}getStandaloneFileBindings(_,$){return G$(this._ctx,_,$)}notifyFileChanged(_,$){j$(this._ctx,_,$)}notifyFileDeleted(_){k$(this._ctx,_)}getImplementationsAtPosition(_,$){return g$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return v$(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return E$(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return u$(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return b$(this._ctx,_,$,J)}findNamePosition(_,$,J){return P$(this._ctx,_,$,J)}getSymbolNode(_,$){return f$(this._ctx,_,$)}getBaseTypes(_,$){return I$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return y$(this._ctx,_,$)}diffSymbols(_,$){return x$(_,$)}onIndexed(_){return m$(this._ctx,_)}async reindex(){return h$(this._ctx)}resolveSymbol(_,$,J){return n$(this._ctx,_,$,J)}async findPattern(_,$){return i$(this._ctx,_,$)}async getHeritageChain(_,$,J){return c$(this._ctx,_,$,J)}onFileChanged(_){return d$(this._ctx,_)}onError(_){return p$(this._ctx,_)}onRoleChanged(_){return l$(this._ctx,_)}searchAnnotations(_){return a$(this._ctx,_)}getSymbolChanges(_,$){return s$(this._ctx,_,$)}pruneChangelog(_){return r$(this._ctx,_)}}import{Visitor as Y2,visitorKeys as Z2}from"oxc-parser";import{walk as U2,parseAndWalk as V2,ScopeTracker as O2}from"oxc-walker";export{U2 as walk,Z2 as visitorKeys,g0 as symbolSearch,v0 as relationSearch,E0 as patternSearch,E_ as parseSource,V2 as parseAndWalk,z_ as normalizePath,eJ as isVariableDeclaration,tJ as isTSQualifiedName,oJ as isMemberExpression,rJ as isIdentifier,pJ as isFunctionNode,sJ as isFunctionExpression,aJ as isFunctionDeclaration,cJ as isCallExpression,iJ as isAssignmentExpression,lJ as isArrowFunctionExpression,_Q as is,O_ as getLineColumn,S_ as extractSymbols,p_ as extractRelations,d_ as buildLineOffsets,Y2 as Visitor,O2 as ScopeTracker,V as GildashError,a0 as Gildash,V0 as DependencyGraph};
2
+ var zQ=Object.defineProperty;var XQ=(_)=>_;function UQ(_,$){this[_]=XQ.bind(null,$)}var VQ=(_,$)=>{for(var Q in $)zQ(_,Q,{get:$[Q],enumerable:!0,configurable:!0,set:UQ.bind($,Q)})};var Q1=import.meta.require;import{isErr as t_}from"@zipbul/result";import y_ from"path";import{existsSync as tJ}from"fs";import{err as Z1,isErr as BQ}from"@zipbul/result";import{Database as GQ}from"bun:sqlite";import{mkdirSync as IQ,unlinkSync as z1,existsSync as X1}from"fs";import{dirname as wQ,join as U1}from"path";import{drizzle as DQ}from"drizzle-orm/bun-sqlite";import{migrate as CQ}from"drizzle-orm/bun-sqlite/migrator";class N extends Error{type;constructor(_,$,Q){super($,Q);this.type=_;this.name="GildashError"}}var A_=".gildash",_0="gildash.db";var w0={};VQ(w0,{watcherOwner:()=>LQ,symbols:()=>l,symbolChangelog:()=>J_,relations:()=>y,files:()=>t,annotations:()=>H_});import{sql as HQ}from"drizzle-orm";import{sqliteTable as k_,text as f,integer as o,real as KQ,index as Z_,primaryKey as MQ,foreignKey as I0,check as OQ}from"drizzle-orm/sqlite-core";var J1=["function","method","class","variable","type","interface","enum","namespace","property"],Y1=["imports","type-references","re-exports","calls","extends","implements"],W1=["jsdoc","line","block"];var t=k_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:KQ("mtime_ms").notNull(),size:o("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:o("line_count")},(_)=>[MQ({columns:[_.project,_.filePath]})]),l=k_("symbols",{id:o("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind",{enum:J1}).notNull(),name:f("name").notNull(),startLine:o("start_line").notNull(),startColumn:o("start_column").notNull(),endLine:o("end_line").notNull(),endColumn:o("end_column").notNull(),isExported:o("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[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),I0({columns:[_.project,_.filePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),y=k_("relations",{id:o("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type",{enum:Y1}).notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:o("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),I0({columns:[_.project,_.srcFilePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),H_=k_("annotations",{id:o("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source",{enum:W1}).notNull(),symbolName:f("symbol_name"),startLine:o("start_line").notNull(),startColumn:o("start_column").notNull(),endLine:o("end_line").notNull(),endColumn:o("end_column").notNull(),indexedAt:f("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),I0({columns:[_.project,_.filePath],foreignColumns:[t.project,t.filePath]}).onDelete("cascade")]),J_=k_("symbol_changelog",{id:o("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),changeType:f("change_type").notNull(),symbolName:f("symbol_name").notNull(),symbolKind:f("symbol_kind").notNull(),filePath:f("file_path").notNull(),oldName:f("old_name"),oldFilePath:f("old_file_path"),fingerprint:f("fingerprint"),changedAt:f("changed_at").notNull(),isFullIndex:o("is_full_index").notNull().default(0),indexRunId:f("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)]),LQ=k_("watcher_owner",{id:o("id").primaryKey(),pid:o("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("instance_id")},(_)=>[OQ("watcher_owner_singleton",HQ`${_.id} = 1`)]);class D0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=U1(_.projectRoot,A_,_0)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{IQ(wQ(this.dbPath),{recursive:!0}),this.client=new GQ(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=DQ(this.client,{schema:w0}),CQ(this.drizzle,{migrationsFolder:U1(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(_)&&X1(this.dbPath)){this.closeClient(),z1(this.dbPath);for(let Q of["-wal","-shm"]){let J=this.dbPath+Q;if(X1(J))z1(J)}let $=this.open();if(BQ($))return Z1(new N("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return Z1(new N("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 Q=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${Q}"`);try{let J=_(this);return $.run(`RELEASE SAVEPOINT "${Q}"`),J}catch(J){throw $.run(`ROLLBACK TO SAVEPOINT "${Q}"`),$.run(`RELEASE SAVEPOINT "${Q}"`),J}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let Q=_();return $.run("COMMIT"),Q}catch(Q){throw $.run("ROLLBACK"),Q}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 Q=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,Q,Q,$??null)}replaceOwner(_,$){let Q=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,Q,Q,$??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",(Q,J)=>{try{return new RegExp(Q).test(J)?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 m_,and as V1}from"drizzle-orm";class C0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(t).where(V1(m_(t.project,_),m_(t.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(t).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[t.project,t.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(t).where(m_(t.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),Q=new Map;for(let J of $)Q.set(J.filePath,J);return Q}deleteFile(_,$){this.db.drizzleDb.delete(t).where(V1(m_(t.project,_),m_(t.filePath,$))).run()}}import{eq as z_,and as p_,sql as A0,count as AQ}from"drizzle-orm";var H1=50;class q0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,Q,J){if(this.db.drizzleDb.delete(l).where(p_(z_(l.project,_),z_(l.filePath,$))).run(),!J.length)return;let Y=new Date().toISOString(),W=J.map((z)=>({project:_,filePath:$,kind:z.kind,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:Q,indexedAt:z.indexedAt??Y,resolvedType:z.resolvedType??null,structuralFingerprint:z.structuralFingerprint??null}));for(let z=0;z<W.length;z+=H1)this.db.drizzleDb.insert(l).values(W.slice(z,z+H1)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(l).where(p_(z_(l.project,_),z_(l.filePath,$))).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:AQ(),fileCount:A0`COUNT(DISTINCT ${l.filePath})`}).from(l).where(z_(l.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(l).where(p_(z_(l.project,_),z_(l.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(l).where(p_(z_(l.project,_),z_(l.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(l).where(p_(_.ftsQuery?A0`${l.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?z_(l.name,_.exactName):void 0,_.project!==void 0?z_(l.project,_.project):void 0,_.kind?z_(l.kind,_.kind):void 0,_.filePath!==void 0?z_(l.filePath,_.filePath):void 0,_.isExported!==void 0?z_(l.isExported,_.isExported?1:0):void 0,_.decorator?A0`${l.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?z_(l.resolvedType,_.resolvedType):void 0)).orderBy(l.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let Q;try{Q=new RegExp(_.regex)}catch{throw new N("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((W)=>Q.test(W.name));let J=[];for(let Y of[5,20,100]){let W=_.limit*Y,z=$.limit(W).all();if(J=z.filter((Z)=>Q.test(Z.name)),J.length>=_.limit||z.length<W)return J.slice(0,_.limit)}return J.slice(0,_.limit)}}import{eq as d,and as w_,isNull as K1,or as qQ}from"drizzle-orm";var d_={project:y.project,type:y.type,srcFilePath:y.srcFilePath,srcSymbolName:y.srcSymbolName,dstProject:y.dstProject,dstFilePath:y.dstFilePath,dstSymbolName:y.dstSymbolName,metaJson:y.metaJson,specifier:y.specifier,isExternal:y.isExternal};class N0{db;constructor(_){this.db=_}replaceFileRelations(_,$,Q){this.db.transaction((J)=>{if(J.drizzleDb.delete(y).where(w_(d(y.project,_),d(y.srcFilePath,$))).run(),!Q.length)return;for(let Y of Q)J.drizzleDb.insert(y).values({project:_,type:Y.type,srcFilePath:Y.srcFilePath??$,srcSymbolName:Y.srcSymbolName??null,dstProject:Y.dstProject??(Y.dstFilePath!=null?_:null),dstFilePath:Y.dstFilePath??null,dstSymbolName:Y.dstSymbolName??null,metaJson:Y.metaJson??null,specifier:Y.specifier??null,isExternal:Y.isExternal??0}).run()})}getOutgoing(_,$,Q){if(Q!==void 0)return this.db.drizzleDb.select(d_).from(y).where(w_(d(y.project,_),d(y.srcFilePath,$),qQ(d(y.srcSymbolName,Q),K1(y.srcSymbolName)))).all();return this.db.drizzleDb.select(d_).from(y).where(w_(d(y.project,_),d(y.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:Q}=_;return this.db.drizzleDb.select(d_).from(y).where(w_(d(y.dstProject,$),d(y.dstFilePath,Q))).all()}getByType(_,$){return this.db.drizzleDb.select(d_).from(y).where(w_(d(y.project,_),d(y.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(y).where(w_(d(y.project,_),d(y.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(y).where(w_(d(y.dstProject,_),d(y.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(d_).from(y).where(w_(_.project!==void 0?d(y.project,_.project):void 0,_.srcFilePath!==void 0?d(y.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?d(y.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?d(y.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?d(y.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?d(y.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?d(y.type,_.type):void 0,_.specifier!==void 0?d(y.specifier,_.specifier):void 0,_.isExternal!==void 0?d(y.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:Q,oldSymbol:J,newFile:Y,newSymbol:W,newDstProject:z}=_,Z=J===null?w_(d(y.dstProject,$),d(y.dstFilePath,Q),K1(y.dstSymbolName)):w_(d(y.dstProject,$),d(y.dstFilePath,Q),d(y.dstSymbolName,J)),X={dstFilePath:Y,dstSymbolName:W};if(z!==void 0)X.dstProject=z;this.db.drizzleDb.update(y).set(X).where(Z).run()}}import{err as M1}from"@zipbul/result";import{subscribe as RQ}from"@parcel/watcher";import S0 from"path";import R0 from"path";function Y_(_){return _.replaceAll("\\","/")}function q_(_,$){return Y_(R0.relative(_,$))}function v_(_,$){return Y_(R0.resolve(_,$))}function NQ(_){return Y_(_)}function K_(_,$){return R0.isAbsolute($)?q_(_,$):NQ($)}var SQ=["**/.git/**",`**/${A_}/**`,"**/dist/**","**/node_modules/**"],TQ=new Set(["package.json","tsconfig.json"]);function EQ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class T0{#$;#_;#J;#Y;#W;#Z;constructor(_,$=RQ,Q=console){this.#_=_.projectRoot,this.#J=[...SQ,..._.ignorePatterns??[]],this.#Y=new Set((_.extensions??[".ts",".mts",".cts"]).map((J)=>J.toLowerCase())),this.#W=$,this.#Z=Q}async start(_){try{this.#$=await this.#W(this.#_,($,Q)=>{if($){this.#Z.error(new N("watcher","Callback error",{cause:$}));return}try{for(let J of Q){let Y=Y_(S0.relative(this.#_,J.path));if(Y.startsWith(".."))continue;let W=S0.basename(Y),z=S0.extname(Y).toLowerCase();if(!TQ.has(W)&&!this.#Y.has(z))continue;if(Y.endsWith(".d.ts"))continue;_({eventType:EQ(J.type),filePath:Y})}}catch(J){this.#Z.error(new N("watcher","Callback error",{cause:J}))}},{ignore:this.#J})}catch($){return M1(new N("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#$)return;try{await this.#$.unsubscribe(),this.#$=void 0}catch(_){return M1(new N("watcher","Failed to close watcher",{cause:_}))}}}import E0 from"path";var FQ=["**/node_modules/**","**/.git/**",`**/${A_}/**`,"**/dist/**"],jQ=FQ.map((_)=>new Bun.Glob(_));function kQ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function $0(_,$=kQ){let Q=[];for await(let J of $(_)){let Y=Y_(J);if(jQ.some((K)=>K.match(Y)))continue;let W=Y_(E0.dirname(J)),z=E0.join(_,J),Z=await Bun.file(z).json(),X=typeof Z?.name==="string"&&Z.name.length>0?Z.name:E0.basename(W==="."?_:W);Q.push({dir:W,project:X})}return Q.sort((J,Y)=>Y.dir.length-J.dir.length),Q}function c(_,$,Q="default"){let J=Y_(_);for(let Y of $){if(Y.dir===".")return Y.project;if(J===Y.dir||J.startsWith(`${Y.dir}/`))return Y.project}return Q}import l_ from"path";var N_=new Map;async function vQ(_){let $=Bun.file(_);if(!await $.exists())return null;try{let Q=await $.text(),J=Bun.JSONC.parse(Q);return typeof J==="object"&&J!==null?J:null}catch{return null}}function gQ(_,$){if($.startsWith(".")){let Q=l_.resolve(_,$);return Q.endsWith(".json")?Q:Q+".json"}return l_.resolve(_,"node_modules",$)}async function O1(_,$=5){if($<=0)return null;let Q=await vQ(_);if(!Q)return null;let J=Q.extends;if(typeof J!=="string"||!J)return Q;let Y=gQ(l_.dirname(_),J),W=await O1(Y,$-1);if(!W)return Q;return{...W,...Q,compilerOptions:{...W.compilerOptions,...Q.compilerOptions}}}async function n_(_){if(N_.has(_))return N_.get(_)??null;let $=l_.join(_,"tsconfig.json"),Q=await O1($);if(!Q)return N_.set(_,null),null;let J=Q.compilerOptions??null;if(!J)return N_.set(_,null),null;let Y=typeof J.baseUrl==="string"?J.baseUrl:null,W=typeof J.paths==="object"&&J.paths!==null?J.paths:null;if(!Y&&!W)return N_.set(_,null),null;let z=Y?l_.resolve(_,Y):_,Z=new Map;if(W)for(let[K,V]of Object.entries(W)){if(!Array.isArray(V))continue;let M=V.filter((w)=>typeof w==="string");Z.set(K,M)}let X={baseUrl:z,paths:Z};return N_.set(_,X),X}function Q0(_){if(_){N_.delete(_);return}N_.clear()}function G_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as R1}from"@zipbul/result";import{err as uQ}from"@zipbul/result";import{parseSync as bQ}from"oxc-parser";function g_(_,$,Q,J=bQ){try{let Y={preserveParens:!1,...Q},W=J(_,$,Y);return{filePath:_,program:W.program,errors:W.errors,comments:W.comments,sourceText:$,module:W.module}}catch(Y){return uQ(new N("parse",`Failed to parse file: ${_}`,{cause:Y}))}}import{join as PQ}from"path";function yQ(_,$){let Q=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(Q).scan({cwd:_,followSymlinks:!1})}async function L1(_){let{projectRoot:$,extensions:Q,ignorePatterns:J,fileRepo:Y,scanFilesFn:W=yQ}=_,z=Y.getFilesMap(),Z=new Set,X=[],K=[],V=J.map((w)=>new Bun.Glob(w));for await(let w of W($,Q)){let C=Y_(w);if(!Q.some((i)=>C.endsWith(i)))continue;if(C.startsWith("node_modules/")||C.includes("/node_modules/"))continue;if(V.some((i)=>i.match(C)))continue;Z.add(C);let I=PQ($,C),D=Bun.file(I),{size:S,lastModified:T}=D,j=z.get(C);if(!j){let i=await D.text(),a=G_(i);X.push({filePath:C,contentHash:a,mtimeMs:T,size:S});continue}if(j.mtimeMs===T&&j.size===S){K.push({filePath:C,contentHash:j.contentHash,mtimeMs:T,size:S});continue}let P=await D.text(),x=G_(P);if(x===j.contentHash)K.push({filePath:C,contentHash:x,mtimeMs:T,size:S});else X.push({filePath:C,contentHash:x,mtimeMs:T,size:S})}let M=[];for(let w of z.keys())if(!Z.has(w))M.push(w);return{changed:X,unchanged:K,deleted:M}}function i_(_){let $=[0];for(let Q=0;Q<_.length;Q++)if(_[Q]===`
3
+ `)$.push(Q+1);return $}function O_(_,$){let Q=0,J=_.length-1;while(Q<J){let Y=Q+J+1>>1;if(_[Y]<=$)Q=Y;else J=Y-1}return{line:Q+1,column:$-_[Q]}}import{err as fQ}from"@zipbul/result";import{parse as xQ}from"comment-parser";function J0(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let J=xQ(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(J.description??"").trim(),tags:(J.tags??[]).map((Y)=>({tag:Y.tag??"",name:Y.name??"",type:Y.type??"",description:Y.description??"",optional:Y.optional??!1,...Y.default!==void 0?{default:Y.default}:{}}))}}catch($){return fQ(new N("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as hQ}from"@zipbul/result";function mQ(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _){let $=_.value;if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return String($)}return"unknown"}function u_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let Q of _.properties)if(Q.type==="RestElement")$.push(...u_(Q.argument));else $.push(...u_(Q.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let Q of _.elements){if(!Q)continue;if(Q.type==="RestElement")$.push(...u_(Q.argument));else $.push(...u_(Q))}return $}if(_.type==="AssignmentPattern")return u_(_.left);return[]}function pQ(_){let $=new Map;for(let Q of _.module.staticImports){let J=Q.moduleRequest.value;for(let Y of Q.entries){let W=Y.localName.value,z=Y.importName.kind==="Name"?Y.importName.name:void 0,Z={specifier:J};if(z&&z!==W)Z.originalName=z;$.set(W,Z)}}return $}function S_(_){let{program:$,sourceText:Q,comments:J}=_,Y=i_(Q),W=pQ(_),z=J.filter((H)=>H.type==="Block"&&H.value.startsWith("*")).sort((H,A)=>H.end-A.end),Z=$.body.map((H)=>H.start).sort((H,A)=>H-A);function X(H,A){return j(H,A)}function K(H,A,B){if(H.type==="PrivateIdentifier")return{kind:"private"};if(!A&&H.type==="Identifier")return;return X(H,B)}function V(H,A){if(A)return Q.slice(H.start,H.end);if(H.type==="PrivateIdentifier")return`#${H.name}`;return mQ(H)}function M(H,A,B){if(!A&&H.type==="Identifier")return{kind:"string",value:H.name};return X(H,B)}function w(H,A){return{start:O_(Y,H),end:O_(Y,A)}}function C(H){let A=0,B=z.length-1,U=-1;while(A<=B){let G=A+B>>>1;if(z[G].end<=H)U=G,A=G+1;else B=G-1}if(U<0)return;let O=z[U];A=0,B=Z.length-1;while(A<=B){let G=A+B>>>1,L=Z[G];if(L<=O.end)A=G+1;else if(L>=H)B=G-1;else return}return`/*${O.value}*/`}function I(H){if(!H)return;let A="typeAnnotation"in H&&H.typeAnnotation?H.typeAnnotation:H;return Q.slice(A.start,A.end)}let D=64;function S(H,A){let B={kind:"unresolvable",sourceText:Q.slice(H.start,H.end)};if(A)B.reason=A;return B}function T(H){if(H.type==="Identifier")return W.get(H.name);if(H.type==="MemberExpression"){let A=H.object;if(A.type==="Identifier")return W.get(A.name)}return}function j(H,A=0){if(A>=D)return S(H,"depth-cap");if(H.type==="Literal"){let B=H.value;if(typeof B==="bigint")return{kind:"bigint",value:"bigint"in H&&typeof H.bigint==="string"?H.bigint:B.toString()};if("regex"in H&&H.regex)return{kind:"regex",value:Q.slice(H.start,H.end)};if(B===null)return{kind:"null",value:null};if(typeof B==="string")return{kind:"string",value:B};if(typeof B==="number")return{kind:"number",value:B};if(typeof B==="boolean")return{kind:"boolean",value:B};return S(H)}if(H.type==="Identifier"){let B=H.name;if(B==="undefined")return{kind:"undefined",value:null};let U=W.get(B),O={kind:"identifier",name:B};if(U){if(O.importSource=U.specifier,U.originalName)O.originalName=U.originalName}return O}if(H.type==="MemberExpression"){if(H.computed){let R=H.property;if(R.type==="Literal"&&typeof R.value==="string"){let E=H.object,g=Q.slice(E.start,E.end),k=E.type==="Identifier"?E.name:void 0,b=k?W.get(k):void 0,p={kind:"member",object:g,property:R.value};if(b)p.importSource=b.specifier;return p}return S(H)}let B=H.object,U=Q.slice(B.start,B.end),O=H.property.name,G=B.type==="Identifier"?B.name:void 0,L=G?W.get(G):void 0,q={kind:"member",object:U,property:O};if(L)q.importSource=L.specifier;return q}if(H.type==="CallExpression"){let B=H.callee,U=Q.slice(B.start,B.end),O=H.arguments.map((q)=>j(q,A+1)),G=T(B),L={kind:"call",callee:U,arguments:O};if(G)L.importSource=G.specifier;return L}if(H.type==="NewExpression"){let B=H.callee,U=Q.slice(B.start,B.end),O=H.arguments.map((q)=>j(q,A+1)),G=T(B),L={kind:"new",callee:U,arguments:O};if(G)L.importSource=G.specifier;return L}if(H.type==="ObjectExpression"){let B=[];for(let U of H.properties){if(U.type==="SpreadElement"){B.push({kind:"spread",argument:j(U.argument,A+1)});continue}let G={kind:"property",key:M(U.key,U.computed,A+1),value:j(U.value,A+1)};if(U.shorthand)G.shorthand=!0;B.push(G)}return{kind:"object",properties:B}}if(H.type==="ArrayExpression")return{kind:"array",elements:H.elements.map((U)=>{if(!U)return{kind:"undefined",value:null};return j(U,A+1)})};if(H.type==="SpreadElement")return{kind:"spread",argument:j(H.argument,A+1)};if(H.type==="ArrowFunctionExpression"||H.type==="FunctionExpression"){let B=H.params.map(x),U={kind:"function",sourceText:Q.slice(H.start,H.end)};if(B.length>0)U.parameters=B;return U}if(H.type==="TemplateLiteral"||H.type==="TaggedTemplateExpression")return{kind:"template",sourceText:Q.slice(H.start,H.end)};if(H.type==="UnaryExpression"){let B=H.argument;if(H.operator==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(H.operator==="void")return{kind:"undefined",value:null};return S(H)}if(H.type==="TSAsExpression"||H.type==="TSSatisfiesExpression"||H.type==="TSNonNullExpression"||H.type==="TSTypeAssertion"||H.type==="TSInstantiationExpression"||H.type==="ParenthesizedExpression")return j(H.expression,A);if(H.type==="ChainExpression")return j(H.expression,A);return S(H)}function P(H){if(!H||H.length===0)return[];return H.map((A)=>{let B=A.expression;if(B.type==="CallExpression"){let U=B.callee,O="name"in U&&typeof U.name==="string"?U.name:("property"in U)&&("name"in U.property)&&typeof U.property.name==="string"?U.property.name:"unknown",G=B.arguments.map((L)=>j(L));return{name:O,arguments:G.length>0?G:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:Q.slice(B.start,B.end)}})}function x(H){if(H.type==="TSParameterProperty")return a(H.parameter,H.decorators);if(H.type==="RestElement"){let A=H,B=A.argument,O=`...${"name"in B&&typeof B.name==="string"?B.name:"unknown"}`,G=A.typeAnnotation,L=G?I(G):void 0,q={name:O,isOptional:!1};if(L)q.type=L;return q}return a(H,H.decorators)}function i(H){if(!H)return;let A=H.typeAnnotation;if(A.type!=="TSTypeReference")return;let B=A.typeName,U=B.type==="Identifier"?B.name:void 0;if(!U)return;return W.get(U)?.specifier}function a(H,A){if(H.type==="AssignmentPattern"){let{left:E,right:g}=H,k="name"in E&&typeof E.name==="string"?E.name:"unknown",b="typeAnnotation"in E?E.typeAnnotation:null,p=b?I(b):void 0,X_=i(b),V_=Q.slice(g.start,g.end),e_="decorators"in E&&Array.isArray(E.decorators)?E.decorators:[],x_=P(e_),h_={name:k,isOptional:!0,defaultValue:V_};if(p)h_.type=p;if(X_)h_.typeImportSource=X_;if(x_.length>0)h_.decorators=x_;return h_}let B="name"in H&&typeof H.name==="string"?H.name:("pattern"in H)&&H.pattern&&typeof H.pattern.name==="string"?H.pattern.name:"unknown",U=!!(("optional"in H)&&H.optional),O="typeAnnotation"in H?H.typeAnnotation:null,G=O?I(O):void 0,L=i(O),q=P(A??[]),R={name:B,isOptional:U};if(G)R.type=G;if(L)R.typeImportSource=L;if(q.length>0)R.decorators=q;return R}function Q_(H,A){let B=[];if(A?.async)B.push("async");if(H.static)B.push("static");if(H.abstract)B.push("abstract");if(H.readonly)B.push("readonly");if(H.override)B.push("override");if(H.declare)B.push("declare");if(H.const)B.push("const");let U=H.accessibility;if(U==="private")B.push("private");else if(U==="protected")B.push("protected");else if(U==="public")B.push("public");return B}function W_(H){if(!H)return;let A=H.params.flatMap((B)=>{let U=B.name.name;return U?[U]:[]});return A.length>0?A:void 0}function I_(H){let A=[];if(H.superClass){let U=Q.slice(H.superClass.start,H.superClass.end);A.push({kind:"extends",name:U})}let B=H.implements??[];for(let U of B){let O=U.expression,G=Q.slice(O.start,O.end);A.push({kind:"implements",name:G})}return A}function M_(H){let A=[],B=H.extends;for(let U of B){let O=U.expression,G=Q.slice(O.start,O.end);A.push({kind:"extends",name:G})}return A}function U_(H){let A=[];for(let B of H)if(B.type==="MethodDefinition"||B.type==="TSAbstractMethodDefinition"){let U=B,O=V(U.key,U.computed),G=K(U.key,U.computed,0),L=U.value,q=U.kind,R=q==="constructor"?"constructor":q==="get"?"getter":q==="set"?"setter":"method",E=Q_(U,L);if(B.type==="TSAbstractMethodDefinition"&&!E.includes("abstract"))E.push("abstract");let g=L.params.map(x),k=I(L.returnType),b=P(U.decorators??[]),p={kind:"method",name:O,span:w(B.start,B.end),isExported:!1,methodKind:R,modifiers:E,parameters:g.length>0?g:void 0,returnType:k};if(G)p.key=G;if(b.length>0)p.decorators=b;A.push(p)}else if(B.type==="PropertyDefinition"||B.type==="TSAbstractPropertyDefinition"||B.type==="AccessorProperty"||B.type==="TSAbstractAccessorProperty"){let U=B,O=V(U.key,U.computed),G=K(U.key,U.computed,0),L=Q_(U);if(B.type==="TSAbstractPropertyDefinition"||B.type==="TSAbstractAccessorProperty"){if(!L.includes("abstract"))L.push("abstract")}if(B.type==="AccessorProperty"||B.type==="TSAbstractAccessorProperty")L.push("accessor");let q=I(U.typeAnnotation),R=U.value,E=R?j(R):void 0,g=P(U.decorators),k={kind:"property",name:O,span:w(B.start,B.end),isExported:!1,modifiers:L,returnType:q,initializer:E};if(G)k.key=G;if(g.length>0)k.decorators=g;A.push(k)}return A}function r(H){let A=[];for(let B of H)if(B.type==="TSMethodSignature"){let U=B,O=V(U.key,U.computed),G=K(U.key,U.computed,0),L=U.params.map(x),q=I(U.returnType),R={kind:"method",name:O,span:w(B.start,B.end),isExported:!1,modifiers:[],methodKind:"method",parameters:L.length>0?L:void 0,returnType:q};if(G)R.key=G;A.push(R)}else if(B.type==="TSPropertySignature"){let U=B,O=V(U.key,U.computed),G=K(U.key,U.computed,0),L=I(U.typeAnnotation),q={kind:"property",name:O,span:w(B.start,B.end),isExported:!1,modifiers:U.readonly?["readonly"]:[],returnType:L};if(G)q.key=G;A.push(q)}return A}function s(H,A){if(H.type==="FunctionDeclaration"||H.type==="FunctionExpression"||H.type==="TSDeclareFunction"||H.type==="TSEmptyBodyFunctionExpression"){let B=H,U=B.id?.name??"default",O=B.params.map(x),G=I(B.returnType),L=Q_(B,B),q=P(B.decorators??[]),R=W_(B.typeParameters),E={kind:"function",name:U,span:w(H.start,H.end),isExported:A,modifiers:L,parameters:O.length>0?O:void 0,returnType:G,decorators:q.length>0?q:void 0};if(R&&R.length>0)E.typeParameters=R;return E}if(H.type==="ClassDeclaration"||H.type==="ClassExpression"){let B=H,U=B.id?.name??"default",O=I_(B),G=U_(B.body.body),L=P(B.decorators),q=Q_(B),R=W_(B.typeParameters),E={kind:"class",name:U,span:w(H.start,H.end),isExported:A,modifiers:q,heritage:O.length>0?O:void 0,members:G.length>0?G:void 0,decorators:L.length>0?L:void 0};if(R&&R.length>0)E.typeParameters=R;return E}if(H.type==="VariableDeclaration"){let B=H,U=[];for(let O of B.declarations){let{id:G,init:L}=O;if(G.type==="ObjectPattern"||G.type==="ArrayPattern"){let X_=u_(G);for(let V_ of X_)U.push({kind:"variable",name:V_.name,span:w(V_.start,V_.end),isExported:A,modifiers:[]});continue}let q="name"in G&&typeof G.name==="string"?G.name:"unknown",R="variable",E,g,k;if(L)if(L.type==="FunctionExpression"||L.type==="ArrowFunctionExpression"){R="function";let X_=L;E=X_.params.map(x),g=I(X_.returnType)}else k=j(L);let b=[],p={kind:R,name:q,span:w(O.start,O.end),isExported:A,modifiers:b,parameters:E,returnType:g};if(k)p.initializer=k;U.push(p)}if(U.length===0)return null;if(U.length===1)return U[0];return U}if(H.type==="TSTypeAliasDeclaration")return{kind:"type",name:H.id.name,span:w(H.start,H.end),isExported:A,modifiers:[]};if(H.type==="TSInterfaceDeclaration"){let B=H,U=B.id.name,O=M_(B),G=r(B.body.body),L=W_(B.typeParameters),q={kind:"interface",name:U,span:w(H.start,H.end),isExported:A,modifiers:[],heritage:O.length>0?O:void 0,members:G.length>0?G:void 0};if(L&&L.length>0)q.typeParameters=L;return q}if(H.type==="TSEnumDeclaration"){let B=H,U=B.id.name,O=Q_(B),L=B.body.members.map((q)=>{let R=q.id,E=R.type!=="Identifier",g="name"in R&&typeof R.name==="string"?R.name:("value"in R)&&typeof R.value==="string"?R.value:"unknown",k=q.initializer?j(q.initializer):void 0,b={kind:"property",name:g,span:w(q.start,q.end),isExported:!1,modifiers:[]};if(E)b.key=X(R,0);if(k)b.initializer=k;return b});return{kind:"enum",name:U,span:w(H.start,H.end),isExported:A,modifiers:O,members:L.length>0?L:void 0}}if(H.type==="TSModuleDeclaration"){let B="name"in H.id?H.id.name:("value"in H.id)?H.id.value:"unknown",U=Q_(H),O=[];if(H.body?.type==="TSModuleBlock")for(let G of H.body.body){if(G.type!=="ExportNamedDeclaration")continue;let L=G.declaration;if(!L)continue;let q=s(L,!1);if(q)if(Array.isArray(q))O.push(...q);else O.push(q)}return{kind:"namespace",name:B,span:w(H.start,H.end),isExported:A,modifiers:U,members:O.length>0?O:void 0}}return null}let R_=[],B_=new Set;for(let H of $.body){let A=null,B=H;if(B.type==="ExportNamedDeclaration"){let O=B;if(O.declaration){if(A=s(O.declaration,!0),A&&!Array.isArray(A))A.span=w(O.start,O.end)}else if(!O.source&&O.specifiers)for(let G of O.specifiers){let L=G.local,q="name"in L?L.name:L.value;if(q)B_.add(q)}}else if(B.type==="ExportDefaultDeclaration"){let O=B,G=O.declaration;if(G){if(A=s(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(O.start,O.end);else if(!A&&G.type==="Identifier"){let L=G.name;if(L)B_.add(L)}}}else{let O=B.type;if(O==="FunctionDeclaration"||O==="TSDeclareFunction"||O==="ClassDeclaration"||O==="VariableDeclaration"||O==="TSTypeAliasDeclaration"||O==="TSInterfaceDeclaration"||O==="TSEnumDeclaration"||O==="TSModuleDeclaration")A=s(B,!1)}let U=Array.isArray(A)?A:A?[A]:[];for(let O of U){let G=H.start,L=C(G);if(L){let q=J0(L);if(!hQ(q))O.jsDoc=q}R_.push(O)}}if(B_.size>0){for(let H of R_)if(!H.isExported&&B_.has(H.name))H.isExported=!0}return R_}function Y0(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(Y0).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((J)=>`${JSON.stringify(J)}:${Y0($[J])}`).join(",")}}`}function dQ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,Q=_.modifiers.includes("async")?1:0;return`params:${$}|async:${Q}`}return null}function lQ(_){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(_.initializer)$.initializer=_.initializer;if(_.key)$.key=_.key;if(_.members?.length)$.members=_.members.map((Q)=>{let J=Q.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),Y={name:Q.name,kind:Q.methodKind??Q.kind,type:Q.returnType,visibility:J,isStatic:Q.modifiers.includes("static")||void 0,isReadonly:Q.modifiers.includes("readonly")||void 0,isAccessor:Q.modifiers.includes("accessor")||void 0};if(Q.key)Y.key=Q.key;if(Q.initializer)Y.initializer=Q.initializer;if(Q.decorators?.length)Y.decorators=Q.decorators;return Y});return Object.keys($).length>0?JSON.stringify($):null}function nQ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let Q=[..._.heritage].sort((J,Y)=>J.name.localeCompare(Y.name)).map((J)=>`${J.kind}:${J.name}`).join(",");$.push(`her:${Q}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((Q)=>Q.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.key)$.push(`k:${Y0(_.key)}`);if(_.members?.length){let Q=_.members.map((J)=>`${J.kind}:${J.modifiers.join(",")}:${J.parameters?.length??""}:${J.returnType??""}:${J.key?Y0(J.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${G_(Q)}`)}return G_($.join("|"))}function B1(_,$,Q,J,Y){let W=dQ(_),z=G_(`${$}|${_.kind}|${W??""}`),Z=nQ(_);return{project:Q,filePath:J,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:W,fingerprint:z,detailJson:lQ(_),contentHash:Y,indexedAt:new Date().toISOString(),structuralFingerprint:Z}}function F0(_){let{parsed:$,project:Q,filePath:J,contentHash:Y,symbolRepo:W}=_,z=S_($),Z=[];for(let X of z){Z.push(B1(X,X.name,Q,J,Y));for(let K of X.members??[])Z.push(B1(K,`${X.name}.${K.name}`,Q,J,Y))}W.replaceFileSymbols(Q,J,Y,Z)}import{resolve as j0,dirname as iQ,extname as cQ}from"path";function T_(_,$,Q){let J=(Y)=>{let W=cQ(Y);if(W===".js")return[Y.slice(0,-3)+".ts"];if(W===".mjs")return[Y.slice(0,-4)+".mts"];if(W===".cjs")return[Y.slice(0,-4)+".cts"];if(W===".ts"||W===".mts"||W===".cts"||W===".d.ts")return[Y];return[Y+".ts",Y+".d.ts",Y+"/index.ts",Y+"/index.d.ts",Y+".mts",Y+"/index.mts",Y+".cts",Y+"/index.cts"]};if($.startsWith(".")){let Y=Y_(j0(iQ(_),$));return J(Y)}if(Q)for(let[Y,W]of Q.paths){if(W.length===0)continue;let z=Y.indexOf("*");if(z===-1){if($===Y){let Z=[];for(let X of W)Z.push(...J(Y_(j0(Q.baseUrl,X))));return Z}}else{let Z=Y.slice(0,z),X=Y.slice(z+1);if($.startsWith(Z)&&(X===""||$.endsWith(X))){let K=$.slice(Z.length,X===""?void 0:$.length-X.length),V=[];for(let M of W)V.push(...J(Y_(j0(Q.baseUrl,M.replace("*",K)))));return V}}}return[]}function G1(_,$,Q,J=T_){let Y=new Map;for(let W of _.body){if(W.type!=="ImportDeclaration")continue;let z=W.source.value,Z=J($,z,Q);if(Z.length===0)continue;let X=Z[0];for(let K of W.specifiers)switch(K.type){case"ImportSpecifier":Y.set(K.local.name,{path:X,importedName:"name"in K.imported?K.imported.name:K.imported.value});break;case"ImportDefaultSpecifier":Y.set(K.local.name,{path:X,importedName:"default"});break;case"ImportNamespaceSpecifier":Y.set(K.local.name,{path:X,importedName:"*"});break}}return Y}import{Visitor as aQ}from"oxc-parser";function W0(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function sQ(_){return!_.startsWith(".")&&!_.startsWith("/")}function E_(_,$,Q,J){let Y=J(_,$,Q),W=Y.length>0?Y[0]:null,z=W===null&&sQ($);return{resolved:W,isExternal:z}}function rQ(_,$,Q,J,Y){for(let W of _.staticImports){let z=W.moduleRequest.value,{resolved:Z,isExternal:X}=E_($,z,Q,J),K={dstFilePath:Z,specifier:z};if(W.entries.length===0){let V={};if(X)V.isExternal=!0;if(Z===null&&!X)V.isUnresolved=!0;Y.push({type:"imports",srcFilePath:$,srcSymbolName:null,...K,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of W.entries){let M=V.isType,w={};if(M)w.isType=!0;if(X)w.isExternal=!0;if(Z===null&&!X)w.isUnresolved=!0;let C,I,D=V.importName.kind;if(D==="Default")C="default",I=V.localName.value;else if(D==="NamespaceObject")C="*",I=V.localName.value,w.importKind="namespace";else C=V.importName.name??"unknown",I=V.localName.value;Y.push({type:M?"type-references":"imports",srcFilePath:$,srcSymbolName:I,...K,dstSymbolName:C,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}}}function oQ(_,$,Q,J,Y){let W=new Map;for(let z of _.staticImports)for(let Z of z.entries)W.set(Z.localName.value,z.moduleRequest.value);for(let z of _.staticExports)for(let Z of z.entries){let X=null;if(Z.moduleRequest)X=Z.moduleRequest.value;else if(Z.localName.name)X=W.get(Z.localName.name)??null;if(!X)continue;let{resolved:K,isExternal:V}=E_($,X,Q,J),M=Z.exportName.name??"default",w=Z.exportName.kind,C=Z.localName.name??Z.importName.name??M,I=Z.isType,D={isReExport:!0};if(w==="None");else D.specifiers=[{local:C,exported:M}];if(I)D.isType=!0;if(V)D.isExternal=!0;if(K===null&&!V)D.isUnresolved=!0;let S=null,T=null,j=Z.importName.kind;if(j==="All"||j==="AllButDefault"){if(w==="Name"&&M)T=M,D.namespaceAlias=M}else T=C,S=M;Y.push({type:I?"type-references":"re-exports",srcFilePath:$,srcSymbolName:S,dstFilePath:K,dstSymbolName:T,specifier:X,metaJson:JSON.stringify(D)})}}function tQ(_,$,Q,J,Y){for(let W of _.body){let z=W;if(z.type==="ImportDeclaration"){let Z=z,X=Z.source.value,{resolved:K,isExternal:V}=E_($,X,Q,J),M=Z.importKind==="type",w=Z.specifiers,C={dstFilePath:K,specifier:X};if(w.length===0){let I={};if(M)I.isType=!0;if(V)I.isExternal=!0;if(K===null&&!V)I.isUnresolved=!0;Y.push({type:M?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...C,dstSymbolName:null,...Object.keys(I).length>0?{metaJson:JSON.stringify(I)}:{}})}else for(let I of w){let D=I.type,S=M||D==="ImportSpecifier"&&I.importKind==="type",T={};if(S)T.isType=!0;if(V)T.isExternal=!0;if(K===null&&!V)T.isUnresolved=!0;let j,P;if(D==="ImportDefaultSpecifier")j="default",P=I.local.name;else if(D==="ImportNamespaceSpecifier")j="*",P=I.local.name,T.importKind="namespace";else j=W0(I.imported),P=I.local.name;Y.push({type:S?"type-references":"imports",srcFilePath:$,srcSymbolName:P,...C,dstSymbolName:j,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}continue}if(z.type==="ExportAllDeclaration"){let Z=z,X=Z.source.value,{resolved:K,isExternal:V}=E_($,X,Q,J),M=Z.exportKind==="type",w=Z.exported,C=w?W0(w):null,I={isReExport:!0};if(M)I.isType=!0;if(V)I.isExternal=!0;if(K===null&&!V)I.isUnresolved=!0;if(C)I.namespaceAlias=C;Y.push({type:M?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:C,specifier:X,metaJson:JSON.stringify(I)});continue}if(z.type==="ExportNamedDeclaration"){let Z=z;if(!Z.source)continue;let X=Z.source.value,{resolved:K,isExternal:V}=E_($,X,Q,J),M=Z.exportKind==="type",w=Z.specifiers??[];for(let C of w){let I=M||C.exportKind==="type",D=W0(C.local),S=W0(C.exported),T={isReExport:!0,specifiers:[{local:D,exported:S}]};if(I)T.isType=!0;if(V)T.isExternal=!0;if(K===null&&!V)T.isUnresolved=!0;Y.push({type:I?"type-references":"re-exports",srcFilePath:$,srcSymbolName:S,dstFilePath:K,dstSymbolName:D,specifier:X,metaJson:JSON.stringify(T)})}}}}function eQ(_,$,Q,J,Y){new aQ({ImportExpression(z){let Z=z.source;if(Z.type!=="Literal"||typeof Z.value!=="string")return;let X=Z.value,{resolved:K,isExternal:V}=E_($,X,Q,J),M={isDynamic:!0};if(V)M.isExternal=!0;if(K===null&&!V)M.isUnresolved=!0;Y.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(M)})},CallExpression(z){let Z=z.callee,X=!1;if(Z.type==="Identifier"&&Z.name==="require");else if(Z.type==="MemberExpression"&&!Z.computed){let D=Z,S=D.object,T=D.property;if(S.type==="Identifier"&&S.name==="require"&&T.name==="resolve")X=!0;else return}else return;let K=z.arguments;if(K.length===0)return;let V=K[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let M=V.value,{resolved:w,isExternal:C}=E_($,M,Q,J),I={isRequire:!0};if(X)I.isRequireResolve=!0;if(C)I.isExternal=!0;if(w===null&&!C)I.isUnresolved=!0;Y.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:w,dstSymbolName:null,specifier:M,metaJson:JSON.stringify(I)})}}).visit(_)}function I1(_,$,Q,J=T_,Y){let W=[];if(Y)rQ(Y,$,Q,J,W),oQ(Y,$,Q,J,W);else tQ(_,$,Q,J,W);return eQ(_,$,Q,J,W),W}import{walk as HJ}from"oxc-walker";function _J(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function $J(_){return _.type==="ArrowFunctionExpression"}function QJ(_){return _.type==="AssignmentExpression"}function JJ(_){return _.type==="CallExpression"}function YJ(_){return _.type==="FunctionDeclaration"}function WJ(_){return _.type==="FunctionExpression"}function ZJ(_){return _.type==="Identifier"}function zJ(_){return _.type==="MemberExpression"}function XJ(_){return _.type==="TSQualifiedName"}function UJ(_){return _.type==="VariableDeclaration"}var w1=new Map,VJ=new Proxy({},{get(_,$,Q){if(typeof $!=="string")return Reflect.get(_,$,Q);let J=$.charCodeAt(0);if(J<65||J>90)return Reflect.get(_,$,Q);let Y=w1.get($);if(Y===void 0)Y=(W)=>W!==null&&W!==void 0&&W.type===$,w1.set($,Y);return Y}});function b_(_){if(!_)return null;if(_.type==="Identifier")return{root:_.name,parts:[],full:_.name};if(_.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(_.type==="Super")return{root:"super",parts:[],full:"super"};if(_.type==="MemberExpression"){let $=[],Q=_;while(Q.type==="MemberExpression"){let W=Q.property;if(!("name"in W)||typeof W.name!=="string")return null;$.push(W.name),Q=Q.object}let J;if(Q.type==="Identifier")J=Q.name;else if(Q.type==="ThisExpression")J="this";else if(Q.type==="Super")J="super";else return null;$.reverse();let Y=[J,...$].join(".");return{root:J,parts:$,full:Y}}return null}function D1(_,$,Q){let J=[],Y=[],W=[];function z(){if(Y.length>0)return Y[Y.length-1]??null;return null}function Z(V){if(!V)return null;let M=Q.get(V.root);if(V.parts.length===0){if(M)return{dstFilePath:M.path,dstSymbolName:M.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(M&&M.importedName==="*"){let w=V.parts[V.parts.length-1];return{dstFilePath:M.path,dstSymbolName:w,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,M){let w=b_(V.callee),C=Z(w);if(C){let I=z(),D={};if(M)D.isNew=!0;if(I===null)D.scope="module";J.push({type:"calls",srcFilePath:$,srcSymbolName:I,dstFilePath:C.dstFilePath,dstSymbolName:C.dstSymbolName,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}}function K(V,M){if(V.type==="FunctionDeclaration"){Y.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(M?.type==="VariableDeclarator"){let I=M.id,D=I.type==="Identifier"?I.name:"anonymous";Y.push(D);return}if(M?.type==="MethodDefinition"||M?.type==="TSAbstractMethodDefinition"){let I=M.key,D=W[W.length-1]??"",S="name"in I?I.name:"anonymous",T=D?`${D}.${S}`:S;Y.push(T);return}let w=z(),C=w?`${w}.<anonymous>`:"<anonymous>";Y.push(C)}}return HJ(_,{enter(V,M){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){K(V,M);return}if(V.type==="CallExpression"){X(V,!1);return}if(V.type==="NewExpression"){X(V,!0);return}},leave(V){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.pop();return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){Y.pop();return}}}),J}import{Visitor as KJ}from"oxc-parser";function C1(_,$,Q){let J=[];function Y(z){let Z=z.id?.name??"AnonymousClass";if(z.superClass){let K=b_(z.superClass);if(K){let V=k0(K,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...V})}}let X=z.implements??[];for(let K of X){let V=b_(K.expression);if(!V)continue;let M=k0(V,$,Q);J.push({type:"implements",srcFilePath:$,srcSymbolName:Z,...M})}}return new KJ({TSInterfaceDeclaration(z){let Z=z.id.name??"AnonymousInterface",X=z.extends;for(let K of X){let V=b_(K.expression);if(!V)continue;let M=k0(V,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...M})}},ClassDeclaration(z){Y(z)},ClassExpression(z){Y(z)}}).visit(_),J}function k0(_,$,Q){let J=Q.get(_.root);if(J){if(J.importedName==="*"){let Y=_.parts[_.parts.length-1]??_.root;return{dstFilePath:J.path,dstSymbolName:Y,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:J.path,dstSymbolName:_.parts.length>0?_.full:J.importedName}}return{dstFilePath:$,dstSymbolName:_.full,metaJson:JSON.stringify({isLocal:!0})}}function c_(_,$,Q,J=T_,Y){let W=G1(_,$,Q,J),z=I1(_,$,Q,J,Y),Z=D1(_,$,W),X=C1(_,$,W);return[...z,...Z,...X]}function v0(_){let{ast:$,project:Q,filePath:J,relationRepo:Y,projectRoot:W,tsconfigPaths:z,knownFiles:Z,boundaries:X,module:K}=_,V=v_(W,J),w=c_($,V,z,Z?(I,D,S)=>{let T=T_(I,D,S);for(let j of T){let P=q_(W,j);if(X){let x=c(P,X);if(Z.has(`${x}::${P}`))return[j]}else if(Z.has(`${Q}::${P}`))return[j]}return[]}:void 0,K),C=[];for(let I of w){if(I.dstFilePath===null){let j=q_(W,I.srcFilePath),P;if(I.metaJson)try{P=JSON.parse(I.metaJson)}catch{}let x=P?.isExternal===!0;C.push({project:Q,type:I.type,srcFilePath:j,srcSymbolName:I.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:I.dstSymbolName??null,metaJson:I.metaJson??null,specifier:I.specifier??null,isExternal:x?1:0});continue}let D=q_(W,I.dstFilePath);if(D.startsWith(".."))continue;let S=q_(W,I.srcFilePath),T=X?c(D,X):Q;C.push({project:Q,type:I.type,srcFilePath:S,srcSymbolName:I.srcSymbolName??null,dstProject:T,dstFilePath:D,dstSymbolName:I.dstSymbolName??null,metaJson:I.metaJson??null,specifier:I.specifier??null,isExternal:0})}return Y.replaceFileRelations(Q,J,C),C.length}import{isErr as MJ}from"@zipbul/result";var A1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function OJ(_){let $=S_(_),Q=[];for(let J of $){Q.push({name:J.name,startLine:J.span.start.line});for(let Y of J.members??[])Q.push({name:`${J.name}.${Y.name}`,startLine:Y.span.start.line})}return Q.sort((J,Y)=>J.startLine-Y.startLine),Q}function g0(_,$,Q){let J=0,Y=_.length-1;while(J<=Y){let W=J+Y>>1;if(_[W].startLine<=$)J=W+1;else Y=W-1}if(J<_.length){let W=_[J];if(W.startLine-$<=Q)return W.name}return null}function Z0(_,$,Q){let J=O_(_,$),Y=O_(_,Q);return{start:J,end:Y}}function q1(_){let{comments:$,sourceText:Q}=_;if(!$.length)return[];let J=i_(Q),Y=OJ(_),W=[],z=[...$].sort((X,K)=>X.start-K.start),Z=null;for(let X of z)if(X.type==="Block"&&X.value.startsWith("*")){Z=null;let K=`/*${X.value}*/`,V=J0(K);if(MJ(V))continue;let M=V;if(!M.tags?.length)continue;let w=O_(J,X.end),C=g0(Y,w.line,3),I=Q.slice(X.start,X.end);for(let D of M.tags){let S=[D.name,D.description].filter(Boolean).join(" "),T=`@${D.tag}`,j=I.indexOf(T),P;if(j>=0){let x=X.start+j,i=Q.indexOf(`
4
+ `,x),a=i>=0?Math.min(i,X.end):X.end;P=Z0(J,x,a)}else P=Z0(J,X.start,X.end);W.push({tag:D.tag,value:S,source:"jsdoc",span:P,symbolName:C})}}else if(X.type==="Block"){Z=null;let K=X.value.split(`
5
+ `),V=0;for(let M of K){let w=M.replace(/^\s*\*?\s?/,""),C=A1.exec(w);if(C){let I=C[1],D=C[2]?.trim()??"",S=`@${I}`,T=M.indexOf(S),j=X.start+2+V+(T>=0?T:0),P=X.start+2+V+M.length,x=Z0(J,j,P),i=O_(J,X.end),a=g0(Y,i.line,3);W.push({tag:I,value:D,source:"block",span:x,symbolName:a})}V+=M.length+1}}else{let K=X.value,V=A1.exec(K),M=O_(J,X.start),w=O_(J,X.end);if(V){let C=V[1],I=V[2]?.trim()??"",D=`@${C}`,S=K.indexOf(D),T=X.start+2+(S>=0?S:0),j=Z0(J,T,X.end),P=g0(Y,w.line,3),x={tag:C,value:I,source:"line",span:j,symbolName:P};W.push(x),Z={annotation:x,endLine:w.line}}else if(Z&&M.line===Z.endLine+1){let C=K.trim();if(C)Z.annotation.value+=" "+C,Z.annotation.span.end=O_(J,X.end),Z.endLine=w.line}else Z=null}return W}function u0(_){let{parsed:$,project:Q,filePath:J,annotationRepo:Y}=_,W=q1($);if(Y.deleteFileAnnotations(Q,J),!W.length)return 0;let z=new Date().toISOString(),Z=W.map((X)=>({project:Q,filePath:J,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 Y.insertBatch(Q,J,Z),W.length}function N1(_,$){let Q=[],J=[],Y=[];for(let[V,M]of $)if(!_.has(V))Q.push({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint});for(let[V,M]of _)if(!$.has(V))J.push({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint});if(!Q.length||!J.length)return{renamed:Y,added:Q,removed:J};let W=new Map,z=new Map;for(let V of Q){let M=W.get(V.filePath)??[];M.push(V),W.set(V.filePath,M)}for(let V of J){let M=z.get(V.filePath)??[];M.push(V),z.set(V.filePath,M)}let Z=new Set,X=new Set;for(let[V,M]of W){let w=z.get(V);if(!w)continue;for(let C of new Set(M.map((I)=>I.kind))){let I=M.filter((P)=>P.kind===C&&!Z.has(P)),D=w.filter((P)=>P.kind===C&&!X.has(P));if(!I.length||!D.length)continue;let S=(P,x)=>{return x.get(`${P.filePath}::${P.name}`)?.structuralFingerprint??null},T=(P,x)=>{return x.get(`${P.filePath}::${P.name}`)?.startLine??0},j=new Map;for(let P of D){let x=S(P,_);if(!x)continue;let i=j.get(x)??[];i.push(P),j.set(x,i)}for(let P of I){if(Z.has(P))continue;let x=S(P,$);if(!x)continue;let i=j.get(x);if(!i)continue;let a=i.filter((W_)=>!X.has(W_));if(!a.length)continue;let Q_=a[0];if(a.length>1){let W_=T(P,$),I_=Math.abs(T(Q_,_)-W_);for(let M_=1;M_<a.length;M_++){let U_=Math.abs(T(a[M_],_)-W_);if(U_<I_)I_=U_,Q_=a[M_]}}Y.push({oldName:Q_.name,newName:P.name,filePath:V,kind:C}),Z.add(P),X.add(Q_)}}}let K=Y.filter((V)=>!V.oldName.includes("."));for(let V of K){let M=`${V.oldName}.`,w=`${V.newName}.`,C=J.filter((D)=>D.filePath===V.filePath&&D.name.startsWith(M)&&!X.has(D)),I=Q.filter((D)=>D.filePath===V.filePath&&D.name.startsWith(w)&&!Z.has(D));for(let D of C){let S=D.name.slice(M.length),T=I.find((j)=>j.name.slice(w.length)===S);if(T)Y.push({oldName:D.name,newName:T.name,filePath:V.filePath,kind:D.kind}),Z.add(T),X.add(D)}}return{renamed:Y,added:Q.filter((V)=>!Z.has(V)),removed:J.filter((V)=>!X.has(V))}}var LJ=100,S1=50;class b0{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=n_(_.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")){Q0(this.opts.projectRoot),this.tsconfigPathsRaw=n_(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??$0;this.boundariesRefresh=$(this.opts.projectRoot).then((Q)=>{this.opts.boundaries=Q,this.opts.onBoundariesChanged?.(Q)}),this.fullIndex().catch((Q)=>{this.logger.error("[IndexCoordinator] fullIndex failed after package.json change:",Q)});return}if(this.pendingEvents.push(_),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},LJ)}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((J,Y)=>{this.pendingFullIndexWaiters.push({resolve:J,reject:Y})});return this.currentIndexing}this.indexingLock=!0;let Q=this.doIndex(_,$).then((J)=>{return this.fireCallbacks(J),J}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let J=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((Y)=>{for(let W of J)W.resolve(Y)}).catch((Y)=>{for(let W of J)W.reject(Y)})}else if(this.pendingEvents.length>0){let J=this.pendingEvents.splice(0);this.startIndex(J,!1).catch((Y)=>this.logger.error("[IndexCoordinator] incremental drain error",Y))}});return this.currentIndexing=Q,Q}async doIndex(_,$){let Q=Date.now(),{fileRepo:J,symbolRepo:Y,relationRepo:W,dbConnection:z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Z,X;if(_!==void 0)Z=_.filter((U)=>U.eventType==="create"||U.eventType==="change").map((U)=>({filePath:U.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((U)=>U.eventType==="delete").map((U)=>U.filePath);else{let U=new Map;for(let G of this.opts.boundaries)for(let[L,q]of J.getFilesMap(G.project))U.set(L,q);let O=await L1({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});Z=O.changed,X=O.deleted}let K=await this.tsconfigPathsRaw??void 0,V=new Map;for(let U of X){let O=c(U,this.opts.boundaries),G=Y.getFileSymbols(O,U);V.set(U,G)}let M=crypto.randomUUID(),w=new Map,C=new Map,I=(U)=>({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint,structuralFingerprint:U.structuralFingerprint??null,startLine:U.startLine,isExported:U.isExported??0});if($)for(let U of this.opts.boundaries)for(let O of J.getAllFiles(U.project))for(let G of Y.getFileSymbols(U.project,O.filePath))w.set(`${G.filePath}::${G.name}`,I(G));else{for(let U of Z){let O=c(U.filePath,this.opts.boundaries);for(let G of Y.getFileSymbols(O,U.filePath))w.set(`${G.filePath}::${G.name}`,I(G))}for(let[,U]of V)for(let O of U)w.set(`${O.filePath}::${O.name}`,I(O))}let D=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath??""}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${G_(U.metaJson??"")}`,S=new Map;if($)for(let U of this.opts.boundaries)for(let O of J.getAllFiles(U.project))for(let G of W.getOutgoing(U.project,O.filePath))S.set(D(G),G);else{for(let U of Z){let O=c(U.filePath,this.opts.boundaries);for(let G of W.getOutgoing(O,U.filePath))S.set(D(G),G)}for(let U of X){let O=c(U,this.opts.boundaries);for(let G of W.getOutgoing(O,U))S.set(D(G),G)}}let{annotationRepo:T,changelogRepo:j}=this.opts,P=()=>{for(let U of X){let O=c(U,this.opts.boundaries);if(Y.deleteFileSymbols(O,U),W.deleteFileRelations(O,U),W.deleteIncomingRelations(O,U),T)T.deleteFileAnnotations(O,U);J.deleteFile(O,U)}},x=0,i=async()=>{let{projectRoot:U,boundaries:O}=this.opts,{parseCache:G}=this.opts,L=0,q=0,R=0,E=[],g=[];for(let b of Z)try{let p=v_(U,b.filePath),X_=Bun.file(p),V_=await X_.text(),e_=b.contentHash||G_(V_),x_=c(b.filePath,O);J.upsertFile({project:x_,filePath:b.filePath,mtimeMs:X_.lastModified,size:X_.size,contentHash:e_,updatedAt:new Date().toISOString(),lineCount:V_.split(`
6
+ `).length});let G0=(this.opts.parseSourceFn??g_)(p,V_);if(R1(G0))throw G0.data;let ZQ=G0;g.push({filePath:b.filePath,text:V_,contentHash:e_,parsed:ZQ,project:x_})}catch(p){this.logger.error(`[IndexCoordinator] Failed to prepare ${b.filePath}:`,p),E.push(b.filePath)}let k=new Set;for(let b of O)for(let[p]of J.getFilesMap(b.project))k.add(`${b.project}::${p}`);return z.transaction(()=>{for(let b of g){if(F0({parsed:b.parsed,project:b.project,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:Y}),q+=v0({ast:b.parsed.program,project:b.project,filePath:b.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:k,boundaries:O,module:b.parsed.module}),T)R+=u0({parsed:b.parsed,project:b.project,filePath:b.filePath,annotationRepo:T});G.set(b.filePath,b.parsed),L+=Y.getFileSymbols(b.project,b.filePath).length}}),{symbols:L,relations:q,annotations:R,failedFiles:E}},a=0,Q_=0,W_=[];if($){let{projectRoot:U,boundaries:O}=this.opts,{parseCache:G}=this.opts,L=[];for(let R=0;R<Z.length;R+=S1){let E=Z.slice(R,R+S1),g=await Promise.allSettled(E.map(async(k)=>{let b=v_(U,k.filePath),p=Bun.file(b),X_=await p.text(),V_=k.contentHash||G_(X_);return{filePath:k.filePath,text:X_,contentHash:V_,mtimeMs:p.lastModified,size:p.size}}));for(let k=0;k<g.length;k++){let b=g[k];if(b.status==="fulfilled")L.push(b.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",b.reason),W_.push(E[k].filePath)}}let q=[];z.transaction(()=>{for(let g of L){let k=c(g.filePath,O);J.deleteFile(k,g.filePath)}for(let g of X){let k=c(g,O);if(Y.deleteFileSymbols(k,g),W.deleteFileRelations(k,g),W.deleteIncomingRelations(k,g),T)T.deleteFileAnnotations(k,g);J.deleteFile(k,g)}for(let g of L){let k=c(g.filePath,O);J.upsertFile({project:k,filePath:g.filePath,mtimeMs:g.mtimeMs,size:g.size,contentHash:g.contentHash,updatedAt:new Date().toISOString(),lineCount:g.text.split(`
7
+ `).length})}let R=new Set;for(let g of O)for(let[k]of J.getFilesMap(g.project))R.add(`${g.project}::${k}`);let E=this.opts.parseSourceFn??g_;for(let g of L){let k=c(g.filePath,O),b=E(v_(U,g.filePath),g.text);if(R1(b))throw b.data;let p=b;if(q.push({filePath:g.filePath,parsed:p}),F0({parsed:p,project:k,filePath:g.filePath,contentHash:g.contentHash,symbolRepo:Y}),T)x+=u0({parsed:p,project:k,filePath:g.filePath,annotationRepo:T});Q_+=v0({ast:p.program,project:k,filePath:g.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:R,boundaries:O,module:p.module}),a+=Y.getFileSymbols(k,g.filePath).length}});for(let R of q)G.set(R.filePath,R.parsed)}else{P();let U=await i();a=U.symbols,Q_=U.relations,x=U.annotations,W_=U.failedFiles}for(let U of Z){let O=c(U.filePath,this.opts.boundaries);for(let G of Y.getFileSymbols(O,U.filePath))C.set(`${G.filePath}::${G.name}`,I(G))}let I_=new Map;for(let U of Z){let O=c(U.filePath,this.opts.boundaries);for(let G of W.getOutgoing(O,U.filePath))I_.set(D(G),G)}let M_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),U_={added:[...I_.entries()].filter(([U])=>!S.has(U)).map(([,U])=>M_(U)),removed:[...S.entries()].filter(([U])=>!I_.has(U)).map(([,U])=>M_(U))},r={added:[],modified:[],removed:[]};for(let[U,O]of C){let G=w.get(U);if(!G)r.added.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});else{let L=G.fingerprint!==O.fingerprint,q=G.isExported!==O.isExported,R=G.structuralFingerprint!==null&&O.structuralFingerprint!==null&&G.structuralFingerprint!==O.structuralFingerprint;if(L||q||R)r.modified.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)})}}for(let[U,O]of w)if(!C.has(U))r.removed.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});let s=N1(w,C),R_=new Set(s.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),B_=new Set(s.renamed.map((U)=>`${U.filePath}::${U.newName}`));r.added=r.added.filter((U)=>!B_.has(`${U.filePath}::${U.name}`)),r.removed=r.removed.filter((U)=>!R_.has(`${U.filePath}::${U.name}`));let H=[];if(!$){for(let[O,G]of V)for(let L of G){if(!L.fingerprint)continue;let q=c(O,this.opts.boundaries),R=Y.getByFingerprint(q,L.fingerprint);if(R.length===1){let E=R[0];W.retargetRelations({dstProject:q,oldFile:O,oldSymbol:L.name,newFile:E.filePath,newSymbol:E.name}),H.push({name:E.name,filePath:E.filePath,kind:E.kind,oldFilePath:O,isExported:E.isExported??0})}}let U=new Set(H.map((O)=>`${O.oldFilePath}::${O.name}`));for(let O of s.removed){if(U.has(`${O.filePath}::${O.name}`))continue;let L=w.get(`${O.filePath}::${O.name}`)?.fingerprint;if(!L)continue;let q=c(O.filePath,this.opts.boundaries),R=Y.getByFingerprint(q,L);if(R.length===1){let E=R[0];if(E.filePath!==O.filePath||E.name!==O.name)W.retargetRelations({dstProject:q,oldFile:O.filePath,oldSymbol:O.name,newFile:E.filePath,newSymbol:E.name}),H.push({name:E.name,filePath:E.filePath,kind:E.kind,oldFilePath:O.filePath,isExported:E.isExported??0})}}}if(H.length){let U=new Set(H.map((G)=>`${G.filePath}::${G.name}`)),O=new Set(H.map((G)=>`${G.oldFilePath}::${G.name}`));r.added=r.added.filter((G)=>!U.has(`${G.filePath}::${G.name}`)),r.removed=r.removed.filter((G)=>!O.has(`${G.filePath}::${G.name}`))}if(j){let U=new Date().toISOString(),O=$?1:0,G=[];for(let L of r.added){let q=`${L.filePath}::${L.name}`,R=C.get(q),E=c(L.filePath,this.opts.boundaries);G.push({project:E,changeType:"added",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:U,isFullIndex:O,indexRunId:M})}for(let L of r.modified){let q=C.get(`${L.filePath}::${L.name}`),R=c(L.filePath,this.opts.boundaries);G.push({project:R,changeType:"modified",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:U,isFullIndex:O,indexRunId:M})}for(let L of r.removed){let q=`${L.filePath}::${L.name}`,R=w.get(q),E=c(L.filePath,this.opts.boundaries);G.push({project:E,changeType:"removed",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:U,isFullIndex:O,indexRunId:M})}for(let L of s.renamed){let q=C.get(`${L.filePath}::${L.newName}`),R=c(L.filePath,this.opts.boundaries);G.push({project:R,changeType:"renamed",symbolName:L.newName,symbolKind:L.kind,filePath:L.filePath,oldName:L.oldName,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:U,isFullIndex:O,indexRunId:M})}for(let L of H){let q=C.get(`${L.filePath}::${L.name}`),R=c(L.filePath,this.opts.boundaries);G.push({project:R,changeType:"moved",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:L.oldFilePath,fingerprint:q?.fingerprint??null,changedAt:U,isFullIndex:O,indexRunId:M})}if(G.length)try{z.transaction(()=>{j.insertBatch(G)})}catch(L){this.logger.error("[IndexCoordinator] changelog insert failed:",L)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let L=new Date(Date.now()-2592000000).toISOString();try{for(let q of this.opts.boundaries)j.pruneOlderThan(q.project,L)}catch(q){this.logger.error("[IndexCoordinator] changelog pruning failed:",q)}}}let A=new Set(W_),B=Z.filter((U)=>!A.has(U.filePath));return{indexedFiles:B.length,removedFiles:X.length,totalSymbols:a,totalRelations:Q_,totalAnnotations:x,durationMs:Date.now()-Q,changedFiles:B.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:W_,changedSymbols:r,renamedSymbols:s.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(C.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:H.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:U_}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(Q){this.logger.error("[IndexCoordinator] onIndexed callback threw:",Q)}}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 BJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function GJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function T1(_,$,Q={}){let J=Q.now??Date.now,Y=Q.isAlive??BJ,W=Q.staleAfterSeconds??60,z=Q.instanceId;return _.immediateTransaction(()=>{let Z=_.selectOwner();if(!Z)return _.insertOwner($,z),"owner";let X=Math.floor((J()-GJ(Z.heartbeat_at))/1000),K=Y(Z.pid);if(K&&z&&Z.instance_id&&Z.instance_id!==z&&Z.pid===$)return _.replaceOwner($,z),"owner";if(K&&X<W)return"reader";return _.replaceOwner($,z),"owner"})}function E1(_,$){_.deleteOwner($)}function F1(_,$){_.touchOwner($)}class a_{#$;#_=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 Q=this.#_.keys().next().value;if(Q!==void 0)this.#_.delete(Q)}}delete(_){return this.#_.delete(_)}clear(){this.#_.clear()}}class P0{lru;constructor(_=500){this.lru=new a_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function z0(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}function y0(_){let{symbolRepo:$,projectRoot:Q,project:J,query:Y}=_,W=Y.project??J,z={kind:Y.kind,filePath:Y.filePath!==void 0?K_(Q,Y.filePath):void 0,isExported:Y.isExported,project:W,limit:Y.limit,resolvedType:Y.resolvedType};if(Y.text)if(Y.exact)z.exactName=Y.text;else{let X=z0(Y.text);if(X)z.ftsQuery=X}if(Y.decorator)z.decorator=Y.decorator;if(Y.regex)z.regex=Y.regex;return $.searchByQuery(z).map((X)=>{let K=X.name.indexOf(".");return{id:X.id,filePath:X.filePath,kind:X.kind,name:X.name,memberName:K>=0?X.name.slice(K+1):null,span:{start:{line:X.startLine,column:X.startColumn},end:{line:X.endLine,column:X.endColumn}},isExported:X.isExported===1,signature:X.signature,fingerprint:X.fingerprint,detail:X.detailJson?(()=>{try{return JSON.parse(X.detailJson)}catch{return{}}})():{}}})}function f0(_){let{relationRepo:$,projectRoot:Q,project:J,query:Y}=_;if(Y.srcFilePath&&Y.srcFilePathPattern)throw new N("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Y.dstFilePath&&Y.dstFilePathPattern)throw new N("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let W=Y.project??J,z=Y.limit,Z=!!(Y.srcFilePathPattern||Y.dstFilePathPattern),X=Z?void 0:z,V=$.searchRelations({srcFilePath:Y.srcFilePath!==void 0?K_(Q,Y.srcFilePath):void 0,srcSymbolName:Y.srcSymbolName,dstFilePath:Y.dstFilePath!==void 0?K_(Q,Y.dstFilePath):void 0,dstSymbolName:Y.dstSymbolName,dstProject:Y.dstProject,type:Y.type,project:W,specifier:Y.specifier,isExternal:Y.isExternal,limit:X}).map((M)=>{let w;if(M.metaJson)try{w=JSON.parse(M.metaJson)}catch{}return{type:M.type,srcFilePath:M.srcFilePath,srcSymbolName:M.srcSymbolName,dstFilePath:M.dstFilePath,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,isExternal:M.isExternal===1,specifier:M.specifier,metaJson:M.metaJson??void 0,meta:w}});if(Y.srcFilePathPattern||Y.dstFilePathPattern){let M=Y.srcFilePathPattern?new Bun.Glob(Y.srcFilePathPattern):null,w=Y.dstFilePathPattern?new Bun.Glob(Y.dstFilePathPattern):null;V=V.filter((C)=>(!M||M.match(C.srcFilePath))&&(!w||C.dstFilePath===null||w.match(C.dstFilePath)))}if(Z&&z!==void 0&&V.length>z)V=V.slice(0,z);return V}import{findInFiles as IJ,Lang as wJ}from"@ast-grep/napi";function DJ(_){let $=new Set,Q=/\${1,3}([A-Z_][A-Z_0-9]*)/g,J;while((J=Q.exec(_))!==null)$.add(J[0]);return[...$]}function CJ(_){return _.replace(/^\$+/,"")}function AJ(_,$){if($.length===0)return;let Q={},J=!1;for(let Y of $){let W=CJ(Y),z=_.getMatch(W);if(z){let X=z.range();Q[Y]={text:z.text(),startLine:X.start.line+1,endLine:X.end.line+1,startColumn:X.start.column,endColumn:X.end.column,startOffset:X.start.index,endOffset:X.end.index},J=!0;continue}let Z=_.getMultipleMatches(W);if(Z.length>0){let X=Z[0].range(),K=Z[Z.length-1].range();Q[Y]={text:Z.map((V)=>V.text()).join(", "),startLine:X.start.line+1,endLine:K.end.line+1,startColumn:X.start.column,endColumn:K.end.column,startOffset:X.start.index,endOffset:K.end.index},J=!0}}return J?Q:void 0}async function x0(_){if(_.filePaths.length===0)return[];let $=DJ(_.pattern),Q=[];return await IJ(wJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,Y)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let W of Y){let z=W.range(),Z={filePath:W.getRoot().filename(),startLine:z.start.line+1,endLine:z.end.line+1,startColumn:z.start.column,endColumn:z.end.column,startOffset:z.start.index,endOffset:z.end.index,matchedText:W.text()},X=AJ(W,$);if(X)Z.captures=X;Q.push(Z)}}),Q}import $_ from"typescript";import{isErr as hJ}from"@zipbul/result";import D_ from"typescript";import qJ from"path";import{err as h0}from"@zipbul/result";function NJ(_){try{return Q1("fs").readFileSync(_,"utf-8")}catch{return}}function RJ(_){try{return Q1("fs").readFileSync(_,"utf-8")}catch{return}}class X0{#$;#_;#J=!1;__testing__;constructor(_,$){this.#$=_,this.#_=$,this.__testing__={host:$}}static create(_,$={}){let Q=$.readConfigFile??NJ,J=$.resolveNonTrackedFile??RJ,Y=qJ.dirname(_),W=Q(_);if(W===void 0)return h0(new N("semantic",`tsconfig not found: ${_}`));let z=D_.parseJsonText(_,W),Z=z.parseDiagnostics;if(Z&&Z.length>0){let M=Z.map((w)=>D_.flattenDiagnosticMessageText(w.messageText,`
8
+ `)).join("; ");return h0(new N("semantic",`tsconfig parse error: ${M}`))}let X=D_.parseJsonSourceFileConfigFileContent(z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(M)=>Q(M)!==void 0||J(M)!==void 0,readFile:(M)=>Q(M)??J(M)},Y);if(X.errors.length>0){let M=X.errors.filter((w)=>w.category===D_.DiagnosticCategory.Error&&w.code!==18003);if(M.length>0){let w=M.map((C)=>D_.flattenDiagnosticMessageText(C.messageText,`
9
+ `)).join("; ");return h0(new N("semantic",`tsconfig compile error: ${w}`))}}let K=new j1(X.fileNames,X.options,Y,J),V=D_.createLanguageService(K);return new X0(V,K)}get isDisposed(){return this.#J}getProgram(){this.#Y();let _=this.#$.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getCompilerOptions(){return this.#Y(),this.#_.getCompilationSettings()}getLanguageService(){return this.#Y(),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()}#Y(){if(this.#J)throw Error("TscProgram is disposed")}}class j1{#$;#_;#J;#Y;#W=new Map;#Z=new Map;#Q=new Map;constructor(_,$,Q,J){this.#$=new Set(_),this.#_=$,this.#J=Q,this.#Y=J}updateFile(_,$){let Q=this.#W.get(_);if(Q){if(Q.content===$)return;this.#Z.delete(`${_}:${Q.version}`),Q.version+=1,Q.content=$}else this.#W.set(_,{version:1,content:$})}removeFile(_){let $=this.#W.get(_);if($)this.#Z.delete(`${_}:${$.version}`);this.#W.delete(_),this.#$.delete(_)}getScriptFileNames(){let _=[...this.#W.keys()];return[...[...this.#$].filter((Q)=>!this.#W.has(Q)),..._]}getScriptVersion(_){let $=this.#W.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#W.get(_);if($){let Y=`${_}:${$.version}`,W=this.#Z.get(Y);if(!W)W=D_.ScriptSnapshot.fromString($.content),this.#Z.set(Y,W);return W}let Q=this.#Q.get(_);if(Q)return Q;let J=this.#Y(_);if(J!==void 0)return Q=D_.ScriptSnapshot.fromString(J),this.#Q.set(_,Q),Q;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#_}getDefaultLibFileName(_){return D_.getDefaultLibFilePath(_)}fileExists(_){if(this.#W.has(_))return!0;return this.#Y(_)!==void 0}readFile(_){let $=this.#W.get(_);if($)return $.content;return this.#Y(_)}}import h from"typescript";import U0 from"typescript";function __(_,$){if($<0||$>=_.getEnd())return;let Q,J=(Y)=>{if($<Y.getStart(_,!1)||$>=Y.getEnd())return;Q=Y,U0.forEachChild(Y,J)};return U0.forEachChild(_,J),Q}function s_(_,$,Q){if($<0||Q<=$||Q>_.getEnd())return;let J,Y=(W)=>{let z=W.getStart(_,!1),Z=W.getEnd();if($<z||Q>Z)return;if(z===$&&Z===Q)J=W;U0.forEachChild(W,Y)};return U0.forEachChild(_,Y),J}var V0=8;function SJ(_){return!!(_.flags&h.TypeFlags.Object)&&!!(_.objectFlags&h.ObjectFlags.Reference)}function L_(_,$,Q=0,J){if(J){let I=J.get($);if(I)return I}let Y=_.typeToString($),W=$.flags,z=!!(W&h.TypeFlags.Union),Z=!!(W&h.TypeFlags.Intersection),X;if(Q<V0&&SJ($)){let I=_.getTypeArguments($);if(I.length>0)X=I}let K=!!(W&h.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(z&&Q<V0)V=$.types.map((I)=>L_(_,I,Q+1,J));else if(Z&&Q<V0)V=$.types.map((I)=>L_(_,I,Q+1,J));let M;if(X&&X.length>0)M=X.map((I)=>L_(_,I,Q+1,J));let w;if(Q<V0&&!!(W&h.TypeFlags.Object)&&!z&&!Z){let I=_.getPropertiesOfType($);if(I.length>0&&I.length<=50){let D=$.symbol?.declarations?.[0];w=[];for(let S of I){let T=S.declarations?.[0]??D;if(!T)continue;try{let j=_.getTypeOfSymbolAtLocation(S,T);w.push({name:S.getName(),type:L_(_,j,Q+1,J)})}catch{}}if(w.length===0)w=void 0}}let C={text:Y,flags:W,isUnion:z,isIntersection:Z,isGeneric:K,members:V,typeArguments:M,properties:w};if(J)J.set($,C);return C}function H0(_,$,Q){if($.flags&h.TypeFlags.Any)return!1;if($.isUnion()){let z=$.types.filter((Z)=>!(Z.flags&(h.TypeFlags.Void|h.TypeFlags.Undefined|h.TypeFlags.Null)));return Q?z.some((Z)=>H0(_,Z,Q)):z.length>0&&z.every((Z)=>H0(_,Z,Q))}if($.isIntersection())return $.types.some((z)=>H0(_,z,Q));let J=_.getPropertyOfType($,"then");if(!J)return!1;let Y=J.declarations?.[0];if(!Y)return!1;return _.getTypeOfSymbolAtLocation(J,Y).getCallSignatures().some((z)=>z.parameters.length>=1)}function TJ(_){return h.isFunctionDeclaration(_)||h.isVariableDeclaration(_)||h.isClassDeclaration(_)||h.isInterfaceDeclaration(_)||h.isTypeAliasDeclaration(_)||h.isEnumDeclaration(_)||h.isMethodDeclaration(_)||h.isPropertyDeclaration(_)||h.isPropertySignature(_)||h.isMethodSignature(_)}var m0="/__gildash_type_probe__.ts";class p0{program;#$=null;constructor(_){this.program=_}#_(_){if(this.#$===_)return;this.program.notifyFileChanged(m0,`declare const __gildash_probe__: ${_};`),this.#$=_}#J(_,$){let Q=_.getSourceFile(m0);if(!Q)return null;let J=Q.statements[0];if(!J||!h.isVariableStatement(J))return null;let Y=J.declarationList.declarations[0];if(!Y)return null;let W=$.getTypeAtLocation(Y.name);if(!!(W.flags&h.TypeFlags.Any)&&W.intrinsicName==="error")return null;return W}clearProbe(){if(this.#$!==null)this.program.removeFile(m0),this.#$=null}collectAt(_,$){let Q=this.program.getProgram(),J=Q.getTypeChecker();if($<0)return null;let Y=Q.getSourceFile(_);if(!Y)return null;if($>=Y.getEnd())return null;let W=__(Y,$);if(!W)return null;if(!h.isIdentifier(W)&&!h.isTypeNode(W))return null;try{let z=J.getTypeAtLocation(W);return L_(J,z,0,new Map)}catch{return null}}collectAtSpan(_,$){let Q=this.program.getProgram(),J=Q.getTypeChecker(),Y=Q.getSourceFile(_);if(!Y)return null;let W=s_(Y,$.start,$.end);if(!W)return null;try{let z=J.getTypeAtLocation(W);return L_(J,z,0,new Map)}catch{return null}}isThenableAtSpan(_,$,Q){let J=this.program.getProgram(),Y=J.getTypeChecker(),W=J.getSourceFile(_);if(!W)return null;let z=s_(W,$.start,$.end);if(!z)return null;try{let Z=Y.getTypeAtLocation(z);return H0(Y,Z,Q?.anyConstituent??!0)}catch{return null}}contextualCallReturnsAtSpan(_,$){let Q=this.program.getProgram(),J=Q.getTypeChecker(),Y=Q.getSourceFile(_);if(!Y)return null;let W=s_(Y,$.start,$.end);if(!W||!h.isExpression(W))return null;try{let z=J.getContextualType(W);if(!z)return null;let Z=z.isUnion()?z.types.filter((V)=>!(V.flags&(h.TypeFlags.Void|h.TypeFlags.Undefined|h.TypeFlags.Null))):[z],X=new Map,K=[];for(let V of Z)for(let M of V.getCallSignatures()){let w=J.getReturnTypeOfSignature(M);K.push(L_(J,w,0,X))}return K}catch{return null}}isAssignableToTypeAtSpan(_,$,Q,J){this.#_(Q);let Y=this.program.getProgram(),W=Y.getTypeChecker(),z=Y.getSourceFile(_);if(!z)return null;let Z=s_(z,$.start,$.end);if(!Z)return null;try{let X=this.#J(Y,W);if(!X)return null;let K=W.getTypeAtLocation(Z);if(J?.anyConstituent&&K.isUnion())return K.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(K,X)}catch{return null}}isAssignableTo(_,$,Q,J){let Y=this.program.getProgram(),W=Y.getTypeChecker(),z=Y.getSourceFile(_);if(!z)return null;let Z=__(z,$);if(!Z||!h.isIdentifier(Z))return null;let X=Y.getSourceFile(Q);if(!X)return null;let K=__(X,J);if(!K||!h.isIdentifier(K))return null;try{let V=W.getTypeAtLocation(Z),M=W.getTypeAtLocation(K);return W.isTypeAssignableTo(V,M)}catch{return null}}isAssignableToType(_,$,Q,J){this.#_(Q);let Y=this.program.getProgram(),W=Y.getTypeChecker(),z=Y.getSourceFile(_);if(!z)return null;let Z=__(z,$);if(!Z||!h.isIdentifier(Z)&&!h.isTypeNode(Z))return null;try{let X=this.#J(Y,W);if(!X)return null;let K=W.getTypeAtLocation(Z);if(J?.anyConstituent&&K.isUnion())return K.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(K,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,Q,J){let Y=new Map;if($.length===0)return Y;this.#_(Q);let W=this.program.getProgram(),z=W.getTypeChecker(),Z=W.getSourceFile(_);if(!Z)return Y;try{let X=this.#J(W,z);if(!X)return Y;let K=Z.getEnd();for(let V of $){if(V<0||V>=K)continue;let M=__(Z,V);if(!M||!h.isIdentifier(M)&&!h.isTypeNode(M))continue;try{let w=z.getTypeAtLocation(M);if(J?.anyConstituent&&w.isUnion())Y.set(V,w.types.some((C)=>z.isTypeAssignableTo(C,X)));else Y.set(V,z.isTypeAssignableTo(w,X))}catch{}}}catch{}return Y}collectAtPositions(_,$){let Q=new Map;if($.length===0)return Q;let J=this.program.getProgram(),Y=J.getTypeChecker(),W=J.getSourceFile(_);if(!W)return Q;let z=W.getEnd(),Z=new Map;for(let X of $){if(X<0||X>=z)continue;let K=__(W,X);if(!K)continue;if(!h.isIdentifier(K)&&!h.isTypeNode(K))continue;try{let V=Y.getTypeAtLocation(K);Q.set(X,L_(Y,V,0,Z))}catch{}}return Q}collectFile(_){let $=new Map,Q=this.program.getProgram(),J=Q.getTypeChecker(),Y=Q.getSourceFile(_);if(!Y)return $;let W=new Map;function z(Z){if(TJ(Z)&&Z.name&&h.isIdentifier(Z.name)){let X=Z.name;try{let K=J.getTypeAtLocation(X),V=X.getStart(Y);$.set(V,L_(J,K,0,W))}catch{}}h.forEachChild(Z,z)}return z(Y),$}}import C_ from"typescript";var EJ=1000,FJ=1;function jJ(_){let $=_.declarations?.[0],Q=$?.getSourceFile(),J=$?C_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:Q?.fileName??"",position:J?.getStart(Q,!1)??$?.getStart(Q,!1)??0}}function K0(_,$=0,Q){let J=_.declarations?.[0],Y=J?.getSourceFile(),W=J?C_.getNameOfDeclaration(J):void 0,z=Y?.fileName??"",Z=W?.getStart(Y,!1)??J?.getStart(Y,!1)??0,X={name:_.getName(),filePath:z,position:Z},K=_;if(K.parent)X.parent=jJ(K.parent);let V=Q&&!!(_.flags&C_.SymbolFlags.Alias)?Q.getAliasedSymbol(_):_;if($<FJ){let M=V.flags,w=!!(M&C_.SymbolFlags.Enum),C=!!(M&(C_.SymbolFlags.NamespaceModule|C_.SymbolFlags.ValueModule)),I=!!(M&(C_.SymbolFlags.Class|C_.SymbolFlags.Interface));if(w&&V.exports&&V.exports.size>0){let D=[];V.exports.forEach((S)=>{D.push(K0(S,$+1,Q))}),X.members=D}else if(I&&V.members&&V.members.size>0){let D=[];V.members.forEach((S)=>{D.push(K0(S,$+1,Q))}),X.members=D}if(C&&V.exports&&V.exports.size>0){let D=[];V.exports.forEach((S)=>{D.push(K0(S,$+1,Q))}),X.exports=D}}return X}class d0{#$;#_;constructor(_,$=EJ){this.#$=_,this.#_=new a_($)}get(_,$){if(this.#$.isDisposed)return null;let Q=`${_}:${$}`,J=this.#_.get(Q);if(J!==void 0)return J;let Y=this.#$.getProgram(),W=Y.getSourceFile(_);if(!W)return null;let z=__(W,$);if(!z||!C_.isIdentifier(z))return null;let Z=Y.getTypeChecker(),X=Z.getSymbolAtLocation(z);if(!X)return null;let K=K0(X,0,Z);return this.#_.set(Q,K),K}clear(){this.#_.clear()}}import n from"typescript";import F from"typescript";function l0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(kJ($))return!0;return!1}function kJ(_){if(!F.canHaveModifiers(_))return!1;return F.getModifiers(_)?.some((Q)=>Q.kind===F.SyntaxKind.DeclareKeyword)??!1}function n0(_){let $=(J,Y)=>({kind:J,pos:Y.getStart(),end:Y.getEnd()}),Q=_.parent;while(Q){if(F.isSourceFile(Q)||F.isModuleDeclaration(Q))return $("module",Q);if(F.isFunctionLike(Q))return $("function",Q);if(F.isClassStaticBlockDeclaration(Q))return $("function",Q);if(F.isPropertyDeclaration(Q))return $("function",Q);if(F.isBlock(Q)){let J=Q.parent;if(J&&(F.isFunctionLike(J)||F.isClassStaticBlockDeclaration(J)))return $("function",J);return $("block",Q)}if(F.isForStatement(Q)||F.isForInStatement(Q)||F.isForOfStatement(Q)||F.isCatchClause(Q)||F.isCaseBlock(Q)||F.isWithStatement(Q))return $("block",Q);Q=Q.parent}return $("module",_.getSourceFile())}function i0(_){let $=_.parent;if(!$)return;if(F.isVariableDeclaration($)&&$.name===_)return"declaration";if(F.isParameter($)&&$.name===_)return"declaration";if(F.isBindingElement($)&&$.name===_)return"declaration";if((F.isForOfStatement($)||F.isForInStatement($))&&$.initializer===_)return"assignment";if((F.isPrefixUnaryExpression($)||F.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===F.SyntaxKind.PlusPlusToken||$.operator===F.SyntaxKind.MinusMinusToken))return"update";let Q=_;while(Q.parent&&F.isParenthesizedExpression(Q.parent))Q=Q.parent;let J=Q.parent;if(J&&F.isBinaryExpression(J)&&J.left===Q)return vJ(J.operatorToken.kind);if(gJ(_))return"assignment";return}function vJ(_){switch(_){case F.SyntaxKind.EqualsToken:return"assignment";case F.SyntaxKind.PlusEqualsToken:case F.SyntaxKind.MinusEqualsToken:case F.SyntaxKind.AsteriskEqualsToken:case F.SyntaxKind.AsteriskAsteriskEqualsToken:case F.SyntaxKind.SlashEqualsToken:case F.SyntaxKind.PercentEqualsToken:case F.SyntaxKind.LessThanLessThanEqualsToken:case F.SyntaxKind.GreaterThanGreaterThanEqualsToken:case F.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case F.SyntaxKind.AmpersandEqualsToken:case F.SyntaxKind.BarEqualsToken:case F.SyntaxKind.CaretEqualsToken:return"compound-assignment";case F.SyntaxKind.AmpersandAmpersandEqualsToken:case F.SyntaxKind.BarBarEqualsToken:case F.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function gJ(_){let $=_.parent;if(!$)return!1;if(!(F.isShorthandPropertyAssignment($)&&$.name===_||F.isPropertyAssignment($)&&$.initializer===_||F.isArrayLiteralExpression($)||F.isSpreadAssignment($)&&$.expression===_||F.isSpreadElement($)&&$.expression===_))return!1;let J=$;while(J.parent){let Y=J.parent;if(F.isBinaryExpression(Y)&&Y.left===J&&Y.operatorToken.kind===F.SyntaxKind.EqualsToken)return!0;if(F.isObjectLiteralExpression(Y)||F.isArrayLiteralExpression(Y)||F.isPropertyAssignment(Y)||F.isShorthandPropertyAssignment(Y)||F.isSpreadAssignment(Y)||F.isSpreadElement(Y)){J=Y;continue}return!1}return!1}class c0{#$;constructor(_){this.#$=_}findAt(_,$){let Q=this.#_(_,$);if(!Q)return[];let J=this.#$.getProgram(),Y=[];for(let W of Q)for(let z of W.references){let Z=J.getSourceFile(z.fileName);if(!Z)continue;Y.push(k1(z,Z))}return Y}findEnrichedAt(_,$){let Q=this.#_(_,$);if(!Q)return[];let J=this.#$.getProgram(),Y=J.getTypeChecker(),W=[];for(let z of Q){let Z=this.#J(z,J,Y);for(let X of z.references){let K=J.getSourceFile(X.fileName);if(!K)continue;let V=__(K,X.textSpan.start),M=V&&n.isIdentifier(V)?V:void 0;W.push({...k1(X,K),writeKind:M?i0(M):void 0,isAmbient:Z,enclosingScope:n0(M??K)})}}return W}findFileBindings(_){if(this.#$.isDisposed)return[];let $=this.#$.getProgram(),Q=$.getSourceFile(_);if(!Q)return[];return a0(Q,$.getTypeChecker())}#_(_,$){if(this.#$.isDisposed)return null;let J=this.#$.getProgram().getSourceFile(_);if(!J)return null;let Y=__(J,$);if(!Y||!n.isIdentifier(Y))return null;let W=this.#$.getLanguageService().findReferences(_,$);if(!W||W.length===0)return null;return W}#J(_,$,Q){let J=_.definition,Y=$.getSourceFile(J.fileName);if(!Y)return!1;let W=__(Y,J.textSpan.start);if(!W)return!1;let Z=Q.getSymbolAtLocation(W)?.declarations;if(!Z||Z.length===0)return!1;return Z.every(l0)}}function a0(_,$){let Q=new Map,J=(W)=>{if(n.isIdentifier(W)&&!uJ(W)){let z=PJ(W,$);if(z){let Z=Q.get(z);if(Z)Z.push(W);else Q.set(z,[W])}}n.forEachChild(W,J)};n.forEachChild(_,J);let Y=[];for(let[W,z]of Q){let Z=W.declarations;if(!Z||Z.length===0)continue;if(Z.every(bJ))continue;let X=Z.every(l0),K=new Set(Z.map((I)=>n.getNameOfDeclaration(I)).filter((I)=>I!==void 0)),V=Z[0],M=n.getNameOfDeclaration(V)??V,w=V.getSourceFile(),C=z.map((I)=>{let D=I.getStart(_),{line:S,character:T}=_.getLineAndCharacterOfPosition(D),j=i0(I);return{filePath:_.fileName,position:D,line:S+1,column:T,isDefinition:K.has(I),isWrite:j!==void 0,writeKind:j,isAmbient:X,enclosingScope:n0(I)}});Y.push({declaration:{filePath:w.fileName,position:M.getStart(w),name:W.getName(),isAmbient:X},references:C})}return Y}function uJ(_){let $=_.parent;return n.isPropertyAccessExpression($)&&$.name===_||n.isQualifiedName($)&&$.right===_||n.isPropertyAssignment($)&&$.name===_||n.isBindingElement($)&&$.propertyName===_||n.isJsxAttribute($)&&$.name===_||n.isImportSpecifier($)&&$.propertyName===_||n.isModuleDeclaration($)&&$.name===_&&($.flags&n.NodeFlags.GlobalAugmentation)!==0}function bJ(_){return n.isPropertyDeclaration(_)||n.isPropertySignature(_)||n.isMethodDeclaration(_)||n.isMethodSignature(_)||n.isGetAccessorDeclaration(_)||n.isSetAccessorDeclaration(_)||n.isEnumMember(_)||n.isParameter(_)&&n.isIndexSignatureDeclaration(_.parent)}function PJ(_,$){let Q=_.parent;if(n.isShorthandPropertyAssignment(Q))return $.getShorthandAssignmentValueSymbol(Q);if(n.isExportSpecifier(Q)){let J=Q.parent.parent;if(n.isExportDeclaration(J)&&J.moduleSpecifier)return;return(Q.propertyName??Q.name)===_?$.getExportSpecifierLocalTargetSymbol(Q):void 0}return $.getSymbolAtLocation(_)}function k1(_,$){let{line:Q,character:J}=$.getLineAndCharacterOfPosition(_.textSpan.start);return{filePath:_.fileName,position:_.textSpan.start,line:Q+1,column:J,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1}}import r_ from"typescript";function v1(_,$,Q={}){let J=r_.createSourceFile(_,$,Q.target??r_.ScriptTarget.ESNext,!0),Y={target:Q.target,module:Q.module,jsx:Q.jsx??(_.endsWith(".tsx")?r_.JsxEmit.Preserve:void 0),jsxFactory:Q.jsxFactory,jsxFragmentFactory:Q.jsxFragmentFactory,jsxImportSource:Q.jsxImportSource,experimentalDecorators:Q.experimentalDecorators,useDefineForClassFields:Q.useDefineForClassFields,noLib:!0,noResolve:!0,types:[]},W=r_.createCompilerHost(Y,!0);W.getSourceFile=(X)=>X===_?J:void 0;let z=r_.createProgram([_],Y,W),Z=z.getSourceFile(_);if(!Z)return[];return a0(Z,z.getTypeChecker())}import m from"typescript";function yJ(_,$){let Q=__(_,$);if(!Q)return;if(g1(Q))return Q;let J=Q.parent;for(let Y=0;Y<5&&J;Y++){if(g1(J))return J;J=J.parent}return Q}function g1(_){return m.isClassDeclaration(_)||m.isClassExpression(_)||m.isFunctionDeclaration(_)||m.isFunctionExpression(_)||m.isArrowFunction(_)||m.isVariableDeclaration(_)||m.isObjectLiteralExpression(_)}function u1(_){if(m.isClassDeclaration(_)||m.isClassExpression(_))return"class";if(m.isFunctionDeclaration(_)||m.isFunctionExpression(_)||m.isArrowFunction(_))return"function";if(m.isObjectLiteralExpression(_))return"object";if(m.isVariableDeclaration(_)&&_.initializer)return u1(_.initializer);return"class"}function fJ(_,$){if(m.isClassDeclaration(_)||m.isFunctionDeclaration(_))return _.name?.getText($)??"";if(m.isClassExpression(_))return _.name?.getText($)??"";if(m.isVariableDeclaration(_)&&m.isIdentifier(_.name))return _.name.getText($);if(m.isFunctionExpression(_))return _.name?.getText($)??"";if(m.isArrowFunction(_)&&_.parent&&m.isVariableDeclaration(_.parent)){if(m.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(m.isObjectLiteralExpression(_)&&_.parent&&m.isVariableDeclaration(_.parent)){if(m.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function xJ(_){if(!m.isClassDeclaration(_)&&!m.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((Q)=>Q.token===m.SyntaxKind.ImplementsKeyword)}class s0{#$;constructor(_){this.#$=_}findAt(_,$){if(this.#$.isDisposed)return[];let Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let Y=__(J,$);if(!Y||!m.isIdentifier(Y))return[];let z=this.#$.getLanguageService().getImplementationAtPosition(_,$);if(!z||z.length===0)return[];let Z=[];for(let X of z){if(X.kind===m.ScriptElementKind.interfaceElement||X.kind===m.ScriptElementKind.typeElement)continue;let K=Q.getSourceFile(X.fileName);if(!K)continue;let V=yJ(K,X.textSpan.start);if(!V)continue;let M=u1(V),w=fJ(V,K),C=xJ(V);Z.push({filePath:X.fileName,symbolName:w,position:X.textSpan.start,kind:M,isExplicit:C})}return Z}}function mJ(_){if($_.isFunctionDeclaration(_))return"function";if($_.isClassDeclaration(_))return"class";if($_.isInterfaceDeclaration(_))return"interface";if($_.isTypeAliasDeclaration(_))return"type";if($_.isEnumDeclaration(_))return"enum";if($_.isVariableDeclaration(_))return"const";if($_.isVariableStatement(_))return"const";return"unknown"}function b1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class M0{#$;#_;#J;#Y;#W;#Z=!1;constructor(_,$,Q,J,Y){this.#$=_,this.#_=$,this.#J=Q,this.#Y=J,this.#W=Y}static create(_,$={}){let Q=X0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(hJ(Q))return Q;let J=Q,Y=$.typeCollector??new p0(J),W=$.symbolGraph??new d0(J),z=$.referenceResolver??new c0(J),Z=$.implementationFinder??new s0(J);return new M0(J,Y,W,z,Z)}get isDisposed(){return this.#Z}collectTypeAt(_,$){return this.#Q(),this.#_.collectAt(_,$)}collectFileTypes(_){return this.#Q(),this.#_.collectFile(_)}collectTypesAtPositions(_,$){return this.#Q(),this.#_.collectAtPositions(_,$)}collectAtSpan(_,$){return this.#Q(),this.#_.collectAtSpan(_,$)}isThenableAtSpan(_,$,Q){return this.#Q(),this.#_.isThenableAtSpan(_,$,Q)}contextualCallReturnsAtSpan(_,$){return this.#Q(),this.#_.contextualCallReturnsAtSpan(_,$)}isTypeAssignableToTypeAtSpan(_,$,Q,J){return this.#Q(),this.#_.isAssignableToTypeAtSpan(_,$,Q,J)}findReferences(_,$){return this.#Q(),this.#Y.findAt(_,$)}findEnrichedReferences(_,$){return this.#Q(),this.#Y.findEnrichedAt(_,$)}getFileBindings(_){return this.#Q(),this.#Y.findFileBindings(_)}getStandaloneFileBindings(_,$){this.#Q();let Q=this.#$.getCompilerOptions();return v1(_,$,{target:Q.target,module:Q.module,jsx:Q.jsx,jsxFactory:Q.jsxFactory,jsxFragmentFactory:Q.jsxFragmentFactory,jsxImportSource:Q.jsxImportSource,experimentalDecorators:Q.experimentalDecorators,useDefineForClassFields:Q.useDefineForClassFields})}getFileBindingsBatch(_){this.#Q();for(let Q of _)this.notifyFileChanged(Q.filePath,Q.content);let $=new Map;for(let Q of _)$.set(Q.filePath,this.#Y.findFileBindings(Q.filePath));return $}findImplementations(_,$){return this.#Q(),this.#W.findAt(_,$)}isTypeAssignableTo(_,$,Q,J){return this.#Q(),this.#_.isAssignableTo(_,$,Q,J)}isTypeAssignableToType(_,$,Q,J){return this.#Q(),this.#_.isAssignableToType(_,$,Q,J)}isTypeAssignableToTypeAtPositions(_,$,Q,J){return this.#Q(),this.#_.isAssignableToTypeAtPositions(_,$,Q,J)}getSymbolNode(_,$){return this.#Q(),this.#J.get(_,$)}getBaseTypes(_,$){this.#Q();let Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return null;let Y=__(J,$);if(!Y)return null;let W=Q.getTypeChecker(),z=W.getTypeAtLocation(Y);if(!(z.flags&$_.TypeFlags.Object)||!(z.objectFlags&$_.ObjectFlags.ClassOrInterface))return null;let Z=W.getBaseTypes(z);if(!Z||Z.length===0)return[];let X=new Map;return Z.map((K)=>L_(W,K,0,X))}getModuleInterface(_){this.#Q();let $=[],Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return{filePath:_,exports:$};let Y=Q.getTypeChecker(),W=Y.getSymbolAtLocation(J);if(W){let z=Y.getExportsOfModule(W),Z=new Map;for(let X of z){let K=X.getName(),V=X.declarations?.[0],M="unknown";if(V){if(M=mJ(V),M==="unknown"&&$_.isExportAssignment(V))M="const"}let w=null;try{let C=Y.getTypeOfSymbolAtLocation(X,V??J);w=L_(Y,C,0,Z)}catch{}$.push({name:K,kind:M,resolvedType:w})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Z)return;this.#$.notifyFileChanged(_,$),this.#J.clear()}notifyFileDeleted(_){if(this.#Z)return;this.#$.removeFile(_),this.#J.clear()}lineColumnToPosition(_,$,Q){this.#Q();let J=this.#$.getProgram().getSourceFile(_);if(!J)return null;try{return $_.getPositionOfLineAndCharacter(J,$-1,Q)}catch{return null}}findNamePosition(_,$,Q){this.#Q();let J=this.#$.getProgram().getSourceFile(_);if(!J)return null;let Y=J.getFullText(),W=$;while(W<Y.length){let z=Y.indexOf(Q,W);if(z<0)return null;let Z=z>0?Y.charCodeAt(z-1):32,X=z+Q.length<Y.length?Y.charCodeAt(z+Q.length):32;if(!b1(Z)&&!b1(X))return z;W=z+1}return null}getDiagnostics(_,$){this.#Q();let Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let Y={[$_.DiagnosticCategory.Error]:"error",[$_.DiagnosticCategory.Warning]:"warning",[$_.DiagnosticCategory.Suggestion]:"suggestion",[$_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?$_.getPreEmitDiagnostics(Q,J):Q.getSemanticDiagnostics(J)).map((z)=>{let Z=1,X=0;if(z.file&&z.start!==void 0){let K=$_.getLineAndCharacterOfPosition(z.file,z.start);Z=K.line+1,X=K.character}return{filePath:z.file?.fileName??_,line:Z,column:X,message:$_.flattenDiagnosticMessageText(z.messageText,`
10
+ `),code:z.code,category:Y[z.category]??"error"}})}dispose(){if(this.#Z)return;this.#Z=!0,this.#_.clearProbe(),this.#$.dispose(),this.#J.clear()}#Q(){if(this.#Z)throw Error("SemanticLayer is disposed")}}import{eq as F_,and as P1,sql as pJ}from"drizzle-orm";var y1=80;class r0{db;constructor(_){this.db=_}insertBatch(_,$,Q){if(!Q.length)return;let J=Q.map((Y)=>({project:_,filePath:$,tag:Y.tag,value:Y.value,source:Y.source,symbolName:Y.symbolName,startLine:Y.startLine,startColumn:Y.startColumn,endLine:Y.endLine,endColumn:Y.endColumn,indexedAt:Y.indexedAt}));for(let Y=0;Y<J.length;Y+=y1)this.db.drizzleDb.insert(H_).values(J.slice(Y,Y+y1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(H_).where(P1(F_(H_.project,_),F_(H_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(H_).where(P1(_.project?F_(H_.project,_.project):void 0,_.tag?F_(H_.tag,_.tag):void 0,_.filePath?F_(H_.filePath,_.filePath):void 0,_.symbolName?F_(H_.symbolName,_.symbolName):void 0,_.source?F_(H_.source,_.source):void 0,_.ftsQuery?pJ`${H_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as P_,and as f1,sql as o_,gt as dJ,gte as lJ}from"drizzle-orm";var x1=80;class o0{db;constructor(_){this.db=_}insertBatch(_){if(!_.length)return;let $=_.map((Q)=>({project:Q.project,changeType:Q.changeType,symbolName:Q.symbolName,symbolKind:Q.symbolKind,filePath:Q.filePath,oldName:Q.oldName,oldFilePath:Q.oldFilePath,fingerprint:Q.fingerprint,changedAt:Q.changedAt,isFullIndex:Q.isFullIndex,indexRunId:Q.indexRunId}));for(let Q=0;Q<$.length;Q+=x1)this.db.drizzleDb.insert(J_).values($.slice(Q,Q+x1)).run()}getSince(_){return this.db.drizzleDb.select().from(J_).where(f1(P_(J_.project,_.project),lJ(J_.changedAt,_.since),_.symbolName?P_(J_.symbolName,_.symbolName):void 0,_.changeTypes?.length?o_`${J_.changeType} IN (${o_.join(_.changeTypes.map(($)=>o_`${$}`),o_`, `)})`:void 0,_.filePath?P_(J_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:P_(J_.isFullIndex,0),_.indexRunId?P_(J_.indexRunId,_.indexRunId):void 0,_.afterId?dJ(J_.id,_.afterId):void 0)).orderBy(J_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(J_).where(f1(P_(J_.project,_),o_`${J_.changedAt} < ${$}`)).run().changes}}function h1(_){let{annotationRepo:$,project:Q,query:J}=_,Y=J.project??Q,W;if(J.text){let Z=z0(J.text);if(Z)W=Z}return $.search({project:Y,tag:J.tag,filePath:J.filePath,symbolName:J.symbolName,source:J.source,ftsQuery:W,limit:J.limit}).map((Z)=>({tag:Z.tag,value:Z.value,source:Z.source,filePath:Z.filePath,symbolName:Z.symbolName,span:{start:{line:Z.startLine,column:Z.startColumn},end:{line:Z.endLine,column:Z.endColumn}}}))}function e(_){if(_.closed)throw new N("closed","Gildash: instance is closed")}function v(_,$,Q,J){e(_);try{return J()}catch(Y){if(Y instanceof N)throw Y;throw new N($,`Gildash: ${Q} failed`,{cause:Y})}}async function t0(_,$,Q,J){e(_);try{return await J()}catch(Y){if(Y instanceof N)throw Y;throw new N($,`Gildash: ${Q} failed`,{cause:Y})}}class O0{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((Q)=>[...this.options.relationRepo.getByType(Q,"imports"),...this.options.relationRepo.getByType(Q,"type-references"),...this.options.relationRepo.getByType(Q,"re-exports")]);for(let Q of $){let{srcFilePath:J,dstFilePath:Y}=Q;if(Y===null)continue;if(!this.adjacencyList.has(J))this.adjacencyList.set(J,new Set);if(this.adjacencyList.get(J).add(Y),!this.adjacencyList.has(Y))this.adjacencyList.set(Y,new Set);if(!this.reverseAdjacencyList.has(Y))this.reverseAdjacencyList.set(Y,new Set);this.reverseAdjacencyList.get(Y).add(J)}}patchFiles(_,$,Q){let J=new Set([..._,...$]);for(let Y of J){let W=this.adjacencyList.get(Y);if(W){for(let Z of W)this.reverseAdjacencyList.get(Z)?.delete(Y);W.clear()}let z=this.reverseAdjacencyList.get(Y);if(z){for(let Z of z)this.adjacencyList.get(Z)?.delete(Y);z.clear()}}for(let Y of $)this.adjacencyList.delete(Y),this.reverseAdjacencyList.delete(Y);for(let Y of _){let W=Q(Y);for(let z of W){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,Q=[_];while(Q.length>0){let J=Q.shift();for(let Y of this.reverseAdjacencyList.get(J)??[])if(!$.has(Y))$.add(Y),Q.push(Y)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let Q of this.adjacencyList.keys()){if(_.has(Q))continue;let J=[{node:Q,entered:!1}];while(J.length>0){let Y=J.pop();if(Y.entered){$.delete(Y.node);continue}if($.has(Y.node))return!0;if(_.has(Y.node))continue;_.add(Y.node),$.add(Y.node),J.push({node:Y.node,entered:!0});for(let W of this.adjacencyList.get(Y.node)??[]){if($.has(W))return!0;if(!_.has(W))J.push({node:W,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let Q of _)for(let J of this.getTransitiveDependents(Q))$.add(J);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,Q]of this.adjacencyList)_.set($,Array.from(Q));return _}getTransitiveDependencies(_){let $=new Set,Q=[_];while(Q.length>0){let J=Q.shift();for(let Y of this.adjacencyList.get(J)??[])if(!$.has(Y))$.add(Y),Q.push(Y)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let Q=new Map;for(let[J,Y]of this.adjacencyList)Q.set(J,Array.from(Y));return sJ(Q,$)}}var nJ=(_,$)=>_.localeCompare($);function iJ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let Q=$;for(let J=1;J<$.length;J++){let Y=$.slice(J).concat($.slice(0,J));if(Y.join("::")<Q.join("::"))Q=Y}return[...Q]}function e0(_,$,Q){let J=iJ(Q);if(J.length===0)return!1;let Y=J.join("->");if(_.has(Y))return!1;return _.add(Y),$.push(J),!0}function cJ(_){let $=0,Q=[],J=new Set,Y=new Map,W=new Map,z=[],Z=(X)=>{Y.set(X,$),W.set(X,$),$+=1,Q.push(X),J.add(X);for(let K of _.get(X)??[])if(!Y.has(K))Z(K),W.set(X,Math.min(W.get(X)??0,W.get(K)??0));else if(J.has(K))W.set(X,Math.min(W.get(X)??0,Y.get(K)??0));if(W.get(X)===Y.get(X)){let K=[],V="";do V=Q.pop()??"",J.delete(V),K.push(V);while(V!==X&&Q.length>0);z.push(K)}};for(let X of _.keys())if(!Y.has(X))Z(X);return{components:z}}function aJ(_,$,Q){let J=[],Y=new Set,W=[..._].sort(nJ),z=(Z,X,K)=>{X.delete(Z);let V=K.get(Z);if(!V)return;for(let M of V)if(X.has(M))z(M,X,K);V.clear()};for(let Z=0;Z<W.length&&J.length<Q;Z++){let X=W[Z]??"",K=new Set(W.slice(Z)),V=new Set,M=new Map,w=[],C=(D)=>($.get(D)??[]).filter((S)=>K.has(S)),I=(D)=>{if(J.length>=Q)return!0;let S=!1;w.push(D),V.add(D);for(let T of C(D)){if(J.length>=Q)break;if(T===X)e0(Y,J,w.concat(X)),S=!0;else if(!V.has(T)){if(I(T))S=!0}}if(S)z(D,V,M);else for(let T of C(D)){let j=M.get(T)??new Set;j.add(D),M.set(T,j)}return w.pop(),S};I(X)}return J}function sJ(_,$){let{components:Q}=cJ(_),J=[],Y=new Set;for(let W of Q){if(J.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))e0(Y,J,[X,X]);continue}let z=$-J.length,Z=aJ(W,_,z);for(let X of Z){if(J.length>=$)break;e0(Y,J,X)}}return J}var rJ=15000;function L0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function j_(_,$){let Q=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>rJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===Q)return _.graphCache;let J=new O0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((Y)=>Y.project)});return J.build(),_.graphCache=J,_.graphCacheKey=Q,_.graphCacheBuiltAt=Date.now(),J}function m1(_,$,Q,J=1e4){return v(_,"search","getDependencies",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{srcFilePath:$,type:"imports",project:Q??_.defaultProject,limit:J}}).filter((Y)=>Y.dstFilePath!==null).map((Y)=>Y.dstFilePath))}function p1(_,$,Q,J=1e4){return v(_,"search","getDependents",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{dstFilePath:$,type:"imports",project:Q??_.defaultProject,limit:J}}).map((Y)=>Y.srcFilePath))}async function d1(_,$,Q){return v(_,"search","getAffected",()=>{return j_(_,Q).getAffectedByChange($.map((Y)=>K_(_.projectRoot,Y)))})}async function l1(_,$){return v(_,"search","hasCycle",()=>{return j_(_,$).hasCycle()})}async function n1(_,$){return v(_,"search","getImportGraph",()=>{return j_(_,$).getAdjacencyList()})}async function i1(_,$,Q){return v(_,"search","getTransitiveDependencies",()=>{return j_(_,Q).getTransitiveDependencies(K_(_.projectRoot,$))})}async function c1(_,$,Q){return v(_,"search","getTransitiveDependents",()=>{return j_(_,Q).getTransitiveDependents(K_(_.projectRoot,$))})}async function a1(_,$,Q){return v(_,"search","getCyclePaths",()=>{return j_(_,$).getCyclePaths(Q)})}async function s1(_,$,Q){return v(_,"search","getFanMetrics",()=>{let J=j_(_,Q),Y=K_(_.projectRoot,$);return{filePath:$,fanIn:J.getDependents(Y).length,fanOut:J.getDependencies(Y).length}})}var eJ=30000,r1=15000,_6=10;function $6(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??y_.basename(_.projectRoot)}function Q6(_,$){return(Q)=>{for(let J of _.onFileChangedCallbacks)try{J(Q)}catch(Y){_.logger.error("[Gildash] onFileChanged callback threw:",Y)}if($.handleWatcherEvent?.(Q),_.semanticLayer)if(Q.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(Q.filePath)}catch(J){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",J);for(let Y of _.onErrorCallbacks)try{Y(J instanceof N?J:new N("semantic","semantic notifyFileDeleted failed",{cause:J}))}catch{}}else _.readFileFn(Q.filePath).then((J)=>{try{_.semanticLayer?.notifyFileChanged(Q.filePath,J)}catch(Y){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",Y);for(let W of _.onErrorCallbacks)try{W(Y instanceof N?Y:new N("semantic","semantic notifyFileChanged failed",{cause:Y}))}catch{}}}).catch((J)=>{_.logger.error("[Gildash] failed to read file for semantic layer",Q.filePath,J);try{_.semanticLayer?.notifyFileDeleted(Q.filePath)}catch(Y){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",Y)}})}}async function J6(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(Q)=>{try{let J=y_.resolve(_.projectRoot,Q.filePath),Y=await _.readFileFn(J);_.semanticLayer?.notifyFileChanged(J,Y)}catch{}}))}async function o1(_,$){let Q=_.coordinatorFactory?_.coordinatorFactory():new b0({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,onBoundariesChanged:(J)=>$6(_,J),logger:_.logger});_.coordinator=Q;for(let J of _.onIndexedCallbacks)Q.onIndexed(J);if(Q.onIndexed((J)=>{let Y=J.changedFiles.length+J.deletedFiles.length;if(_.graphCache&&Y>0&&Y<100){let W=_.relationRepo;_.graphCache.patchFiles(J.changedFiles,J.deletedFiles,(z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>W.getByType(X,"imports").concat(W.getByType(X,"type-references")).concat(W.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 L0(_)}),$.isWatchMode){let J=_.watcherFactory?_.watcherFactory():new T0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await J.start(Q6(_,Q)).then((Y)=>{if(t_(Y))throw Y.data}),_.watcher=J,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},eJ)}await Q.fullIndex(),await J6(_)}function Y6(_,$){let Q=["SIGTERM","SIGINT","beforeExit"];for(let J of Q){let Y=()=>{$().catch((W)=>_.logger.error("[Gildash] close error during signal",J,W))};if(J==="beforeExit")process.on("beforeExit",Y);else process.on(J,Y);_.signalHandlers.push([J,Y])}}async function t1(_){let{projectRoot:$,extensions:Q=[".ts",".mts",".cts"],ignorePatterns:J=["**/node_modules/**"],parseCacheCapacity:Y=500,logger:W=console,existsSyncFn:z=tJ,dbConnectionFactory:Z,watcherFactory:X,coordinatorFactory:K,repositoryFactory:V,acquireWatcherRoleFn:M=T1,releaseWatcherRoleFn:w=E1,updateHeartbeatFn:C=F1,discoverProjectsFn:I=$0,parseSourceFn:D=g_,extractSymbolsFn:S=S_,extractRelationsFn:T=c_,symbolSearchFn:j=y0,relationSearchFn:P=f0,patternSearchFn:x=x0,loadTsconfigPathsFn:i=n_,readFileFn:a=async(s)=>Bun.file(s).text(),unlinkFn:Q_=async(s)=>{await Bun.file(s).unlink()},watchMode:W_,semantic:I_,semanticLayerFactory:M_}=_;if(!y_.isAbsolute($))throw new N("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!z($))throw new N("validation",`Gildash: projectRoot does not exist: "${$}"`);let U_=Z?Z():new D0({projectRoot:$}),r=U_.open();if(t_(r))throw r.data;try{let s=await I($),R_=s[0]?.project??y_.basename($),B_=V?V():(()=>{let q=U_;return{fileRepo:new C0(q),symbolRepo:new q0(q),relationRepo:new N0(q),parseCache:new P0(Y)}})(),H=V?null:U_,A=H?new r0(H):null,B=H?new o0(H):null,U=W_??!0,O=crypto.randomUUID(),G;if(U)G=await Promise.resolve(M(U_,process.pid,{instanceId:O}));else G="owner";let L={projectRoot:$,extensions:Q,ignorePatterns:J,logger:W,defaultProject:R_,role:G,db:U_,symbolRepo:B_.symbolRepo,relationRepo:B_.relationRepo,fileRepo:B_.fileRepo,parseCache:B_.parseCache,annotationRepo:A,changelogRepo:B,annotationSearchFn:h1,releaseWatcherRoleFn:w,parseSourceFn:D,extractSymbolsFn:S,extractRelationsFn:T,symbolSearchFn:j,relationSearchFn:P,patternSearchFn:x,readFileFn:a,unlinkFn:Q_,existsSyncFn:z,acquireWatcherRoleFn:M,updateHeartbeatFn:C,watcherFactory:X,coordinatorFactory:K,instanceId:O,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:s,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(Q0($),L.tsconfigPaths=await i($),I_){let q=y_.join($,"tsconfig.json");try{if(M_)L.semanticLayer=M_(q);else{let R=M0.create(q);if(t_(R))throw R.data;L.semanticLayer=R}}catch(R){if(R instanceof N)throw R;throw new N("semantic","Gildash: semantic layer creation failed",{cause:R})}}if(G==="owner")await o1(L,{isWatchMode:U});else{let q=0,R=async()=>{try{let E=await Promise.resolve(L.acquireWatcherRoleFn(L.db,process.pid,{instanceId:L.instanceId}));if(q=0,E==="owner"){L.role="owner";for(let g of L.onRoleChangedCallbacks)try{g("owner")}catch(k){L.logger.error("[Gildash] onRoleChanged callback threw:",k)}clearInterval(L.timer),L.timer=null;try{await o1(L,{isWatchMode:!0})}catch(g){if(L.logger.error("[Gildash] owner promotion failed, reverting to reader",g),L.role="reader",L.timer!==null)clearInterval(L.timer),L.timer=null;if(L.watcher){let k=await L.watcher.close();if(t_(k))L.logger.error("[Gildash] watcher close error during promotion rollback",k.data);L.watcher=null}if(L.coordinator)await L.coordinator.shutdown().catch((k)=>L.logger.error("[Gildash] coordinator shutdown error during promotion rollback",k)),L.coordinator=null;try{L.releaseWatcherRoleFn(L.db,process.pid)}catch(k){L.logger.error("[Gildash] failed to release watcher role during promotion rollback",k)}L.timer=setInterval(R,r1)}}}catch(E){q++;let g=E instanceof N?E:new N("watcher","Gildash: healthcheck error",{cause:E});for(let k of L.onErrorCallbacks)try{k(g)}catch(b){L.logger.error("[Gildash] onError callback threw:",b)}if(L.logger.error("[Gildash] healthcheck error",E),q>=_6)L.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(L.timer),L.timer=null,B0(L).catch((k)=>L.logger.error("[Gildash] close error during healthcheck shutdown",k))}};L.timer=setInterval(R,r1)}if(U)Y6(L,()=>B0(L));return L}catch(s){if(U_.close(),s instanceof N)throw s;throw new N("store","Gildash: initialization failed",{cause:s})}}async function B0(_,$){if(_.closed)return;_.closed=!0;let Q=[];for(let[J,Y]of _.signalHandlers)if(J==="beforeExit")process.off("beforeExit",Y);else process.off(J,Y);if(_.signalHandlers=[],_.semanticLayer){try{_.semanticLayer.dispose()}catch(J){Q.push(J instanceof Error?J:Error(String(J)))}_.semanticLayer=null}if(_.coordinator)try{await _.coordinator.shutdown()}catch(J){Q.push(J instanceof Error?J:Error(String(J)))}if(_.watcher){let J=await _.watcher.close();if(t_(J))Q.push(J.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(J){Q.push(J instanceof Error?J:Error(String(J)))}try{_.db.close()}catch(J){Q.push(J instanceof Error?J:Error(String(J)))}if($?.cleanup)for(let J of["","-wal","-shm"])try{await _.unlinkFn(y_.join(_.projectRoot,A_,_0+J))}catch{}if(Q.length>0)throw new N("close","Gildash: one or more errors occurred during close()",{cause:Q})}import{isErr as e1}from"@zipbul/result";function _$(_,$,Q,J){e(_);let Y=_.parseSourceFn($,Q,J);if(e1(Y))throw Y.data;return _.parseCache.set($,Y),Y}async function $$(_,$,Q){e(_);let J=new Map,Y=[];return await Promise.all($.map(async(W)=>{try{let z=await _.readFileFn(W),Z=_.parseSourceFn(W,z,Q);if(!e1(Z))J.set(W,Z);else Y.push({filePath:W,error:Z.data})}catch(z){Y.push({filePath:W,error:z instanceof Error?z:Error(String(z))})}})),{parsed:J,failures:Y}}function Q$(_,$){return e(_),_.parseCache.get($)}function J$(_,$){return e(_),_.extractSymbolsFn($)}function Y$(_,$){return e(_),_.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import W$ from"path";function Z$(_,$){return v(_,"store","getStats",()=>_.symbolRepo.getStats($??_.defaultProject))}function _1(_,$){return v(_,"search","searchSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function z$(_,$){return v(_,"search","searchRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function X$(_,$){return v(_,"search","searchAllSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function U$(_,$){return v(_,"search","searchAllRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function V$(_,$){return v(_,"store","listIndexedFiles",()=>_.fileRepo.getAllFiles($??_.defaultProject))}function H$(_,$,Q){return v(_,"search","getInternalRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}}))}function K$(_,$,Q,J){return v(_,"search","getFullSymbol",()=>{let Y=J??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:Y,query:{text:$,exact:!0,filePath:Q,limit:1}});if(W.length===0)return null;let z=W[0],Z=z.detail,X={...z,members:Z.members,jsDoc:Z.jsDoc,parameters:Z.parameters,returnType:Z.returnType,heritage:Z.heritage,decorators:Z.decorators,typeParameters:Z.typeParameters,initializer:Z.initializer};if(_.semanticLayer)try{let K=W$.isAbsolute(Q)?Q:W$.resolve(_.projectRoot,Q),V=_.semanticLayer.lineColumnToPosition(K,z.span.start.line,z.span.start.column);if(V!==null){let M=_.semanticLayer.findNamePosition(K,V,z.name)??V,w=_.semanticLayer.collectTypeAt(K,M);if(w)X.resolvedType=w}}catch{}return X})}function M$(_,$,Q){return v(_,"store","getFileStats",()=>{let J=Q??_.defaultProject,Y=K_(_.projectRoot,$),W=_.fileRepo.getFile(J,Y);if(!W)throw new N("search",`Gildash: file '${$}' is not in the index`);let z=_.symbolRepo.getFileSymbols(J,Y),Z=_.relationRepo.getOutgoing(J,Y);return{filePath:W.filePath,lineCount:W.lineCount??0,size:W.size,symbolCount:z.length,exportedSymbolCount:z.filter((X)=>X.isExported).length,relationCount:Z.length}})}function O$(_,$,Q){return v(_,"store","getFileInfo",()=>_.fileRepo.getFile(Q??_.defaultProject,K_(_.projectRoot,$)))}function L$(_,$,Q){return _1(_,{filePath:$,project:Q??void 0,limit:1e4})}function B$(_,$,Q){return v(_,"search","getModuleInterface",()=>{let Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((z)=>`${z.name}${z.isOptional?"?":""}: ${z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:Y}})}import u from"path";function f_(_,$,Q,J){let Y=J??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:Y,query:{text:$,exact:!0,filePath:Q,limit:1}});if(W.length===0)return null;let z=W[0],Z=u.isAbsolute(Q)?Q:u.resolve(_.projectRoot,Q),X=_.semanticLayer.lineColumnToPosition(Z,z.span.start.line,z.span.start.column);if(X===null)return null;let K=_.semanticLayer.findNamePosition(Z,X,z.name)??X;return{sym:z,position:K,absPath:Z}}function G$(_,$,Q,J){return v(_,"search","getResolvedType",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=f_(_,$,Q,J);if(!Y)return null;return _.semanticLayer.collectTypeAt(Y.absPath,Y.position)})}function I$(_,$,Q,J){return v(_,"search","getSemanticReferences",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=f_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findReferences(Y.absPath,Y.position)})}function w$(_,$,Q,J){return v(_,"search","getEnrichedReferences",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=f_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findEnrichedReferences(Y.absPath,Y.position)})}function D$(_,$,Q,J){return v(_,"search","getImplementations",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=f_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findImplementations(Y.absPath,Y.position)})}function C$(_,$,Q,J,Y,W){return v(_,"semantic","isTypeAssignableTo",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let z=f_(_,$,Q,W);if(!z)throw new N("search",`Gildash: source symbol '${$}' not found in '${Q}'`);let Z=f_(_,J,Y,W);if(!Z)throw new N("search",`Gildash: target symbol '${J}' not found in '${Y}'`);return _.semanticLayer.isTypeAssignableTo(z.absPath,z.position,Z.absPath,Z.position)})}function A$(_,$){return v(_,"semantic","getFileTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(Q)})}function q$(_,$,Q,J){return v(_,"semantic","getResolvedTypeAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=u.isAbsolute($)?$:u.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(Y,Q,J);if(W===null)return null;return _.semanticLayer.collectTypeAt(Y,W)})}function N$(_,$){return v(_,"semantic","isTypeAssignableToAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=u.isAbsolute($.source.filePath)?$.source.filePath:u.resolve(_.projectRoot,$.source.filePath),J=u.isAbsolute($.target.filePath)?$.target.filePath:u.resolve(_.projectRoot,$.target.filePath),Y=_.semanticLayer.lineColumnToPosition(Q,$.source.line,$.source.column);if(Y===null)return null;let W=_.semanticLayer.lineColumnToPosition(J,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(Q,Y,J,W)})}function R$(_,$){return v(_,"search","getSemanticModuleInterface",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");return _.semanticLayer.getModuleInterface($)})}function S$(_,$,Q){return v(_,"semantic","getBaseTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(J,Q)})}function T$(_,$,Q){return v(_,"semantic","getResolvedTypesAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(J,Q)})}function E$(_,$,Q){return v(_,"semantic","getExpressionTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.collectAtSpan(J,Q)})}function F$(_,$,Q,J){return v(_,"semantic","isThenableAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.isThenableAtSpan(Y,Q,J)})}function j$(_,$,Q){return v(_,"semantic","getContextualCallReturnsAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.contextualCallReturnsAtSpan(J,Q)})}function k$(_,$,Q,J,Y){return v(_,"semantic","isTypeAssignableToTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtSpan(W,Q,J,Y)})}function v$(_,$,Q){return v(_,"semantic","getResolvedTypeAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(J,Q)})}function g$(_,$,Q){return v(_,"semantic","getSemanticReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(J,Q)})}function u$(_,$,Q){return v(_,"semantic","getEnrichedReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(J,Q)})}function b$(_,$){return v(_,"semantic","getFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(Q)})}function P$(_,$){return v(_,"semantic","getFileBindingsBatch",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=$.map((W)=>({orig:W.filePath,abs:u.isAbsolute(W.filePath)?W.filePath:u.resolve(_.projectRoot,W.filePath),content:W.content})),J=_.semanticLayer.getFileBindingsBatch(Q.map((W)=>({filePath:W.abs,content:W.content}))),Y=new Map;for(let W of Q)Y.set(W.orig,J.get(W.abs)??[]);return Y})}function y$(_,$,Q){return v(_,"semantic","getStandaloneFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.getStandaloneFileBindings(J,Q)})}function f$(_,$,Q){return v(_,"semantic","notifyFileChanged",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);_.semanticLayer.notifyFileChanged(J,Q)})}function x$(_,$){return v(_,"semantic","notifyFileDeleted",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);_.semanticLayer.notifyFileDeleted(Q)})}function h$(_,$,Q){return v(_,"semantic","getImplementationsAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(J,Q)})}function m$(_,$,Q,J,Y){return v(_,"semantic","isTypeAssignableToAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=u.isAbsolute($)?$:u.resolve(_.projectRoot,$),z=u.isAbsolute(J)?J:u.resolve(_.projectRoot,J);return _.semanticLayer.isTypeAssignableTo(W,Q,z,Y)})}function p$(_,$,Q,J,Y){return v(_,"semantic","isTypeAssignableToType",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,Q,J,Y)})}function d$(_,$,Q,J,Y){return v(_,"semantic","isTypeAssignableToTypeAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,Q,J,Y)})}function l$(_,$,Q,J){return v(_,"semantic","lineColumnToPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(Y,Q,J)})}function n$(_,$,Q,J){return v(_,"semantic","findNamePosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(Y,Q,J)})}function i$(_,$,Q){return v(_,"semantic","getSymbolNode",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(J,Q)})}function c$(_,$,Q){return v(_,"semantic","getSemanticDiagnostics",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=u.isAbsolute($)?$:u.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(J,Q)})}import U6 from"path";function a$(_,$){let Q=new Map(_.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),J=new Map($.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),Y=[],W=[],z=[];for(let[Z,X]of J){let K=Q.get(Z);if(!K)Y.push(X);else if(K.fingerprint!==X.fingerprint)z.push({before:K,after:X})}for(let[Z,X]of Q)if(!J.has(Z))W.push(X);return{added:Y,removed:W,modified:z}}function s$(_,$){if(e(_),_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let Q=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),Q()}}async function r$(_){return t0(_,"index","reindex",async()=>{if(!_.coordinator)throw new N("closed","Gildash: reindex() is not available for readers");let $=await _.coordinator.fullIndex();return L0(_),$})}function o$(_,$,Q,J){return v(_,"search","resolveSymbol",()=>{let Y=J??_.defaultProject,W=new Set,z=[],Z=$,X=Q;for(;;){let K=`${X}::${Z}`;if(W.has(K))return{originalName:Z,originalFilePath:X,reExportChain:z,circular:!0};W.add(K);let V=_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Y,query:{type:"re-exports",srcFilePath:X,limit:500}}),M,w;for(let C of V){let I;if(C.metaJson)try{let S=JSON.parse(C.metaJson);if(Array.isArray(S.specifiers))I=S.specifiers}catch{}if(!I)continue;let D=I.find((S)=>S.exported===Z);if(!D)continue;M=C.dstFilePath??void 0,w=D.local;break}if(!M||!w)return{originalName:Z,originalFilePath:X,reExportChain:z,circular:!1};z.push({filePath:X,exportedAs:Z}),X=M,Z=w}})}function t$(_,$){return e(_),_.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function e$(_,$){return e(_),_.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function _Q(_,$){return e(_),_.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function $Q(_,$,Q){return t0(_,"search","findPattern",async()=>{let J=Q?.project??_.defaultProject,Y=Q?.filePaths?Q.filePaths:_.fileRepo.getAllFiles(J).map((W)=>W.filePath);return await _.patternSearchFn({pattern:$,filePaths:Y})})}async function QQ(_,$,Q,J){return v(_,"search","getHeritageChain",()=>{let Y=J??_.defaultProject,W=new Set,z=(X,K,V)=>{let M=`${X}::${K}`;if(W.has(M))return{symbolName:X,filePath:K,kind:V,children:[]};W.add(M);let I=_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Y,query:{srcFilePath:K,srcSymbolName:X,limit:1000}}).filter((D)=>D.type==="extends"||D.type==="implements").filter((D)=>D.dstSymbolName!=null&&D.dstFilePath!=null).map((D)=>z(D.dstSymbolName,D.dstFilePath,D.type));return{symbolName:X,filePath:K,kind:V,children:I}},Z=U6.isAbsolute(Q)?q_(_.projectRoot,Q):Q;return z($,Z)})}function JQ(_,$){if(e(_),!_.annotationRepo||!_.annotationSearchFn)return[];let{annotationRepo:Q,annotationSearchFn:J}=_;return v(_,"search","searchAnnotations",()=>J({annotationRepo:Q,project:$.project??_.defaultProject,query:$}))}function YQ(_,$,Q){if(e(_),!_.changelogRepo)return[];let J=$ instanceof Date?$.toISOString():$,Y=Q?.project??_.defaultProject,W=Q?.limit??1000;return _.changelogRepo.getSince({project:Y,since:J,symbolName:Q?.symbolName,changeTypes:Q?.changeTypes,filePath:Q?.filePath,includeFullIndex:Q?.includeFullIndex,indexRunId:Q?.indexRunId,afterId:Q?.afterId,limit:W}).map((Z)=>({changeType:Z.changeType,symbolName:Z.symbolName,symbolKind:Z.symbolKind,filePath:Z.filePath,oldName:Z.oldName,oldFilePath:Z.oldFilePath,fingerprint:Z.fingerprint,changedAt:Z.changedAt,isFullIndex:Z.isFullIndex===1,indexRunId:Z.indexRunId}))}function WQ(_,$){if(e(_),!_.changelogRepo)return 0;let Q=$ instanceof Date?$.toISOString():$,J=0,Y=[_.defaultProject,..._.boundaries.map((z)=>z.project)],W=[...new Set(Y)];for(let z of W)J+=_.changelogRepo.pruneOlderThan(z,Q);return J}class $1{_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 t1(_);return new $1($)}async close(_){return B0(this._ctx,_)}parseSource(_,$,Q){return _$(this._ctx,_,$,Q)}async batchParse(_,$){return $$(this._ctx,_,$)}getParsedAst(_){return Q$(this._ctx,_)}extractSymbols(_){return J$(this._ctx,_)}extractRelations(_){return Y$(this._ctx,_)}getStats(_){return Z$(this._ctx,_)}searchSymbols(_){return _1(this._ctx,_)}searchRelations(_){return z$(this._ctx,_)}searchAllSymbols(_){return X$(this._ctx,_)}searchAllRelations(_){return U$(this._ctx,_)}listIndexedFiles(_){return V$(this._ctx,_)}getInternalRelations(_,$){return H$(this._ctx,_,$)}getFullSymbol(_,$,Q){return K$(this._ctx,_,$,Q)}getFileStats(_,$){return M$(this._ctx,_,$)}getFileInfo(_,$){return O$(this._ctx,_,$)}getSymbolsByFile(_,$){return L$(this._ctx,_,$)}getModuleInterface(_,$){return B$(this._ctx,_,$)}getDependencies(_,$,Q=1e4){return m1(this._ctx,_,$,Q)}getDependents(_,$,Q=1e4){return p1(this._ctx,_,$,Q)}async getAffected(_,$){return d1(this._ctx,_,$)}async hasCycle(_){return l1(this._ctx,_)}async getImportGraph(_){return n1(this._ctx,_)}async getTransitiveDependencies(_,$){return i1(this._ctx,_,$)}async getTransitiveDependents(_,$){return c1(this._ctx,_,$)}async getCyclePaths(_,$){return a1(this._ctx,_,$)}async getFanMetrics(_,$){return s1(this._ctx,_,$)}getResolvedType(_,$,Q){return G$(this._ctx,_,$,Q)}getSemanticReferences(_,$,Q){return I$(this._ctx,_,$,Q)}getEnrichedReferences(_,$,Q){return w$(this._ctx,_,$,Q)}getImplementations(_,$,Q){return D$(this._ctx,_,$,Q)}isTypeAssignableTo(_,$,Q,J,Y){return C$(this._ctx,_,$,Q,J,Y)}getSemanticModuleInterface(_){return R$(this._ctx,_)}getFileTypes(_){return A$(this._ctx,_)}getResolvedTypeAt(_,$,Q){return q$(this._ctx,_,$,Q)}isTypeAssignableToAt(_){return N$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return v$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return T$(this._ctx,_,$)}getExpressionTypeAtSpan(_,$){return E$(this._ctx,_,$)}isThenableAtSpan(_,$,Q){return F$(this._ctx,_,$,Q)}getContextualCallReturnsAtSpan(_,$){return j$(this._ctx,_,$)}isTypeAssignableToTypeAtSpan(_,$,Q,J){return k$(this._ctx,_,$,Q,J)}getSemanticReferencesAtPosition(_,$){return g$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return u$(this._ctx,_,$)}getFileBindings(_){return b$(this._ctx,_)}getFileBindingsBatch(_){return P$(this._ctx,_)}getStandaloneFileBindings(_,$){return y$(this._ctx,_,$)}notifyFileChanged(_,$){f$(this._ctx,_,$)}notifyFileDeleted(_){x$(this._ctx,_)}getImplementationsAtPosition(_,$){return h$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,Q,J){return m$(this._ctx,_,$,Q,J)}isTypeAssignableToType(_,$,Q,J){return p$(this._ctx,_,$,Q,J)}isTypeAssignableToTypeAtPositions(_,$,Q,J){return d$(this._ctx,_,$,Q,J)}lineColumnToPosition(_,$,Q){return l$(this._ctx,_,$,Q)}findNamePosition(_,$,Q){return n$(this._ctx,_,$,Q)}getSymbolNode(_,$){return i$(this._ctx,_,$)}getBaseTypes(_,$){return S$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return c$(this._ctx,_,$)}diffSymbols(_,$){return a$(_,$)}onIndexed(_){return s$(this._ctx,_)}async reindex(){return r$(this._ctx)}resolveSymbol(_,$,Q){return o$(this._ctx,_,$,Q)}async findPattern(_,$){return $Q(this._ctx,_,$)}async getHeritageChain(_,$,Q){return QQ(this._ctx,_,$,Q)}onFileChanged(_){return t$(this._ctx,_)}onError(_){return e$(this._ctx,_)}onRoleChanged(_){return _Q(this._ctx,_)}searchAnnotations(_){return JQ(this._ctx,_)}getSymbolChanges(_,$){return YQ(this._ctx,_,$)}pruneChangelog(_){return WQ(this._ctx,_)}}import{Visitor as S2,visitorKeys as T2}from"oxc-parser";import{walk as F2,parseAndWalk as j2,ScopeTracker as k2}from"oxc-walker";export{F2 as walk,T2 as visitorKeys,y0 as symbolSearch,f0 as relationSearch,x0 as patternSearch,g_ as parseSource,j2 as parseAndWalk,Y_ as normalizePath,UJ as isVariableDeclaration,XJ as isTSQualifiedName,zJ as isMemberExpression,ZJ as isIdentifier,_J as isFunctionNode,WJ as isFunctionExpression,YJ as isFunctionDeclaration,JJ as isCallExpression,QJ as isAssignmentExpression,$J as isArrowFunctionExpression,VJ as is,O_ as getLineColumn,S_ as extractSymbols,c_ as extractRelations,i_ as buildLineOffsets,S2 as Visitor,k2 as ScopeTracker,N as GildashError,$1 as Gildash,O0 as DependencyGraph};