@zipbul/gildash 0.34.1 → 0.34.3

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 ZQ=Object.defineProperty;var zQ=(_)=>_;function XQ(_,$){this[_]=zQ.bind(null,$)}var UQ=(_,$)=>{for(var Q in $)ZQ(_,Q,{get:$[Q],enumerable:!0,configurable:!0,set:XQ.bind($,Q)})};var $1=import.meta.require;import{isErr as t_}from"@zipbul/result";import f_ from"path";import{existsSync as oJ}from"fs";import{err as W1,isErr as LQ}from"@zipbul/result";import{Database as BQ}from"bun:sqlite";import{mkdirSync as GQ,unlinkSync as Z1,existsSync as z1}from"fs";import{dirname as IQ,join as X1}from"path";import{drizzle as wQ}from"drizzle-orm/bun-sqlite";import{migrate as DQ}from"drizzle-orm/bun-sqlite/migrator";class N extends Error{type;constructor(_,$,Q){super($,Q);this.type=_;this.name="GildashError"}}var q_=".gildash",e_="gildash.db";var I0={};UQ(I0,{watcherOwner:()=>OQ,symbols:()=>l,symbolChangelog:()=>J_,relations:()=>b,files:()=>e,annotations:()=>H_});import{sql as VQ}from"drizzle-orm";import{sqliteTable as v_,text as x,integer as t,real as HQ,index as W_,primaryKey as KQ,foreignKey as G0,check as MQ}from"drizzle-orm/sqlite-core";var Q1=["function","method","class","variable","type","interface","enum","namespace","property"],J1=["imports","type-references","re-exports","calls","extends","implements"],Y1=["jsdoc","line","block"];var e=v_("files",{project:x("project").notNull(),filePath:x("file_path").notNull(),mtimeMs:HQ("mtime_ms").notNull(),size:t("size").notNull(),contentHash:x("content_hash").notNull(),updatedAt:x("updated_at").notNull(),lineCount:t("line_count")},(_)=>[KQ({columns:[_.project,_.filePath]})]),l=v_("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:x("project").notNull(),filePath:x("file_path").notNull(),kind:x("kind",{enum:Q1}).notNull(),name:x("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:x("signature"),fingerprint:x("fingerprint"),detailJson:x("detail_json"),contentHash:x("content_hash").notNull(),indexedAt:x("indexed_at").notNull(),resolvedType:x("resolved_type"),structuralFingerprint:x("structural_fingerprint")},(_)=>[W_("idx_symbols_project_file").on(_.project,_.filePath),W_("idx_symbols_project_kind").on(_.project,_.kind),W_("idx_symbols_project_name").on(_.project,_.name),W_("idx_symbols_fingerprint").on(_.project,_.fingerprint),G0({columns:[_.project,_.filePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),b=v_("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:x("project").notNull(),type:x("type",{enum:J1}).notNull(),srcFilePath:x("src_file_path").notNull(),srcSymbolName:x("src_symbol_name"),dstProject:x("dst_project"),dstFilePath:x("dst_file_path"),dstSymbolName:x("dst_symbol_name"),metaJson:x("meta_json"),specifier:x("specifier"),isExternal:t("is_external").notNull().default(0)},(_)=>[W_("idx_relations_src").on(_.project,_.srcFilePath),W_("idx_relations_dst").on(_.dstProject,_.dstFilePath),W_("idx_relations_type").on(_.project,_.type),W_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),W_("idx_relations_specifier").on(_.project,_.specifier),G0({columns:[_.project,_.srcFilePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),H_=v_("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:x("project").notNull(),filePath:x("file_path").notNull(),tag:x("tag").notNull(),value:x("value").notNull().default(""),source:x("source",{enum:Y1}).notNull(),symbolName:x("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:x("indexed_at").notNull()},(_)=>[W_("idx_annotations_project_file").on(_.project,_.filePath),W_("idx_annotations_project_tag").on(_.project,_.tag),W_("idx_annotations_project_symbol").on(_.project,_.symbolName),G0({columns:[_.project,_.filePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),J_=v_("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:x("project").notNull(),changeType:x("change_type").notNull(),symbolName:x("symbol_name").notNull(),symbolKind:x("symbol_kind").notNull(),filePath:x("file_path").notNull(),oldName:x("old_name"),oldFilePath:x("old_file_path"),fingerprint:x("fingerprint"),changedAt:x("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:x("index_run_id").notNull()},(_)=>[W_("idx_changelog_project_changed_at").on(_.project,_.changedAt),W_("idx_changelog_project_name").on(_.project,_.symbolName),W_("idx_changelog_project_run").on(_.project,_.indexRunId)]),OQ=v_("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:x("started_at").notNull(),heartbeatAt:x("heartbeat_at").notNull(),instanceId:x("instance_id")},(_)=>[MQ("watcher_owner_singleton",VQ`${_.id} = 1`)]);class w0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=X1(_.projectRoot,q_,e_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{GQ(IQ(this.dbPath),{recursive:!0}),this.client=new BQ(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=wQ(this.client,{schema:I0}),DQ(this.drizzle,{migrationsFolder:X1(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(_)&&z1(this.dbPath)){this.closeClient(),Z1(this.dbPath);for(let Q of["-wal","-shm"]){let J=this.dbPath+Q;if(z1(J))Z1(J)}let $=this.open();if(LQ($))return W1(new N("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return W1(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 U1}from"drizzle-orm";class D0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(e).where(U1(m_(e.project,_),m_(e.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(e).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[e.project,e.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(e).where(m_(e.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(e).where(U1(m_(e.project,_),m_(e.filePath,$))).run()}}import{eq as Z_,and as p_,sql as C0,count as CQ}from"drizzle-orm";var V1=50;class A0{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+=V1)this.db.drizzleDb.insert(l).values(W.slice(z,z+V1)).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:CQ(),fileCount:C0`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?C0`${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?C0`${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 I_,isNull as H1,or as AQ}from"drizzle-orm";var d_={project:b.project,type:b.type,srcFilePath:b.srcFilePath,srcSymbolName:b.srcSymbolName,dstProject:b.dstProject,dstFilePath:b.dstFilePath,dstSymbolName:b.dstSymbolName,metaJson:b.metaJson,specifier:b.specifier,isExternal:b.isExternal};class q0{db;constructor(_){this.db=_}replaceFileRelations(_,$,Q){this.db.transaction((J)=>{if(J.drizzleDb.delete(b).where(I_(d(b.project,_),d(b.srcFilePath,$))).run(),!Q.length)return;for(let Y of Q)J.drizzleDb.insert(b).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(b).where(I_(d(b.project,_),d(b.srcFilePath,$),AQ(d(b.srcSymbolName,Q),H1(b.srcSymbolName)))).all();return this.db.drizzleDb.select(d_).from(b).where(I_(d(b.project,_),d(b.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:Q}=_;return this.db.drizzleDb.select(d_).from(b).where(I_(d(b.dstProject,$),d(b.dstFilePath,Q))).all()}getByType(_,$){return this.db.drizzleDb.select(d_).from(b).where(I_(d(b.project,_),d(b.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(b).where(I_(d(b.project,_),d(b.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(b).where(I_(d(b.dstProject,_),d(b.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(d_).from(b).where(I_(_.project!==void 0?d(b.project,_.project):void 0,_.srcFilePath!==void 0?d(b.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?d(b.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?d(b.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?d(b.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?d(b.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?d(b.type,_.type):void 0,_.specifier!==void 0?d(b.specifier,_.specifier):void 0,_.isExternal!==void 0?d(b.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?I_(d(b.dstProject,$),d(b.dstFilePath,Q),H1(b.dstSymbolName)):I_(d(b.dstProject,$),d(b.dstFilePath,Q),d(b.dstSymbolName,J)),X={dstFilePath:Y,dstSymbolName:W};if(z!==void 0)X.dstProject=z;this.db.drizzleDb.update(b).set(X).where(Z).run()}}import{err as K1}from"@zipbul/result";import{subscribe as NQ}from"@parcel/watcher";import R0 from"path";import N0 from"path";function Y_(_){return _.replaceAll("\\","/")}function N_(_,$){return Y_(N0.relative(_,$))}function g_(_,$){return Y_(N0.resolve(_,$))}function qQ(_){return Y_(_)}function K_(_,$){return N0.isAbsolute($)?N_(_,$):qQ($)}var RQ=["**/.git/**",`**/${q_}/**`,"**/dist/**","**/node_modules/**"],SQ=new Set(["package.json","tsconfig.json"]);function TQ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class S0{#$;#_;#J;#Y;#W;#Z;constructor(_,$=NQ,Q=console){this.#_=_.projectRoot,this.#J=[...RQ,..._.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_(R0.relative(this.#_,J.path));if(Y.startsWith(".."))continue;let W=R0.basename(Y),z=R0.extname(Y).toLowerCase();if(!SQ.has(W)&&!this.#Y.has(z))continue;if(Y.endsWith(".d.ts"))continue;_({eventType:TQ(J.type),filePath:Y})}}catch(J){this.#Z.error(new N("watcher","Callback error",{cause:J}))}},{ignore:this.#J})}catch($){return K1(new N("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#$)return;try{await this.#$.unsubscribe(),this.#$=void 0}catch(_){return K1(new N("watcher","Failed to close watcher",{cause:_}))}}}import T0 from"path";var EQ=["**/node_modules/**","**/.git/**",`**/${q_}/**`,"**/dist/**"],FQ=EQ.map((_)=>new Bun.Glob(_));function jQ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function _0(_,$=jQ){let Q=[];for await(let J of $(_)){let Y=Y_(J);if(FQ.some((K)=>K.match(Y)))continue;let W=Y_(T0.dirname(J)),z=T0.join(_,J),Z=await Bun.file(z).json(),X=typeof Z?.name==="string"&&Z.name.length>0?Z.name:T0.basename(W==="."?_:W);Q.push({dir:W,project:X})}return Q.sort((J,Y)=>Y.dir.length-J.dir.length),Q}function r(_,$,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 R_=new Map;async function kQ(_){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 vQ(_,$){if($.startsWith(".")){let Q=l_.resolve(_,$);return Q.endsWith(".json")?Q:Q+".json"}return l_.resolve(_,"node_modules",$)}async function M1(_,$=5){if($<=0)return null;let Q=await kQ(_);if(!Q)return null;let J=Q.extends;if(typeof J!=="string"||!J)return Q;let Y=vQ(l_.dirname(_),J),W=await M1(Y,$-1);if(!W)return Q;return{...W,...Q,compilerOptions:{...W.compilerOptions,...Q.compilerOptions}}}async function n_(_){if(R_.has(_))return R_.get(_)??null;let $=l_.join(_,"tsconfig.json"),Q=await M1($);if(!Q)return R_.set(_,null),null;let J=Q.compilerOptions??null;if(!J)return R_.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 R_.set(_,null),null;let z=Y?l_.resolve(_,Y):_,Z=new Map;if(W)for(let[K,U]of Object.entries(W)){if(!Array.isArray(U))continue;let M=U.filter((w)=>typeof w==="string");Z.set(K,M)}let X={baseUrl:z,paths:Z};return R_.set(_,X),X}function $0(_){if(_){R_.delete(_);return}R_.clear()}function B_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as N1}from"@zipbul/result";import{err as gQ}from"@zipbul/result";import{parseSync as uQ}from"oxc-parser";function u_(_,$,Q,J=uQ){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 gQ(new N("parse",`Failed to parse file: ${_}`,{cause:Y}))}}import{join as bQ}from"path";function PQ(_,$){let Q=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(Q).scan({cwd:_,followSymlinks:!1})}async function O1(_){let{projectRoot:$,extensions:Q,ignorePatterns:J,fileRepo:Y,scanFilesFn:W=PQ}=_,z=Y.getFilesMap(),Z=new Set,X=[],K=[],U=J.map((w)=>new Bun.Glob(w));for await(let w of W($,Q)){let q=Y_(w);if(!Q.some((i)=>q.endsWith(i)))continue;if(q.startsWith("node_modules/")||q.includes("/node_modules/"))continue;if(U.some((i)=>i.match(q)))continue;Z.add(q);let G=bQ($,q),C=Bun.file(G),{size:E,lastModified:R}=C,u=z.get(q);if(!u){let i=await C.text(),c=B_(i);X.push({filePath:q,contentHash:c,mtimeMs:R,size:E});continue}if(u.mtimeMs===R&&u.size===E){K.push({filePath:q,contentHash:u.contentHash,mtimeMs:R,size:E});continue}let P=await C.text(),m=B_(P);if(m===u.contentHash)K.push({filePath:q,contentHash:m,mtimeMs:R,size:E});else X.push({filePath:q,contentHash:m,mtimeMs:R,size:E})}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 yQ}from"@zipbul/result";import{parse as fQ}from"comment-parser";function Q0(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let J=fQ(`/** ${$} */`)[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 yQ(new N("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as xQ}from"@zipbul/result";function hQ(_){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 b_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let Q of _.properties)if(Q.type==="RestElement")$.push(...b_(Q.argument));else $.push(...b_(Q.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let Q of _.elements){if(!Q)continue;if(Q.type==="RestElement")$.push(...b_(Q.argument));else $.push(...b_(Q))}return $}if(_.type==="AssignmentPattern")return b_(_.left);return[]}function mQ(_){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 T_(_){let{program:$,sourceText:Q,comments:J}=_,Y=i_(Q),W=mQ(_),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 R(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 U(H,A){if(A)return Q.slice(H.start,H.end);if(H.type==="PrivateIdentifier")return`#${H.name}`;return hQ(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 q(H){let A=0,B=z.length-1,D=-1;while(A<=B){let O=A+B>>>1;if(z[O].end<=H)D=O,A=O+1;else B=O-1}if(D<0)return;let V=z[D];A=0,B=Z.length-1;while(A<=B){let O=A+B>>>1,I=Z[O];if(I<=V.end)A=O+1;else if(I>=H)B=O-1;else return}return`/*${V.value}*/`}function G(H){if(!H)return;let A="typeAnnotation"in H&&H.typeAnnotation?H.typeAnnotation:H;return Q.slice(A.start,A.end)}let C=8;function E(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 R(H,A=0){if(A>=C)return{kind:"unresolvable",sourceText:Q.slice(H.start,H.end)};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{kind:"unresolvable",sourceText:Q.slice(H.start,H.end)}}if(H.type==="Identifier"){let B=H.name;if(B==="undefined")return{kind:"undefined",value:null};let D=W.get(B),V={kind:"identifier",name:B};if(D){if(V.importSource=D.specifier,D.originalName)V.originalName=D.originalName}return V}if(H.type==="MemberExpression"){if(H.computed){let S=H.property;if(S.type==="Literal"&&typeof S.value==="string"){let T=H.object,f=Q.slice(T.start,T.end),j=T.type==="Identifier"?T.name:void 0,v=j?W.get(j):void 0,y={kind:"member",object:f,property:S.value};if(v)y.importSource=v.specifier;return y}return{kind:"unresolvable",sourceText:Q.slice(H.start,H.end)}}let B=H.object,D=Q.slice(B.start,B.end),V=H.property.name,O=B.type==="Identifier"?B.name:void 0,I=O?W.get(O):void 0,L={kind:"member",object:D,property:V};if(I)L.importSource=I.specifier;return L}if(H.type==="CallExpression"){let B=H.callee,D=Q.slice(B.start,B.end),V=H.arguments.map((L)=>R(L,A+1)),O=E(B),I={kind:"call",callee:D,arguments:V};if(O)I.importSource=O.specifier;return I}if(H.type==="NewExpression"){let B=H.callee,D=Q.slice(B.start,B.end),V=H.arguments.map((L)=>R(L,A+1)),O=E(B),I={kind:"new",callee:D,arguments:V};if(O)I.importSource=O.specifier;return I}if(H.type==="ObjectExpression"){let B=[];for(let D of H.properties){if(D.type==="SpreadElement"){B.push({kind:"spread",argument:R(D.argument,A+1)});continue}let O={kind:"property",key:M(D.key,D.computed,A+1),value:R(D.value,A+1)};if(D.shorthand)O.shorthand=!0;B.push(O)}return{kind:"object",properties:B}}if(H.type==="ArrayExpression")return{kind:"array",elements:H.elements.map((D)=>{if(!D)return{kind:"undefined",value:null};return R(D,A+1)})};if(H.type==="SpreadElement")return{kind:"spread",argument:R(H.argument,A+1)};if(H.type==="ArrowFunctionExpression"||H.type==="FunctionExpression"){let B=H.params.map(P),D={kind:"function",sourceText:Q.slice(H.start,H.end)};if(B.length>0)D.parameters=B;return D}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{kind:"unresolvable",sourceText:Q.slice(H.start,H.end)}}if(H.type==="TSAsExpression"||H.type==="TSSatisfiesExpression"||H.type==="TSNonNullExpression"||H.type==="TSTypeAssertion"||H.type==="TSInstantiationExpression"||H.type==="ParenthesizedExpression")return R(H.expression,A);if(H.type==="ChainExpression")return R(H.expression,A);return{kind:"unresolvable",sourceText:Q.slice(H.start,H.end)}}function u(H){if(!H||H.length===0)return[];return H.map((A)=>{let B=A.expression;if(B.type==="CallExpression"){let D=B.callee,V="name"in D&&typeof D.name==="string"?D.name:("property"in D)&&("name"in D.property)&&typeof D.property.name==="string"?D.property.name:"unknown",O=B.arguments.map((I)=>R(I));return{name:V,arguments:O.length>0?O:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:Q.slice(B.start,B.end)}})}function P(H){if(H.type==="TSParameterProperty")return i(H.parameter,H.decorators);if(H.type==="RestElement"){let A=H,B=A.argument,V=`...${"name"in B&&typeof B.name==="string"?B.name:"unknown"}`,O=A.typeAnnotation,I=O?G(O):void 0,L={name:V,isOptional:!1};if(I)L.type=I;return L}return i(H,H.decorators)}function m(H){if(!H)return;let A=H.typeAnnotation;if(A.type!=="TSTypeReference")return;let B=A.typeName,D=B.type==="Identifier"?B.name:void 0;if(!D)return;return W.get(D)?.specifier}function i(H,A){if(H.type==="AssignmentPattern"){let{left:T,right:f}=H,j="name"in T&&typeof T.name==="string"?T.name:"unknown",v="typeAnnotation"in T?T.typeAnnotation:null,y=v?G(v):void 0,a=m(v),V_=Q.slice(f.start,f.end),A_="decorators"in T&&Array.isArray(T.decorators)?T.decorators:[],h_=u(A_),S_={name:j,isOptional:!0,defaultValue:V_};if(y)S_.type=y;if(a)S_.typeImportSource=a;if(h_.length>0)S_.decorators=h_;return S_}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",D=!!(("optional"in H)&&H.optional),V="typeAnnotation"in H?H.typeAnnotation:null,O=V?G(V):void 0,I=m(V),L=u(A??[]),S={name:B,isOptional:D};if(O)S.type=O;if(I)S.typeImportSource=I;if(L.length>0)S.decorators=L;return S}function c(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 D=H.accessibility;if(D==="private")B.push("private");else if(D==="protected")B.push("protected");else if(D==="public")B.push("public");return B}function z_(H){if(!H)return;let A=H.params.flatMap((B)=>{let D=B.name.name;return D?[D]:[]});return A.length>0?A:void 0}function X_(H){let A=[];if(H.superClass){let D=Q.slice(H.superClass.start,H.superClass.end);A.push({kind:"extends",name:D})}let B=H.implements??[];for(let D of B){let V=D.expression,O=Q.slice(V.start,V.end);A.push({kind:"implements",name:O})}return A}function G_(H){let A=[],B=H.extends;for(let D of B){let V=D.expression,O=Q.slice(V.start,V.end);A.push({kind:"extends",name:O})}return A}function M_(H){let A=[];for(let B of H)if(B.type==="MethodDefinition"||B.type==="TSAbstractMethodDefinition"){let D=B,V=U(D.key,D.computed),O=K(D.key,D.computed,0),I=D.value,L=D.kind,S=L==="constructor"?"constructor":L==="get"?"getter":L==="set"?"setter":"method",T=c(D,I);if(B.type==="TSAbstractMethodDefinition"&&!T.includes("abstract"))T.push("abstract");let f=I.params.map(P),j=G(I.returnType),v=u(D.decorators??[]),y={kind:"method",name:V,span:w(B.start,B.end),isExported:!1,methodKind:S,modifiers:T,parameters:f.length>0?f:void 0,returnType:j};if(O)y.key=O;if(v.length>0)y.decorators=v;A.push(y)}else if(B.type==="PropertyDefinition"||B.type==="TSAbstractPropertyDefinition"||B.type==="AccessorProperty"||B.type==="TSAbstractAccessorProperty"){let D=B,V=U(D.key,D.computed),O=K(D.key,D.computed,0),I=c(D);if(B.type==="TSAbstractPropertyDefinition"||B.type==="TSAbstractAccessorProperty"){if(!I.includes("abstract"))I.push("abstract")}if(B.type==="AccessorProperty"||B.type==="TSAbstractAccessorProperty")I.push("accessor");let L=G(D.typeAnnotation),S=D.value,T=S?R(S):void 0,f=u(D.decorators),j={kind:"property",name:V,span:w(B.start,B.end),isExported:!1,modifiers:I,returnType:L,initializer:T};if(O)j.key=O;if(f.length>0)j.decorators=f;A.push(j)}return A}function U_(H){let A=[];for(let B of H)if(B.type==="TSMethodSignature"){let D=B,V=U(D.key,D.computed),O=K(D.key,D.computed,0),I=D.params.map(P),L=G(D.returnType),S={kind:"method",name:V,span:w(B.start,B.end),isExported:!1,modifiers:[],methodKind:"method",parameters:I.length>0?I:void 0,returnType:L};if(O)S.key=O;A.push(S)}else if(B.type==="TSPropertySignature"){let D=B,V=U(D.key,D.computed),O=K(D.key,D.computed,0),I=G(D.typeAnnotation),L={kind:"property",name:V,span:w(B.start,B.end),isExported:!1,modifiers:D.readonly?["readonly"]:[],returnType:I};if(O)L.key=O;A.push(L)}return A}function s(H,A){if(H.type==="FunctionDeclaration"||H.type==="FunctionExpression"||H.type==="TSDeclareFunction"||H.type==="TSEmptyBodyFunctionExpression"){let B=H,D=B.id?.name??"default",V=B.params.map(P),O=G(B.returnType),I=c(B,B),L=u(B.decorators??[]),S=z_(B.typeParameters),T={kind:"function",name:D,span:w(H.start,H.end),isExported:A,modifiers:I,parameters:V.length>0?V:void 0,returnType:O,decorators:L.length>0?L:void 0};if(S&&S.length>0)T.typeParameters=S;return T}if(H.type==="ClassDeclaration"||H.type==="ClassExpression"){let B=H,D=B.id?.name??"default",V=X_(B),O=M_(B.body.body),I=u(B.decorators),L=c(B),S=z_(B.typeParameters),T={kind:"class",name:D,span:w(H.start,H.end),isExported:A,modifiers:L,heritage:V.length>0?V:void 0,members:O.length>0?O:void 0,decorators:I.length>0?I:void 0};if(S&&S.length>0)T.typeParameters=S;return T}if(H.type==="VariableDeclaration"){let B=H,D=[];for(let V of B.declarations){let{id:O,init:I}=V;if(O.type==="ObjectPattern"||O.type==="ArrayPattern"){let a=b_(O);for(let V_ of a)D.push({kind:"variable",name:V_.name,span:w(V_.start,V_.end),isExported:A,modifiers:[]});continue}let L="name"in O&&typeof O.name==="string"?O.name:"unknown",S="variable",T,f,j;if(I)if(I.type==="FunctionExpression"||I.type==="ArrowFunctionExpression"){S="function";let a=I;T=a.params.map(P),f=G(a.returnType)}else j=R(I);let v=[],y={kind:S,name:L,span:w(V.start,V.end),isExported:A,modifiers:v,parameters:T,returnType:f};if(j)y.initializer=j;D.push(y)}if(D.length===0)return null;if(D.length===1)return D[0];return D}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,D=B.id.name,V=G_(B),O=U_(B.body.body),I=z_(B.typeParameters),L={kind:"interface",name:D,span:w(H.start,H.end),isExported:A,modifiers:[],heritage:V.length>0?V:void 0,members:O.length>0?O:void 0};if(I&&I.length>0)L.typeParameters=I;return L}if(H.type==="TSEnumDeclaration"){let B=H,D=B.id.name,V=c(B),I=B.body.members.map((L)=>{let S=L.id,T=S.type!=="Identifier",f="name"in S&&typeof S.name==="string"?S.name:("value"in S)&&typeof S.value==="string"?S.value:"unknown",j=L.initializer?R(L.initializer):void 0,v={kind:"property",name:f,span:w(L.start,L.end),isExported:!1,modifiers:[]};if(T)v.key=X(S,0);if(j)v.initializer=j;return v});return{kind:"enum",name:D,span:w(H.start,H.end),isExported:A,modifiers:V,members:I.length>0?I:void 0}}if(H.type==="TSModuleDeclaration"){let B="name"in H.id?H.id.name:("value"in H.id)?H.id.value:"unknown",D=c(H),V=[];if(H.body?.type==="TSModuleBlock")for(let O of H.body.body){if(O.type!=="ExportNamedDeclaration")continue;let I=O.declaration;if(!I)continue;let L=s(I,!1);if(L)if(Array.isArray(L))V.push(...L);else V.push(L)}return{kind:"namespace",name:B,span:w(H.start,H.end),isExported:A,modifiers:D,members:V.length>0?V:void 0}}return null}let o=[],C_=new Set;for(let H of $.body){let A=null,B=H;if(B.type==="ExportNamedDeclaration"){let V=B;if(V.declaration){if(A=s(V.declaration,!0),A&&!Array.isArray(A))A.span=w(V.start,V.end)}else if(!V.source&&V.specifiers)for(let O of V.specifiers){let I=O.local,L="name"in I?I.name:I.value;if(L)C_.add(L)}}else if(B.type==="ExportDefaultDeclaration"){let V=B,O=V.declaration;if(O){if(A=s(O,!0),A&&!Array.isArray(A))A.name="id"in O&&O.id&&typeof O.id.name==="string"?O.id.name:"default",A.isExported=!0,A.span=w(V.start,V.end);else if(!A&&O.type==="Identifier"){let I=O.name;if(I)C_.add(I)}}}else{let V=B.type;if(V==="FunctionDeclaration"||V==="TSDeclareFunction"||V==="ClassDeclaration"||V==="VariableDeclaration"||V==="TSTypeAliasDeclaration"||V==="TSInterfaceDeclaration"||V==="TSEnumDeclaration"||V==="TSModuleDeclaration")A=s(B,!1)}let D=Array.isArray(A)?A:A?[A]:[];for(let V of D){let O=H.start,I=q(O);if(I){let L=Q0(I);if(!xQ(L))V.jsDoc=L}o.push(V)}}if(C_.size>0){for(let H of o)if(!H.isExported&&C_.has(H.name))H.isExported=!0}return o}function J0(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(J0).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((J)=>`${JSON.stringify(J)}:${J0($[J])}`).join(",")}}`}function pQ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,Q=_.modifiers.includes("async")?1:0;return`params:${$}|async:${Q}`}return null}function dQ(_){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 lQ(_){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:${J0(_.key)}`);if(_.members?.length){let Q=_.members.map((J)=>`${J.kind}:${J.modifiers.join(",")}:${J.parameters?.length??""}:${J.returnType??""}:${J.key?J0(J.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${B_(Q)}`)}return B_($.join("|"))}function L1(_,$,Q,J,Y){let W=pQ(_),z=B_(`${$}|${_.kind}|${W??""}`),Z=lQ(_);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:dQ(_),contentHash:Y,indexedAt:new Date().toISOString(),structuralFingerprint:Z}}function E0(_){let{parsed:$,project:Q,filePath:J,contentHash:Y,symbolRepo:W}=_,z=T_($),Z=[];for(let X of z){Z.push(L1(X,X.name,Q,J,Y));for(let K of X.members??[])Z.push(L1(K,`${X.name}.${K.name}`,Q,J,Y))}W.replaceFileSymbols(Q,J,Y,Z)}import{resolve as F0,dirname as nQ,extname as iQ}from"path";function E_(_,$,Q){let J=(Y)=>{let W=iQ(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_(F0(nQ(_),$));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_(F0(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),U=[];for(let M of W)U.push(...J(Y_(F0(Q.baseUrl,M.replace("*",K)))));return U}}}return[]}function B1(_,$,Q,J=E_){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 cQ}from"oxc-parser";function Y0(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function aQ(_){return!_.startsWith(".")&&!_.startsWith("/")}function F_(_,$,Q,J){let Y=J(_,$,Q),W=Y.length>0?Y[0]:null,z=W===null&&aQ($);return{resolved:W,isExternal:z}}function sQ(_,$,Q,J,Y){for(let W of _.staticImports){let z=W.moduleRequest.value,{resolved:Z,isExternal:X}=F_($,z,Q,J),K={dstFilePath:Z,specifier:z};if(W.entries.length===0){let U={};if(X)U.isExternal=!0;if(Z===null&&!X)U.isUnresolved=!0;Y.push({type:"imports",srcFilePath:$,srcSymbolName:null,...K,dstSymbolName:null,...Object.keys(U).length>0?{metaJson:JSON.stringify(U)}:{}});continue}for(let U of W.entries){let M=U.isType,w={};if(M)w.isType=!0;if(X)w.isExternal=!0;if(Z===null&&!X)w.isUnresolved=!0;let q,G,C=U.importName.kind;if(C==="Default")q="default",G=U.localName.value;else if(C==="NamespaceObject")q="*",G=U.localName.value,w.importKind="namespace";else q=U.importName.name??"unknown",G=U.localName.value;Y.push({type:M?"type-references":"imports",srcFilePath:$,srcSymbolName:G,...K,dstSymbolName:q,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}}}function rQ(_,$,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:U}=F_($,X,Q,J),M=Z.exportName.name??"default",w=Z.exportName.kind,q=Z.localName.name??Z.importName.name??M,G=Z.isType,C={isReExport:!0};if(w==="None");else C.specifiers=[{local:q,exported:M}];if(G)C.isType=!0;if(U)C.isExternal=!0;if(K===null&&!U)C.isUnresolved=!0;let E=null,R=null,u=Z.importName.kind;if(u==="All"||u==="AllButDefault"){if(w==="Name"&&M)R=M,C.namespaceAlias=M}else R=q,E=M;Y.push({type:G?"type-references":"re-exports",srcFilePath:$,srcSymbolName:E,dstFilePath:K,dstSymbolName:R,specifier:X,metaJson:JSON.stringify(C)})}}function oQ(_,$,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:U}=F_($,X,Q,J),M=Z.importKind==="type",w=Z.specifiers,q={dstFilePath:K,specifier:X};if(w.length===0){let G={};if(M)G.isType=!0;if(U)G.isExternal=!0;if(K===null&&!U)G.isUnresolved=!0;Y.push({type:M?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...q,dstSymbolName:null,...Object.keys(G).length>0?{metaJson:JSON.stringify(G)}:{}})}else for(let G of w){let C=G.type,E=M||C==="ImportSpecifier"&&G.importKind==="type",R={};if(E)R.isType=!0;if(U)R.isExternal=!0;if(K===null&&!U)R.isUnresolved=!0;let u,P;if(C==="ImportDefaultSpecifier")u="default",P=G.local.name;else if(C==="ImportNamespaceSpecifier")u="*",P=G.local.name,R.importKind="namespace";else u=Y0(G.imported),P=G.local.name;Y.push({type:E?"type-references":"imports",srcFilePath:$,srcSymbolName:P,...q,dstSymbolName:u,...Object.keys(R).length>0?{metaJson:JSON.stringify(R)}:{}})}continue}if(z.type==="ExportAllDeclaration"){let Z=z,X=Z.source.value,{resolved:K,isExternal:U}=F_($,X,Q,J),M=Z.exportKind==="type",w=Z.exported,q=w?Y0(w):null,G={isReExport:!0};if(M)G.isType=!0;if(U)G.isExternal=!0;if(K===null&&!U)G.isUnresolved=!0;if(q)G.namespaceAlias=q;Y.push({type:M?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:q,specifier:X,metaJson:JSON.stringify(G)});continue}if(z.type==="ExportNamedDeclaration"){let Z=z;if(!Z.source)continue;let X=Z.source.value,{resolved:K,isExternal:U}=F_($,X,Q,J),M=Z.exportKind==="type",w=Z.specifiers??[];for(let q of w){let G=M||q.exportKind==="type",C=Y0(q.local),E=Y0(q.exported),R={isReExport:!0,specifiers:[{local:C,exported:E}]};if(G)R.isType=!0;if(U)R.isExternal=!0;if(K===null&&!U)R.isUnresolved=!0;Y.push({type:G?"type-references":"re-exports",srcFilePath:$,srcSymbolName:E,dstFilePath:K,dstSymbolName:C,specifier:X,metaJson:JSON.stringify(R)})}}}}function tQ(_,$,Q,J,Y){new cQ({ImportExpression(z){let Z=z.source;if(Z.type!=="Literal"||typeof Z.value!=="string")return;let X=Z.value,{resolved:K,isExternal:U}=F_($,X,Q,J),M={isDynamic:!0};if(U)M.isExternal=!0;if(K===null&&!U)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 C=Z,E=C.object,R=C.property;if(E.type==="Identifier"&&E.name==="require"&&R.name==="resolve")X=!0;else return}else return;let K=z.arguments;if(K.length===0)return;let U=K[0];if(U.type!=="Literal"||typeof U.value!=="string")return;let M=U.value,{resolved:w,isExternal:q}=F_($,M,Q,J),G={isRequire:!0};if(X)G.isRequireResolve=!0;if(q)G.isExternal=!0;if(w===null&&!q)G.isUnresolved=!0;Y.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:w,dstSymbolName:null,specifier:M,metaJson:JSON.stringify(G)})}}).visit(_)}function G1(_,$,Q,J=E_,Y){let W=[];if(Y)sQ(Y,$,Q,J,W),rQ(Y,$,Q,J,W);else oQ(_,$,Q,J,W);return tQ(_,$,Q,J,W),W}import{walk as VJ}from"oxc-walker";function eQ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function _J(_){return _.type==="ArrowFunctionExpression"}function $J(_){return _.type==="AssignmentExpression"}function QJ(_){return _.type==="CallExpression"}function JJ(_){return _.type==="FunctionDeclaration"}function YJ(_){return _.type==="FunctionExpression"}function WJ(_){return _.type==="Identifier"}function ZJ(_){return _.type==="MemberExpression"}function zJ(_){return _.type==="TSQualifiedName"}function XJ(_){return _.type==="VariableDeclaration"}var I1=new Map,UJ=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=I1.get($);if(Y===void 0)Y=(W)=>W!==null&&W!==void 0&&W.type===$,I1.set($,Y);return Y}});function P_(_){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 w1(_,$,Q){let J=[],Y=[],W=[];function z(){if(Y.length>0)return Y[Y.length-1]??null;return null}function Z(U){if(!U)return null;let M=Q.get(U.root);if(U.parts.length===0){if(M)return{dstFilePath:M.path,dstSymbolName:M.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:U.root,resolution:"local"}}else{if(M&&M.importedName==="*"){let w=U.parts[U.parts.length-1];return{dstFilePath:M.path,dstSymbolName:w,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:U.full,resolution:"local-member"}}}function X(U,M){let w=P_(U.callee),q=Z(w);if(q){let G=z(),C={};if(M)C.isNew=!0;if(G===null)C.scope="module";J.push({type:"calls",srcFilePath:$,srcSymbolName:G,dstFilePath:q.dstFilePath,dstSymbolName:q.dstSymbolName,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}function K(U,M){if(U.type==="FunctionDeclaration"){Y.push(U.id?.name??"anonymous");return}if(U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){if(M?.type==="VariableDeclarator"){let G=M.id,C=G.type==="Identifier"?G.name:"anonymous";Y.push(C);return}if(M?.type==="MethodDefinition"||M?.type==="TSAbstractMethodDefinition"){let G=M.key,C=W[W.length-1]??"",E="name"in G?G.name:"anonymous",R=C?`${C}.${E}`:E;Y.push(R);return}let w=z(),q=w?`${w}.<anonymous>`:"<anonymous>";Y.push(q)}}return VJ(_,{enter(U,M){if(U.type==="ClassDeclaration"||U.type==="ClassExpression"){W.push(U.id?.name??"AnonymousClass");return}if(U.type==="FunctionDeclaration"||U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){K(U,M);return}if(U.type==="CallExpression"){X(U,!1);return}if(U.type==="NewExpression"){X(U,!0);return}},leave(U){if(U.type==="ClassDeclaration"||U.type==="ClassExpression"){W.pop();return}if(U.type==="FunctionDeclaration"||U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){Y.pop();return}}}),J}import{Visitor as HJ}from"oxc-parser";function D1(_,$,Q){let J=[];function Y(z){let Z=z.id?.name??"AnonymousClass";if(z.superClass){let K=P_(z.superClass);if(K){let U=j0(K,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...U})}}let X=z.implements??[];for(let K of X){let U=P_(K.expression);if(!U)continue;let M=j0(U,$,Q);J.push({type:"implements",srcFilePath:$,srcSymbolName:Z,...M})}}return new HJ({TSInterfaceDeclaration(z){let Z=z.id.name??"AnonymousInterface",X=z.extends;for(let K of X){let U=P_(K.expression);if(!U)continue;let M=j0(U,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...M})}},ClassDeclaration(z){Y(z)},ClassExpression(z){Y(z)}}).visit(_),J}function j0(_,$,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=E_,Y){let W=B1(_,$,Q,J),z=G1(_,$,Q,J,Y),Z=w1(_,$,W),X=D1(_,$,W);return[...z,...Z,...X]}function k0(_){let{ast:$,project:Q,filePath:J,relationRepo:Y,projectRoot:W,tsconfigPaths:z,knownFiles:Z,boundaries:X,module:K}=_,U=g_(W,J),w=c_($,U,z,Z?(G,C,E)=>{let R=E_(G,C,E);for(let u of R){let P=N_(W,u);if(X){let m=r(P,X);if(Z.has(`${m}::${P}`))return[u]}else if(Z.has(`${Q}::${P}`))return[u]}return[]}:void 0,K),q=[];for(let G of w){if(G.dstFilePath===null){let u=N_(W,G.srcFilePath),P;if(G.metaJson)try{P=JSON.parse(G.metaJson)}catch{}let m=P?.isExternal===!0;q.push({project:Q,type:G.type,srcFilePath:u,srcSymbolName:G.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:G.dstSymbolName??null,metaJson:G.metaJson??null,specifier:G.specifier??null,isExternal:m?1:0});continue}let C=N_(W,G.dstFilePath);if(C.startsWith(".."))continue;let E=N_(W,G.srcFilePath),R=X?r(C,X):Q;q.push({project:Q,type:G.type,srcFilePath:E,srcSymbolName:G.srcSymbolName??null,dstProject:R,dstFilePath:C,dstSymbolName:G.dstSymbolName??null,metaJson:G.metaJson??null,specifier:G.specifier??null,isExternal:0})}return Y.replaceFileRelations(Q,J,q),q.length}import{isErr as KJ}from"@zipbul/result";var C1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function MJ(_){let $=T_(_),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 v0(_,$,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 W0(_,$,Q){let J=O_(_,$),Y=O_(_,Q);return{start:J,end:Y}}function A1(_){let{comments:$,sourceText:Q}=_;if(!$.length)return[];let J=i_(Q),Y=MJ(_),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}*/`,U=Q0(K);if(KJ(U))continue;let M=U;if(!M.tags?.length)continue;let w=O_(J,X.end),q=v0(Y,w.line,3),G=Q.slice(X.start,X.end);for(let C of M.tags){let E=[C.name,C.description].filter(Boolean).join(" "),R=`@${C.tag}`,u=G.indexOf(R),P;if(u>=0){let m=X.start+u,i=Q.indexOf(`
4
- `,m),c=i>=0?Math.min(i,X.end):X.end;P=W0(J,m,c)}else P=W0(J,X.start,X.end);W.push({tag:C.tag,value:E,source:"jsdoc",span:P,symbolName:q})}}else if(X.type==="Block"){Z=null;let K=X.value.split(`
5
- `),U=0;for(let M of K){let w=M.replace(/^\s*\*?\s?/,""),q=C1.exec(w);if(q){let G=q[1],C=q[2]?.trim()??"",E=`@${G}`,R=M.indexOf(E),u=X.start+2+U+(R>=0?R:0),P=X.start+2+U+M.length,m=W0(J,u,P),i=O_(J,X.end),c=v0(Y,i.line,3);W.push({tag:G,value:C,source:"block",span:m,symbolName:c})}U+=M.length+1}}else{let K=X.value,U=C1.exec(K),M=O_(J,X.start),w=O_(J,X.end);if(U){let q=U[1],G=U[2]?.trim()??"",C=`@${q}`,E=K.indexOf(C),R=X.start+2+(E>=0?E:0),u=W0(J,R,X.end),P=v0(Y,w.line,3),m={tag:q,value:G,source:"line",span:u,symbolName:P};W.push(m),Z={annotation:m,endLine:w.line}}else if(Z&&M.line===Z.endLine+1){let q=K.trim();if(q)Z.annotation.value+=" "+q,Z.annotation.span.end=O_(J,X.end),Z.endLine=w.line}else Z=null}return W}function g0(_){let{parsed:$,project:Q,filePath:J,annotationRepo:Y}=_,W=A1($);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 q1(_,$){let Q=[],J=[],Y=[];for(let[U,M]of $)if(!_.has(U))Q.push({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint});for(let[U,M]of _)if(!$.has(U))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 U of Q){let M=W.get(U.filePath)??[];M.push(U),W.set(U.filePath,M)}for(let U of J){let M=z.get(U.filePath)??[];M.push(U),z.set(U.filePath,M)}let Z=new Set,X=new Set;for(let[U,M]of W){let w=z.get(U);if(!w)continue;for(let q of new Set(M.map((G)=>G.kind))){let G=M.filter((P)=>P.kind===q&&!Z.has(P)),C=w.filter((P)=>P.kind===q&&!X.has(P));if(!G.length||!C.length)continue;let E=(P,m)=>{return m.get(`${P.filePath}::${P.name}`)?.structuralFingerprint??null},R=(P,m)=>{return m.get(`${P.filePath}::${P.name}`)?.startLine??0},u=new Map;for(let P of C){let m=E(P,_);if(!m)continue;let i=u.get(m)??[];i.push(P),u.set(m,i)}for(let P of G){if(Z.has(P))continue;let m=E(P,$);if(!m)continue;let i=u.get(m);if(!i)continue;let c=i.filter((X_)=>!X.has(X_));if(!c.length)continue;let z_=c[0];if(c.length>1){let X_=R(P,$),G_=Math.abs(R(z_,_)-X_);for(let M_=1;M_<c.length;M_++){let U_=Math.abs(R(c[M_],_)-X_);if(U_<G_)G_=U_,z_=c[M_]}}Y.push({oldName:z_.name,newName:P.name,filePath:U,kind:q}),Z.add(P),X.add(z_)}}}let K=Y.filter((U)=>!U.oldName.includes("."));for(let U of K){let M=`${U.oldName}.`,w=`${U.newName}.`,q=J.filter((C)=>C.filePath===U.filePath&&C.name.startsWith(M)&&!X.has(C)),G=Q.filter((C)=>C.filePath===U.filePath&&C.name.startsWith(w)&&!Z.has(C));for(let C of q){let E=C.name.slice(M.length),R=G.find((u)=>u.name.slice(w.length)===E);if(R)Y.push({oldName:C.name,newName:R.name,filePath:U.filePath,kind:C.kind}),Z.add(R),X.add(C)}}return{renamed:Y,added:Q.filter((U)=>!Z.has(U)),removed:J.filter((U)=>!X.has(U))}}var OJ=100,R1=50;class u0{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")){$0(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()},OJ)}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((V)=>V.eventType==="create"||V.eventType==="change").map((V)=>({filePath:V.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((V)=>V.eventType==="delete").map((V)=>V.filePath);else{let V=new Map;for(let I of this.opts.boundaries)for(let[L,S]of J.getFilesMap(I.project))V.set(L,S);let O=await O1({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>V}});Z=O.changed,X=O.deleted}let K=await this.tsconfigPathsRaw??void 0,U=new Map;for(let V of X){let O=r(V,this.opts.boundaries),I=Y.getFileSymbols(O,V);U.set(V,I)}let M=crypto.randomUUID(),w=new Map,q=new Map,G=(V)=>({name:V.name,filePath:V.filePath,kind:V.kind,fingerprint:V.fingerprint,structuralFingerprint:V.structuralFingerprint??null,startLine:V.startLine,isExported:V.isExported??0});if($)for(let V of this.opts.boundaries)for(let O of J.getAllFiles(V.project))for(let I of Y.getFileSymbols(V.project,O.filePath))w.set(`${I.filePath}::${I.name}`,G(I));else{for(let V of Z){let O=r(V.filePath,this.opts.boundaries);for(let I of Y.getFileSymbols(O,V.filePath))w.set(`${I.filePath}::${I.name}`,G(I))}for(let[,V]of U)for(let O of V)w.set(`${O.filePath}::${O.name}`,G(O))}let C=(V)=>`${V.type}|${V.srcFilePath}|${V.dstFilePath??""}|${V.srcSymbolName??""}|${V.dstSymbolName??""}|${B_(V.metaJson??"")}`,E=new Map;if($)for(let V of this.opts.boundaries)for(let O of J.getAllFiles(V.project))for(let I of W.getOutgoing(V.project,O.filePath))E.set(C(I),I);else{for(let V of Z){let O=r(V.filePath,this.opts.boundaries);for(let I of W.getOutgoing(O,V.filePath))E.set(C(I),I)}for(let V of X){let O=r(V,this.opts.boundaries);for(let I of W.getOutgoing(O,V))E.set(C(I),I)}}let{annotationRepo:R,changelogRepo:u}=this.opts,P=()=>{for(let V of X){let O=r(V,this.opts.boundaries);if(Y.deleteFileSymbols(O,V),W.deleteFileRelations(O,V),W.deleteIncomingRelations(O,V),R)R.deleteFileAnnotations(O,V);J.deleteFile(O,V)}},m=0,i=async()=>{let{projectRoot:V,boundaries:O}=this.opts,{parseCache:I}=this.opts,L=0,S=0,T=0,f=[],j=[];for(let y of Z)try{let a=g_(V,y.filePath),V_=Bun.file(a),A_=await V_.text(),h_=y.contentHash||B_(A_),S_=r(y.filePath,O);J.upsertFile({project:S_,filePath:y.filePath,mtimeMs:V_.lastModified,size:V_.size,contentHash:h_,updatedAt:new Date().toISOString(),lineCount:A_.split(`
6
- `).length});let B0=(this.opts.parseSourceFn??u_)(a,A_);if(N1(B0))throw B0.data;let WQ=B0;j.push({filePath:y.filePath,text:A_,contentHash:h_,parsed:WQ,project:S_})}catch(a){this.logger.error(`[IndexCoordinator] Failed to prepare ${y.filePath}:`,a),f.push(y.filePath)}let v=new Set;for(let y of O)for(let[a]of J.getFilesMap(y.project))v.add(`${y.project}::${a}`);return z.transaction(()=>{for(let y of j){if(E0({parsed:y.parsed,project:y.project,filePath:y.filePath,contentHash:y.contentHash,symbolRepo:Y}),S+=k0({ast:y.parsed.program,project:y.project,filePath:y.filePath,relationRepo:W,projectRoot:V,tsconfigPaths:K,knownFiles:v,boundaries:O,module:y.parsed.module}),R)T+=g0({parsed:y.parsed,project:y.project,filePath:y.filePath,annotationRepo:R});I.set(y.filePath,y.parsed),L+=Y.getFileSymbols(y.project,y.filePath).length}}),{symbols:L,relations:S,annotations:T,failedFiles:f}},c=0,z_=0,X_=[];if($){let{projectRoot:V,boundaries:O}=this.opts,{parseCache:I}=this.opts,L=[];for(let T=0;T<Z.length;T+=R1){let f=Z.slice(T,T+R1),j=await Promise.allSettled(f.map(async(v)=>{let y=g_(V,v.filePath),a=Bun.file(y),V_=await a.text(),A_=v.contentHash||B_(V_);return{filePath:v.filePath,text:V_,contentHash:A_,mtimeMs:a.lastModified,size:a.size}}));for(let v=0;v<j.length;v++){let y=j[v];if(y.status==="fulfilled")L.push(y.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",y.reason),X_.push(f[v].filePath)}}let S=[];z.transaction(()=>{for(let j of L){let v=r(j.filePath,O);J.deleteFile(v,j.filePath)}for(let j of X){let v=r(j,O);if(Y.deleteFileSymbols(v,j),W.deleteFileRelations(v,j),W.deleteIncomingRelations(v,j),R)R.deleteFileAnnotations(v,j);J.deleteFile(v,j)}for(let j of L){let v=r(j.filePath,O);J.upsertFile({project:v,filePath:j.filePath,mtimeMs:j.mtimeMs,size:j.size,contentHash:j.contentHash,updatedAt:new Date().toISOString(),lineCount:j.text.split(`
7
- `).length})}let T=new Set;for(let j of O)for(let[v]of J.getFilesMap(j.project))T.add(`${j.project}::${v}`);let f=this.opts.parseSourceFn??u_;for(let j of L){let v=r(j.filePath,O),y=f(g_(V,j.filePath),j.text);if(N1(y))throw y.data;let a=y;if(S.push({filePath:j.filePath,parsed:a}),E0({parsed:a,project:v,filePath:j.filePath,contentHash:j.contentHash,symbolRepo:Y}),R)m+=g0({parsed:a,project:v,filePath:j.filePath,annotationRepo:R});z_+=k0({ast:a.program,project:v,filePath:j.filePath,relationRepo:W,projectRoot:V,tsconfigPaths:K,knownFiles:T,boundaries:O,module:a.module}),c+=Y.getFileSymbols(v,j.filePath).length}});for(let T of S)I.set(T.filePath,T.parsed)}else{P();let V=await i();c=V.symbols,z_=V.relations,m=V.annotations,X_=V.failedFiles}for(let V of Z){let O=r(V.filePath,this.opts.boundaries);for(let I of Y.getFileSymbols(O,V.filePath))q.set(`${I.filePath}::${I.name}`,G(I))}let G_=new Map;for(let V of Z){let O=r(V.filePath,this.opts.boundaries);for(let I of W.getOutgoing(O,V.filePath))G_.set(C(I),I)}let M_=(V)=>({type:V.type,srcFilePath:V.srcFilePath,dstFilePath:V.dstFilePath,srcSymbolName:V.srcSymbolName,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,metaJson:V.metaJson}),U_={added:[...G_.entries()].filter(([V])=>!E.has(V)).map(([,V])=>M_(V)),removed:[...E.entries()].filter(([V])=>!G_.has(V)).map(([,V])=>M_(V))},s={added:[],modified:[],removed:[]};for(let[V,O]of q){let I=w.get(V);if(!I)s.added.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});else{let L=I.fingerprint!==O.fingerprint,S=I.isExported!==O.isExported,T=I.structuralFingerprint!==null&&O.structuralFingerprint!==null&&I.structuralFingerprint!==O.structuralFingerprint;if(L||S||T)s.modified.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)})}}for(let[V,O]of w)if(!q.has(V))s.removed.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});let o=q1(w,q),C_=new Set(o.renamed.map((V)=>`${V.filePath}::${V.oldName}`)),H=new Set(o.renamed.map((V)=>`${V.filePath}::${V.newName}`));s.added=s.added.filter((V)=>!H.has(`${V.filePath}::${V.name}`)),s.removed=s.removed.filter((V)=>!C_.has(`${V.filePath}::${V.name}`));let A=[];if(!$){for(let[O,I]of U)for(let L of I){if(!L.fingerprint)continue;let S=r(O,this.opts.boundaries),T=Y.getByFingerprint(S,L.fingerprint);if(T.length===1){let f=T[0];W.retargetRelations({dstProject:S,oldFile:O,oldSymbol:L.name,newFile:f.filePath,newSymbol:f.name}),A.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:O,isExported:f.isExported??0})}}let V=new Set(A.map((O)=>`${O.oldFilePath}::${O.name}`));for(let O of o.removed){if(V.has(`${O.filePath}::${O.name}`))continue;let L=w.get(`${O.filePath}::${O.name}`)?.fingerprint;if(!L)continue;let S=r(O.filePath,this.opts.boundaries),T=Y.getByFingerprint(S,L);if(T.length===1){let f=T[0];if(f.filePath!==O.filePath||f.name!==O.name)W.retargetRelations({dstProject:S,oldFile:O.filePath,oldSymbol:O.name,newFile:f.filePath,newSymbol:f.name}),A.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:O.filePath,isExported:f.isExported??0})}}}if(A.length){let V=new Set(A.map((I)=>`${I.filePath}::${I.name}`)),O=new Set(A.map((I)=>`${I.oldFilePath}::${I.name}`));s.added=s.added.filter((I)=>!V.has(`${I.filePath}::${I.name}`)),s.removed=s.removed.filter((I)=>!O.has(`${I.filePath}::${I.name}`))}if(u){let V=new Date().toISOString(),O=$?1:0,I=[];for(let L of s.added){let S=`${L.filePath}::${L.name}`,T=q.get(S),f=r(L.filePath,this.opts.boundaries);I.push({project:f,changeType:"added",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:T?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:M})}for(let L of s.modified){let S=q.get(`${L.filePath}::${L.name}`),T=r(L.filePath,this.opts.boundaries);I.push({project:T,changeType:"modified",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:M})}for(let L of s.removed){let S=`${L.filePath}::${L.name}`,T=w.get(S),f=r(L.filePath,this.opts.boundaries);I.push({project:f,changeType:"removed",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:T?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:M})}for(let L of o.renamed){let S=q.get(`${L.filePath}::${L.newName}`),T=r(L.filePath,this.opts.boundaries);I.push({project:T,changeType:"renamed",symbolName:L.newName,symbolKind:L.kind,filePath:L.filePath,oldName:L.oldName,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:M})}for(let L of A){let S=q.get(`${L.filePath}::${L.name}`),T=r(L.filePath,this.opts.boundaries);I.push({project:T,changeType:"moved",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:L.oldFilePath,fingerprint:S?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:M})}if(I.length)try{z.transaction(()=>{u.insertBatch(I)})}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 S of this.opts.boundaries)u.pruneOlderThan(S.project,L)}catch(S){this.logger.error("[IndexCoordinator] changelog pruning failed:",S)}}}let B=new Set(X_),D=Z.filter((V)=>!B.has(V.filePath));return{indexedFiles:D.length,removedFiles:X.length,totalSymbols:c,totalRelations:z_,totalAnnotations:m,durationMs:Date.now()-Q,changedFiles:D.map((V)=>V.filePath),deletedFiles:[...X],failedFiles:X_,changedSymbols:s,renamedSymbols:o.renamed.map((V)=>({oldName:V.oldName,newName:V.newName,filePath:V.filePath,kind:V.kind,isExported:Boolean(q.get(`${V.filePath}::${V.newName}`)?.isExported)})),movedSymbols:A.map((V)=>({name:V.name,oldFilePath:V.oldFilePath,newFilePath:V.filePath,kind:V.kind,isExported:Boolean(V.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 LJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function BJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function S1(_,$,Q={}){let J=Q.now??Date.now,Y=Q.isAlive??LJ,W=Q.staleAfterSeconds??60,z=Q.instanceId;return _.immediateTransaction(()=>{let Z=_.selectOwner();if(!Z)return _.insertOwner($,z),"owner";let X=Math.floor((J()-BJ(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 T1(_,$){_.deleteOwner($)}function E1(_,$){_.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 b0{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 P0(_){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 y0(_){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,U=$.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;U=U.filter((q)=>(!M||M.match(q.srcFilePath))&&(!w||q.dstFilePath===null||w.match(q.dstFilePath)))}if(Z&&z!==void 0&&U.length>z)U=U.slice(0,z);return U}import{findInFiles as GJ,Lang as IJ}from"@ast-grep/napi";function wJ(_){let $=new Set,Q=/\${1,3}([A-Z_][A-Z_0-9]*)/g,J;while((J=Q.exec(_))!==null)$.add(J[0]);return[...$]}function DJ(_){return _.replace(/^\$+/,"")}function CJ(_,$){if($.length===0)return;let Q={},J=!1;for(let Y of $){let W=DJ(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((U)=>U.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 f0(_){if(_.filePaths.length===0)return[];let $=wJ(_.pattern),Q=[];return await GJ(IJ.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=CJ(W,$);if(X)Z.captures=X;Q.push(Z)}}),Q}import Q_ from"typescript";import{isErr as xJ}from"@zipbul/result";import w_ from"typescript";import AJ from"path";import{err as x0}from"@zipbul/result";function qJ(_){try{return $1("fs").readFileSync(_,"utf-8")}catch{return}}function NJ(_){try{return $1("fs").readFileSync(_,"utf-8")}catch{return}}class z0{#$;#_;#J=!1;__testing__;constructor(_,$){this.#$=_,this.#_=$,this.__testing__={host:$}}static create(_,$={}){let Q=$.readConfigFile??qJ,J=$.resolveNonTrackedFile??NJ,Y=AJ.dirname(_),W=Q(_);if(W===void 0)return x0(new N("semantic",`tsconfig not found: ${_}`));let z=w_.parseJsonText(_,W),Z=z.parseDiagnostics;if(Z&&Z.length>0){let M=Z.map((w)=>w_.flattenDiagnosticMessageText(w.messageText,`
8
- `)).join("; ");return x0(new N("semantic",`tsconfig parse error: ${M}`))}let X=w_.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===w_.DiagnosticCategory.Error&&w.code!==18003);if(M.length>0){let w=M.map((q)=>w_.flattenDiagnosticMessageText(q.messageText,`
9
- `)).join("; ");return x0(new N("semantic",`tsconfig compile error: ${w}`))}}let K=new F1(X.fileNames,X.options,Y,J),U=w_.createLanguageService(K);return new z0(U,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 F1{#$;#_;#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=w_.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=w_.ScriptSnapshot.fromString(J),this.#Q.set(_,Q),Q;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#_}getDefaultLibFileName(_){return w_.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 X0 from"typescript";function $_(_,$){if($<0||$>=_.getEnd())return;let Q,J=(Y)=>{if($<Y.getStart(_,!1)||$>=Y.getEnd())return;Q=Y,X0.forEachChild(Y,J)};return X0.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;X0.forEachChild(W,Y)};return X0.forEachChild(_,Y),J}var U0=8;function RJ(_){return!!(_.flags&h.TypeFlags.Object)&&!!(_.objectFlags&h.ObjectFlags.Reference)}function L_(_,$,Q=0,J){if(J){let G=J.get($);if(G)return G}let Y=_.typeToString($),W=$.flags,z=!!(W&h.TypeFlags.Union),Z=!!(W&h.TypeFlags.Intersection),X;if(Q<U0&&RJ($)){let G=_.getTypeArguments($);if(G.length>0)X=G}let K=!!(W&h.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,U;if(z&&Q<U0)U=$.types.map((G)=>L_(_,G,Q+1,J));else if(Z&&Q<U0)U=$.types.map((G)=>L_(_,G,Q+1,J));let M;if(X&&X.length>0)M=X.map((G)=>L_(_,G,Q+1,J));let w;if(Q<U0&&!!(W&h.TypeFlags.Object)&&!z&&!Z){let G=_.getPropertiesOfType($);if(G.length>0&&G.length<=50){let C=$.symbol?.declarations?.[0];w=[];for(let E of G){let R=E.declarations?.[0]??C;if(!R)continue;try{let u=_.getTypeOfSymbolAtLocation(E,R);w.push({name:E.getName(),type:L_(_,u,Q+1,J)})}catch{}}if(w.length===0)w=void 0}}let q={text:Y,flags:W,isUnion:z,isIntersection:Z,isGeneric:K,members:U,typeArguments:M,properties:w};if(J)J.set($,q);return q}function V0(_,$,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)=>V0(_,Z,Q)):z.length>0&&z.every((Z)=>V0(_,Z,Q))}if($.isIntersection())return $.types.some((z)=>V0(_,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 SJ(_){return h.isFunctionDeclaration(_)||h.isVariableDeclaration(_)||h.isClassDeclaration(_)||h.isInterfaceDeclaration(_)||h.isTypeAliasDeclaration(_)||h.isEnumDeclaration(_)||h.isMethodDeclaration(_)||h.isPropertyDeclaration(_)||h.isPropertySignature(_)||h.isMethodSignature(_)}var h0="/__gildash_type_probe__.ts";class m0{program;#$=null;constructor(_){this.program=_}#_(_){if(this.#$===_)return;this.program.notifyFileChanged(h0,`declare const __gildash_probe__: ${_};`),this.#$=_}#J(_,$){let Q=_.getSourceFile(h0);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(h0),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 V0(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((U)=>!(U.flags&(h.TypeFlags.Void|h.TypeFlags.Undefined|h.TypeFlags.Null))):[z],X=new Map,K=[];for(let U of Z)for(let M of U.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((U)=>W.isTypeAssignableTo(U,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 U=W.getTypeAtLocation(Z),M=W.getTypeAtLocation(K);return W.isTypeAssignableTo(U,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((U)=>W.isTypeAssignableTo(U,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 U of $){if(U<0||U>=K)continue;let M=$_(Z,U);if(!M||!h.isIdentifier(M)&&!h.isTypeNode(M))continue;try{let w=z.getTypeAtLocation(M);if(J?.anyConstituent&&w.isUnion())Y.set(U,w.types.some((q)=>z.isTypeAssignableTo(q,X)));else Y.set(U,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 U=Y.getTypeAtLocation(K);Q.set(X,L_(Y,U,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(SJ(Z)&&Z.name&&h.isIdentifier(Z.name)){let X=Z.name;try{let K=J.getTypeAtLocation(X),U=X.getStart(Y);$.set(U,L_(J,K,0,W))}catch{}}h.forEachChild(Z,z)}return z(Y),$}}import D_ from"typescript";var TJ=1000,EJ=1;function FJ(_){let $=_.declarations?.[0],Q=$?.getSourceFile(),J=$?D_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:Q?.fileName??"",position:J?.getStart(Q,!1)??$?.getStart(Q,!1)??0}}function H0(_,$=0,Q){let J=_.declarations?.[0],Y=J?.getSourceFile(),W=J?D_.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=FJ(K.parent);let U=Q&&!!(_.flags&D_.SymbolFlags.Alias)?Q.getAliasedSymbol(_):_;if($<EJ){let M=U.flags,w=!!(M&D_.SymbolFlags.Enum),q=!!(M&(D_.SymbolFlags.NamespaceModule|D_.SymbolFlags.ValueModule)),G=!!(M&(D_.SymbolFlags.Class|D_.SymbolFlags.Interface));if(w&&U.exports&&U.exports.size>0){let C=[];U.exports.forEach((E)=>{C.push(H0(E,$+1,Q))}),X.members=C}else if(G&&U.members&&U.members.size>0){let C=[];U.members.forEach((E)=>{C.push(H0(E,$+1,Q))}),X.members=C}if(q&&U.exports&&U.exports.size>0){let C=[];U.exports.forEach((E)=>{C.push(H0(E,$+1,Q))}),X.exports=C}}return X}class p0{#$;#_;constructor(_,$=TJ){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||!D_.isIdentifier(z))return null;let Z=Y.getTypeChecker(),X=Z.getSymbolAtLocation(z);if(!X)return null;let K=H0(X,0,Z);return this.#_.set(Q,K),K}clear(){this.#_.clear()}}import n from"typescript";import F from"typescript";function d0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(jJ($))return!0;return!1}function jJ(_){if(!F.canHaveModifiers(_))return!1;return F.getModifiers(_)?.some((Q)=>Q.kind===F.SyntaxKind.DeclareKeyword)??!1}function l0(_){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 n0(_){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 kJ(J.operatorToken.kind);if(vJ(_))return"assignment";return}function kJ(_){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 vJ(_){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 i0{#$;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(j1(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 U=$_(K,X.textSpan.start),M=U&&n.isIdentifier(U)?U:void 0;W.push({...j1(X,K),writeKind:M?n0(M):void 0,isAmbient:Z,enclosingScope:l0(M??K)})}}return W}findFileBindings(_){if(this.#$.isDisposed)return[];let $=this.#$.getProgram(),Q=$.getSourceFile(_);if(!Q)return[];return c0(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(d0)}}function c0(_,$){let Q=new Map,J=(W)=>{if(n.isIdentifier(W)&&!gJ(W)){let z=bJ(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(uJ))continue;let X=Z.every(d0),K=new Set(Z.map((G)=>n.getNameOfDeclaration(G)).filter((G)=>G!==void 0)),U=Z[0],M=n.getNameOfDeclaration(U)??U,w=U.getSourceFile(),q=z.map((G)=>{let C=G.getStart(_),{line:E,character:R}=_.getLineAndCharacterOfPosition(C),u=n0(G);return{filePath:_.fileName,position:C,line:E+1,column:R,isDefinition:K.has(G),isWrite:u!==void 0,writeKind:u,isAmbient:X,enclosingScope:l0(G)}});Y.push({declaration:{filePath:w.fileName,position:M.getStart(w),name:W.getName(),isAmbient:X},references:q})}return Y}function gJ(_){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 uJ(_){return n.isPropertyDeclaration(_)||n.isPropertySignature(_)||n.isMethodDeclaration(_)||n.isMethodSignature(_)||n.isGetAccessorDeclaration(_)||n.isSetAccessorDeclaration(_)||n.isEnumMember(_)||n.isParameter(_)&&n.isIndexSignatureDeclaration(_.parent)}function bJ(_,$){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 j1(_,$){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 k1(_,$,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 c0(Z,z.getTypeChecker())}import p from"typescript";function PJ(_,$){let Q=$_(_,$);if(!Q)return;if(v1(Q))return Q;let J=Q.parent;for(let Y=0;Y<5&&J;Y++){if(v1(J))return J;J=J.parent}return Q}function v1(_){return p.isClassDeclaration(_)||p.isClassExpression(_)||p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_)||p.isVariableDeclaration(_)||p.isObjectLiteralExpression(_)}function g1(_){if(p.isClassDeclaration(_)||p.isClassExpression(_))return"class";if(p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_))return"function";if(p.isObjectLiteralExpression(_))return"object";if(p.isVariableDeclaration(_)&&_.initializer)return g1(_.initializer);return"class"}function yJ(_,$){if(p.isClassDeclaration(_)||p.isFunctionDeclaration(_))return _.name?.getText($)??"";if(p.isClassExpression(_))return _.name?.getText($)??"";if(p.isVariableDeclaration(_)&&p.isIdentifier(_.name))return _.name.getText($);if(p.isFunctionExpression(_))return _.name?.getText($)??"";if(p.isArrowFunction(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(p.isObjectLiteralExpression(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function fJ(_){if(!p.isClassDeclaration(_)&&!p.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((Q)=>Q.token===p.SyntaxKind.ImplementsKeyword)}class a0{#$;constructor(_){this.#$=_}findAt(_,$){if(this.#$.isDisposed)return[];let Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let Y=$_(J,$);if(!Y||!p.isIdentifier(Y))return[];let z=this.#$.getLanguageService().getImplementationAtPosition(_,$);if(!z||z.length===0)return[];let Z=[];for(let X of z){if(X.kind===p.ScriptElementKind.interfaceElement||X.kind===p.ScriptElementKind.typeElement)continue;let K=Q.getSourceFile(X.fileName);if(!K)continue;let U=PJ(K,X.textSpan.start);if(!U)continue;let M=g1(U),w=yJ(U,K),q=fJ(U);Z.push({filePath:X.fileName,symbolName:w,position:X.textSpan.start,kind:M,isExplicit:q})}return Z}}function hJ(_){if(Q_.isFunctionDeclaration(_))return"function";if(Q_.isClassDeclaration(_))return"class";if(Q_.isInterfaceDeclaration(_))return"interface";if(Q_.isTypeAliasDeclaration(_))return"type";if(Q_.isEnumDeclaration(_))return"enum";if(Q_.isVariableDeclaration(_))return"const";if(Q_.isVariableStatement(_))return"const";return"unknown"}function u1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class K0{#$;#_;#J;#Y;#W;#Z=!1;constructor(_,$,Q,J,Y){this.#$=_,this.#_=$,this.#J=Q,this.#Y=J,this.#W=Y}static create(_,$={}){let Q=z0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(xJ(Q))return Q;let J=Q,Y=$.typeCollector??new m0(J),W=$.symbolGraph??new p0(J),z=$.referenceResolver??new i0(J),Z=$.implementationFinder??new a0(J);return new K0(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 k1(_,$,{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&Q_.TypeFlags.Object)||!(z.objectFlags&Q_.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(),U=X.declarations?.[0],M="unknown";if(U){if(M=hJ(U),M==="unknown"&&Q_.isExportAssignment(U))M="const"}let w=null;try{let q=Y.getTypeOfSymbolAtLocation(X,U??J);w=L_(Y,q,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 Q_.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(!u1(Z)&&!u1(X))return z;W=z+1}return null}getDiagnostics(_,$){this.#Q();let Q=this.#$.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let Y={[Q_.DiagnosticCategory.Error]:"error",[Q_.DiagnosticCategory.Warning]:"warning",[Q_.DiagnosticCategory.Suggestion]:"suggestion",[Q_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?Q_.getPreEmitDiagnostics(Q,J):Q.getSemanticDiagnostics(J)).map((z)=>{let Z=1,X=0;if(z.file&&z.start!==void 0){let K=Q_.getLineAndCharacterOfPosition(z.file,z.start);Z=K.line+1,X=K.character}return{filePath:z.file?.fileName??_,line:Z,column:X,message:Q_.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 j_,and as b1,sql as mJ}from"drizzle-orm";var P1=80;class s0{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+=P1)this.db.drizzleDb.insert(H_).values(J.slice(Y,Y+P1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(H_).where(b1(j_(H_.project,_),j_(H_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(H_).where(b1(_.project?j_(H_.project,_.project):void 0,_.tag?j_(H_.tag,_.tag):void 0,_.filePath?j_(H_.filePath,_.filePath):void 0,_.symbolName?j_(H_.symbolName,_.symbolName):void 0,_.source?j_(H_.source,_.source):void 0,_.ftsQuery?mJ`${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 y_,and as y1,sql as o_,gt as pJ,gte as dJ}from"drizzle-orm";var f1=80;class r0{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+=f1)this.db.drizzleDb.insert(J_).values($.slice(Q,Q+f1)).run()}getSince(_){return this.db.drizzleDb.select().from(J_).where(y1(y_(J_.project,_.project),dJ(J_.changedAt,_.since),_.symbolName?y_(J_.symbolName,_.symbolName):void 0,_.changeTypes?.length?o_`${J_.changeType} IN (${o_.join(_.changeTypes.map(($)=>o_`${$}`),o_`, `)})`:void 0,_.filePath?y_(J_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:y_(J_.isFullIndex,0),_.indexRunId?y_(J_.indexRunId,_.indexRunId):void 0,_.afterId?pJ(J_.id,_.afterId):void 0)).orderBy(J_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(J_).where(y1(y_(J_.project,_),o_`${J_.changedAt} < ${$}`)).run().changes}}function x1(_){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 __(_){if(_.closed)throw new N("closed","Gildash: instance is closed")}function k(_,$,Q,J){__(_);try{return J()}catch(Y){if(Y instanceof N)throw Y;throw new N($,`Gildash: ${Q} failed`,{cause:Y})}}async function o0(_,$,Q,J){__(_);try{return await J()}catch(Y){if(Y instanceof N)throw Y;throw new N($,`Gildash: ${Q} failed`,{cause:Y})}}class M0{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 aJ(Q,$)}}var lJ=(_,$)=>_.localeCompare($);function nJ(_){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 t0(_,$,Q){let J=nJ(Q);if(J.length===0)return!1;let Y=J.join("->");if(_.has(Y))return!1;return _.add(Y),$.push(J),!0}function iJ(_){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=[],U="";do U=Q.pop()??"",J.delete(U),K.push(U);while(U!==X&&Q.length>0);z.push(K)}};for(let X of _.keys())if(!Y.has(X))Z(X);return{components:z}}function cJ(_,$,Q){let J=[],Y=new Set,W=[..._].sort(lJ),z=(Z,X,K)=>{X.delete(Z);let U=K.get(Z);if(!U)return;for(let M of U)if(X.has(M))z(M,X,K);U.clear()};for(let Z=0;Z<W.length&&J.length<Q;Z++){let X=W[Z]??"",K=new Set(W.slice(Z)),U=new Set,M=new Map,w=[],q=(C)=>($.get(C)??[]).filter((E)=>K.has(E)),G=(C)=>{if(J.length>=Q)return!0;let E=!1;w.push(C),U.add(C);for(let R of q(C)){if(J.length>=Q)break;if(R===X)t0(Y,J,w.concat(X)),E=!0;else if(!U.has(R)){if(G(R))E=!0}}if(E)z(C,U,M);else for(let R of q(C)){let u=M.get(R)??new Set;u.add(C),M.set(R,u)}return w.pop(),E};G(X)}return J}function aJ(_,$){let{components:Q}=iJ(_),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))t0(Y,J,[X,X]);continue}let z=$-J.length,Z=cJ(W,_,z);for(let X of Z){if(J.length>=$)break;t0(Y,J,X)}}return J}var sJ=15000;function O0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function k_(_,$){let Q=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>sJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===Q)return _.graphCache;let J=new M0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((Y)=>Y.project)});return J.build(),_.graphCache=J,_.graphCacheKey=Q,_.graphCacheBuiltAt=Date.now(),J}function h1(_,$,Q,J=1e4){return k(_,"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 m1(_,$,Q,J=1e4){return k(_,"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 p1(_,$,Q){return k(_,"search","getAffected",()=>{return k_(_,Q).getAffectedByChange($.map((Y)=>K_(_.projectRoot,Y)))})}async function d1(_,$){return k(_,"search","hasCycle",()=>{return k_(_,$).hasCycle()})}async function l1(_,$){return k(_,"search","getImportGraph",()=>{return k_(_,$).getAdjacencyList()})}async function n1(_,$,Q){return k(_,"search","getTransitiveDependencies",()=>{return k_(_,Q).getTransitiveDependencies(K_(_.projectRoot,$))})}async function i1(_,$,Q){return k(_,"search","getTransitiveDependents",()=>{return k_(_,Q).getTransitiveDependents(K_(_.projectRoot,$))})}async function c1(_,$,Q){return k(_,"search","getCyclePaths",()=>{return k_(_,$).getCyclePaths(Q)})}async function a1(_,$,Q){return k(_,"search","getFanMetrics",()=>{let J=k_(_,Q),Y=K_(_.projectRoot,$);return{filePath:$,fanIn:J.getDependents(Y).length,fanOut:J.getDependencies(Y).length}})}var tJ=30000,s1=15000,eJ=10;function _6(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??f_.basename(_.projectRoot)}function $6(_,$){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 Q6(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(Q)=>{try{let J=f_.resolve(_.projectRoot,Q.filePath),Y=await _.readFileFn(J);_.semanticLayer?.notifyFileChanged(J,Y)}catch{}}))}async function r1(_,$){let Q=_.coordinatorFactory?_.coordinatorFactory():new u0({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 O0(_)}),$.isWatchMode){let J=_.watcherFactory?_.watcherFactory():new S0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await J.start($6(_,Q)).then((Y)=>{if(t_(Y))throw Y.data}),_.watcher=J,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},tJ)}await Q.fullIndex(),await Q6(_)}function J6(_,$){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 o1(_){let{projectRoot:$,extensions:Q=[".ts",".mts",".cts"],ignorePatterns:J=["**/node_modules/**"],parseCacheCapacity:Y=500,logger:W=console,existsSyncFn:z=oJ,dbConnectionFactory:Z,watcherFactory:X,coordinatorFactory:K,repositoryFactory:U,acquireWatcherRoleFn:M=S1,releaseWatcherRoleFn:w=T1,updateHeartbeatFn:q=E1,discoverProjectsFn:G=_0,parseSourceFn:C=u_,extractSymbolsFn:E=T_,extractRelationsFn:R=c_,symbolSearchFn:u=P0,relationSearchFn:P=y0,patternSearchFn:m=f0,loadTsconfigPathsFn:i=n_,readFileFn:c=async(o)=>Bun.file(o).text(),unlinkFn:z_=async(o)=>{await Bun.file(o).unlink()},watchMode:X_,semantic:G_,semanticLayerFactory:M_}=_;if(!f_.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 w0({projectRoot:$}),s=U_.open();if(t_(s))throw s.data;try{let o=await G($),C_=o[0]?.project??f_.basename($),H=U?U():(()=>{let S=U_;return{fileRepo:new D0(S),symbolRepo:new A0(S),relationRepo:new q0(S),parseCache:new b0(Y)}})(),A=U?null:U_,B=A?new s0(A):null,D=A?new r0(A):null,V=X_??!0,O=crypto.randomUUID(),I;if(V)I=await Promise.resolve(M(U_,process.pid,{instanceId:O}));else I="owner";let L={projectRoot:$,extensions:Q,ignorePatterns:J,logger:W,defaultProject:C_,role:I,db:U_,symbolRepo:H.symbolRepo,relationRepo:H.relationRepo,fileRepo:H.fileRepo,parseCache:H.parseCache,annotationRepo:B,changelogRepo:D,annotationSearchFn:x1,releaseWatcherRoleFn:w,parseSourceFn:C,extractSymbolsFn:E,extractRelationsFn:R,symbolSearchFn:u,relationSearchFn:P,patternSearchFn:m,readFileFn:c,unlinkFn:z_,existsSyncFn:z,acquireWatcherRoleFn:M,updateHeartbeatFn:q,watcherFactory:X,coordinatorFactory:K,instanceId:O,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:o,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if($0($),L.tsconfigPaths=await i($),G_){let S=f_.join($,"tsconfig.json");try{if(M_)L.semanticLayer=M_(S);else{let T=K0.create(S);if(t_(T))throw T.data;L.semanticLayer=T}}catch(T){if(T instanceof N)throw T;throw new N("semantic","Gildash: semantic layer creation failed",{cause:T})}}if(I==="owner")await r1(L,{isWatchMode:V});else{let S=0,T=async()=>{try{let f=await Promise.resolve(L.acquireWatcherRoleFn(L.db,process.pid,{instanceId:L.instanceId}));if(S=0,f==="owner"){L.role="owner";for(let j of L.onRoleChangedCallbacks)try{j("owner")}catch(v){L.logger.error("[Gildash] onRoleChanged callback threw:",v)}clearInterval(L.timer),L.timer=null;try{await r1(L,{isWatchMode:!0})}catch(j){if(L.logger.error("[Gildash] owner promotion failed, reverting to reader",j),L.role="reader",L.timer!==null)clearInterval(L.timer),L.timer=null;if(L.watcher){let v=await L.watcher.close();if(t_(v))L.logger.error("[Gildash] watcher close error during promotion rollback",v.data);L.watcher=null}if(L.coordinator)await L.coordinator.shutdown().catch((v)=>L.logger.error("[Gildash] coordinator shutdown error during promotion rollback",v)),L.coordinator=null;try{L.releaseWatcherRoleFn(L.db,process.pid)}catch(v){L.logger.error("[Gildash] failed to release watcher role during promotion rollback",v)}L.timer=setInterval(T,s1)}}}catch(f){S++;let j=f instanceof N?f:new N("watcher","Gildash: healthcheck error",{cause:f});for(let v of L.onErrorCallbacks)try{v(j)}catch(y){L.logger.error("[Gildash] onError callback threw:",y)}if(L.logger.error("[Gildash] healthcheck error",f),S>=eJ)L.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(L.timer),L.timer=null,L0(L).catch((v)=>L.logger.error("[Gildash] close error during healthcheck shutdown",v))}};L.timer=setInterval(T,s1)}if(V)J6(L,()=>L0(L));return L}catch(o){if(U_.close(),o instanceof N)throw o;throw new N("store","Gildash: initialization failed",{cause:o})}}async function L0(_,$){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(f_.join(_.projectRoot,q_,e_+J))}catch{}if(Q.length>0)throw new N("close","Gildash: one or more errors occurred during close()",{cause:Q})}import{isErr as t1}from"@zipbul/result";function e1(_,$,Q,J){__(_);let Y=_.parseSourceFn($,Q,J);if(t1(Y))throw Y.data;return _.parseCache.set($,Y),Y}async function _$(_,$,Q){__(_);let J=new Map,Y=[];return await Promise.all($.map(async(W)=>{try{let z=await _.readFileFn(W),Z=_.parseSourceFn(W,z,Q);if(!t1(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 $$(_,$){return __(_),_.parseCache.get($)}function Q$(_,$){return __(_),_.extractSymbolsFn($)}function J$(_,$){return __(_),_.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import Y$ from"path";function W$(_,$){return k(_,"store","getStats",()=>_.symbolRepo.getStats($??_.defaultProject))}function e0(_,$){return k(_,"search","searchSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function Z$(_,$){return k(_,"search","searchRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function z$(_,$){return k(_,"search","searchAllSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function X$(_,$){return k(_,"search","searchAllRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function U$(_,$){return k(_,"store","listIndexedFiles",()=>_.fileRepo.getAllFiles($??_.defaultProject))}function V$(_,$,Q){return k(_,"search","getInternalRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}}))}function H$(_,$,Q,J){return k(_,"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=Y$.isAbsolute(Q)?Q:Y$.resolve(_.projectRoot,Q),U=_.semanticLayer.lineColumnToPosition(K,z.span.start.line,z.span.start.column);if(U!==null){let M=_.semanticLayer.findNamePosition(K,U,z.name)??U,w=_.semanticLayer.collectTypeAt(K,M);if(w)X.resolvedType=w}}catch{}return X})}function K$(_,$,Q){return k(_,"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 M$(_,$,Q){return k(_,"store","getFileInfo",()=>_.fileRepo.getFile(Q??_.defaultProject,K_(_.projectRoot,$)))}function O$(_,$,Q){return e0(_,{filePath:$,project:Q??void 0,limit:1e4})}function L$(_,$,Q){return k(_,"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 g from"path";function x_(_,$,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=g.isAbsolute(Q)?Q:g.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 B$(_,$,Q,J){return k(_,"search","getResolvedType",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=x_(_,$,Q,J);if(!Y)return null;return _.semanticLayer.collectTypeAt(Y.absPath,Y.position)})}function G$(_,$,Q,J){return k(_,"search","getSemanticReferences",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=x_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findReferences(Y.absPath,Y.position)})}function I$(_,$,Q,J){return k(_,"search","getEnrichedReferences",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=x_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findEnrichedReferences(Y.absPath,Y.position)})}function w$(_,$,Q,J){return k(_,"search","getImplementations",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=x_(_,$,Q,J);if(!Y)throw new N("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findImplementations(Y.absPath,Y.position)})}function D$(_,$,Q,J,Y,W){return k(_,"semantic","isTypeAssignableTo",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let z=x_(_,$,Q,W);if(!z)throw new N("search",`Gildash: source symbol '${$}' not found in '${Q}'`);let Z=x_(_,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 C$(_,$){return k(_,"semantic","getFileTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(Q)})}function A$(_,$,Q,J){return k(_,"semantic","getResolvedTypeAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=g.isAbsolute($)?$:g.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(Y,Q,J);if(W===null)return null;return _.semanticLayer.collectTypeAt(Y,W)})}function q$(_,$){return k(_,"semantic","isTypeAssignableToAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=g.isAbsolute($.source.filePath)?$.source.filePath:g.resolve(_.projectRoot,$.source.filePath),J=g.isAbsolute($.target.filePath)?$.target.filePath:g.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 N$(_,$){return k(_,"search","getSemanticModuleInterface",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");return _.semanticLayer.getModuleInterface($)})}function R$(_,$,Q){return k(_,"semantic","getBaseTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(J,Q)})}function S$(_,$,Q){return k(_,"semantic","getResolvedTypesAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(J,Q)})}function T$(_,$,Q){return k(_,"semantic","getExpressionTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.collectAtSpan(J,Q)})}function E$(_,$,Q,J){return k(_,"semantic","isThenableAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.isThenableAtSpan(Y,Q,J)})}function F$(_,$,Q){return k(_,"semantic","getContextualCallReturnsAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.contextualCallReturnsAtSpan(J,Q)})}function j$(_,$,Q,J,Y){return k(_,"semantic","isTypeAssignableToTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtSpan(W,Q,J,Y)})}function k$(_,$,Q){return k(_,"semantic","getResolvedTypeAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(J,Q)})}function v$(_,$,Q){return k(_,"semantic","getSemanticReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(J,Q)})}function g$(_,$,Q){return k(_,"semantic","getEnrichedReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(J,Q)})}function u$(_,$){return k(_,"semantic","getFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(Q)})}function b$(_,$){return k(_,"semantic","getFileBindingsBatch",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=$.map((W)=>({orig:W.filePath,abs:g.isAbsolute(W.filePath)?W.filePath:g.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 P$(_,$,Q){return k(_,"semantic","getStandaloneFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.getStandaloneFileBindings(J,Q)})}function y$(_,$,Q){return k(_,"semantic","notifyFileChanged",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);_.semanticLayer.notifyFileChanged(J,Q)})}function f$(_,$){return k(_,"semantic","notifyFileDeleted",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);_.semanticLayer.notifyFileDeleted(Q)})}function x$(_,$,Q){return k(_,"semantic","getImplementationsAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(J,Q)})}function h$(_,$,Q,J,Y){return k(_,"semantic","isTypeAssignableToAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=g.isAbsolute($)?$:g.resolve(_.projectRoot,$),z=g.isAbsolute(J)?J:g.resolve(_.projectRoot,J);return _.semanticLayer.isTypeAssignableTo(W,Q,z,Y)})}function m$(_,$,Q,J,Y){return k(_,"semantic","isTypeAssignableToType",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,Q,J,Y)})}function p$(_,$,Q,J,Y){return k(_,"semantic","isTypeAssignableToTypeAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,Q,J,Y)})}function d$(_,$,Q,J){return k(_,"semantic","lineColumnToPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(Y,Q,J)})}function l$(_,$,Q,J){return k(_,"semantic","findNamePosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(Y,Q,J)})}function n$(_,$,Q){return k(_,"semantic","getSymbolNode",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(J,Q)})}function i$(_,$,Q){return k(_,"semantic","getSemanticDiagnostics",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=g.isAbsolute($)?$:g.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(J,Q)})}import X6 from"path";function c$(_,$){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 a$(_,$){if(__(_),_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let Q=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),Q()}}async function s$(_){return o0(_,"index","reindex",async()=>{if(!_.coordinator)throw new N("closed","Gildash: reindex() is not available for readers");let $=await _.coordinator.fullIndex();return O0(_),$})}function r$(_,$,Q,J){return k(_,"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 U=_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Y,query:{type:"re-exports",srcFilePath:X,limit:500}}),M,w;for(let q of U){let G;if(q.metaJson)try{let E=JSON.parse(q.metaJson);if(Array.isArray(E.specifiers))G=E.specifiers}catch{}if(!G)continue;let C=G.find((E)=>E.exported===Z);if(!C)continue;M=q.dstFilePath??void 0,w=C.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 o$(_,$){return __(_),_.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function t$(_,$){return __(_),_.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function e$(_,$){return __(_),_.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function _Q(_,$,Q){return o0(_,"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 $Q(_,$,Q,J){return k(_,"search","getHeritageChain",()=>{let Y=J??_.defaultProject,W=new Set,z=(X,K,U)=>{let M=`${X}::${K}`;if(W.has(M))return{symbolName:X,filePath:K,kind:U,children:[]};W.add(M);let G=_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Y,query:{srcFilePath:K,srcSymbolName:X,limit:1000}}).filter((C)=>C.type==="extends"||C.type==="implements").filter((C)=>C.dstSymbolName!=null&&C.dstFilePath!=null).map((C)=>z(C.dstSymbolName,C.dstFilePath,C.type));return{symbolName:X,filePath:K,kind:U,children:G}},Z=X6.isAbsolute(Q)?N_(_.projectRoot,Q):Q;return z($,Z)})}function QQ(_,$){if(__(_),!_.annotationRepo||!_.annotationSearchFn)return[];let{annotationRepo:Q,annotationSearchFn:J}=_;return k(_,"search","searchAnnotations",()=>J({annotationRepo:Q,project:$.project??_.defaultProject,query:$}))}function JQ(_,$,Q){if(__(_),!_.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 YQ(_,$){if(__(_),!_.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 o1(_);return new _1($)}async close(_){return L0(this._ctx,_)}parseSource(_,$,Q){return e1(this._ctx,_,$,Q)}async batchParse(_,$){return _$(this._ctx,_,$)}getParsedAst(_){return $$(this._ctx,_)}extractSymbols(_){return Q$(this._ctx,_)}extractRelations(_){return J$(this._ctx,_)}getStats(_){return W$(this._ctx,_)}searchSymbols(_){return e0(this._ctx,_)}searchRelations(_){return Z$(this._ctx,_)}searchAllSymbols(_){return z$(this._ctx,_)}searchAllRelations(_){return X$(this._ctx,_)}listIndexedFiles(_){return U$(this._ctx,_)}getInternalRelations(_,$){return V$(this._ctx,_,$)}getFullSymbol(_,$,Q){return H$(this._ctx,_,$,Q)}getFileStats(_,$){return K$(this._ctx,_,$)}getFileInfo(_,$){return M$(this._ctx,_,$)}getSymbolsByFile(_,$){return O$(this._ctx,_,$)}getModuleInterface(_,$){return L$(this._ctx,_,$)}getDependencies(_,$,Q=1e4){return h1(this._ctx,_,$,Q)}getDependents(_,$,Q=1e4){return m1(this._ctx,_,$,Q)}async getAffected(_,$){return p1(this._ctx,_,$)}async hasCycle(_){return d1(this._ctx,_)}async getImportGraph(_){return l1(this._ctx,_)}async getTransitiveDependencies(_,$){return n1(this._ctx,_,$)}async getTransitiveDependents(_,$){return i1(this._ctx,_,$)}async getCyclePaths(_,$){return c1(this._ctx,_,$)}async getFanMetrics(_,$){return a1(this._ctx,_,$)}getResolvedType(_,$,Q){return B$(this._ctx,_,$,Q)}getSemanticReferences(_,$,Q){return G$(this._ctx,_,$,Q)}getEnrichedReferences(_,$,Q){return I$(this._ctx,_,$,Q)}getImplementations(_,$,Q){return w$(this._ctx,_,$,Q)}isTypeAssignableTo(_,$,Q,J,Y){return D$(this._ctx,_,$,Q,J,Y)}getSemanticModuleInterface(_){return N$(this._ctx,_)}getFileTypes(_){return C$(this._ctx,_)}getResolvedTypeAt(_,$,Q){return A$(this._ctx,_,$,Q)}isTypeAssignableToAt(_){return q$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return k$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return S$(this._ctx,_,$)}getExpressionTypeAtSpan(_,$){return T$(this._ctx,_,$)}isThenableAtSpan(_,$,Q){return E$(this._ctx,_,$,Q)}getContextualCallReturnsAtSpan(_,$){return F$(this._ctx,_,$)}isTypeAssignableToTypeAtSpan(_,$,Q,J){return j$(this._ctx,_,$,Q,J)}getSemanticReferencesAtPosition(_,$){return v$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return g$(this._ctx,_,$)}getFileBindings(_){return u$(this._ctx,_)}getFileBindingsBatch(_){return b$(this._ctx,_)}getStandaloneFileBindings(_,$){return P$(this._ctx,_,$)}notifyFileChanged(_,$){y$(this._ctx,_,$)}notifyFileDeleted(_){f$(this._ctx,_)}getImplementationsAtPosition(_,$){return x$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,Q,J){return h$(this._ctx,_,$,Q,J)}isTypeAssignableToType(_,$,Q,J){return m$(this._ctx,_,$,Q,J)}isTypeAssignableToTypeAtPositions(_,$,Q,J){return p$(this._ctx,_,$,Q,J)}lineColumnToPosition(_,$,Q){return d$(this._ctx,_,$,Q)}findNamePosition(_,$,Q){return l$(this._ctx,_,$,Q)}getSymbolNode(_,$){return n$(this._ctx,_,$)}getBaseTypes(_,$){return R$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return i$(this._ctx,_,$)}diffSymbols(_,$){return c$(_,$)}onIndexed(_){return a$(this._ctx,_)}async reindex(){return s$(this._ctx)}resolveSymbol(_,$,Q){return r$(this._ctx,_,$,Q)}async findPattern(_,$){return _Q(this._ctx,_,$)}async getHeritageChain(_,$,Q){return $Q(this._ctx,_,$,Q)}onFileChanged(_){return o$(this._ctx,_)}onError(_){return t$(this._ctx,_)}onRoleChanged(_){return e$(this._ctx,_)}searchAnnotations(_){return QQ(this._ctx,_)}getSymbolChanges(_,$){return JQ(this._ctx,_,$)}pruneChangelog(_){return YQ(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,P0 as symbolSearch,y0 as relationSearch,f0 as patternSearch,u_ as parseSource,j2 as parseAndWalk,Y_ as normalizePath,XJ as isVariableDeclaration,zJ as isTSQualifiedName,ZJ as isMemberExpression,WJ as isIdentifier,eQ as isFunctionNode,YJ as isFunctionExpression,JJ as isFunctionDeclaration,QJ as isCallExpression,$J as isAssignmentExpression,_J as isArrowFunctionExpression,UJ as is,O_ as getLineColumn,T_ as extractSymbols,c_ as extractRelations,i_ as buildLineOffsets,S2 as Visitor,k2 as ScopeTracker,N as GildashError,_1 as Gildash,M0 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:()=>Y_,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")]),Y_=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 W_(_){return _.replaceAll("\\","/")}function q_(_,$){return W_(R0.relative(_,$))}function v_(_,$){return W_(R0.resolve(_,$))}function NQ(_){return W_(_)}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=W_(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 jQ=["**/node_modules/**","**/.git/**",`**/${A_}/**`,"**/dist/**"],FQ=jQ.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=W_(J);if(FQ.some((K)=>K.match(Y)))continue;let W=W_(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=W_(_);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=W_(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,F=z.get(C);if(!F){let i=await D.text(),a=G_(i);X.push({filePath:C,contentHash:a,mtimeMs:T,size:S});continue}if(F.mtimeMs===T&&F.size===S){K.push({filePath:C,contentHash:F.contentHash,mtimeMs:T,size:S});continue}let P=await D.text(),x=G_(P);if(x===F.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 F(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 F(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,k=Q.slice(E.start,E.end),v=E.type==="Identifier"?E.name:void 0,u=v?W.get(v):void 0,p={kind:"member",object:k,property:R.value};if(u)p.importSource=u.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)=>F(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)=>F(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:F(U.argument,A+1)});continue}let G={kind:"property",key:M(U.key,U.computed,A+1),value:F(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 F(U,A+1)})};if(H.type==="SpreadElement")return{kind:"spread",argument:F(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 F(H.expression,A);if(H.type==="ChainExpression")return F(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)=>F(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:k}=H,v="name"in E&&typeof E.name==="string"?E.name:"unknown",u="typeAnnotation"in E?E.typeAnnotation:null,p=u?I(u):void 0,X_=i(u),V_=Q.slice(k.start,k.end),e_="decorators"in E&&Array.isArray(E.decorators)?E.decorators:[],x_=P(e_),h_={name:v,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 J_(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 k=L.params.map(x),v=I(L.returnType),u=P(U.decorators??[]),p={kind:"method",name:O,span:w(B.start,B.end),isExported:!1,methodKind:R,modifiers:E,parameters:k.length>0?k:void 0,returnType:v};if(G)p.key=G;if(u.length>0)p.decorators=u;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?F(R):void 0,k=P(U.decorators),v={kind:"property",name:O,span:w(B.start,B.end),isExported:!1,modifiers:L,returnType:q,initializer:E};if(G)v.key=G;if(k.length>0)v.decorators=k;A.push(v)}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=J_(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=J_(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,k,v;if(L)if(L.type==="FunctionExpression"||L.type==="ArrowFunctionExpression"){R="function";let X_=L;E=X_.params.map(x),k=I(X_.returnType)}else v=F(L);let u=[],p={kind:R,name:q,span:w(O.start,O.end),isExported:A,modifiers:u,parameters:E,returnType:k};if(v)p.initializer=v;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=J_(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",k="name"in R&&typeof R.name==="string"?R.name:("value"in R)&&typeof R.value==="string"?R.value:"unknown",v=q.initializer?F(q.initializer):void 0,u={kind:"property",name:k,span:w(q.start,q.end),isExported:!1,modifiers:[]};if(E)u.key=X(R,0);if(v)u.initializer=v;return u});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 j0(_){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 F0,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=W_(F0(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(W_(F0(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(W_(F0(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,F=Z.importName.kind;if(F==="All"||F==="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 F,P;if(D==="ImportDefaultSpecifier")F="default",P=I.local.name;else if(D==="ImportNamespaceSpecifier")F="*",P=I.local.name,T.importKind="namespace";else F=W0(I.imported),P=I.local.name;Y.push({type:S?"type-references":"imports",srcFilePath:$,srcSymbolName:P,...C,dstSymbolName:F,...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 F of T){let P=q_(W,F);if(X){let x=c(P,X);if(Z.has(`${x}::${P}`))return[F]}else if(Z.has(`${Q}::${P}`))return[F]}return[]}:void 0,K),C=[];for(let I of w){if(I.dstFilePath===null){let F=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:F,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}`,F=I.indexOf(T),P;if(F>=0){let x=X.start+F,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),F=X.start+2+V+(T>=0?T:0),P=X.start+2+V+M.length,x=Z0(J,F,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),F=Z0(J,T,X.end),P=g0(Y,w.line,3),x={tag:C,value:I,source:"line",span:F,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},F=new Map;for(let P of D){let x=S(P,_);if(!x)continue;let i=F.get(x)??[];i.push(P),F.set(x,i)}for(let P of I){if(Z.has(P))continue;let x=S(P,$);if(!x)continue;let i=F.get(x);if(!i)continue;let a=i.filter((J_)=>!X.has(J_));if(!a.length)continue;let Q_=a[0];if(a.length>1){let J_=T(P,$),I_=Math.abs(T(Q_,_)-J_);for(let M_=1;M_<a.length;M_++){let U_=Math.abs(T(a[M_],_)-J_);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((F)=>F.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:F}=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=[],k=[];for(let u of Z)try{let p=v_(U,u.filePath),X_=Bun.file(p),V_=await X_.text(),e_=u.contentHash||G_(V_),x_=c(u.filePath,O);J.upsertFile({project:x_,filePath:u.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;k.push({filePath:u.filePath,text:V_,contentHash:e_,parsed:ZQ,project:x_})}catch(p){this.logger.error(`[IndexCoordinator] Failed to prepare ${u.filePath}:`,p),E.push(u.filePath)}let v=new Set;for(let u of O)for(let[p]of J.getFilesMap(u.project))v.add(`${u.project}::${p}`);return z.transaction(()=>{for(let u of k){if(j0({parsed:u.parsed,project:u.project,filePath:u.filePath,contentHash:u.contentHash,symbolRepo:Y}),q+=v0({ast:u.parsed.program,project:u.project,filePath:u.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:v,boundaries:O,module:u.parsed.module}),T)R+=u0({parsed:u.parsed,project:u.project,filePath:u.filePath,annotationRepo:T});G.set(u.filePath,u.parsed),L+=Y.getFileSymbols(u.project,u.filePath).length}}),{symbols:L,relations:q,annotations:R,failedFiles:E}},a=0,Q_=0,J_=[];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),k=await Promise.allSettled(E.map(async(v)=>{let u=v_(U,v.filePath),p=Bun.file(u),X_=await p.text(),V_=v.contentHash||G_(X_);return{filePath:v.filePath,text:X_,contentHash:V_,mtimeMs:p.lastModified,size:p.size}}));for(let v=0;v<k.length;v++){let u=k[v];if(u.status==="fulfilled")L.push(u.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",u.reason),J_.push(E[v].filePath)}}let q=[];z.transaction(()=>{for(let k of L){let v=c(k.filePath,O);J.deleteFile(v,k.filePath)}for(let k of X){let v=c(k,O);if(Y.deleteFileSymbols(v,k),W.deleteFileRelations(v,k),W.deleteIncomingRelations(v,k),T)T.deleteFileAnnotations(v,k);J.deleteFile(v,k)}for(let k of L){let v=c(k.filePath,O);J.upsertFile({project:v,filePath:k.filePath,mtimeMs:k.mtimeMs,size:k.size,contentHash:k.contentHash,updatedAt:new Date().toISOString(),lineCount:k.text.split(`
7
+ `).length})}let R=new Set;for(let k of O)for(let[v]of J.getFilesMap(k.project))R.add(`${k.project}::${v}`);let E=this.opts.parseSourceFn??g_;for(let k of L){let v=c(k.filePath,O),u;try{let p=E(v_(U,k.filePath),k.text);if(R1(p))throw p.data;u=p}catch(p){this.logger.error(`[IndexCoordinator] Failed to parse ${k.filePath}:`,p),J_.push(k.filePath);continue}if(q.push({filePath:k.filePath,parsed:u}),j0({parsed:u,project:v,filePath:k.filePath,contentHash:k.contentHash,symbolRepo:Y}),T)x+=u0({parsed:u,project:v,filePath:k.filePath,annotationRepo:T});Q_+=v0({ast:u.program,project:v,filePath:k.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:R,boundaries:O,module:u.module}),a+=Y.getFileSymbols(v,k.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,J_=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(F){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(()=>{F.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)F.pruneOlderThan(q.project,L)}catch(q){this.logger.error("[IndexCoordinator] changelog pruning failed:",q)}}}let A=new Set(J_),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:J_,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 j1(_,$){_.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 F1(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 F1{#$;#_;#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 F=_.getTypeOfSymbolAtLocation(S,T);w.push({name:S.getName(),type:L_(_,F,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,jJ=1;function FJ(_){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=FJ(K.parent);let V=Q&&!!(_.flags&C_.SymbolFlags.Alias)?Q.getAliasedSymbol(_):_;if($<jJ){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 j from"typescript";function l0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(kJ($))return!0;return!1}function kJ(_){if(!j.canHaveModifiers(_))return!1;return j.getModifiers(_)?.some((Q)=>Q.kind===j.SyntaxKind.DeclareKeyword)??!1}function n0(_){let $=(J,Y)=>({kind:J,pos:Y.getStart(),end:Y.getEnd()}),Q=_.parent;while(Q){if(j.isSourceFile(Q)||j.isModuleDeclaration(Q))return $("module",Q);if(j.isFunctionLike(Q))return $("function",Q);if(j.isClassStaticBlockDeclaration(Q))return $("function",Q);if(j.isPropertyDeclaration(Q))return $("function",Q);if(j.isBlock(Q)){let J=Q.parent;if(J&&(j.isFunctionLike(J)||j.isClassStaticBlockDeclaration(J)))return $("function",J);return $("block",Q)}if(j.isForStatement(Q)||j.isForInStatement(Q)||j.isForOfStatement(Q)||j.isCatchClause(Q)||j.isCaseBlock(Q)||j.isWithStatement(Q))return $("block",Q);Q=Q.parent}return $("module",_.getSourceFile())}function i0(_){let $=_.parent;if(!$)return;if(j.isVariableDeclaration($)&&$.name===_)return"declaration";if(j.isParameter($)&&$.name===_)return"declaration";if(j.isBindingElement($)&&$.name===_)return"declaration";if((j.isForOfStatement($)||j.isForInStatement($))&&$.initializer===_)return"assignment";if((j.isPrefixUnaryExpression($)||j.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===j.SyntaxKind.PlusPlusToken||$.operator===j.SyntaxKind.MinusMinusToken))return"update";let Q=_;while(Q.parent&&j.isParenthesizedExpression(Q.parent))Q=Q.parent;let J=Q.parent;if(J&&j.isBinaryExpression(J)&&J.left===Q)return vJ(J.operatorToken.kind);if(gJ(_))return"assignment";return}function vJ(_){switch(_){case j.SyntaxKind.EqualsToken:return"assignment";case j.SyntaxKind.PlusEqualsToken:case j.SyntaxKind.MinusEqualsToken:case j.SyntaxKind.AsteriskEqualsToken:case j.SyntaxKind.AsteriskAsteriskEqualsToken:case j.SyntaxKind.SlashEqualsToken:case j.SyntaxKind.PercentEqualsToken:case j.SyntaxKind.LessThanLessThanEqualsToken:case j.SyntaxKind.GreaterThanGreaterThanEqualsToken:case j.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case j.SyntaxKind.AmpersandEqualsToken:case j.SyntaxKind.BarEqualsToken:case j.SyntaxKind.CaretEqualsToken:return"compound-assignment";case j.SyntaxKind.AmpersandAmpersandEqualsToken:case j.SyntaxKind.BarBarEqualsToken:case j.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function gJ(_){let $=_.parent;if(!$)return!1;if(!(j.isShorthandPropertyAssignment($)&&$.name===_||j.isPropertyAssignment($)&&$.initializer===_||j.isArrayLiteralExpression($)||j.isSpreadAssignment($)&&$.expression===_||j.isSpreadElement($)&&$.expression===_))return!1;let J=$;while(J.parent){let Y=J.parent;if(j.isBinaryExpression(Y)&&Y.left===J&&Y.operatorToken.kind===j.SyntaxKind.EqualsToken)return!0;if(j.isObjectLiteralExpression(Y)||j.isArrayLiteralExpression(Y)||j.isPropertyAssignment(Y)||j.isShorthandPropertyAssignment(Y)||j.isSpreadAssignment(Y)||j.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),F=i0(I);return{filePath:_.fileName,position:D,line:S+1,column:T,isDefinition:K.has(I),isWrite:F!==void 0,writeKind:F,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 j_,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(j_(H_.project,_),j_(H_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(H_).where(P1(_.project?j_(H_.project,_.project):void 0,_.tag?j_(H_.tag,_.tag):void 0,_.filePath?j_(H_.filePath,_.filePath):void 0,_.symbolName?j_(H_.symbolName,_.symbolName):void 0,_.source?j_(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(Y_).values($.slice(Q,Q+x1)).run()}getSince(_){return this.db.drizzleDb.select().from(Y_).where(f1(P_(Y_.project,_.project),lJ(Y_.changedAt,_.since),_.symbolName?P_(Y_.symbolName,_.symbolName):void 0,_.changeTypes?.length?o_`${Y_.changeType} IN (${o_.join(_.changeTypes.map(($)=>o_`${$}`),o_`, `)})`:void 0,_.filePath?P_(Y_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:P_(Y_.isFullIndex,0),_.indexRunId?P_(Y_.indexRunId,_.indexRunId):void 0,_.afterId?dJ(Y_.id,_.afterId):void 0)).orderBy(Y_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(Y_).where(f1(P_(Y_.project,_),o_`${Y_.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 g(_,$,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 F=M.get(T)??new Set;F.add(D),M.set(T,F)}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 F_(_,$){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 g(_,"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 g(_,"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 g(_,"search","getAffected",()=>{return F_(_,Q).getAffectedByChange($.map((Y)=>K_(_.projectRoot,Y)))})}async function l1(_,$){return g(_,"search","hasCycle",()=>{return F_(_,$).hasCycle()})}async function n1(_,$){return g(_,"search","getImportGraph",()=>{return F_(_,$).getAdjacencyList()})}async function i1(_,$,Q){return g(_,"search","getTransitiveDependencies",()=>{return F_(_,Q).getTransitiveDependencies(K_(_.projectRoot,$))})}async function c1(_,$,Q){return g(_,"search","getTransitiveDependents",()=>{return F_(_,Q).getTransitiveDependents(K_(_.projectRoot,$))})}async function a1(_,$,Q){return g(_,"search","getCyclePaths",()=>{return F_(_,$).getCyclePaths(Q)})}async function s1(_,$,Q){return g(_,"search","getFanMetrics",()=>{let J=F_(_,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=j1,discoverProjectsFn:I=$0,parseSourceFn:D=g_,extractSymbolsFn:S=S_,extractRelationsFn:T=c_,symbolSearchFn:F=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:J_,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=J_??!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:F,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 k of L.onRoleChangedCallbacks)try{k("owner")}catch(v){L.logger.error("[Gildash] onRoleChanged callback threw:",v)}clearInterval(L.timer),L.timer=null;try{await o1(L,{isWatchMode:!0})}catch(k){if(L.logger.error("[Gildash] owner promotion failed, reverting to reader",k),L.role="reader",L.timer!==null)clearInterval(L.timer),L.timer=null;if(L.watcher){let v=await L.watcher.close();if(t_(v))L.logger.error("[Gildash] watcher close error during promotion rollback",v.data);L.watcher=null}if(L.coordinator)await L.coordinator.shutdown().catch((v)=>L.logger.error("[Gildash] coordinator shutdown error during promotion rollback",v)),L.coordinator=null;try{L.releaseWatcherRoleFn(L.db,process.pid)}catch(v){L.logger.error("[Gildash] failed to release watcher role during promotion rollback",v)}L.timer=setInterval(R,r1)}}}catch(E){q++;let k=E instanceof N?E:new N("watcher","Gildash: healthcheck error",{cause:E});for(let v of L.onErrorCallbacks)try{v(k)}catch(u){L.logger.error("[Gildash] onError callback threw:",u)}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((v)=>L.logger.error("[Gildash] close error during healthcheck shutdown",v))}};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 g(_,"store","getStats",()=>_.symbolRepo.getStats($??_.defaultProject))}function _1(_,$){return g(_,"search","searchSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function z$(_,$){return g(_,"search","searchRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:_.defaultProject,query:$}))}function X$(_,$){return g(_,"search","searchAllSymbols",()=>_.symbolSearchFn({symbolRepo:_.symbolRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function U$(_,$){return g(_,"search","searchAllRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:void 0,query:$}))}function V$(_,$){return g(_,"store","listIndexedFiles",()=>_.fileRepo.getAllFiles($??_.defaultProject))}function H$(_,$,Q){return g(_,"search","getInternalRelations",()=>_.relationSearchFn({relationRepo:_.relationRepo,projectRoot:_.projectRoot,project:Q??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}}))}function K$(_,$,Q,J){return g(_,"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 g(_,"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 g(_,"store","getFileInfo",()=>_.fileRepo.getFile(Q??_.defaultProject,K_(_.projectRoot,$)))}function L$(_,$,Q){return _1(_,{filePath:$,project:Q??void 0,limit:1e4})}function B$(_,$,Q){return g(_,"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 b 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=b.isAbsolute(Q)?Q:b.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 g(_,"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 g(_,"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 g(_,"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 g(_,"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 g(_,"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 g(_,"semantic","getFileTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(Q)})}function q$(_,$,Q,J){return g(_,"semantic","getResolvedTypeAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=b.isAbsolute($)?$:b.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(Y,Q,J);if(W===null)return null;return _.semanticLayer.collectTypeAt(Y,W)})}function N$(_,$){return g(_,"semantic","isTypeAssignableToAt",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=b.isAbsolute($.source.filePath)?$.source.filePath:b.resolve(_.projectRoot,$.source.filePath),J=b.isAbsolute($.target.filePath)?$.target.filePath:b.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 g(_,"search","getSemanticModuleInterface",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");return _.semanticLayer.getModuleInterface($)})}function S$(_,$,Q){return g(_,"semantic","getBaseTypes",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(J,Q)})}function T$(_,$,Q){return g(_,"semantic","getResolvedTypesAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(J,Q)})}function E$(_,$,Q){return g(_,"semantic","getExpressionTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.collectAtSpan(J,Q)})}function j$(_,$,Q,J){return g(_,"semantic","isThenableAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.isThenableAtSpan(Y,Q,J)})}function F$(_,$,Q){return g(_,"semantic","getContextualCallReturnsAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.contextualCallReturnsAtSpan(J,Q)})}function k$(_,$,Q,J,Y){return g(_,"semantic","isTypeAssignableToTypeAtSpan",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtSpan(W,Q,J,Y)})}function v$(_,$,Q){return g(_,"semantic","getResolvedTypeAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(J,Q)})}function g$(_,$,Q){return g(_,"semantic","getSemanticReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(J,Q)})}function u$(_,$,Q){return g(_,"semantic","getEnrichedReferencesAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(J,Q)})}function b$(_,$){return g(_,"semantic","getFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(Q)})}function P$(_,$){return g(_,"semantic","getFileBindingsBatch",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=$.map((W)=>({orig:W.filePath,abs:b.isAbsolute(W.filePath)?W.filePath:b.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 g(_,"semantic","getStandaloneFileBindings",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.getStandaloneFileBindings(J,Q)})}function f$(_,$,Q){return g(_,"semantic","notifyFileChanged",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);_.semanticLayer.notifyFileChanged(J,Q)})}function x$(_,$){return g(_,"semantic","notifyFileDeleted",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Q=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);_.semanticLayer.notifyFileDeleted(Q)})}function h$(_,$,Q){return g(_,"semantic","getImplementationsAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(J,Q)})}function m$(_,$,Q,J,Y){return g(_,"semantic","isTypeAssignableToAtPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=b.isAbsolute($)?$:b.resolve(_.projectRoot,$),z=b.isAbsolute(J)?J:b.resolve(_.projectRoot,J);return _.semanticLayer.isTypeAssignableTo(W,Q,z,Y)})}function p$(_,$,Q,J,Y){return g(_,"semantic","isTypeAssignableToType",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,Q,J,Y)})}function d$(_,$,Q,J,Y){return g(_,"semantic","isTypeAssignableToTypeAtPositions",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let W=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,Q,J,Y)})}function l$(_,$,Q,J){return g(_,"semantic","lineColumnToPosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(Y,Q,J)})}function n$(_,$,Q,J){return g(_,"semantic","findNamePosition",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let Y=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(Y,Q,J)})}function i$(_,$,Q){return g(_,"semantic","getSymbolNode",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(J,Q)})}function c$(_,$,Q){return g(_,"semantic","getSemanticDiagnostics",()=>{if(!_.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");let J=b.isAbsolute($)?$:b.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 g(_,"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 g(_,"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 g(_,"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 j$(this._ctx,_,$,Q)}getContextualCallReturnsAtSpan(_,$){return F$(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 j2,parseAndWalk as F2,ScopeTracker as k2}from"oxc-walker";export{j2 as walk,T2 as visitorKeys,y0 as symbolSearch,f0 as relationSearch,x0 as patternSearch,g_ as parseSource,F2 as parseAndWalk,W_ 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};
@@ -132,6 +132,15 @@ export interface ExpressionTemplate {
132
132
  export interface ExpressionUnresolvable {
133
133
  kind: 'unresolvable';
134
134
  sourceText: string;
135
+ /**
136
+ * Why the node could not be structurally represented.
137
+ *
138
+ * - `'depth-cap'` — the node was truncated at the extractor's recursion depth
139
+ * limit for stack safety, *not* because its form is unsupported. The real
140
+ * value is recoverable by re-parsing `sourceText`.
141
+ * - `undefined` — the node's syntactic form is genuinely not representable.
142
+ */
143
+ reason?: 'depth-cap';
135
144
  }
136
145
  /**
137
146
  * The kind of a symbol extracted from TypeScript source.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zipbul/gildash",
3
- "version": "0.34.1",
3
+ "version": "0.34.3",
4
4
  "description": "TypeScript code indexing and dependency graph engine for Bun",
5
5
  "license": "MIT",
6
6
  "repository": {