@zipbul/gildash 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- var g1=Object.defineProperty;var R1=(_)=>_;function T1(_,$){this[_]=R1.bind(null,$)}var F1=(_,$)=>{for(var J in $)g1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:T1.bind($,J)})};var P$=import.meta.require;import{isErr as i_}from"@zipbul/result";import k_ from"path";import{existsSync as $Q}from"fs";import{err as y$,isErr as b1}from"@zipbul/result";import{Database as f1}from"bun:sqlite";import{mkdirSync as P1,unlinkSync as x$,existsSync as m$}from"fs";import{dirname as y1,join as n$}from"path";import{drizzle as x1}from"drizzle-orm/bun-sqlite";import{migrate as m1}from"drizzle-orm/bun-sqlite/migrator";class H extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var B_=".gildash",p_="gildash.db";var Y$={};F1(Y$,{watcherOwner:()=>v1,symbols:()=>m,symbolChangelog:()=>t,relations:()=>E,files:()=>s,annotations:()=>Z_});import{sql as G1}from"drizzle-orm";import{sqliteTable as u_,text as f,integer as a,real as j1,index as Q_,primaryKey as k1,foreignKey as Z$,check as E1}from"drizzle-orm/sqlite-core";var s=u_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:j1("mtime_ms").notNull(),size:a("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:a("line_count")},(_)=>[k1({columns:[_.project,_.filePath]})]),m=u_("symbols",{id:a("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind").notNull(),name:f("name").notNull(),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),isExported:a("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[Q_("idx_symbols_project_file").on(_.project,_.filePath),Q_("idx_symbols_project_kind").on(_.project,_.kind),Q_("idx_symbols_project_name").on(_.project,_.name),Q_("idx_symbols_fingerprint").on(_.project,_.fingerprint),Z$({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),E=u_("relations",{id:a("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type").notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:a("is_external").notNull().default(0)},(_)=>[Q_("idx_relations_src").on(_.project,_.srcFilePath),Q_("idx_relations_dst").on(_.dstProject,_.dstFilePath),Q_("idx_relations_type").on(_.project,_.type),Q_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),Q_("idx_relations_specifier").on(_.project,_.specifier),Z$({columns:[_.project,_.srcFilePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),Z_=u_("annotations",{id:a("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source").notNull(),symbolName:f("symbol_name"),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),indexedAt:f("indexed_at").notNull()},(_)=>[Q_("idx_annotations_project_file").on(_.project,_.filePath),Q_("idx_annotations_project_tag").on(_.project,_.tag),Q_("idx_annotations_project_symbol").on(_.project,_.symbolName),Z$({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),t=u_("symbol_changelog",{id:a("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:a("is_full_index").notNull().default(0),indexRunId:f("index_run_id").notNull()},(_)=>[Q_("idx_changelog_project_changed_at").on(_.project,_.changedAt),Q_("idx_changelog_project_name").on(_.project,_.symbolName),Q_("idx_changelog_project_run").on(_.project,_.indexRunId)]),v1=u_("watcher_owner",{id:a("id").primaryKey(),pid:a("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("instance_id")},(_)=>[E1("watcher_owner_singleton",G1`${_.id} = 1`)]);class X${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=n$(_.projectRoot,B_,p_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{P1(y1(this.dbPath),{recursive:!0}),this.client=new f1(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=x1(this.client,{schema:Y$}),m1(this.drizzle,{migrationsFolder:n$(import.meta.dirname,"migrations")});let _=this.client.prepare("PRAGMA foreign_key_check").all();if(_.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(_.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(_){if(this.isCorruptionError(_)&&m$(this.dbPath)){this.closeClient(),x$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(m$(Q))x$(Q)}let $=this.open();if(b1($))return y$(new H("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return y$(new H("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as v_,and as h$}from"drizzle-orm";class U${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(s).where(h$(v_(s.project,_),v_(s.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(s).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[s.project,s.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(s).where(v_(s.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(s).where(h$(v_(s.project,_),v_(s.filePath,$))).run()}}import{eq as r,and as I_,sql as l_,count as n1}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i$=50;class V${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(m).where(I_(r(m.project,_),r(m.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),W=Q.map((Y)=>({project:_,filePath:$,kind:Y.kind??"unknown",name:Y.name??"",startLine:Y.startLine??0,startColumn:Y.startColumn??0,endLine:Y.endLine??0,endColumn:Y.endColumn??0,isExported:Y.isExported??0,signature:Y.signature??null,fingerprint:Y.fingerprint??null,detailJson:Y.detailJson??null,contentHash:J,indexedAt:Y.indexedAt??z,resolvedType:Y.resolvedType??null,structuralFingerprint:Y.structuralFingerprint??null}));for(let Y=0;Y<W.length;Y+=i$)this.db.drizzleDb.insert(m).values(W.slice(Y,Y+i$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(m).where(I_(r(m.project,_),r(m.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(m).where(I_(l_`${m.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,r(m.project,_),J.kind?r(m.kind,J.kind):void 0)).orderBy(m.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(m).where(I_(r(m.project,_),r(m.kind,$))).orderBy(m.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:n1(),fileCount:l_`COUNT(DISTINCT ${m.filePath})`}).from(m).where(r(m.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(m).where(I_(r(m.project,_),r(m.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(m).where(I_(r(m.project,_),r(m.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(m).where(I_(_.ftsQuery?l_`${m.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?r(m.name,_.exactName):void 0,_.project!==void 0?r(m.project,_.project):void 0,_.kind?r(m.kind,_.kind):void 0,_.filePath!==void 0?r(m.filePath,_.filePath):void 0,_.isExported!==void 0?r(m.isExported,_.isExported?1:0):void 0,_.decorator?l_`${m.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?r(m.resolvedType,_.resolvedType):void 0)).orderBy(m.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new H("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Y=$.limit(W).all();if(Q=Y.filter((Z)=>J.test(Z.name)),Q.length>=_.limit||Y.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as h,and as O_,isNull as d$,or as h1}from"drizzle-orm";var b_={project:E.project,type:E.type,srcFilePath:E.srcFilePath,srcSymbolName:E.srcSymbolName,dstProject:E.dstProject,dstFilePath:E.dstFilePath,dstSymbolName:E.dstSymbolName,metaJson:E.metaJson,specifier:E.specifier,isExternal:E.isExternal};class H${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(E).where(O_(h(E.project,_),h(E.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(E).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(b_).from(E).where(O_(h(E.project,_),h(E.srcFilePath,$),h1(h(E.srcSymbolName,J),d$(E.srcSymbolName)))).all();return this.db.drizzleDb.select(b_).from(E).where(O_(h(E.project,_),h(E.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(b_).from(E).where(O_(h(E.dstProject,$),h(E.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(b_).from(E).where(O_(h(E.project,_),h(E.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(E).where(O_(h(E.project,_),h(E.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(E).where(O_(h(E.dstProject,_),h(E.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(b_).from(E).where(O_(_.project!==void 0?h(E.project,_.project):void 0,_.srcFilePath!==void 0?h(E.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?h(E.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?h(E.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?h(E.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?h(E.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?h(E.type,_.type):void 0,_.specifier!==void 0?h(E.specifier,_.specifier):void 0,_.isExternal!==void 0?h(E.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:W,newDstProject:Y}=_,Z=Q===null?O_(h(E.dstProject,$),h(E.dstFilePath,J),d$(E.dstSymbolName)):O_(h(E.dstProject,$),h(E.dstFilePath,J),h(E.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Y!==void 0)X.dstProject=Y;this.db.drizzleDb.update(E).set(X).where(Z).run()}}import{err as l$}from"@zipbul/result";import{subscribe as i1}from"@parcel/watcher";import O$ from"path";import p$ from"path";function z_(_){return _.replaceAll("\\","/")}function f_(_,$){return z_(p$.relative(_,$))}function R_(_,$){return z_(p$.resolve(_,$))}var d1=["**/.git/**",`**/${B_}/**`,"**/dist/**","**/node_modules/**"],p1=new Set(["package.json","tsconfig.json"]);function l1(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class M${#_;#$;#J;#Z;#z;#W;constructor(_,$=i1,J=console){this.#$=_.projectRoot,this.#J=[...d1,..._.ignorePatterns??[]],this.#Z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#z=$,this.#W=J}async start(_){try{this.#_=await this.#z(this.#$,($,J)=>{if($){this.#W.error(new H("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=z_(O$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let W=O$.basename(z),Y=O$.extname(z).toLowerCase();if(!p1.has(W)&&!this.#Z.has(Y))continue;if(z.endsWith(".d.ts"))continue;_({eventType:l1(Q.type),filePath:z})}}catch(Q){this.#W.error(new H("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return l$(new H("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return l$(new H("watcher","Failed to close watcher",{cause:_}))}}}import L$ from"path";var c1=["**/node_modules/**","**/.git/**",`**/${B_}/**`,"**/dist/**"],a1=c1.map((_)=>new Bun.Glob(_));function s1(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function c_(_,$=s1){let J=[];for await(let Q of $(_)){let z=z_(Q);if(a1.some((M)=>M.match(z)))continue;let W=z_(L$.dirname(Q)),Y=L$.join(_,Q),Z=await Bun.file(Y).json(),X=typeof Z?.name==="string"&&Z.name.length>0?Z.name:L$.basename(W==="."?_:W);J.push({dir:W,project:X})}return J.sort((Q,z)=>z.dir.length-Q.dir.length),J}function l(_,$,J="default"){let Q=z_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import P_ from"path";var K_=new Map;async function r1(_){let $=Bun.file(_);if(!await $.exists())return null;try{let J=await $.text(),Q=Bun.JSONC.parse(J);return typeof Q==="object"&&Q!==null?Q:null}catch{return null}}function o1(_,$){if($.startsWith(".")){let J=P_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return P_.resolve(_,"node_modules",$)}async function c$(_,$=5){if($<=0)return null;let J=await r1(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=o1(P_.dirname(_),Q),W=await c$(z,$-1);if(!W)return J;let Y=typeof W.compilerOptions==="object"&&W.compilerOptions!==null?W.compilerOptions:{},Z=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...W,...J,compilerOptions:{...Y,...Z}}}async function y_(_){if(K_.has(_))return K_.get(_)??null;let $=P_.join(_,"tsconfig.json"),J=await c$($);if(!J)return K_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return K_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,W=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!W)return K_.set(_,null),null;let Y=z?P_.resolve(_,z):_,Z=new Map;if(W)for(let[M,U]of Object.entries(W)){if(!Array.isArray(U))continue;let w=U.filter((A)=>typeof A==="string");Z.set(M,w)}let X={baseUrl:Y,paths:Z};return K_.set(_,X),X}function a_(_){if(_){K_.delete(_);return}K_.clear()}function V_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Q0}from"@zipbul/result";import{err as t1}from"@zipbul/result";import{parseSync as e1}from"oxc-parser";function T_(_,$,J,Q=e1){try{let z={preserveParens:!1,...J},W=Q(_,$,z);return{filePath:_,program:W.program,errors:W.errors,comments:W.comments,sourceText:$,module:W.module}}catch(z){return t1(new H("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{join as _J}from"path";function $J(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function a$(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z,scanFilesFn:W=$J}=_,Y=z.getFilesMap(),Z=new Set,X=[],M=[],U=Q.map((A)=>new Bun.Glob(A));for await(let A of W($,J)){let S=z_(A);if(!J.some((d)=>S.endsWith(d)))continue;if(S.startsWith("node_modules/")||S.includes("/node_modules/"))continue;if(U.some((d)=>d.match(S)))continue;Z.add(S);let D=_J($,S),q=Bun.file(D),{size:R,lastModified:T}=q,b=Y.get(S);if(!b){let d=await q.text(),c=V_(d);X.push({filePath:S,contentHash:c,mtimeMs:T,size:R});continue}if(b.mtimeMs===T&&b.size===R){M.push({filePath:S,contentHash:b.contentHash,mtimeMs:T,size:R});continue}let v=await q.text(),P=V_(v);if(P===b.contentHash)M.push({filePath:S,contentHash:P,mtimeMs:T,size:R});else X.push({filePath:S,contentHash:P,mtimeMs:T,size:R})}let w=[];for(let A of Y.keys())if(!Z.has(A))w.push(A);return{changed:X,unchanged:M,deleted:w}}function x_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
3
- `)$.push(J+1);return $}function U_(_,$){let J=0,Q=_.length-1;while(J<Q){let z=J+Q+1>>1;if(_[z]<=$)J=z;else Q=z-1}return{line:J+1,column:$-_[J]}}import{err as JJ}from"@zipbul/result";import{parse as QJ}from"comment-parser";function s_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=QJ(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((z)=>({tag:z.tag??"",name:z.name??"",type:z.type??"",description:z.description??"",optional:z.optional??!1,...z.default!==void 0?{default:z.default}:{}}))}}catch($){return JJ(new H("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as zJ}from"@zipbul/result";function WJ(_){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 F_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...F_(J.argument));else $.push(...F_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...F_(J.argument));else $.push(...F_(J))}return $}if(_.type==="AssignmentPattern")return F_(_.left);return[]}function ZJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let z of J.entries){let W=z.localName.value,Y=z.importName.kind==="Name"?z.importName.name:void 0,Z={specifier:Q};if(Y&&Y!==W)Z.originalName=Y;$.set(W,Z)}}return $}function C_(_){let{program:$,sourceText:J,comments:Q}=_,z=x_(J),W=ZJ(_),Y=Q.filter((L)=>L.type==="Block"&&L.value.startsWith("*")).sort((L,u)=>L.end-u.end),Z=$.body.map((L)=>L.start).sort((L,u)=>L-u);function X(L,u){if(u)return"computed";if(L.type==="PrivateIdentifier")return"private";if(L.type==="Identifier")return;return"literal"}function M(L,u){if(u)return J.slice(L.start,L.end);return WJ(L)}function U(L,u){return{start:U_(z,L),end:U_(z,u)}}function w(L){let u=0,N=Y.length-1,B=-1;while(u<=N){let O=u+N>>>1;if(Y[O].end<=L)B=O,u=O+1;else N=O-1}if(B<0)return;let V=Y[B];u=0,N=Z.length-1;while(u<=N){let O=u+N>>>1,K=Z[O];if(K<=V.end)u=O+1;else if(K>=L)N=O-1;else return}return`/*${V.value}*/`}function A(L){if(!L)return;let u="typeAnnotation"in L&&L.typeAnnotation?L.typeAnnotation:L;return J.slice(u.start,u.end)}let S=8;function D(L){if(L.type==="Identifier")return W.get(L.name);if(L.type==="MemberExpression"){let u=L.object;if(u.type==="Identifier")return W.get(u.name)}return}function q(L,u=0){if(u>=S)return{kind:"unresolvable",sourceText:J.slice(L.start,L.end)};let N=L.type;if(N==="Literal"){let B=L.value;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:J.slice(L.start,L.end)}}if(N==="Identifier"){let B=L.name;if(B==="undefined")return{kind:"undefined",value:null};let V=W.get(B),O={kind:"identifier",name:B};if(V){if(O.importSource=V.specifier,V.originalName)O.originalName=V.originalName}return O}if(N==="MemberExpression"){if(L.computed){let I=L.property;if(I.type==="Literal"&&typeof I.value==="string"){let F=L.object,G=J.slice(F.start,F.end),k=F.type==="Identifier"?F.name:void 0,j=k?W.get(k):void 0,y={kind:"member",object:G,property:I.value};if(j)y.importSource=j.specifier;return y}return{kind:"unresolvable",sourceText:J.slice(L.start,L.end)}}let B=L.object,V=J.slice(B.start,B.end),O=L.property.name??J.slice(L.property.start,L.property.end),K=B.type==="Identifier"?B.name:void 0,C=K?W.get(K):void 0,g={kind:"member",object:V,property:O};if(C)g.importSource=C.specifier;return g}if(N==="CallExpression"){let B=L.callee,V=J.slice(B.start,B.end),K=(L.arguments??[]).map((I)=>q(I,u+1)),C=D(B),g={kind:"call",callee:V,arguments:K};if(C)g.importSource=C.specifier;return g}if(N==="NewExpression"){let B=L.callee,V=J.slice(B.start,B.end),K=(L.arguments??[]).map((I)=>q(I,u+1)),C=D(B),g={kind:"new",callee:V,arguments:K};if(C)g.importSource=C.specifier;return g}if(N==="ObjectExpression")return{kind:"object",properties:(L.properties??[]).map((O)=>{if(O.type==="SpreadElement"){let k=O.argument;return{key:"...",value:{kind:"spread",argument:q(k,u+1)}}}let K=O.key,C=K.name??K.value,g=C!=null?String(C):J.slice(K.start,K.end),I=O.value,F=O.computed||void 0,G=O.shorthand||void 0;return{key:g,value:q(I,u+1),computed:F,shorthand:G}})};if(N==="ArrayExpression")return{kind:"array",elements:(L.elements??[]).map((O)=>{if(!O)return{kind:"undefined",value:null};return q(O,u+1)})};if(N==="SpreadElement"){let B=L.argument;return{kind:"spread",argument:q(B,u+1)}}if(N==="ArrowFunctionExpression"||N==="FunctionExpression"){let V=L.params.map(T),O={kind:"function",sourceText:J.slice(L.start,L.end)};if(V.length>0)O.parameters=V;return O}if(N==="TemplateLiteral"||N==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(L.start,L.end)};if(N==="UnaryExpression"){let{operator:B,argument:V}=L;if(B==="-"&&V.type==="Literal"&&typeof V.value==="number")return{kind:"number",value:-V.value};if(B==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(L.start,L.end)}}if(N==="TSAsExpression"||N==="TSSatisfiesExpression"||N==="TSNonNullExpression"||N==="TSTypeAssertion"||N==="TSInstantiationExpression"||N==="ParenthesizedExpression"||N==="ChainExpression"){let B=L.expression;if(B)return q(B,u)}return{kind:"unresolvable",sourceText:J.slice(L.start,L.end)}}function R(L){if(!L||L.length===0)return[];return L.map((u)=>{let N=u.expression;if(N.type==="CallExpression"){let B=N,V=B.callee,O="name"in V&&typeof V.name==="string"?V.name:("property"in V)&&V.property&&typeof V.property.name==="string"?V.property.name:"unknown",K=B.arguments.map((C)=>q(C));return{name:O,arguments:K.length>0?K:void 0}}if(N.type==="Identifier")return{name:N.name??"unknown"};return{name:J.slice(N.start,N.end)}})}function T(L){if(L.type==="TSParameterProperty"){let N=L;return v(N.parameter,N.decorators)}if(L.type==="RestElement"){let N=L,B=N.argument,O=`...${"name"in B&&typeof B.name==="string"?B.name:"unknown"}`,K=N.typeAnnotation,C=K?A(K):void 0,g={name:O,isOptional:!1};if(C)g.type=C;return g}let u=L;return v(u,u.decorators)}function b(L){if(!L)return;let u="typeAnnotation"in L&&L.typeAnnotation?L.typeAnnotation:null;if(!u)return;let B=u.typeName?.name;if(!B)return;return W.get(B)?.specifier}function v(L,u){if(L.type==="AssignmentPattern"){let{left:I,right:F}=L,G="name"in I&&typeof I.name==="string"?I.name:"unknown",k="typeAnnotation"in I?I.typeAnnotation:null,j=k?A(k):void 0,y=b(k),J_=J.slice(F.start,F.end),W_="decorators"in I&&Array.isArray(I.decorators)?I.decorators:[],E_=R(W_),D_={name:G,isOptional:!0,defaultValue:J_};if(j)D_.type=j;if(y)D_.typeImportSource=y;if(E_.length>0)D_.decorators=E_;return D_}let N="name"in L&&typeof L.name==="string"?L.name:("pattern"in L)&&L.pattern&&typeof L.pattern.name==="string"?L.pattern.name:"unknown",B=!!(("optional"in L)&&L.optional),V="typeAnnotation"in L?L.typeAnnotation:null,O=V?A(V):void 0,K=b(V),C=R(u??[]),g={name:N,isOptional:B};if(O)g.type=O;if(K)g.typeImportSource=K;if(C.length>0)g.decorators=C;return g}function P(L,u){let N=[];if(u?.async)N.push("async");if(L.static)N.push("static");if(L.abstract)N.push("abstract");if(L.readonly)N.push("readonly");if(L.override)N.push("override");if(L.declare)N.push("declare");if(L.const)N.push("const");let B=L.accessibility;if(B==="private")N.push("private");else if(B==="protected")N.push("protected");else if(B==="public")N.push("public");return N}function d(L){if(!L)return;let u=L.params.flatMap((N)=>{let B=N.name.name;return B?[B]:[]});return u.length>0?u:void 0}function c(L){let u=[];if(L.superClass){let B=J.slice(L.superClass.start,L.superClass.end);u.push({kind:"extends",name:B})}let N=L.implements??[];for(let B of N){let V=B.expression,O=J.slice(V.start,V.end);u.push({kind:"implements",name:O})}return u}function Y_(L){let u=[],N=L.extends;for(let B of N){let V=B.expression,O=J.slice(V.start,V.end);u.push({kind:"extends",name:O})}return u}function X_(L){let u=[];for(let N of L)if(N.type==="MethodDefinition"||N.type==="TSAbstractMethodDefinition"){let B=N,V=M(B.key,B.computed),O=X(B.key,B.computed),K=B.value,C=B.kind,g=C==="constructor"?"constructor":C==="get"?"getter":C==="set"?"setter":"method",I=P(B,K);if(N.type==="TSAbstractMethodDefinition"&&!I.includes("abstract"))I.push("abstract");let F=K.params.map(T),G=A(K.returnType),k=R(B.decorators??[]),j={kind:"method",name:V,span:U(N.start,N.end),isExported:!1,methodKind:g,modifiers:I,parameters:F.length>0?F:void 0,returnType:G};if(O)j.keyKind=O;if(k.length>0)j.decorators=k;u.push(j)}else if(N.type==="PropertyDefinition"||N.type==="TSAbstractPropertyDefinition"){let B=N,V=M(B.key,B.computed),O=X(B.key,B.computed),K=P(B);if(N.type==="TSAbstractPropertyDefinition"&&!K.includes("abstract"))K.push("abstract");let C=A(B.typeAnnotation),g=B.value,I=g?q(g):void 0,F=R(B.decorators??[]),G={kind:"property",name:V,span:U(N.start,N.end),isExported:!1,modifiers:K,returnType:C,initializer:I};if(O)G.keyKind=O;if(F.length>0)G.decorators=F;u.push(G)}return u}function H_(L){let u=[];for(let N of L)if(N.type==="TSMethodSignature"){let B=N,V=M(B.key,B.computed),O=X(B.key,B.computed),K=B.params.map(T),C=A(B.returnType),g={kind:"method",name:V,span:U(N.start,N.end),isExported:!1,modifiers:[],methodKind:"method",parameters:K.length>0?K:void 0,returnType:C};if(O)g.keyKind=O;u.push(g)}else if(N.type==="TSPropertySignature"){let B=N,V=M(B.key,B.computed),O=X(B.key,B.computed),K=A(B.typeAnnotation),C={kind:"property",name:V,span:U(N.start,N.end),isExported:!1,modifiers:B.readonly?["readonly"]:[],returnType:K};if(O)C.keyKind=O;u.push(C)}return u}function __(L,u){let N=L.type;if(N==="FunctionDeclaration"||N==="FunctionExpression"||N==="TSDeclareFunction"||N==="TSEmptyBodyFunctionExpression"){let B=L,V=B.id?.name??"default",O=B.params.map(T),K=A(B.returnType),C=P(B,B),g=R(B.decorators??[]),I=d(B.typeParameters),F={kind:"function",name:V,span:U(L.start,L.end),isExported:u,modifiers:C,parameters:O.length>0?O:void 0,returnType:K,decorators:g.length>0?g:void 0};if(I&&I.length>0)F.typeParameters=I;return F}if(N==="ClassDeclaration"||N==="ClassExpression"){let B=L,V=B.id?.name??"default",O=c(B),K=X_(B.body.body),C=R(B.decorators),g=P(B),I=d(B.typeParameters),F={kind:"class",name:V,span:U(L.start,L.end),isExported:u,modifiers:g,heritage:O.length>0?O:void 0,members:K.length>0?K:void 0,decorators:C.length>0?C:void 0};if(I&&I.length>0)F.typeParameters=I;return F}if(N==="VariableDeclaration"){let B=L,V=[];for(let O of B.declarations){let{id:K,init:C}=O;if(K.type==="ObjectPattern"||K.type==="ArrayPattern"){let J_=F_(K);for(let W_ of J_)V.push({kind:"variable",name:W_.name,span:U(W_.start,W_.end),isExported:u,modifiers:[]});continue}let g="name"in K&&typeof K.name==="string"?K.name:"unknown",I="variable",F,G,k;if(C)if(C.type==="FunctionExpression"||C.type==="ArrowFunctionExpression"){I="function";let J_=C;F=J_.params.map(T),G=A(J_.returnType)}else k=q(C);let j=[],y={kind:I,name:g,span:U(O.start,O.end),isExported:u,modifiers:j,parameters:F,returnType:G};if(k)y.initializer=k;V.push(y)}if(V.length===0)return null;if(V.length===1)return V[0];return V}if(N==="TSTypeAliasDeclaration")return{kind:"type",name:L.id.name,span:U(L.start,L.end),isExported:u,modifiers:[]};if(N==="TSInterfaceDeclaration"){let B=L,V=B.id.name,O=Y_(B),K=H_(B.body.body),C=d(B.typeParameters),g={kind:"interface",name:V,span:U(L.start,L.end),isExported:u,modifiers:[],heritage:O.length>0?O:void 0,members:K.length>0?K:void 0};if(C&&C.length>0)g.typeParameters=C;return g}if(N==="TSEnumDeclaration"){let B=L,V=B.id.name,O=P(B),C=B.body.members.map((g)=>{let I=g.id,F="name"in I&&typeof I.name==="string"?I.name:("value"in I)&&typeof I.value==="string"?I.value:"unknown",G=g.initializer,k=G?q(G):void 0,j={kind:"property",name:F,span:U(g.start,g.end),isExported:!1,modifiers:[]};if(k)j.initializer=k;return j});return{kind:"enum",name:V,span:U(L.start,L.end),isExported:u,modifiers:O,members:C.length>0?C:void 0}}if(N==="TSModuleDeclaration"){let B=L,V=B.id.name??B.id.value??"unknown",O=P(B),K=[];if(B.body?.type==="TSModuleBlock")for(let C of B.body.body??[]){if(C.type!=="ExportNamedDeclaration")continue;let g=C.declaration;if(!g)continue;let I=__(g,!1);if(I)if(Array.isArray(I))K.push(...I);else K.push(I)}return{kind:"namespace",name:V,span:U(L.start,L.end),isExported:u,modifiers:O,members:K.length>0?K:void 0}}return null}let $_=[],p=new Set;for(let L of $.body){let u=null,N=L;if(N.type==="ExportNamedDeclaration"){let V=N;if(V.declaration){if(u=__(V.declaration,!0),u&&!Array.isArray(u))u.span=U(V.start,V.end)}else if(!V.source&&V.specifiers)for(let O of V.specifiers){let K=O.local,C="name"in K?K.name:K.value;if(C)p.add(C)}}else if(N.type==="ExportDefaultDeclaration"){let V=N,O=V.declaration;if(O){if(u=__(O,!0),u&&!Array.isArray(u))u.name="id"in O&&O.id&&typeof O.id.name==="string"?O.id.name:"default",u.isExported=!0,u.span=U(V.start,V.end);else if(!u&&"type"in O&&O.type==="Identifier"){let K=O.name;if(K)p.add(K)}}}else{let V=N.type;if(V==="FunctionDeclaration"||V==="TSDeclareFunction"||V==="ClassDeclaration"||V==="VariableDeclaration"||V==="TSTypeAliasDeclaration"||V==="TSInterfaceDeclaration"||V==="TSEnumDeclaration"||V==="TSModuleDeclaration")u=__(N,!1)}let B=Array.isArray(u)?u:u?[u]:[];for(let V of B){let O=L.start,K=w(O);if(K){let C=s_(K);if(!zJ(C))V.jsDoc=C}$_.push(V)}}if(p.size>0){for(let L of $_)if(!L.isExported&&p.has(L.name))L.isExported=!0}return $_}function YJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function XJ(_){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(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),z={name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0};if(J.initializer)z.initializer=J.initializer;if(J.decorators?.length)z.decorators=J.decorators;return z});return Object.keys($).length>0?JSON.stringify($):null}function UJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${V_(J)}`)}return V_($.join("|"))}function s$(_,$,J,Q,z){let W=YJ(_),Y=V_(`${$}|${_.kind}|${W??""}`),Z=UJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:W,fingerprint:Y,detailJson:XJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Z}}function w$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Y=C_($),Z=[];for(let X of Y){Z.push(s$(X,X.name,J,Q,z));for(let M of X.members??[])Z.push(s$(M,`${X.name}.${M.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Z)}import{resolve as B$,dirname as VJ,extname as HJ}from"path";function A_(_,$,J){let Q=(z)=>{let W=HJ(z);if(W===".js")return[z.slice(0,-3)+".ts"];if(W===".mjs")return[z.slice(0,-4)+".mts"];if(W===".cjs")return[z.slice(0,-4)+".cts"];if(W===".ts"||W===".mts"||W===".cts"||W===".d.ts")return[z];return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"]};if($.startsWith(".")){let z=z_(B$(VJ(_),$));return Q(z)}if(J)for(let[z,W]of J.paths){if(W.length===0)continue;let Y=z.indexOf("*");if(Y===-1){if($===z){let Z=[];for(let X of W)Z.push(...Q(z_(B$(J.baseUrl,X))));return Z}}else{let Z=z.slice(0,Y),X=z.slice(Y+1);if($.startsWith(Z)&&(X===""||$.endsWith(X))){let M=$.slice(Z.length,X===""?void 0:$.length-X.length),U=[];for(let w of W)U.push(...Q(z_(B$(J.baseUrl,w.replace("*",M)))));return U}}}return[]}function r$(_,$,J,Q=A_){let z=new Map,W=_.body??[];for(let Y of W){if(Y.type!=="ImportDeclaration")continue;let Z=Y.source?.value??"",X=Q($,Z,J);if(X.length===0)continue;let M=X[0],U=Y.specifiers??[];for(let w of U)switch(w.type){case"ImportSpecifier":z.set(w.local.name,{path:M,importedName:w.imported.name});break;case"ImportDefaultSpecifier":z.set(w.local.name,{path:M,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(w.local.name,{path:M,importedName:"*"});break}}return z}import{Visitor as OJ}from"oxc-parser";function r_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function MJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function N_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Y=W===null&&MJ($);return{resolved:W,isExternal:Y}}function LJ(_,$,J,Q,z){for(let W of _.staticImports){let Y=W.moduleRequest.value,{resolved:Z,isExternal:X}=N_($,Y,J,Q),M=Z===null?{dstFilePath:null,specifier:Y}:{dstFilePath:Z};if(W.entries.length===0){let U={};if(X)U.isExternal=!0;if(Z===null&&!X)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...M,dstSymbolName:null,...Object.keys(U).length>0?{metaJson:JSON.stringify(U)}:{}});continue}for(let U of W.entries){let w=U.isType,A={};if(w)A.isType=!0;if(X)A.isExternal=!0;if(Z===null&&!X)A.isUnresolved=!0;let S,D,q=U.importName.kind;if(q==="Default")S="default",D=U.localName.value;else if(q==="NamespaceObject")S="*",D=U.localName.value,A.importKind="namespace";else S=U.importName.name??"unknown",D=U.localName.value;z.push({type:w?"type-references":"imports",srcFilePath:$,srcSymbolName:D,...M,dstSymbolName:S,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}}}function wJ(_,$,J,Q,z){let W=new Map;for(let Y of _.staticImports)for(let Z of Y.entries)W.set(Z.localName.value,Y.moduleRequest.value);for(let Y of _.staticExports)for(let Z of Y.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:M,isExternal:U}=N_($,X,J,Q),w=Z.exportName.name??"default",A=Z.exportName.kind,S=Z.localName.name??Z.importName.name??w,D=Z.isType,q={isReExport:!0};if(A==="None");else q.specifiers=[{local:S,exported:w}];if(D)q.isType=!0;if(U)q.isExternal=!0;if(M===null&&!U)q.isUnresolved=!0;let R=null,T=null,b=Z.importName.kind;if(b==="All"||b==="AllButDefault"){if(A==="Name"&&w)T=w,q.namespaceAlias=w}else T=S,R=w;z.push({type:D?"type-references":"re-exports",srcFilePath:$,srcSymbolName:R,dstFilePath:M,dstSymbolName:T,metaJson:JSON.stringify(q),...M===null?{specifier:X}:{}})}}function BJ(_,$,J,Q,z){for(let W of _.body){let Y=W;if(Y.type==="ImportDeclaration"){let Z=Y,X=Z.source.value,{resolved:M,isExternal:U}=N_($,X,J,Q),w=Z.importKind==="type",A=Z.specifiers,S=M===null?{dstFilePath:null,specifier:X}:{dstFilePath:M};if(A.length===0){let D={};if(w)D.isType=!0;if(U)D.isExternal=!0;if(M===null&&!U)D.isUnresolved=!0;z.push({type:w?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...S,dstSymbolName:null,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}else for(let D of A){let q=D.type,R=w||q==="ImportSpecifier"&&D.importKind==="type",T={};if(R)T.isType=!0;if(U)T.isExternal=!0;if(M===null&&!U)T.isUnresolved=!0;let b,v;if(q==="ImportDefaultSpecifier")b="default",v=D.local.name;else if(q==="ImportNamespaceSpecifier")b="*",v=D.local.name,T.importKind="namespace";else b=r_(D.imported),v=D.local.name;z.push({type:R?"type-references":"imports",srcFilePath:$,srcSymbolName:v,...S,dstSymbolName:b,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}continue}if(Y.type==="ExportAllDeclaration"){let Z=Y,X=Z.source.value,{resolved:M,isExternal:U}=N_($,X,J,Q),w=Z.exportKind==="type",A=Z.exported,S=A?r_(A):null,D={isReExport:!0};if(w)D.isType=!0;if(U)D.isExternal=!0;if(M===null&&!U)D.isUnresolved=!0;if(S)D.namespaceAlias=S;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:S,metaJson:JSON.stringify(D),...M===null?{specifier:X}:{}});continue}if(Y.type==="ExportNamedDeclaration"){let Z=Y;if(!Z.source)continue;let X=Z.source.value,{resolved:M,isExternal:U}=N_($,X,J,Q),w=Z.exportKind==="type",A=Z.specifiers??[];for(let S of A){let D=w||S.exportKind==="type",q=r_(S.local),R=r_(S.exported),T={isReExport:!0,specifiers:[{local:q,exported:R}]};if(D)T.isType=!0;if(U)T.isExternal=!0;if(M===null&&!U)T.isUnresolved=!0;z.push({type:D?"type-references":"re-exports",srcFilePath:$,srcSymbolName:R,dstFilePath:M,dstSymbolName:q,metaJson:JSON.stringify(T),...M===null?{specifier:X}:{}})}}}}function KJ(_,$,J,Q,z){new OJ({ImportExpression(Y){let Z=Y.source;if(Z.type!=="Literal"||typeof Z.value!=="string")return;let X=Z.value,{resolved:M,isExternal:U}=N_($,X,J,Q),w={isDynamic:!0};if(U)w.isExternal=!0;if(M===null&&!U)w.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:null,metaJson:JSON.stringify(w),...M===null?{specifier:X}:{}})},CallExpression(Y){let Z=Y.callee,X=!1;if(Z.type==="Identifier"&&Z.name==="require");else if(Z.type==="MemberExpression"&&!Z.computed){let q=Z,R=q.object,T=q.property;if(R.type==="Identifier"&&R.name==="require"&&T.name==="resolve")X=!0;else return}else return;let M=Y.arguments;if(M.length===0)return;let U=M[0];if(U.type!=="Literal"||typeof U.value!=="string")return;let w=U.value,{resolved:A,isExternal:S}=N_($,w,J,Q),D={isRequire:!0};if(X)D.isRequireResolve=!0;if(S)D.isExternal=!0;if(A===null&&!S)D.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:A,dstSymbolName:null,metaJson:JSON.stringify(D),...A===null?{specifier:w}:{}})}}).visit(_)}function o$(_,$,J,Q=A_,z){let W=[];if(z)LJ(z,$,J,Q,W),wJ(z,$,J,Q,W);else BJ(_,$,J,Q,W);return KJ(_,$,J,Q,W),W}import{walk as DJ}from"oxc-walker";function G_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Y=Q.property;if(!Y||typeof Y.name!=="string")return null;J.push(Y.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let W=[z,...J].join(".");return{root:z,parts:J,full:W}}return null}function t$(_,$,J){let Q=[],z=[],W=[];function Y(){if(z.length>0)return z[z.length-1]??null;return null}function Z(U){if(!U)return null;let w=J.get(U.root);if(U.parts.length===0){if(w)return{dstFilePath:w.path,dstSymbolName:w.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:U.root,resolution:"local"}}else{if(w&&w.importedName==="*"){let A=U.parts[U.parts.length-1];return{dstFilePath:w.path,dstSymbolName:A,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:U.full,resolution:"local-member"}}}function X(U,w){let A=G_(U.callee),S=Z(A);if(S){let D=Y(),q={};if(w)q.isNew=!0;if(D===null)q.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:D,dstFilePath:S.dstFilePath,dstSymbolName:S.dstSymbolName,...Object.keys(q).length>0?{metaJson:JSON.stringify(q)}:{}})}}function M(U,w){if(U.type==="FunctionDeclaration"){z.push(U.id?.name??"anonymous");return}if(U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){if(w?.type==="VariableDeclarator"){let D=w.id,q=D.type==="Identifier"?D.name:"anonymous";z.push(q);return}if(w?.type==="MethodDefinition"||w?.type==="TSAbstractMethodDefinition"){let D=w.key,q=W[W.length-1]??"",R="name"in D?D.name:"anonymous",T=q?`${q}.${R}`:R;z.push(T);return}let A=Y(),S=A?`${A}.<anonymous>`:"<anonymous>";z.push(S)}}return DJ(_,{enter(U,w){if(U.type==="ClassDeclaration"||U.type==="ClassExpression"){W.push(U.id?.name??"AnonymousClass");return}if(U.type==="FunctionDeclaration"||U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){M(U,w);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"){z.pop();return}}}),Q}import{Visitor as IJ}from"oxc-parser";function e$(_,$,J){let Q=[];function z(Y){let Z=Y.id?.name??"AnonymousClass";if(Y.superClass){let M=G_(Y.superClass);if(M){let U=K$(M,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...U})}}let X=Y.implements??[];for(let M of X){let U=G_(M.expression);if(!U)continue;let w=K$(U,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Z,...w})}}return new IJ({TSInterfaceDeclaration(Y){let Z=Y.id.name??"AnonymousInterface",X=Y.extends;for(let M of X){let U=G_(M.expression);if(!U)continue;let w=K$(U,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...w})}},ClassDeclaration(Y){z(Y)},ClassExpression(Y){z(Y)}}).visit(_),Q}function K$(_,$,J){let Q=J.get(_.root);if(Q){if(Q.importedName==="*"){let z=_.parts[_.parts.length-1]??_.root;return{dstFilePath:Q.path,dstSymbolName:z,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:Q.path,dstSymbolName:_.parts.length>0?_.full:Q.importedName}}return{dstFilePath:$,dstSymbolName:_.full,metaJson:JSON.stringify({isLocal:!0})}}function m_(_,$,J,Q=A_,z){let W=r$(_,$,J,Q),Y=o$(_,$,J,Q,z),Z=t$(_,$,W),X=e$(_,$,W);return[...Y,...Z,...X]}function D$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Y,knownFiles:Z,boundaries:X,module:M}=_,U=R_(W,Q),A=m_($,U,Y,Z?(D,q,R)=>{let T=A_(D,q,R);for(let b of T){let v=f_(W,b);if(X){let P=l(v,X);if(Z.has(`${P}::${v}`))return[b]}else if(Z.has(`${J}::${v}`))return[b]}return[]}:void 0,M),S=[];for(let D of A){if(D.dstFilePath===null){let b=f_(W,D.srcFilePath),v;if(D.metaJson)try{v=JSON.parse(D.metaJson)}catch{}let P=v?.isExternal===!0;S.push({project:J,type:D.type,srcFilePath:b,srcSymbolName:D.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:D.dstSymbolName??null,metaJson:D.metaJson??null,specifier:D.specifier??null,isExternal:P?1:0});continue}let q=f_(W,D.dstFilePath);if(q.startsWith(".."))continue;let R=f_(W,D.srcFilePath),T=X?l(q,X):J;S.push({project:J,type:D.type,srcFilePath:R,srcSymbolName:D.srcSymbolName??null,dstProject:T,dstFilePath:q,dstSymbolName:D.dstSymbolName??null,metaJson:D.metaJson??null,specifier:D.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,S),S.length}import{isErr as CJ}from"@zipbul/result";var _0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function AJ(_){let $=C_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function I$(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let W=Q+z>>1;if(_[W].startLine<=$)Q=W+1;else z=W-1}if(Q<_.length){let W=_[Q];if(W.startLine-$<=J)return W.name}return null}function o_(_,$,J){let Q=U_(_,$),z=U_(_,J);return{start:Q,end:z}}function $0(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=x_(J),z=AJ(_),W=[],Y=[...$].sort((X,M)=>X.start-M.start),Z=null;for(let X of Y)if(X.type==="Block"&&X.value.startsWith("*")){Z=null;let M=`/*${X.value}*/`,U=s_(M);if(CJ(U))continue;let w=U;if(!w.tags?.length)continue;let A=U_(Q,X.end),S=I$(z,A.line,3),D=J.slice(X.start,X.end);for(let q of w.tags){let R=[q.name,q.description].filter(Boolean).join(" "),T=`@${q.tag}`,b=D.indexOf(T),v;if(b>=0){let P=X.start+b,d=J.indexOf(`
4
- `,P),c=d>=0?Math.min(d,X.end):X.end;v=o_(Q,P,c)}else v=o_(Q,X.start,X.end);W.push({tag:q.tag,value:R,source:"jsdoc",span:v,symbolName:S})}}else if(X.type==="Block"){Z=null;let M=X.value.split(`
5
- `),U=0;for(let w of M){let A=w.replace(/^\s*\*?\s?/,""),S=_0.exec(A);if(S){let D=S[1],q=S[2]?.trim()??"",R=`@${D}`,T=w.indexOf(R),b=X.start+2+U+(T>=0?T:0),v=X.start+2+U+w.length,P=o_(Q,b,v),d=U_(Q,X.end),c=I$(z,d.line,3);W.push({tag:D,value:q,source:"block",span:P,symbolName:c})}U+=w.length+1}}else{let M=X.value,U=_0.exec(M),w=U_(Q,X.start),A=U_(Q,X.end);if(U){let S=U[1],D=U[2]?.trim()??"",q=`@${S}`,R=M.indexOf(q),T=X.start+2+(R>=0?R:0),b=o_(Q,T,X.end),v=I$(z,A.line,3),P={tag:S,value:D,source:"line",span:b,symbolName:v};W.push(P),Z={annotation:P,endLine:A.line}}else if(Z&&w.line===Z.endLine+1){let S=M.trim();if(S)Z.annotation.value+=" "+S,Z.annotation.span.end=U_(Q,X.end),Z.endLine=A.line}else Z=null}return W}function C$(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,W=$0($);if(z.deleteFileAnnotations(J,Q),!W.length)return 0;let Y=new Date().toISOString(),Z=W.map((X)=>({project:J,filePath:Q,tag:X.tag,value:X.value,source:X.source,symbolName:X.symbolName,startLine:X.span.start.line,startColumn:X.span.start.column,endLine:X.span.end.line,endColumn:X.span.end.column,indexedAt:Y}));return z.insertBatch(J,Q,Z),W.length}function J0(_,$){let J=[],Q=[],z=[];for(let[U,w]of $)if(!_.has(U))J.push({name:w.name,filePath:w.filePath,kind:w.kind,fingerprint:w.fingerprint});for(let[U,w]of _)if(!$.has(U))Q.push({name:w.name,filePath:w.filePath,kind:w.kind,fingerprint:w.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Y=new Map;for(let U of J){let w=W.get(U.filePath)??[];w.push(U),W.set(U.filePath,w)}for(let U of Q){let w=Y.get(U.filePath)??[];w.push(U),Y.set(U.filePath,w)}let Z=new Set,X=new Set;for(let[U,w]of W){let A=Y.get(U);if(!A)continue;for(let S of new Set(w.map((D)=>D.kind))){let D=w.filter((v)=>v.kind===S&&!Z.has(v)),q=A.filter((v)=>v.kind===S&&!X.has(v));if(!D.length||!q.length)continue;let R=(v,P)=>{return P.get(`${v.filePath}::${v.name}`)?.structuralFingerprint??null},T=(v,P)=>{return P.get(`${v.filePath}::${v.name}`)?.startLine??0},b=new Map;for(let v of q){let P=R(v,_);if(!P)continue;let d=b.get(P)??[];d.push(v),b.set(P,d)}for(let v of D){if(Z.has(v))continue;let P=R(v,$);if(!P)continue;let d=b.get(P);if(!d)continue;let c=d.filter((X_)=>!X.has(X_));if(!c.length)continue;let Y_=c[0];if(c.length>1){let X_=T(v,$),H_=Math.abs(T(Y_,_)-X_);for(let __=1;__<c.length;__++){let $_=Math.abs(T(c[__],_)-X_);if($_<H_)H_=$_,Y_=c[__]}}z.push({oldName:Y_.name,newName:v.name,filePath:U,kind:S}),Z.add(v),X.add(Y_)}}}let M=z.filter((U)=>!U.oldName.includes("."));for(let U of M){let w=`${U.oldName}.`,A=`${U.newName}.`,S=Q.filter((q)=>q.filePath===U.filePath&&q.name.startsWith(w)&&!X.has(q)),D=J.filter((q)=>q.filePath===U.filePath&&q.name.startsWith(A)&&!Z.has(q));for(let q of S){let R=q.name.slice(w.length),T=D.find((b)=>b.name.slice(A.length)===R);if(T)z.push({oldName:q.name,newName:T.name,filePath:U.filePath,kind:q.kind}),Z.add(T),X.add(q)}}return{renamed:z,added:J.filter((U)=>!Z.has(U)),removed:Q.filter((U)=>!X.has(U))}}var NJ=100,z0=50;class A${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=y_(_.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")){a_(this.opts.projectRoot),this.tsconfigPathsRaw=y_(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??c_;this.boundariesRefresh=$(this.opts.projectRoot).then((J)=>{this.opts.boundaries=J,this.opts.onBoundariesChanged?.(J)}),this.fullIndex().catch((J)=>{this.logger.error("[IndexCoordinator] fullIndex failed after package.json change:",J)});return}if(this.pendingEvents.push(_),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},NJ)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(_,$){if(this.indexingLock){if($)return this.pendingFullIndex=!0,new Promise((Q,z)=>{this.pendingFullIndexWaiters.push({resolve:Q,reject:z})});return this.currentIndexing}this.indexingLock=!0;let J=this.doIndex(_,$).then((Q)=>{return this.fireCallbacks(Q),Q}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let Q=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((z)=>{for(let W of Q)W.resolve(z)}).catch((z)=>{for(let W of Q)W.reject(z)})}else if(this.pendingEvents.length>0){let Q=this.pendingEvents.splice(0);this.startIndex(Q,!1).catch((z)=>this.logger.error("[IndexCoordinator] incremental drain error",z))}});return this.currentIndexing=J,J}async doIndex(_,$){let J=Date.now(),{fileRepo:Q,symbolRepo:z,relationRepo:W,dbConnection:Y}=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 K of this.opts.boundaries)for(let[C,g]of Q.getFilesMap(K.project))V.set(C,g);let O=await a$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>V}});Z=O.changed,X=O.deleted}let M=await this.tsconfigPathsRaw??void 0,U=new Map;for(let V of X){let O=l(V,this.opts.boundaries),K=z.getFileSymbols(O,V);U.set(V,K)}let w=crypto.randomUUID(),A=new Map,S=new Map,D=(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 Q.getAllFiles(V.project))for(let K of z.getFileSymbols(V.project,O.filePath))A.set(`${K.filePath}::${K.name}`,D(K));else{for(let V of Z){let O=l(V.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(O,V.filePath))A.set(`${K.filePath}::${K.name}`,D(K))}for(let[,V]of U)for(let O of V)A.set(`${O.filePath}::${O.name}`,D(O))}let q=(V)=>`${V.type}|${V.srcFilePath}|${V.dstFilePath??""}|${V.srcSymbolName??""}|${V.dstSymbolName??""}|${V_(V.metaJson??"")}`,R=new Map;if($)for(let V of this.opts.boundaries)for(let O of Q.getAllFiles(V.project))for(let K of W.getOutgoing(V.project,O.filePath))R.set(q(K),K);else{for(let V of Z){let O=l(V.filePath,this.opts.boundaries);for(let K of W.getOutgoing(O,V.filePath))R.set(q(K),K)}for(let V of X){let O=l(V,this.opts.boundaries);for(let K of W.getOutgoing(O,V))R.set(q(K),K)}}let{annotationRepo:T,changelogRepo:b}=this.opts,v=()=>{for(let V of X){let O=l(V,this.opts.boundaries);if(z.deleteFileSymbols(O,V),W.deleteFileRelations(O,V),W.deleteIncomingRelations(O,V),T)T.deleteFileAnnotations(O,V);Q.deleteFile(O,V)}},P=0,d=async()=>{let{projectRoot:V,boundaries:O}=this.opts,{parseCache:K}=this.opts,C=0,g=0,I=0,F=[],G=[];for(let j of Z)try{let y=R_(V,j.filePath),J_=Bun.file(y),W_=await J_.text(),E_=j.contentHash||V_(W_),D_=l(j.filePath,O);Q.upsertFile({project:D_,filePath:j.filePath,mtimeMs:J_.lastModified,size:J_.size,contentHash:E_,updatedAt:new Date().toISOString(),lineCount:W_.split(`
6
- `).length});let W$=(this.opts.parseSourceFn??T_)(y,W_);if(Q0(W$))throw W$.data;let u1=W$;G.push({filePath:j.filePath,text:W_,contentHash:E_,parsed:u1,project:D_})}catch(y){this.logger.error(`[IndexCoordinator] Failed to prepare ${j.filePath}:`,y),F.push(j.filePath)}let k=new Set;for(let j of O)for(let[y]of Q.getFilesMap(j.project))k.add(`${j.project}::${y}`);return Y.transaction(()=>{for(let j of G){if(w$({parsed:j.parsed,project:j.project,filePath:j.filePath,contentHash:j.contentHash,symbolRepo:z}),g+=D$({ast:j.parsed.program,project:j.project,filePath:j.filePath,relationRepo:W,projectRoot:V,tsconfigPaths:M,knownFiles:k,boundaries:O,module:j.parsed.module}),T)I+=C$({parsed:j.parsed,project:j.project,filePath:j.filePath,annotationRepo:T});K.set(j.filePath,j.parsed),C+=z.getFileSymbols(j.project,j.filePath).length}}),{symbols:C,relations:g,annotations:I,failedFiles:F}},c=0,Y_=0,X_=[];if($){let{projectRoot:V,boundaries:O}=this.opts,{parseCache:K}=this.opts,C=[];for(let I=0;I<Z.length;I+=z0){let F=Z.slice(I,I+z0),G=await Promise.allSettled(F.map(async(k)=>{let j=R_(V,k.filePath),y=Bun.file(j),J_=await y.text(),W_=k.contentHash||V_(J_);return{filePath:k.filePath,text:J_,contentHash:W_,mtimeMs:y.lastModified,size:y.size}}));for(let k=0;k<G.length;k++){let j=G[k];if(j.status==="fulfilled")C.push(j.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",j.reason),X_.push(F[k].filePath)}}let g=[];Y.transaction(()=>{for(let G of C){let k=l(G.filePath,O);Q.deleteFile(k,G.filePath)}for(let G of X){let k=l(G,O);if(z.deleteFileSymbols(k,G),W.deleteFileRelations(k,G),W.deleteIncomingRelations(k,G),T)T.deleteFileAnnotations(k,G);Q.deleteFile(k,G)}for(let G of C){let k=l(G.filePath,O);Q.upsertFile({project:k,filePath:G.filePath,mtimeMs:G.mtimeMs,size:G.size,contentHash:G.contentHash,updatedAt:new Date().toISOString(),lineCount:G.text.split(`
7
- `).length})}let I=new Set;for(let G of O)for(let[k]of Q.getFilesMap(G.project))I.add(`${G.project}::${k}`);let F=this.opts.parseSourceFn??T_;for(let G of C){let k=l(G.filePath,O),j=F(R_(V,G.filePath),G.text);if(Q0(j))throw j.data;let y=j;if(g.push({filePath:G.filePath,parsed:y}),w$({parsed:y,project:k,filePath:G.filePath,contentHash:G.contentHash,symbolRepo:z}),T)P+=C$({parsed:y,project:k,filePath:G.filePath,annotationRepo:T});Y_+=D$({ast:y.program,project:k,filePath:G.filePath,relationRepo:W,projectRoot:V,tsconfigPaths:M,knownFiles:I,boundaries:O,module:y.module}),c+=z.getFileSymbols(k,G.filePath).length}});for(let I of g)K.set(I.filePath,I.parsed)}else{v();let V=await d();c=V.symbols,Y_=V.relations,P=V.annotations,X_=V.failedFiles}for(let V of Z){let O=l(V.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(O,V.filePath))S.set(`${K.filePath}::${K.name}`,D(K))}let H_=new Map;for(let V of Z){let O=l(V.filePath,this.opts.boundaries);for(let K of W.getOutgoing(O,V.filePath))H_.set(q(K),K)}let __=(V)=>({type:V.type,srcFilePath:V.srcFilePath,dstFilePath:V.dstFilePath,srcSymbolName:V.srcSymbolName,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,metaJson:V.metaJson}),$_={added:[...H_.entries()].filter(([V])=>!R.has(V)).map(([,V])=>__(V)),removed:[...R.entries()].filter(([V])=>!H_.has(V)).map(([,V])=>__(V))},p={added:[],modified:[],removed:[]};for(let[V,O]of S){let K=A.get(V);if(!K)p.added.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});else{let C=K.fingerprint!==O.fingerprint,g=K.isExported!==O.isExported,I=K.structuralFingerprint!==null&&O.structuralFingerprint!==null&&K.structuralFingerprint!==O.structuralFingerprint;if(C||g||I)p.modified.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)})}}for(let[V,O]of A)if(!S.has(V))p.removed.push({name:O.name,filePath:O.filePath,kind:O.kind,isExported:Boolean(O.isExported)});let L=J0(A,S),u=new Set(L.renamed.map((V)=>`${V.filePath}::${V.oldName}`)),N=new Set(L.renamed.map((V)=>`${V.filePath}::${V.newName}`));p.added=p.added.filter((V)=>!N.has(`${V.filePath}::${V.name}`)),p.removed=p.removed.filter((V)=>!u.has(`${V.filePath}::${V.name}`));let B=[];if(!$){for(let[O,K]of U)for(let C of K){if(!C.fingerprint)continue;let g=l(O,this.opts.boundaries),I=z.getByFingerprint(g,C.fingerprint);if(I.length===1){let F=I[0];W.retargetRelations({dstProject:g,oldFile:O,oldSymbol:C.name,newFile:F.filePath,newSymbol:F.name}),B.push({name:F.name,filePath:F.filePath,kind:F.kind,oldFilePath:O,isExported:F.isExported??0})}}let V=new Set(B.map((O)=>`${O.oldFilePath}::${O.name}`));for(let O of L.removed){if(V.has(`${O.filePath}::${O.name}`))continue;let C=A.get(`${O.filePath}::${O.name}`)?.fingerprint;if(!C)continue;let g=l(O.filePath,this.opts.boundaries),I=z.getByFingerprint(g,C);if(I.length===1){let F=I[0];if(F.filePath!==O.filePath||F.name!==O.name)W.retargetRelations({dstProject:g,oldFile:O.filePath,oldSymbol:O.name,newFile:F.filePath,newSymbol:F.name}),B.push({name:F.name,filePath:F.filePath,kind:F.kind,oldFilePath:O.filePath,isExported:F.isExported??0})}}}if(B.length){let V=new Set(B.map((K)=>`${K.filePath}::${K.name}`)),O=new Set(B.map((K)=>`${K.oldFilePath}::${K.name}`));p.added=p.added.filter((K)=>!V.has(`${K.filePath}::${K.name}`)),p.removed=p.removed.filter((K)=>!O.has(`${K.filePath}::${K.name}`))}if(b){let V=new Date().toISOString(),O=$?1:0,K=[];for(let C of p.added){let g=`${C.filePath}::${C.name}`,I=S.get(g),F=l(C.filePath,this.opts.boundaries);K.push({project:F,changeType:"added",symbolName:C.name,symbolKind:C.kind,filePath:C.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:w})}for(let C of p.modified){let g=S.get(`${C.filePath}::${C.name}`),I=l(C.filePath,this.opts.boundaries);K.push({project:I,changeType:"modified",symbolName:C.name,symbolKind:C.kind,filePath:C.filePath,oldName:null,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:w})}for(let C of p.removed){let g=`${C.filePath}::${C.name}`,I=A.get(g),F=l(C.filePath,this.opts.boundaries);K.push({project:F,changeType:"removed",symbolName:C.name,symbolKind:C.kind,filePath:C.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:w})}for(let C of L.renamed){let g=S.get(`${C.filePath}::${C.newName}`),I=l(C.filePath,this.opts.boundaries);K.push({project:I,changeType:"renamed",symbolName:C.newName,symbolKind:C.kind,filePath:C.filePath,oldName:C.oldName,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:w})}for(let C of B){let g=S.get(`${C.filePath}::${C.name}`),I=l(C.filePath,this.opts.boundaries);K.push({project:I,changeType:"moved",symbolName:C.name,symbolKind:C.kind,filePath:C.filePath,oldName:null,oldFilePath:C.oldFilePath,fingerprint:g?.fingerprint??null,changedAt:V,isFullIndex:O,indexRunId:w})}if(K.length)try{Y.transaction(()=>{b.insertBatch(K)})}catch(C){this.logger.error("[IndexCoordinator] changelog insert failed:",C)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let C=new Date(Date.now()-2592000000).toISOString();try{for(let g of this.opts.boundaries)b.pruneOlderThan(g.project,C)}catch(g){this.logger.error("[IndexCoordinator] changelog pruning failed:",g)}}}return{indexedFiles:Z.length,removedFiles:X.length,totalSymbols:c,totalRelations:Y_,totalAnnotations:P,durationMs:Date.now()-J,changedFiles:Z.map((V)=>V.filePath),deletedFiles:[...X],failedFiles:X_,changedSymbols:p,renamedSymbols:L.renamed.map((V)=>({oldName:V.oldName,newName:V.newName,filePath:V.filePath,kind:V.kind,isExported:Boolean(S.get(`${V.filePath}::${V.newName}`)?.isExported)})),movedSymbols:B.map((V)=>({name:V.name,oldFilePath:V.oldFilePath,newFilePath:V.filePath,kind:V.kind,isExported:Boolean(V.isExported)})),changedRelations:$_}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function qJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function SJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function W0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??qJ,W=J.staleAfterSeconds??60,Y=J.instanceId;return _.immediateTransaction(()=>{let Z=_.selectOwner();if(!Z)return _.insertOwner($,Y),"owner";let X=Math.floor((Q()-SJ(Z.heartbeat_at))/1000),M=z(Z.pid);if(M&&Y&&Z.instance_id&&Z.instance_id!==Y&&Z.pid===$)return _.replaceOwner($,Y),"owner";if(M&&X<W)return"reader";return _.replaceOwner($,Y),"owner"})}function Z0(_,$){_.deleteOwner($)}function Y0(_,$){_.touchOwner($)}class n_{#_;#$=new Map;constructor(_){this.#_=Math.max(1,_)}get size(){return this.#$.size}has(_){return this.#$.has(_)}get(_){if(!this.#$.has(_))return;let $=this.#$.get(_);return this.#$.delete(_),this.#$.set(_,$),$}set(_,$){if(this.#$.has(_))this.#$.delete(_);if(this.#$.set(_,$),this.#$.size>this.#_){let J=this.#$.keys().next().value;if(J!==void 0)this.#$.delete(J)}}delete(_){return this.#$.delete(_)}clear(){this.#$.clear()}}class N${lru;constructor(_=500){this.lru=new n_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function q$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,W={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)W.exactName=Q.text;else{let Z=g_(Q.text);if(Z)W.ftsQuery=Z}if(Q.decorator)W.decorator=Q.decorator;if(Q.regex)W.regex=Q.regex;return $.searchByQuery(W).map((Z)=>{let X=Z.name.indexOf(".");return{id:Z.id,filePath:Z.filePath,kind:Z.kind,name:Z.name,memberName:X>=0?Z.name.slice(X+1):null,span:{start:{line:Z.startLine,column:Z.startColumn},end:{line:Z.endLine,column:Z.endColumn}},isExported:Z.isExported===1,signature:Z.signature,fingerprint:Z.fingerprint,detail:Z.detailJson?(()=>{try{return JSON.parse(Z.detailJson)}catch{return{}}})():{}}})}function S$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new H("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new H("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,W=Q.limit,Y=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Z=Y?void 0:W,M=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:Z}).map((U)=>{let w;if(U.metaJson)try{w=JSON.parse(U.metaJson)}catch{}return{type:U.type,srcFilePath:U.srcFilePath,srcSymbolName:U.srcSymbolName,dstFilePath:U.dstFilePath,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,isExternal:U.isExternal===1,specifier:U.specifier,metaJson:U.metaJson??void 0,meta:w}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let U=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,w=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;M=M.filter((A)=>(!U||U.match(A.srcFilePath))&&(!w||A.dstFilePath===null||w.match(A.dstFilePath)))}if(Y&&W!==void 0&&M.length>W)M=M.slice(0,W);return M}import{findInFiles as uJ,Lang as gJ}from"@ast-grep/napi";function RJ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function TJ(_){return _.replace(/^\$+/,"")}function FJ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=TJ(z),Y=_.getMatch(W);if(Y){let X=Y.range();J[z]={text:Y.text(),startLine:X.start.line+1,endLine:X.end.line+1,startColumn:X.start.column,endColumn:X.end.column,startOffset:X.start.index,endOffset:X.end.index},Q=!0;continue}let Z=_.getMultipleMatches(W);if(Z.length>0){let X=Z[0].range(),M=Z[Z.length-1].range();J[z]={text:Z.map((U)=>U.text()).join(", "),startLine:X.start.line+1,endLine:M.end.line+1,startColumn:X.start.column,endColumn:M.end.column,startOffset:X.start.index,endOffset:M.end.index},Q=!0}}return Q?J:void 0}async function u$(_){if(_.filePaths.length===0)return[];let $=RJ(_.pattern),J=[];return await uJ(gJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Y=W.range(),Z={filePath:W.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,startColumn:Y.start.column,endColumn:Y.end.column,startOffset:Y.start.index,endOffset:Y.end.index,matchedText:W.text()},X=FJ(W,$);if(X)Z.captures=X;J.push(Z)}}),J}import o from"typescript";import{isErr as iJ}from"@zipbul/result";import L_ from"typescript";import GJ from"path";import{err as g$}from"@zipbul/result";function jJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}function kJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}class t_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??jJ,Q=$.resolveNonTrackedFile??kJ,z=GJ.dirname(_),W=J(_);if(W===void 0)return g$(new H("semantic",`tsconfig not found: ${_}`));let Y=L_.parseJsonText(_,W),Z=Y.parseDiagnostics;if(Z&&Z.length>0){let w=Z.map((A)=>L_.flattenDiagnosticMessageText(A.messageText,`
8
- `)).join("; ");return g$(new H("semantic",`tsconfig parse error: ${w}`))}let X=L_.parseJsonSourceFileConfigFileContent(Y,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(w)=>J(w)!==void 0||Q(w)!==void 0,readFile:(w)=>J(w)??Q(w)},z);if(X.errors.length>0){let w=X.errors.filter((A)=>A.category===L_.DiagnosticCategory.Error&&A.code!==18003);if(w.length>0){let A=w.map((S)=>L_.flattenDiagnosticMessageText(S.messageText,`
9
- `)).join("; ");return g$(new H("semantic",`tsconfig compile error: ${A}`))}}let M=new X0(X.fileNames,X.options,z,Q),U=L_.createLanguageService(M);return new t_(U,M)}get isDisposed(){return this.#J}getProgram(){this.#Z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#Z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#Z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#Z(){if(this.#J)throw Error("TscProgram is disposed")}}class X0{#_;#$;#J;#Z;#z=new Map;#W=new Map;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#Z=Q}updateFile(_,$){let J=this.#z.get(_);if(J)this.#W.delete(`${_}:${J.version}`),J.version+=1,J.content=$;else this.#z.set(_,{version:1,content:$})}removeFile(_){let $=this.#z.get(_);if($)this.#W.delete(`${_}:${$.version}`);this.#z.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#z.keys()];return[...[...this.#_].filter((J)=>!this.#z.has(J)),..._]}getScriptVersion(_){let $=this.#z.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#z.get(_);if($){let z=`${_}:${$.version}`,W=this.#W.get(z);if(!W)W=L_.ScriptSnapshot.fromString($.content),this.#W.set(z,W);return W}let J=this.#Q.get(_);if(J)return J;let Q=this.#Z(_);if(Q!==void 0)return J=L_.ScriptSnapshot.fromString(Q),this.#Q.set(_,J),J;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return L_.getDefaultLibFilePath(_)}fileExists(_){if(this.#z.has(_))return!0;return this.#Z(_)!==void 0}readFile(_){let $=this.#z.get(_);if($)return $.content;return this.#Z(_)}}import i from"typescript";import EJ from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let J=EJ.getTokenAtPosition(_,$);if(J.getStart(_,!1)>$)return;return J}var e_=8;function vJ(_){return!!(_.flags&i.TypeFlags.Object)&&!!(_.objectFlags&i.ObjectFlags.Reference)}function M_(_,$,J=0,Q){if(Q){let D=Q.get($);if(D)return D}let z=_.typeToString($),W=$.flags,Y=!!(W&i.TypeFlags.Union),Z=!!(W&i.TypeFlags.Intersection),X;if(J<e_&&vJ($)){let D=_.getTypeArguments($);if(D.length>0)X=D}let M=!!(W&i.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,U;if(Y&&J<e_)U=$.types.map((D)=>M_(_,D,J+1,Q));else if(Z&&J<e_)U=$.types.map((D)=>M_(_,D,J+1,Q));let w;if(X&&X.length>0)w=X.map((D)=>M_(_,D,J+1,Q));let A;if(J<e_&&!!(W&i.TypeFlags.Object)&&!Y&&!Z){let D=_.getPropertiesOfType($);if(D.length>0&&D.length<=50){let q=$.symbol?.declarations?.[0];A=[];for(let R of D){let T=R.declarations?.[0]??q;if(!T)continue;try{let b=_.getTypeOfSymbolAtLocation(R,T);A.push({name:R.getName(),type:M_(_,b,J+1,Q)})}catch{}}if(A.length===0)A=void 0}}let S={text:z,flags:W,isUnion:Y,isIntersection:Z,isGeneric:M,members:U,typeArguments:w,properties:A};if(Q)Q.set($,S);return S}function bJ(_){return i.isFunctionDeclaration(_)||i.isVariableDeclaration(_)||i.isClassDeclaration(_)||i.isInterfaceDeclaration(_)||i.isTypeAliasDeclaration(_)||i.isEnumDeclaration(_)||i.isMethodDeclaration(_)||i.isPropertyDeclaration(_)||i.isPropertySignature(_)||i.isMethodSignature(_)}var R$="/__gildash_type_probe__.ts";class T${program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(R$,`declare const __gildash_probe__: ${_};`),this.#_=_}#J(_,$){let J=_.getSourceFile(R$);if(!J)return null;let Q=J.statements[0];if(!Q||!i.isVariableStatement(Q))return null;let z=Q.declarationList.declarations[0];if(!z)return null;return $.getTypeAtLocation(z.name)}clearProbe(){if(this.#_!==null)this.program.removeFile(R$),this.#_=null}collectAt(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let W=e(z,$);if(!W)return null;if(!i.isIdentifier(W)&&!i.isTypeNode(W))return null;try{let Y=Q.getTypeAtLocation(W);return M_(Q,Y,0,new Map)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getProgram(),W=z.getTypeChecker(),Y=z.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!i.isIdentifier(Z))return null;let X=z.getSourceFile(J);if(!X)return null;let M=e(X,Q);if(!M||!i.isIdentifier(M))return null;try{let U=W.getTypeAtLocation(Z),w=W.getTypeAtLocation(M);return W.isTypeAssignableTo(U,w)}catch{return null}}isAssignableToType(_,$,J,Q){this.#$(J);let z=this.program.getProgram(),W=z.getTypeChecker(),Y=z.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!i.isIdentifier(Z)&&!i.isTypeNode(Z))return null;try{let X=this.#J(z,W);if(!X)return null;let M=W.getTypeAtLocation(Z);if(Q?.anyConstituent&&M.isUnion())return M.types.some((U)=>W.isTypeAssignableTo(U,X));return W.isTypeAssignableTo(M,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#$(J);let W=this.program.getProgram(),Y=W.getTypeChecker(),Z=W.getSourceFile(_);if(!Z)return z;try{let X=this.#J(W,Y);if(!X)return z;let M=Z.getEnd();for(let U of $){if(U<0||U>=M)continue;let w=e(Z,U);if(!w||!i.isIdentifier(w)&&!i.isTypeNode(w))continue;try{let A=Y.getTypeAtLocation(w);if(Q?.anyConstituent&&A.isUnion())z.set(U,A.types.some((S)=>Y.isTypeAssignableTo(S,X)));else z.set(U,Y.isTypeAssignableTo(A,X))}catch{}}}catch{}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return J;let Y=W.getEnd(),Z=new Map;for(let X of $){if(X<0||X>=Y)continue;let M=e(W,X);if(!M)continue;if(!i.isIdentifier(M)&&!i.isTypeNode(M))continue;try{let U=z.getTypeAtLocation(M);J.set(X,M_(z,U,0,Z))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return $;let W=new Map;function Y(Z){if(bJ(Z)&&Z.name&&i.isIdentifier(Z.name)){let X=Z.name;try{let M=Q.getTypeAtLocation(X),U=X.getStart(z);$.set(U,M_(Q,M,0,W))}catch{}}i.forEachChild(Z,Y)}return Y(z),$}}import w_ from"typescript";var fJ=1000,PJ=1;function yJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?w_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function _$(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),W=Q?w_.getNameOfDeclaration(Q):void 0,Y=z?.fileName??"",Z=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Y,position:Z},M=_;if(M.parent)X.parent=yJ(M.parent);let U=J&&!!(_.flags&w_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<PJ){let w=U.flags,A=!!(w&w_.SymbolFlags.Enum),S=!!(w&(w_.SymbolFlags.NamespaceModule|w_.SymbolFlags.ValueModule)),D=!!(w&(w_.SymbolFlags.Class|w_.SymbolFlags.Interface));if(A&&U.exports&&U.exports.size>0){let q=[];U.exports.forEach((R)=>{q.push(_$(R,$+1,J))}),X.members=q}else if(D&&U.members&&U.members.size>0){let q=[];U.members.forEach((R)=>{q.push(_$(R,$+1,J))}),X.members=q}if(S&&U.exports&&U.exports.size>0){let q=[];U.exports.forEach((R)=>{q.push(_$(R,$+1,J))}),X.exports=q}}return X}class F${#_;#$;#J=new Map;constructor(_,$=fJ){this.#_=_,this.#$=new n_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let z=this.#_.getProgram(),W=z.getSourceFile(_);if(!W)return null;let Y=e(W,$);if(!Y||!w_.isIdentifier(Y))return null;let Z=z.getTypeChecker(),X=Z.getSymbolAtLocation(Y);if(!X)return null;let M=_$(X,0,Z);this.#$.set(J,M);let U=this.#J.get(_);if(!U)U=new Set,this.#J.set(_,U);return U.add(J),M}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import xJ from"typescript";class G${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=e(Q,$);if(!z||!xJ.isIdentifier(z))return[];let Y=this.#_.getLanguageService().findReferences(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y)for(let M of X.references){let U=J.getSourceFile(M.fileName);if(!U)continue;let{line:w,character:A}=U.getLineAndCharacterOfPosition(M.textSpan.start);Z.push({filePath:M.fileName,position:M.textSpan.start,line:w+1,column:A,isDefinition:M.isDefinition??!1,isWrite:M.isWriteAccess??!1})}return Z}}import n from"typescript";function mJ(_,$){let J=e(_,$);if(!J)return;if(U0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(U0(Q))return Q;Q=Q.parent}return J}function U0(_){return n.isClassDeclaration(_)||n.isClassExpression(_)||n.isFunctionDeclaration(_)||n.isFunctionExpression(_)||n.isArrowFunction(_)||n.isVariableDeclaration(_)||n.isObjectLiteralExpression(_)}function V0(_){if(n.isClassDeclaration(_)||n.isClassExpression(_))return"class";if(n.isFunctionDeclaration(_)||n.isFunctionExpression(_)||n.isArrowFunction(_))return"function";if(n.isObjectLiteralExpression(_))return"object";if(n.isVariableDeclaration(_)&&_.initializer)return V0(_.initializer);return"class"}function nJ(_,$){if(n.isClassDeclaration(_)||n.isFunctionDeclaration(_))return _.name?.getText($)??"";if(n.isClassExpression(_))return _.name?.getText($)??"";if(n.isVariableDeclaration(_)&&n.isIdentifier(_.name))return _.name.getText($);if(n.isFunctionExpression(_))return _.name?.getText($)??"";if(n.isArrowFunction(_)&&_.parent&&n.isVariableDeclaration(_.parent)){if(n.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(n.isObjectLiteralExpression(_)&&_.parent&&n.isVariableDeclaration(_.parent)){if(n.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function hJ(_){if(!n.isClassDeclaration(_)&&!n.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===n.SyntaxKind.ImplementsKeyword)}class j${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=e(Q,$);if(!z||!n.isIdentifier(z))return[];let Y=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y){if(X.kind===n.ScriptElementKind.interfaceElement||X.kind===n.ScriptElementKind.typeElement)continue;let M=J.getSourceFile(X.fileName);if(!M)continue;let U=mJ(M,X.textSpan.start);if(!U)continue;let w=V0(U),A=nJ(U,M),S=hJ(U);Z.push({filePath:X.fileName,symbolName:A,position:X.textSpan.start,kind:w,isExplicit:S})}return Z}}function dJ(_){if(o.isFunctionDeclaration(_))return"function";if(o.isClassDeclaration(_))return"class";if(o.isInterfaceDeclaration(_))return"interface";if(o.isTypeAliasDeclaration(_))return"type";if(o.isEnumDeclaration(_))return"enum";if(o.isVariableDeclaration(_))return"const";if(o.isVariableStatement(_))return"const";return"unknown"}function H0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class $${#_;#$;#J;#Z;#z;#W=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#Z=Q,this.#z=z}static create(_,$={}){let J=t_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(iJ(J))return J;let Q=J,z=$.typeCollector??new T$(Q),W=$.symbolGraph??new F$(Q),Y=$.referenceResolver??new G$(Q),Z=$.implementationFinder??new j$(Q);return new $$(Q,z,W,Y,Z)}get isDisposed(){return this.#W}collectTypeAt(_,$){return this.#Q(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#Q(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#Q(),this.#$.collectAtPositions(_,$)}findReferences(_,$){return this.#Q(),this.#Z.findAt(_,$)}findImplementations(_,$){return this.#Q(),this.#z.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#Q(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#Q(),this.#$.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#Q(),this.#$.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#Q(),this.#J.get(_,$)}getBaseTypes(_,$){this.#Q();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z)return null;let W=J.getTypeChecker(),Y=W.getTypeAtLocation(z);if(!(Y.flags&o.TypeFlags.Object)||!(Y.objectFlags&o.ObjectFlags.ClassOrInterface))return null;let Z=W.getBaseTypes(Y);if(!Z||Z.length===0)return[];let X=new Map;return Z.map((M)=>M_(W,M,0,X))}getModuleInterface(_){this.#Q();let $=[],J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=J.getTypeChecker(),W=z.getSymbolAtLocation(Q);if(W){let Y=z.getExportsOfModule(W),Z=new Map;for(let X of Y){let M=X.getName(),U=X.declarations?.[0],w="unknown";if(U){if(w=dJ(U),w==="unknown"&&o.isExportAssignment(U))w="const"}let A=null;try{let S=z.getTypeOfSymbolAtLocation(X,U??Q);A=M_(z,S,0,Z)}catch{}$.push({name:M,kind:w,resolvedType:A})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#W)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#W)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return o.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),W=$;while(W<z.length){let Y=z.indexOf(J,W);if(Y<0)return null;let Z=Y>0?z.charCodeAt(Y-1):32,X=Y+J.length<z.length?z.charCodeAt(Y+J.length):32;if(!H0(Z)&&!H0(X))return Y;W=Y+1}return null}getDiagnostics(_,$){this.#Q();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[o.DiagnosticCategory.Error]:"error",[o.DiagnosticCategory.Warning]:"warning",[o.DiagnosticCategory.Suggestion]:"suggestion",[o.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?o.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Y)=>{let Z=1,X=0;if(Y.file&&Y.start!==void 0){let M=o.getLineAndCharacterOfPosition(Y.file,Y.start);Z=M.line+1,X=M.character}return{filePath:Y.file?.fileName??_,line:Z,column:X,message:o.flattenDiagnosticMessageText(Y.messageText,`
10
- `),code:Y.code,category:z[Y.category]??"error"}})}dispose(){if(this.#W)return;this.#W=!0,this.#$.clearProbe(),this.#_.dispose(),this.#J.clear()}#Q(){if(this.#W)throw Error("SemanticLayer is disposed")}}import{eq as q_,and as O0,sql as pJ}from"drizzle-orm";var M0=80;class k${db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((z)=>({project:_,filePath:$,tag:z.tag,value:z.value,source:z.source,symbolName:z.symbolName,startLine:z.startLine,startColumn:z.startColumn,endLine:z.endLine,endColumn:z.endColumn,indexedAt:z.indexedAt}));for(let z=0;z<Q.length;z+=M0)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(O0(q_(Z_.project,_),q_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(O0(_.project?q_(Z_.project,_.project):void 0,_.tag?q_(Z_.tag,_.tag):void 0,_.filePath?q_(Z_.filePath,_.filePath):void 0,_.symbolName?q_(Z_.symbolName,_.symbolName):void 0,_.source?q_(Z_.source,_.source):void 0,_.ftsQuery?pJ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as j_,and as L0,sql as h_,gt as lJ,gte as cJ}from"drizzle-orm";var w0=80;class E${db;constructor(_){this.db=_}insertBatch(_){if(!_.length)return;let $=_.map((J)=>({project:J.project,changeType:J.changeType,symbolName:J.symbolName,symbolKind:J.symbolKind,filePath:J.filePath,oldName:J.oldName,oldFilePath:J.oldFilePath,fingerprint:J.fingerprint,changedAt:J.changedAt,isFullIndex:J.isFullIndex,indexRunId:J.indexRunId}));for(let J=0;J<$.length;J+=w0)this.db.drizzleDb.insert(t).values($.slice(J,J+w0)).run()}getSince(_){return this.db.drizzleDb.select().from(t).where(L0(j_(t.project,_.project),cJ(t.changedAt,_.since),_.symbolName?j_(t.symbolName,_.symbolName):void 0,_.changeTypes?.length?h_`${t.changeType} IN (${h_.join(_.changeTypes.map(($)=>h_`${$}`),h_`, `)})`:void 0,_.filePath?j_(t.filePath,_.filePath):void 0,_.includeFullIndex?void 0:j_(t.isFullIndex,0),_.indexRunId?j_(t.indexRunId,_.indexRunId):void 0,_.afterId?lJ(t.id,_.afterId):void 0)).orderBy(t.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(t).where(L0(j_(t.project,_),h_`${t.changedAt} < ${$}`)).run().changes}}function B0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Z=g_(Q.text);if(Z)W=Z}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:W,limit:Q.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}}}))}class J${options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let W=this.adjacencyList.get(z);if(W){for(let Z of W)this.reverseAdjacencyList.get(Z)?.delete(z);W.clear()}let Y=this.reverseAdjacencyList.get(z);if(Y){for(let Z of Y)this.adjacencyList.get(Z)?.delete(z);Y.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let W=J(z);for(let Y of W){if(!this.adjacencyList.has(Y.srcFilePath))this.adjacencyList.set(Y.srcFilePath,new Set);if(this.adjacencyList.get(Y.srcFilePath).add(Y.dstFilePath),!this.adjacencyList.has(Y.dstFilePath))this.adjacencyList.set(Y.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Y.dstFilePath))this.reverseAdjacencyList.set(Y.dstFilePath,new Set);this.reverseAdjacencyList.get(Y.dstFilePath).add(Y.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let W of this.adjacencyList.get(z.node)??[]){if($.has(W))return!0;if(!_.has(W))Q.push({node:W,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return tJ(J,$)}}var aJ=(_,$)=>_.localeCompare($);function sJ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let J=$;for(let Q=1;Q<$.length;Q++){let z=$.slice(Q).concat($.slice(0,Q));if(z.join("::")<J.join("::"))J=z}return[...J]}function v$(_,$,J){let Q=sJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function rJ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Y=[],Z=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let M of _.get(X)??[])if(!z.has(M))Z(M),W.set(X,Math.min(W.get(X)??0,W.get(M)??0));else if(Q.has(M))W.set(X,Math.min(W.get(X)??0,z.get(M)??0));if(W.get(X)===z.get(X)){let M=[],U="";do U=J.pop()??"",Q.delete(U),M.push(U);while(U!==X&&J.length>0);Y.push(M)}};for(let X of _.keys())if(!z.has(X))Z(X);return{components:Y}}function oJ(_,$,J){let Q=[],z=new Set,W=[..._].sort(aJ),Y=(Z,X,M)=>{X.delete(Z);let U=M.get(Z);if(!U)return;for(let w of U)if(X.has(w))Y(w,X,M);U.clear()};for(let Z=0;Z<W.length&&Q.length<J;Z++){let X=W[Z]??"",M=new Set(W.slice(Z)),U=new Set,w=new Map,A=[],S=(q)=>($.get(q)??[]).filter((R)=>M.has(R)),D=(q)=>{if(Q.length>=J)return!0;let R=!1;A.push(q),U.add(q);for(let T of S(q)){if(Q.length>=J)break;if(T===X)v$(z,Q,A.concat(X)),R=!0;else if(!U.has(T)){if(D(T))R=!0}}if(R)Y(q,U,w);else for(let T of S(q)){let b=w.get(T)??new Set;b.add(q),w.set(T,b)}return A.pop(),R};D(X)}return Q}function tJ(_,$){let{components:J}=rJ(_),Q=[],z=new Set;for(let W of J){if(Q.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))v$(z,Q,[X,X]);continue}let Y=$-Q.length,Z=oJ(W,_,Y);for(let X of Z){if(Q.length>=$)break;v$(z,Q,X)}}return Q}var eJ=15000;function Q$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function S_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>eJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new J$({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function K0(_,$,J,Q=1e4){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getDependencies failed",{cause:z})}}function D0(_,$,J,Q=1e4){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getDependents failed",{cause:z})}}async function I0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getAffected failed",{cause:Q})}}async function C0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,$).hasCycle()}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: hasCycle failed",{cause:J})}}async function A0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,$).getAdjacencyList()}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: getImportGraph failed",{cause:J})}}async function N0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function q0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function S0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return S_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getCyclePaths failed",{cause:Q})}}async function u0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let Q=S_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getFanMetrics failed",{cause:Q})}}var JQ=30000,g0=15000,QQ=10;function zQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??k_.basename(_.projectRoot)}function WQ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof H?Q:new H("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let W of _.onErrorCallbacks)try{W(z instanceof H?z:new H("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function ZQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=k_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function R0(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new A$({projectRoot:_.projectRoot,boundaries:_.boundaries,extensions:_.extensions,ignorePatterns:_.ignorePatterns,dbConnection:_.db,parseCache:_.parseCache,fileRepo:_.fileRepo,symbolRepo:_.symbolRepo,relationRepo:_.relationRepo,annotationRepo:_.annotationRepo??void 0,changelogRepo:_.changelogRepo??void 0,onBoundariesChanged:(Q)=>zQ(_,Q),logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let W=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Y)=>{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===Y||X.dstFilePath===Y)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else Q$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new M$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(WQ(_,J)).then((z)=>{if(i_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},JQ)}await J.fullIndex(),await ZQ(_)}function YQ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((W)=>_.logger.error("[Gildash] close error during signal",Q,W))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function T0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:W=console,existsSyncFn:Y=$Q,dbConnectionFactory:Z,watcherFactory:X,coordinatorFactory:M,repositoryFactory:U,acquireWatcherRoleFn:w=W0,releaseWatcherRoleFn:A=Z0,updateHeartbeatFn:S=Y0,discoverProjectsFn:D=c_,parseSourceFn:q=T_,extractSymbolsFn:R=C_,extractRelationsFn:T=m_,symbolSearchFn:b=q$,relationSearchFn:v=S$,patternSearchFn:P=u$,loadTsconfigPathsFn:d=y_,readFileFn:c=async(L)=>Bun.file(L).text(),unlinkFn:Y_=async(L)=>{await Bun.file(L).unlink()},watchMode:X_,semantic:H_,semanticLayerFactory:__}=_;if(!k_.isAbsolute($))throw new H("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Y($))throw new H("validation",`Gildash: projectRoot does not exist: "${$}"`);let $_=Z?Z():new X$({projectRoot:$}),p=$_.open();if(i_(p))throw p.data;try{let L=await D($),u=L[0]?.project??k_.basename($),N=U?U():(()=>{let F=$_;return{fileRepo:new U$(F),symbolRepo:new V$(F),relationRepo:new H$(F),parseCache:new N$(z)}})(),B=U?null:$_,V=B?new k$(B):null,O=B?new E$(B):null,K=X_??!0,C=crypto.randomUUID(),g;if(K)g=await Promise.resolve(w($_,process.pid,{instanceId:C}));else g="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:u,role:g,db:$_,symbolRepo:N.symbolRepo,relationRepo:N.relationRepo,fileRepo:N.fileRepo,parseCache:N.parseCache,annotationRepo:V,changelogRepo:O,annotationSearchFn:B0,releaseWatcherRoleFn:A,parseSourceFn:q,extractSymbolsFn:R,extractRelationsFn:T,symbolSearchFn:b,relationSearchFn:v,patternSearchFn:P,readFileFn:c,unlinkFn:Y_,existsSyncFn:Y,acquireWatcherRoleFn:w,updateHeartbeatFn:S,watcherFactory:X,coordinatorFactory:M,instanceId:C,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:L,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(a_($),I.tsconfigPaths=await d($),H_){let F=k_.join($,"tsconfig.json");try{if(__)I.semanticLayer=__(F);else{let G=$$.create(F);if(i_(G))throw G.data;I.semanticLayer=G}}catch(G){if(G instanceof H)throw G;throw new H("semantic","Gildash: semantic layer creation failed",{cause:G})}}if(g==="owner")await R0(I,{isWatchMode:K});else{let F=0,G=async()=>{try{let k=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(F=0,k==="owner"){I.role="owner";for(let j of I.onRoleChangedCallbacks)try{j("owner")}catch(y){I.logger.error("[Gildash] onRoleChanged callback threw:",y)}clearInterval(I.timer),I.timer=null;try{await R0(I,{isWatchMode:!0})}catch(j){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",j),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let y=await I.watcher.close();if(i_(y))I.logger.error("[Gildash] watcher close error during promotion rollback",y.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((y)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",y)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(y){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",y)}I.timer=setInterval(G,g0)}}}catch(k){F++;let j=k instanceof H?k:new H("watcher","Gildash: healthcheck error",{cause:k});for(let y of I.onErrorCallbacks)try{y(j)}catch(J_){I.logger.error("[Gildash] onError callback threw:",J_)}if(I.logger.error("[Gildash] healthcheck error",k),F>=QQ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,z$(I).catch((y)=>I.logger.error("[Gildash] close error during healthcheck shutdown",y))}};I.timer=setInterval(G,g0)}if(K)YQ(I,()=>z$(I));return I}catch(L){if($_.close(),L instanceof H)throw L;throw new H("store","Gildash: initialization failed",{cause:L})}}async function z$(_,$){if(_.closed)return;_.closed=!0;let J=[];for(let[Q,z]of _.signalHandlers)if(Q==="beforeExit")process.off("beforeExit",z);else process.off(Q,z);if(_.signalHandlers=[],_.semanticLayer){try{_.semanticLayer.dispose()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}_.semanticLayer=null}if(_.coordinator)try{await _.coordinator.shutdown()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if(_.watcher){let Q=await _.watcher.close();if(i_(Q))J.push(Q.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}try{_.db.close()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if($?.cleanup)for(let Q of["","-wal","-shm"])try{await _.unlinkFn(k_.join(_.projectRoot,B_,p_+Q))}catch{}if(J.length>0)throw new H("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as F0}from"@zipbul/result";function G0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(F0(z))throw z.data;return _.parseCache.set($,z),z}async function j0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Y=await _.readFileFn(W),Z=_.parseSourceFn(W,Y,J);if(!F0(Z))Q.set(W,Z);else z.push({filePath:W,error:Z.data})}catch(Y){z.push({filePath:W,error:Y instanceof Error?Y:Error(String(Y))})}})),{parsed:Q,failures:z}}function k0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");return _.parseCache.get($)}function E0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function v0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import b0 from"path";function f0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof H)throw J;throw new H("store","Gildash: getStats failed",{cause:J})}}function b$(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: searchSymbols failed",{cause:J})}}function P0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: searchRelations failed",{cause:J})}}function y0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: searchAllSymbols failed",{cause:J})}}function x0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: searchAllRelations failed",{cause:J})}}function m0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof H)throw J;throw new H("store","Gildash: listIndexedFiles failed",{cause:J})}}function n0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getInternalRelations failed",{cause:Q})}}function h0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Y=W[0],Z=Y.detail,X={...Y,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 M=b0.isAbsolute(J)?J:b0.resolve(_.projectRoot,J),U=_.semanticLayer.lineColumnToPosition(M,Y.span.start.line,Y.span.start.column);if(U!==null){let w=_.semanticLayer.findNamePosition(M,U,Y.name)??U,A=_.semanticLayer.collectTypeAt(M,w);if(A)X.resolvedType=A}}catch{}return X}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getFullSymbol failed",{cause:z})}}function i0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new H("search",`Gildash: file '${$}' is not in the index`);let W=_.symbolRepo.getFileSymbols(Q,$),Y=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Z)=>Z.isExported).length,relationCount:Y.length}}catch(Q){if(Q instanceof H)throw Q;throw new H("store","Gildash: getFileStats failed",{cause:Q})}}function d0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof H)throw Q;throw new H("store","Gildash: getFileInfo failed",{cause:Q})}}function p0(_,$,J){return b$(_,{filePath:$,project:J??void 0,limit:1e4})}function l0(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Y)=>`${Y.name}${Y.isOptional?"?":""}: ${Y.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: getModuleInterface failed",{cause:Q})}}import x from"path";function d_(_,$,J,Q){let z=Q??_.defaultProject,W=x.isAbsolute(J)?x.relative(_.projectRoot,J):J,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:W,limit:1}});if(Y.length===0)return null;let Z=Y[0],X=x.isAbsolute(J)?J:x.resolve(_.projectRoot,J),M=_.semanticLayer.lineColumnToPosition(X,Z.span.start.line,Z.span.start.column);if(M===null)return null;let U=_.semanticLayer.findNamePosition(X,M,Z.name)??M;return{sym:Z,position:U,absPath:X}}function c0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=d_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getResolvedType failed",{cause:z})}}function a0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=d_(_,$,J,Q);if(!z)throw new H("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getSemanticReferences failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=d_(_,$,J,Q);if(!z)throw new H("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getImplementations failed",{cause:z})}}function r0(_,$,J,Q,z,W){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Y=d_(_,$,J,W);if(!Y)throw new H("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Z=d_(_,Q,z,W);if(!Z)throw new H("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Y.absPath,Y.position,Z.absPath,Z.position)}catch(Y){if(Y instanceof H)throw Y;throw new H("semantic","Gildash: isTypeAssignableTo failed",{cause:Y})}}function o0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let J=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof H)throw J;throw new H("semantic","Gildash: getFileTypes failed",{cause:J})}}function t0(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=x.isAbsolute($)?$:x.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof H)throw z;throw new H("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function e0(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let J=x.isAbsolute($.source.filePath)?$.source.filePath:x.resolve(_.projectRoot,$.source.filePath),Q=x.isAbsolute($.target.filePath)?$.target.filePath:x.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let W=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,W)}catch(J){if(J instanceof H)throw J;throw new H("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function _1(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof H)throw J;throw new H("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function $1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function J1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function W1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function Z1(_,$,J,Q,z){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let W=x.isAbsolute($)?$:x.resolve(_.projectRoot,$),Y=x.isAbsolute(Q)?Q:x.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Y,z)}catch(W){if(W instanceof H)throw W;throw new H("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function Y1(_,$,J,Q,z){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let W=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof H)throw W;throw new H("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function X1(_,$,J,Q,z){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let W=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof H)throw W;throw new H("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function U1(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof H)throw z;throw new H("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function V1(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let z=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof H)throw z;throw new H("semantic","Gildash: findNamePosition failed",{cause:z})}}function H1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function O1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new H("semantic","Gildash: semantic layer is not enabled");try{let Q=x.isAbsolute($)?$:x.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof H)throw Q;throw new H("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function M1(_,$){let J=new Map(_.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),Q=new Map($.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),z=[],W=[],Y=[];for(let[Z,X]of Q){let M=J.get(Z);if(!M)z.push(X);else if(M.fingerprint!==X.fingerprint)Y.push({before:M,after:X})}for(let[Z,X]of J)if(!Q.has(Z))W.push(X);return{added:z,removed:W,modified:Y}}function L1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function w1(_){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.coordinator)throw new H("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return Q$(_),$}catch($){if($ instanceof H)throw $;throw new H("index","Gildash: reindex failed",{cause:$})}}function B1(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Y=[],Z=$,X=J;for(;;){let M=`${X}::${Z}`;if(W.has(M))return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!0};W.add(M);let U=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),w,A;for(let S of U){let D;if(S.metaJson)try{let R=JSON.parse(S.metaJson);if(Array.isArray(R.specifiers))D=R.specifiers}catch{}if(!D)continue;let q=D.find((R)=>R.exported===Z);if(!q)continue;w=S.dstFilePath??void 0,A=q.local;break}if(!w||!A)return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!1};Y.push({filePath:X,exportedAs:Z}),X=w,Z=A}}function K1(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function D1(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function I1(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function C1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((W)=>W.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof H)throw Q;throw new H("search","Gildash: findPattern failed",{cause:Q})}}async function A1(_,$,J,Q){if(_.closed)throw new H("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Y=(Z,X,M)=>{let U=`${Z}::${X}`;if(W.has(U))return{symbolName:Z,filePath:X,kind:M,children:[]};W.add(U);let S=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Z,limit:1000}}).filter((D)=>D.type==="extends"||D.type==="implements").filter((D)=>D.dstSymbolName!=null&&D.dstFilePath!=null).map((D)=>Y(D.dstSymbolName,D.dstFilePath,D.type));return{symbolName:Z,filePath:X,kind:M,children:S}};return Y($,J)}catch(z){if(z instanceof H)throw z;throw new H("search","Gildash: getHeritageChain failed",{cause:z})}}function N1(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function q1(_,$,J){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,W=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:W}).map((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 S1(_,$){if(_.closed)throw new H("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Y)=>Y.project)],W=[...new Set(z)];for(let Y of W)Q+=_.changelogRepo.pruneOlderThan(Y,J);return Q}class f${_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 T0(_);return new f$($)}async close(_){return z$(this._ctx,_)}parseSource(_,$,J){return G0(this._ctx,_,$,J)}async batchParse(_,$){return j0(this._ctx,_,$)}getParsedAst(_){return k0(this._ctx,_)}extractSymbols(_){return E0(this._ctx,_)}extractRelations(_){return v0(this._ctx,_)}getStats(_){return f0(this._ctx,_)}searchSymbols(_){return b$(this._ctx,_)}searchRelations(_){return P0(this._ctx,_)}searchAllSymbols(_){return y0(this._ctx,_)}searchAllRelations(_){return x0(this._ctx,_)}listIndexedFiles(_){return m0(this._ctx,_)}getInternalRelations(_,$){return n0(this._ctx,_,$)}getFullSymbol(_,$,J){return h0(this._ctx,_,$,J)}getFileStats(_,$){return i0(this._ctx,_,$)}getFileInfo(_,$){return d0(this._ctx,_,$)}getSymbolsByFile(_,$){return p0(this._ctx,_,$)}getModuleInterface(_,$){return l0(this._ctx,_,$)}getDependencies(_,$,J=1e4){return K0(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return D0(this._ctx,_,$,J)}async getAffected(_,$){return I0(this._ctx,_,$)}async hasCycle(_){return C0(this._ctx,_)}async getImportGraph(_){return A0(this._ctx,_)}async getTransitiveDependencies(_,$){return N0(this._ctx,_,$)}async getTransitiveDependents(_,$){return q0(this._ctx,_,$)}async getCyclePaths(_,$){return S0(this._ctx,_,$)}async getFanMetrics(_,$){return u0(this._ctx,_,$)}getResolvedType(_,$,J){return c0(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return a0(this._ctx,_,$,J)}getImplementations(_,$,J){return s0(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return r0(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return _1(this._ctx,_)}getFileTypes(_){return o0(this._ctx,_)}getResolvedTypeAt(_,$,J){return t0(this._ctx,_,$,J)}isTypeAssignableToAt(_){return e0(this._ctx,_)}getResolvedTypeAtPosition(_,$){return Q1(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return J1(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return z1(this._ctx,_,$)}getImplementationsAtPosition(_,$){return W1(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return Z1(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return Y1(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return X1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return U1(this._ctx,_,$,J)}findNamePosition(_,$,J){return V1(this._ctx,_,$,J)}getSymbolNode(_,$){return H1(this._ctx,_,$)}getBaseTypes(_,$){return $1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return O1(this._ctx,_,$)}diffSymbols(_,$){return M1(_,$)}onIndexed(_){return L1(this._ctx,_)}async reindex(){return w1(this._ctx)}resolveSymbol(_,$,J){return B1(this._ctx,_,$,J)}async findPattern(_,$){return C1(this._ctx,_,$)}async getHeritageChain(_,$,J){return A1(this._ctx,_,$,J)}onFileChanged(_){return K1(this._ctx,_)}onError(_){return D1(this._ctx,_)}onRoleChanged(_){return I1(this._ctx,_)}searchAnnotations(_){return N1(this._ctx,_)}getSymbolChanges(_,$){return q1(this._ctx,_,$)}pruneChangelog(_){return S1(this._ctx,_)}}import{Visitor as V3,visitorKeys as H3}from"oxc-parser";export{H3 as visitorKeys,q$ as symbolSearch,S$ as relationSearch,u$ as patternSearch,T_ as parseSource,z_ as normalizePath,U_ as getLineColumn,C_ as extractSymbols,m_ as extractRelations,x_ as buildLineOffsets,V3 as Visitor,H as GildashError,f$ as Gildash,J$ as DependencyGraph};
2
+ var F$=Object.defineProperty;var g$=(_)=>_;function j$(_,$){this[_]=g$.bind(null,$)}var k$=(_,$)=>{for(var Q in $)F$(_,Q,{get:$[Q],enumerable:!0,configurable:!0,set:j$.bind($,Q)})};var x0=import.meta.require;import{isErr as p_}from"@zipbul/result";import v_ from"path";import{existsSync as JJ}from"fs";import{err as h0,isErr as f$}from"@zipbul/result";import{Database as y$}from"bun:sqlite";import{mkdirSync as x$,unlinkSync as n0,existsSync as m0}from"fs";import{dirname as h$,join as d0}from"path";import{drizzle as n$}from"drizzle-orm/bun-sqlite";import{migrate as m$}from"drizzle-orm/bun-sqlite/migrator";class O extends Error{type;constructor(_,$,Q){super($,Q);this.type=_;this.name="GildashError"}}var I_=".gildash",l_="gildash.db";var V0={};k$(V0,{watcherOwner:()=>P$,symbols:()=>f,symbolChangelog:()=>t,relations:()=>k,files:()=>s,annotations:()=>z_});import{sql as u$}from"drizzle-orm";import{sqliteTable as G_,text as b,integer as a,real as E$,index as $_,primaryKey as v$,foreignKey as X0,check as b$}from"drizzle-orm/sqlite-core";var s=G_("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:E$("mtime_ms").notNull(),size:a("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:a("line_count")},(_)=>[v$({columns:[_.project,_.filePath]})]),f=G_("symbols",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),isExported:a("is_exported").notNull().default(0),signature:b("signature"),fingerprint:b("fingerprint"),detailJson:b("detail_json"),contentHash:b("content_hash").notNull(),indexedAt:b("indexed_at").notNull(),resolvedType:b("resolved_type"),structuralFingerprint:b("structural_fingerprint")},(_)=>[$_("idx_symbols_project_file").on(_.project,_.filePath),$_("idx_symbols_project_kind").on(_.project,_.kind),$_("idx_symbols_project_name").on(_.project,_.name),$_("idx_symbols_fingerprint").on(_.project,_.fingerprint),X0({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),k=G_("relations",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),type:b("type").notNull(),srcFilePath:b("src_file_path").notNull(),srcSymbolName:b("src_symbol_name"),dstProject:b("dst_project"),dstFilePath:b("dst_file_path"),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json"),specifier:b("specifier"),isExternal:a("is_external").notNull().default(0)},(_)=>[$_("idx_relations_src").on(_.project,_.srcFilePath),$_("idx_relations_dst").on(_.dstProject,_.dstFilePath),$_("idx_relations_type").on(_.project,_.type),$_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),$_("idx_relations_specifier").on(_.project,_.specifier),X0({columns:[_.project,_.srcFilePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),z_=G_("annotations",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),tag:b("tag").notNull(),value:b("value").notNull().default(""),source:b("source").notNull(),symbolName:b("symbol_name"),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),indexedAt:b("indexed_at").notNull()},(_)=>[$_("idx_annotations_project_file").on(_.project,_.filePath),$_("idx_annotations_project_tag").on(_.project,_.tag),$_("idx_annotations_project_symbol").on(_.project,_.symbolName),X0({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),t=G_("symbol_changelog",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),changeType:b("change_type").notNull(),symbolName:b("symbol_name").notNull(),symbolKind:b("symbol_kind").notNull(),filePath:b("file_path").notNull(),oldName:b("old_name"),oldFilePath:b("old_file_path"),fingerprint:b("fingerprint"),changedAt:b("changed_at").notNull(),isFullIndex:a("is_full_index").notNull().default(0),indexRunId:b("index_run_id").notNull()},(_)=>[$_("idx_changelog_project_changed_at").on(_.project,_.changedAt),$_("idx_changelog_project_name").on(_.project,_.symbolName),$_("idx_changelog_project_run").on(_.project,_.indexRunId)]),P$=G_("watcher_owner",{id:a("id").primaryKey(),pid:a("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull(),instanceId:b("instance_id")},(_)=>[b$("watcher_owner_singleton",u$`${_.id} = 1`)]);class U0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=d0(_.projectRoot,I_,l_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{x$(h$(this.dbPath),{recursive:!0}),this.client=new y$(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=n$(this.client,{schema:V0}),m$(this.drizzle,{migrationsFolder:d0(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(_)&&m0(this.dbPath)){this.closeClient(),n0(this.dbPath);for(let Q of["-wal","-shm"]){let J=this.dbPath+Q;if(m0(J))n0(J)}let $=this.open();if(f$($))return h0(new O("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return h0(new O("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 b_,and as p0}from"drizzle-orm";class O0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(s).where(p0(b_(s.project,_),b_(s.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(s).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[s.project,s.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(s).where(b_(s.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(s).where(p0(b_(s.project,_),b_(s.filePath,$))).run()}}import{eq as r,and as A_,sql as c_,count as d$}from"drizzle-orm";function F_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i0=50;class H0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,Q,J){if(this.db.drizzleDb.delete(f).where(A_(r(f.project,_),r(f.filePath,$))).run(),!J.length)return;let W=new Date().toISOString(),z=J.map((Y)=>({project:_,filePath:$,kind:Y.kind??"unknown",name:Y.name??"",startLine:Y.startLine??0,startColumn:Y.startColumn??0,endLine:Y.endLine??0,endColumn:Y.endColumn??0,isExported:Y.isExported??0,signature:Y.signature??null,fingerprint:Y.fingerprint??null,detailJson:Y.detailJson??null,contentHash:Q,indexedAt:Y.indexedAt??W,resolvedType:Y.resolvedType??null,structuralFingerprint:Y.structuralFingerprint??null}));for(let Y=0;Y<z.length;Y+=i0)this.db.drizzleDb.insert(f).values(z.slice(Y,Y+i0)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.filePath,$))).all()}searchByName(_,$,Q={}){let J=Q.limit??50,W=F_($);if(!W)return[];return this.db.drizzleDb.select().from(f).where(A_(c_`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${W})`,r(f.project,_),Q.kind?r(f.kind,Q.kind):void 0)).orderBy(f.name).limit(J).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.kind,$))).orderBy(f.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:d$(),fileCount:c_`COUNT(DISTINCT ${f.filePath})`}).from(f).where(r(f.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(f).where(A_(r(f.project,_),r(f.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(f).where(A_(_.ftsQuery?c_`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?r(f.name,_.exactName):void 0,_.project!==void 0?r(f.project,_.project):void 0,_.kind?r(f.kind,_.kind):void 0,_.filePath!==void 0?r(f.filePath,_.filePath):void 0,_.isExported!==void 0?r(f.isExported,_.isExported?1:0):void 0,_.decorator?c_`${f.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?r(f.resolvedType,_.resolvedType):void 0)).orderBy(f.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let Q;try{Q=new RegExp(_.regex)}catch{throw new O("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((z)=>Q.test(z.name));let J=[];for(let W of[5,20,100]){let z=_.limit*W,Y=$.limit(z).all();if(J=Y.filter((Z)=>Q.test(Z.name)),J.length>=_.limit||Y.length<z)return J.slice(0,_.limit)}return J.slice(0,_.limit)}}import{eq as h,and as H_,isNull as l0,or as p$}from"drizzle-orm";var P_={project:k.project,type:k.type,srcFilePath:k.srcFilePath,srcSymbolName:k.srcSymbolName,dstProject:k.dstProject,dstFilePath:k.dstFilePath,dstSymbolName:k.dstSymbolName,metaJson:k.metaJson,specifier:k.specifier,isExternal:k.isExternal};class M0{db;constructor(_){this.db=_}replaceFileRelations(_,$,Q){this.db.transaction((J)=>{if(J.drizzleDb.delete(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).run(),!Q.length)return;for(let W of Q)J.drizzleDb.insert(k).values({project:_,type:W.type??"unknown",srcFilePath:W.srcFilePath??$,srcSymbolName:W.srcSymbolName??null,dstProject:W.dstProject??(W.dstFilePath!=null?_:null),dstFilePath:W.dstFilePath??null,dstSymbolName:W.dstSymbolName??null,metaJson:W.metaJson??null,specifier:W.specifier??null,isExternal:W.isExternal??0}).run()})}getOutgoing(_,$,Q){if(Q!==void 0)return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.srcFilePath,$),p$(h(k.srcSymbolName,Q),l0(k.srcSymbolName)))).all();return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:Q}=_;return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.dstProject,$),h(k.dstFilePath,Q))).all()}getByType(_,$){return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(k).where(H_(h(k.dstProject,_),h(k.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(P_).from(k).where(H_(_.project!==void 0?h(k.project,_.project):void 0,_.srcFilePath!==void 0?h(k.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?h(k.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?h(k.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?h(k.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?h(k.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?h(k.type,_.type):void 0,_.specifier!==void 0?h(k.specifier,_.specifier):void 0,_.isExternal!==void 0?h(k.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:Q,oldSymbol:J,newFile:W,newSymbol:z,newDstProject:Y}=_,Z=J===null?H_(h(k.dstProject,$),h(k.dstFilePath,Q),l0(k.dstSymbolName)):H_(h(k.dstProject,$),h(k.dstFilePath,Q),h(k.dstSymbolName,J)),X={dstFilePath:W,dstSymbolName:z};if(Y!==void 0)X.dstProject=Y;this.db.drizzleDb.update(k).set(X).where(Z).run()}}import{err as a0}from"@zipbul/result";import{subscribe as i$}from"@parcel/watcher";import K0 from"path";import c0 from"path";function Q_(_){return _.replaceAll("\\","/")}function f_(_,$){return Q_(c0.relative(_,$))}function g_(_,$){return Q_(c0.resolve(_,$))}var l$=["**/.git/**",`**/${I_}/**`,"**/dist/**","**/node_modules/**"],c$=new Set(["package.json","tsconfig.json"]);function a$(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class L0{#_;#$;#Q;#Z;#W;#z;constructor(_,$=i$,Q=console){this.#$=_.projectRoot,this.#Q=[...l$,..._.ignorePatterns??[]],this.#Z=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 O("watcher","Callback error",{cause:$}));return}try{for(let J of Q){let W=Q_(K0.relative(this.#$,J.path));if(W.startsWith(".."))continue;let z=K0.basename(W),Y=K0.extname(W).toLowerCase();if(!c$.has(z)&&!this.#Z.has(Y))continue;if(W.endsWith(".d.ts"))continue;_({eventType:a$(J.type),filePath:W})}}catch(J){this.#z.error(new O("watcher","Callback error",{cause:J}))}},{ignore:this.#Q})}catch($){return a0(new O("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return a0(new O("watcher","Failed to close watcher",{cause:_}))}}}import B0 from"path";var s$=["**/node_modules/**","**/.git/**",`**/${I_}/**`,"**/dist/**"],r$=s$.map((_)=>new Bun.Glob(_));function o$(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function a_(_,$=o$){let Q=[];for await(let J of $(_)){let W=Q_(J);if(r$.some((K)=>K.match(W)))continue;let z=Q_(B0.dirname(J)),Y=B0.join(_,J),Z=await Bun.file(Y).json(),X=typeof Z?.name==="string"&&Z.name.length>0?Z.name:B0.basename(z==="."?_:z);Q.push({dir:z,project:X})}return Q.sort((J,W)=>W.dir.length-J.dir.length),Q}function l(_,$,Q="default"){let J=Q_(_);for(let W of $){if(W.dir===".")return W.project;if(J===W.dir||J.startsWith(`${W.dir}/`))return W.project}return Q}import y_ from"path";var C_=new Map;async function t$(_){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 e$(_,$){if($.startsWith(".")){let Q=y_.resolve(_,$);return Q.endsWith(".json")?Q:Q+".json"}return y_.resolve(_,"node_modules",$)}async function s0(_,$=5){if($<=0)return null;let Q=await t$(_);if(!Q)return null;let J=Q.extends;if(typeof J!=="string"||!J)return Q;let W=e$(y_.dirname(_),J),z=await s0(W,$-1);if(!z)return Q;let Y=typeof z.compilerOptions==="object"&&z.compilerOptions!==null?z.compilerOptions:{},Z=typeof Q.compilerOptions==="object"&&Q.compilerOptions!==null?Q.compilerOptions:{};return{...z,...Q,compilerOptions:{...Y,...Z}}}async function x_(_){if(C_.has(_))return C_.get(_)??null;let $=y_.join(_,"tsconfig.json"),Q=await s0($);if(!Q)return C_.set(_,null),null;let J=typeof Q.compilerOptions==="object"&&Q.compilerOptions!==null?Q.compilerOptions:null;if(!J)return C_.set(_,null),null;let W=typeof J.baseUrl==="string"?J.baseUrl:null,z=typeof J.paths==="object"&&J.paths!==null?J.paths:null;if(!W&&!z)return C_.set(_,null),null;let Y=W?y_.resolve(_,W):_,Z=new Map;if(z)for(let[K,U]of Object.entries(z)){if(!Array.isArray(U))continue;let L=U.filter((C)=>typeof C==="string");Z.set(K,L)}let X={baseUrl:Y,paths:Z};return C_.set(_,X),X}function s_(_){if(_){C_.delete(_);return}C_.clear()}function U_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as z1}from"@zipbul/result";import{err as _Q}from"@zipbul/result";import{parseSync as $Q}from"oxc-parser";function j_(_,$,Q,J=$Q){try{let W={preserveParens:!1,...Q},z=J(_,$,W);return{filePath:_,program:z.program,errors:z.errors,comments:z.comments,sourceText:$,module:z.module}}catch(W){return _Q(new O("parse",`Failed to parse file: ${_}`,{cause:W}))}}import{join as QQ}from"path";function JQ(_,$){let Q=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(Q).scan({cwd:_,followSymlinks:!1})}async function r0(_){let{projectRoot:$,extensions:Q,ignorePatterns:J,fileRepo:W,scanFilesFn:z=JQ}=_,Y=W.getFilesMap(),Z=new Set,X=[],K=[],U=J.map((C)=>new Bun.Glob(C));for await(let C of z($,Q)){let q=Q_(C);if(!Q.some((d)=>q.endsWith(d)))continue;if(q.startsWith("node_modules/")||q.includes("/node_modules/"))continue;if(U.some((d)=>d.match(q)))continue;Z.add(q);let w=QQ($,q),S=Bun.file(w),{size:F,lastModified:G}=S,E=Y.get(q);if(!E){let d=await S.text(),p=U_(d);X.push({filePath:q,contentHash:p,mtimeMs:G,size:F});continue}if(E.mtimeMs===G&&E.size===F){K.push({filePath:q,contentHash:E.contentHash,mtimeMs:G,size:F});continue}let u=await S.text(),y=U_(u);if(y===E.contentHash)K.push({filePath:q,contentHash:y,mtimeMs:G,size:F});else X.push({filePath:q,contentHash:y,mtimeMs:G,size:F})}let L=[];for(let C of Y.keys())if(!Z.has(C))L.push(C);return{changed:X,unchanged:K,deleted:L}}function h_(_){let $=[0];for(let Q=0;Q<_.length;Q++)if(_[Q]===`
3
+ `)$.push(Q+1);return $}function V_(_,$){let Q=0,J=_.length-1;while(Q<J){let W=Q+J+1>>1;if(_[W]<=$)Q=W;else J=W-1}return{line:Q+1,column:$-_[Q]}}import{err as WQ}from"@zipbul/result";import{parse as zQ}from"comment-parser";function r_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let J=zQ(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(J.description??"").trim(),tags:(J.tags??[]).map((W)=>({tag:W.tag??"",name:W.name??"",type:W.type??"",description:W.description??"",optional:W.optional??!1,...W.default!==void 0?{default:W.default}:{}}))}}catch($){return WQ(new O("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as ZQ}from"@zipbul/result";function YQ(_){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 k_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let Q of _.properties)if(Q.type==="RestElement")$.push(...k_(Q.argument));else $.push(...k_(Q.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let Q of _.elements){if(!Q)continue;if(Q.type==="RestElement")$.push(...k_(Q.argument));else $.push(...k_(Q))}return $}if(_.type==="AssignmentPattern")return k_(_.left);return[]}function XQ(_){let $=new Map;for(let Q of _.module.staticImports){let J=Q.moduleRequest.value;for(let W of Q.entries){let z=W.localName.value,Y=W.importName.kind==="Name"?W.importName.name:void 0,Z={specifier:J};if(Y&&Y!==z)Z.originalName=Y;$.set(z,Z)}}return $}function N_(_){let{program:$,sourceText:Q,comments:J}=_,W=h_(Q),z=XQ(_),Y=J.filter((I)=>I.type==="Block"&&I.value.startsWith("*")).sort((I,N)=>I.end-N.end),Z=$.body.map((I)=>I.start).sort((I,N)=>I-N);function X(I,N){return G(I,N)}function K(I,N,V){if(I.type==="PrivateIdentifier")return{kind:"private"};if(!N&&I.type==="Identifier")return;return X(I,V)}function U(I,N){if(N)return Q.slice(I.start,I.end);if(I.type==="PrivateIdentifier")return`#${I.name}`;return YQ(I)}function L(I,N,V){let H=I;if(!N&&H.type==="Identifier")return{kind:"string",value:H.name};return X(I,V)}function C(I,N){return{start:V_(W,I),end:V_(W,N)}}function q(I){let N=0,V=Y.length-1,H=-1;while(N<=V){let B=N+V>>>1;if(Y[B].end<=I)H=B,N=B+1;else V=B-1}if(H<0)return;let M=Y[H];N=0,V=Z.length-1;while(N<=V){let B=N+V>>>1,A=Z[B];if(A<=M.end)N=B+1;else if(A>=I)V=B-1;else return}return`/*${M.value}*/`}function w(I){if(!I)return;let N="typeAnnotation"in I&&I.typeAnnotation?I.typeAnnotation:I;return Q.slice(N.start,N.end)}let S=8;function F(I){if(I.type==="Identifier")return z.get(I.name);if(I.type==="MemberExpression"){let N=I.object;if(N.type==="Identifier")return z.get(N.name)}return}function G(I,N=0){let V=I;if(N>=S)return{kind:"unresolvable",sourceText:Q.slice(V.start,V.end)};let H=V.type;if(H==="Literal"){let M=V.value;if(typeof M==="bigint")return{kind:"bigint",value:typeof V.bigint==="string"?V.bigint:M.toString()};if(typeof V.regex==="object"&&V.regex!==null)return{kind:"regex",value:Q.slice(V.start,V.end)};if(M===null)return{kind:"null",value:null};if(typeof M==="string")return{kind:"string",value:M};if(typeof M==="number")return{kind:"number",value:M};if(typeof M==="boolean")return{kind:"boolean",value:M};return{kind:"unresolvable",sourceText:Q.slice(V.start,V.end)}}if(H==="Identifier"){let M=V.name;if(M==="undefined")return{kind:"undefined",value:null};let B=z.get(M),A={kind:"identifier",name:M};if(B){if(A.importSource=B.specifier,B.originalName)A.originalName=B.originalName}return A}if(H==="MemberExpression"){if(V.computed){let g=V.property;if(g.type==="Literal"&&typeof g.value==="string"){let j=V.object,v=Q.slice(j.start,j.end),m=j.type==="Identifier"?j.name:void 0,__=m?z.get(m):void 0,X_={kind:"member",object:v,property:g.value};if(__)X_.importSource=__.specifier;return X_}return{kind:"unresolvable",sourceText:Q.slice(V.start,V.end)}}let M=V.object,B=Q.slice(M.start,M.end),A=V.property.name??Q.slice(V.property.start,V.property.end),D=M.type==="Identifier"?M.name:void 0,T=D?z.get(D):void 0,R={kind:"member",object:B,property:A};if(T)R.importSource=T.specifier;return R}if(H==="CallExpression"){let M=V.callee,B=Q.slice(M.start,M.end),D=(V.arguments??[]).map((g)=>G(g,N+1)),T=F(M),R={kind:"call",callee:B,arguments:D};if(T)R.importSource=T.specifier;return R}if(H==="NewExpression"){let M=V.callee,B=Q.slice(M.start,M.end),D=(V.arguments??[]).map((g)=>G(g,N+1)),T=F(M),R={kind:"new",callee:B,arguments:D};if(T)R.importSource=T.specifier;return R}if(H==="ObjectExpression"){let M=V.properties??[],B=[];for(let A of M){if(A.type==="SpreadElement"){let m=A.argument;B.push({kind:"spread",argument:G(m,N+1)});continue}let D=A.key,T=A.computed===!0,R=A.value,g=A.shorthand||void 0,v={kind:"property",key:L(D,T,N+1),value:G(R,N+1)};if(g)v.shorthand=!0;B.push(v)}return{kind:"object",properties:B}}if(H==="ArrayExpression")return{kind:"array",elements:(V.elements??[]).map((A)=>{if(!A)return{kind:"undefined",value:null};return G(A,N+1)})};if(H==="SpreadElement"){let M=V.argument;return{kind:"spread",argument:G(M,N+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let B=V.params.map(u),A={kind:"function",sourceText:Q.slice(V.start,V.end)};if(B.length>0)A.parameters=B;return A}if(H==="TemplateLiteral"||H==="TaggedTemplateExpression")return{kind:"template",sourceText:Q.slice(V.start,V.end)};if(H==="UnaryExpression"){let{operator:M,argument:B}=V;if(M==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(M==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:Q.slice(V.start,V.end)}}if(H==="TSAsExpression"||H==="TSSatisfiesExpression"||H==="TSNonNullExpression"||H==="TSTypeAssertion"||H==="TSInstantiationExpression"||H==="ParenthesizedExpression"||H==="ChainExpression"){let M=V.expression;if(M)return G(M,N)}return{kind:"unresolvable",sourceText:Q.slice(V.start,V.end)}}function E(I){if(!I||I.length===0)return[];return I.map((N)=>{let V=N.expression;if(V.type==="CallExpression"){let H=V,M=H.callee,B="name"in M&&typeof M.name==="string"?M.name:("property"in M)&&M.property&&typeof M.property.name==="string"?M.property.name:"unknown",A=H.arguments.map((D)=>G(D));return{name:B,arguments:A.length>0?A:void 0}}if(V.type==="Identifier")return{name:V.name??"unknown"};return{name:Q.slice(V.start,V.end)}})}function u(I){if(I.type==="TSParameterProperty"){let V=I;return d(V.parameter,V.decorators)}if(I.type==="RestElement"){let V=I,H=V.argument,B=`...${"name"in H&&typeof H.name==="string"?H.name:"unknown"}`,A=V.typeAnnotation,D=A?w(A):void 0,T={name:B,isOptional:!1};if(D)T.type=D;return T}let N=I;return d(N,N.decorators)}function y(I){if(!I)return;let N="typeAnnotation"in I&&I.typeAnnotation?I.typeAnnotation:null;if(!N)return;let H=N.typeName?.name;if(!H)return;return z.get(H)?.specifier}function d(I,N){if(I.type==="AssignmentPattern"){let{left:R,right:g}=I,j="name"in R&&typeof R.name==="string"?R.name:"unknown",v="typeAnnotation"in R?R.typeAnnotation:null,m=v?w(v):void 0,__=y(v),X_=Q.slice(g.start,g.end),K_="decorators"in R&&Array.isArray(R.decorators)?R.decorators:[],Y0=E(K_),D_={name:j,isOptional:!0,defaultValue:X_};if(m)D_.type=m;if(__)D_.typeImportSource=__;if(Y0.length>0)D_.decorators=Y0;return D_}let V="name"in I&&typeof I.name==="string"?I.name:("pattern"in I)&&I.pattern&&typeof I.pattern.name==="string"?I.pattern.name:"unknown",H=!!(("optional"in I)&&I.optional),M="typeAnnotation"in I?I.typeAnnotation:null,B=M?w(M):void 0,A=y(M),D=E(N??[]),T={name:V,isOptional:H};if(B)T.type=B;if(A)T.typeImportSource=A;if(D.length>0)T.decorators=D;return T}function p(I,N){let V=[];if(N?.async)V.push("async");if(I.static)V.push("static");if(I.abstract)V.push("abstract");if(I.readonly)V.push("readonly");if(I.override)V.push("override");if(I.declare)V.push("declare");if(I.const)V.push("const");let H=I.accessibility;if(H==="private")V.push("private");else if(H==="protected")V.push("protected");else if(H==="public")V.push("public");return V}function J_(I){if(!I)return;let N=I.params.flatMap((V)=>{let H=V.name.name;return H?[H]:[]});return N.length>0?N:void 0}function Z_(I){let N=[];if(I.superClass){let H=Q.slice(I.superClass.start,I.superClass.end);N.push({kind:"extends",name:H})}let V=I.implements??[];for(let H of V){let M=H.expression,B=Q.slice(M.start,M.end);N.push({kind:"implements",name:B})}return N}function O_(I){let N=[],V=I.extends;for(let H of V){let M=H.expression,B=Q.slice(M.start,M.end);N.push({kind:"extends",name:B})}return N}function Y_(I){let N=[];for(let V of I)if(V.type==="MethodDefinition"||V.type==="TSAbstractMethodDefinition"){let H=V,M=U(H.key,H.computed),B=K(H.key,H.computed,0),A=H.value,D=H.kind,T=D==="constructor"?"constructor":D==="get"?"getter":D==="set"?"setter":"method",R=p(H,A);if(V.type==="TSAbstractMethodDefinition"&&!R.includes("abstract"))R.push("abstract");let g=A.params.map(u),j=w(A.returnType),v=E(H.decorators??[]),m={kind:"method",name:M,span:C(V.start,V.end),isExported:!1,methodKind:T,modifiers:R,parameters:g.length>0?g:void 0,returnType:j};if(B)m.key=B;if(v.length>0)m.decorators=v;N.push(m)}else if(V.type==="PropertyDefinition"||V.type==="TSAbstractPropertyDefinition"||V.type==="AccessorProperty"||V.type==="TSAbstractAccessorProperty"){let H=V,M=U(H.key,H.computed),B=K(H.key,H.computed,0),A=p(H);if(V.type==="TSAbstractPropertyDefinition"||V.type==="TSAbstractAccessorProperty"){if(!A.includes("abstract"))A.push("abstract")}if(V.type==="AccessorProperty"||V.type==="TSAbstractAccessorProperty")A.push("accessor");let D=w(H.typeAnnotation),T=H.value,R=T?G(T):void 0,g=E(H.decorators??[]),j={kind:"property",name:M,span:C(V.start,V.end),isExported:!1,modifiers:A,returnType:D,initializer:R};if(B)j.key=B;if(g.length>0)j.decorators=g;N.push(j)}return N}function W_(I){let N=[];for(let V of I)if(V.type==="TSMethodSignature"){let H=V,M=U(H.key,H.computed),B=K(H.key,H.computed,0),A=H.params.map(u),D=w(H.returnType),T={kind:"method",name:M,span:C(V.start,V.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:D};if(B)T.key=B;N.push(T)}else if(V.type==="TSPropertySignature"){let H=V,M=U(H.key,H.computed),B=K(H.key,H.computed,0),A=w(H.typeAnnotation),D={kind:"property",name:M,span:C(V.start,V.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:A};if(B)D.key=B;N.push(D)}return N}function i(I,N){let V=I.type;if(V==="FunctionDeclaration"||V==="FunctionExpression"||V==="TSDeclareFunction"||V==="TSEmptyBodyFunctionExpression"){let H=I,M=H.id?.name??"default",B=H.params.map(u),A=w(H.returnType),D=p(H,H),T=E(H.decorators??[]),R=J_(H.typeParameters),g={kind:"function",name:M,span:C(I.start,I.end),isExported:N,modifiers:D,parameters:B.length>0?B:void 0,returnType:A,decorators:T.length>0?T:void 0};if(R&&R.length>0)g.typeParameters=R;return g}if(V==="ClassDeclaration"||V==="ClassExpression"){let H=I,M=H.id?.name??"default",B=Z_(H),A=Y_(H.body.body),D=E(H.decorators),T=p(H),R=J_(H.typeParameters),g={kind:"class",name:M,span:C(I.start,I.end),isExported:N,modifiers:T,heritage:B.length>0?B:void 0,members:A.length>0?A:void 0,decorators:D.length>0?D:void 0};if(R&&R.length>0)g.typeParameters=R;return g}if(V==="VariableDeclaration"){let H=I,M=[];for(let B of H.declarations){let{id:A,init:D}=B;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let X_=k_(A);for(let K_ of X_)M.push({kind:"variable",name:K_.name,span:C(K_.start,K_.end),isExported:N,modifiers:[]});continue}let T="name"in A&&typeof A.name==="string"?A.name:"unknown",R="variable",g,j,v;if(D)if(D.type==="FunctionExpression"||D.type==="ArrowFunctionExpression"){R="function";let X_=D;g=X_.params.map(u),j=w(X_.returnType)}else v=G(D);let m=[],__={kind:R,name:T,span:C(B.start,B.end),isExported:N,modifiers:m,parameters:g,returnType:j};if(v)__.initializer=v;M.push(__)}if(M.length===0)return null;if(M.length===1)return M[0];return M}if(V==="TSTypeAliasDeclaration")return{kind:"type",name:I.id.name,span:C(I.start,I.end),isExported:N,modifiers:[]};if(V==="TSInterfaceDeclaration"){let H=I,M=H.id.name,B=O_(H),A=W_(H.body.body),D=J_(H.typeParameters),T={kind:"interface",name:M,span:C(I.start,I.end),isExported:N,modifiers:[],heritage:B.length>0?B:void 0,members:A.length>0?A:void 0};if(D&&D.length>0)T.typeParameters=D;return T}if(V==="TSEnumDeclaration"){let H=I,M=H.id.name,B=p(H),D=H.body.members.map((T)=>{let R=T.id,g=R.type!=="Identifier",j="name"in R&&typeof R.name==="string"?R.name:("value"in R)&&typeof R.value==="string"?R.value:"unknown",v=T.initializer?G(T.initializer):void 0,m={kind:"property",name:j,span:C(T.start,T.end),isExported:!1,modifiers:[]};if(g)m.key=X(R,0);if(v)m.initializer=v;return m});return{kind:"enum",name:M,span:C(I.start,I.end),isExported:N,modifiers:B,members:D.length>0?D:void 0}}if(V==="TSModuleDeclaration"){let H=I,M=H.id.name??H.id.value??"unknown",B=p(H),A=[];if(H.body?.type==="TSModuleBlock")for(let D of H.body.body??[]){if(D.type!=="ExportNamedDeclaration")continue;let T=D.declaration;if(!T)continue;let R=i(T,!1);if(R)if(Array.isArray(R))A.push(...R);else A.push(R)}return{kind:"namespace",name:M,span:C(I.start,I.end),isExported:N,modifiers:B,members:A.length>0?A:void 0}}return null}let c=[],w_=new Set;for(let I of $.body){let N=null,V=I;if(V.type==="ExportNamedDeclaration"){let M=V;if(M.declaration){if(N=i(M.declaration,!0),N&&!Array.isArray(N))N.span=C(M.start,M.end)}else if(!M.source&&M.specifiers)for(let B of M.specifiers){let A=B.local,D="name"in A?A.name:A.value;if(D)w_.add(D)}}else if(V.type==="ExportDefaultDeclaration"){let M=V,B=M.declaration;if(B){if(N=i(B,!0),N&&!Array.isArray(N))N.name="id"in B&&B.id&&typeof B.id.name==="string"?B.id.name:"default",N.isExported=!0,N.span=C(M.start,M.end);else if(!N&&"type"in B&&B.type==="Identifier"){let A=B.name;if(A)w_.add(A)}}}else{let M=V.type;if(M==="FunctionDeclaration"||M==="TSDeclareFunction"||M==="ClassDeclaration"||M==="VariableDeclaration"||M==="TSTypeAliasDeclaration"||M==="TSInterfaceDeclaration"||M==="TSEnumDeclaration"||M==="TSModuleDeclaration")N=i(V,!1)}let H=Array.isArray(N)?N:N?[N]:[];for(let M of H){let B=I.start,A=q(B);if(A){let D=r_(A);if(!ZQ(D))M.jsDoc=D}c.push(M)}}if(w_.size>0){for(let I of c)if(!I.isExported&&w_.has(I.name))I.isExported=!0}return c}function o_(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(o_).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((J)=>`${JSON.stringify(J)}:${o_($[J])}`).join(",")}}`}function VQ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,Q=_.modifiers.includes("async")?1:0;return`params:${$}|async:${Q}`}return null}function UQ(_){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((z)=>z==="private"||z==="protected"||z==="public"),W={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)W.key=Q.key;if(Q.initializer)W.initializer=Q.initializer;if(Q.decorators?.length)W.decorators=Q.decorators;return W});return Object.keys($).length>0?JSON.stringify($):null}function OQ(_){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,W)=>J.name.localeCompare(W.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:${o_(_.key)}`);if(_.members?.length){let Q=_.members.map((J)=>`${J.kind}:${J.modifiers.join(",")}:${J.parameters?.length??""}:${J.returnType??""}:${J.key?o_(J.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${U_(Q)}`)}return U_($.join("|"))}function o0(_,$,Q,J,W){let z=VQ(_),Y=U_(`${$}|${_.kind}|${z??""}`),Z=OQ(_);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:z,fingerprint:Y,detailJson:UQ(_),contentHash:W,indexedAt:new Date().toISOString(),structuralFingerprint:Z}}function w0(_){let{parsed:$,project:Q,filePath:J,contentHash:W,symbolRepo:z}=_,Y=N_($),Z=[];for(let X of Y){Z.push(o0(X,X.name,Q,J,W));for(let K of X.members??[])Z.push(o0(K,`${X.name}.${K.name}`,Q,J,W))}z.replaceFileSymbols(Q,J,W,Z)}import{resolve as D0,dirname as HQ,extname as MQ}from"path";function q_(_,$,Q){let J=(W)=>{let z=MQ(W);if(z===".js")return[W.slice(0,-3)+".ts"];if(z===".mjs")return[W.slice(0,-4)+".mts"];if(z===".cjs")return[W.slice(0,-4)+".cts"];if(z===".ts"||z===".mts"||z===".cts"||z===".d.ts")return[W];return[W+".ts",W+".d.ts",W+"/index.ts",W+"/index.d.ts",W+".mts",W+"/index.mts",W+".cts",W+"/index.cts"]};if($.startsWith(".")){let W=Q_(D0(HQ(_),$));return J(W)}if(Q)for(let[W,z]of Q.paths){if(z.length===0)continue;let Y=W.indexOf("*");if(Y===-1){if($===W){let Z=[];for(let X of z)Z.push(...J(Q_(D0(Q.baseUrl,X))));return Z}}else{let Z=W.slice(0,Y),X=W.slice(Y+1);if($.startsWith(Z)&&(X===""||$.endsWith(X))){let K=$.slice(Z.length,X===""?void 0:$.length-X.length),U=[];for(let L of z)U.push(...J(Q_(D0(Q.baseUrl,L.replace("*",K)))));return U}}}return[]}function t0(_,$,Q,J=q_){let W=new Map,z=_.body??[];for(let Y of z){if(Y.type!=="ImportDeclaration")continue;let Z=Y.source?.value??"",X=J($,Z,Q);if(X.length===0)continue;let K=X[0],U=Y.specifiers??[];for(let L of U)switch(L.type){case"ImportSpecifier":W.set(L.local.name,{path:K,importedName:L.imported.name});break;case"ImportDefaultSpecifier":W.set(L.local.name,{path:K,importedName:"default"});break;case"ImportNamespaceSpecifier":W.set(L.local.name,{path:K,importedName:"*"});break}}return W}import{Visitor as KQ}from"oxc-parser";function t_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function LQ(_){return!_.startsWith(".")&&!_.startsWith("/")}function R_(_,$,Q,J){let W=J(_,$,Q),z=W.length>0?W[0]:null,Y=z===null&&LQ($);return{resolved:z,isExternal:Y}}function BQ(_,$,Q,J,W){for(let z of _.staticImports){let Y=z.moduleRequest.value,{resolved:Z,isExternal:X}=R_($,Y,Q,J),K={dstFilePath:Z,specifier:Y};if(z.entries.length===0){let U={};if(X)U.isExternal=!0;if(Z===null&&!X)U.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,...K,dstSymbolName:null,...Object.keys(U).length>0?{metaJson:JSON.stringify(U)}:{}});continue}for(let U of z.entries){let L=U.isType,C={};if(L)C.isType=!0;if(X)C.isExternal=!0;if(Z===null&&!X)C.isUnresolved=!0;let q,w,S=U.importName.kind;if(S==="Default")q="default",w=U.localName.value;else if(S==="NamespaceObject")q="*",w=U.localName.value,C.importKind="namespace";else q=U.importName.name??"unknown",w=U.localName.value;W.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:w,...K,dstSymbolName:q,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}}function wQ(_,$,Q,J,W){let z=new Map;for(let Y of _.staticImports)for(let Z of Y.entries)z.set(Z.localName.value,Y.moduleRequest.value);for(let Y of _.staticExports)for(let Z of Y.entries){let X=null;if(Z.moduleRequest)X=Z.moduleRequest.value;else if(Z.localName.name)X=z.get(Z.localName.name)??null;if(!X)continue;let{resolved:K,isExternal:U}=R_($,X,Q,J),L=Z.exportName.name??"default",C=Z.exportName.kind,q=Z.localName.name??Z.importName.name??L,w=Z.isType,S={isReExport:!0};if(C==="None");else S.specifiers=[{local:q,exported:L}];if(w)S.isType=!0;if(U)S.isExternal=!0;if(K===null&&!U)S.isUnresolved=!0;let F=null,G=null,E=Z.importName.kind;if(E==="All"||E==="AllButDefault"){if(C==="Name"&&L)G=L,S.namespaceAlias=L}else G=q,F=L;W.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:K,dstSymbolName:G,specifier:X,metaJson:JSON.stringify(S)})}}function DQ(_,$,Q,J,W){for(let z of _.body){let Y=z;if(Y.type==="ImportDeclaration"){let Z=Y,X=Z.source.value,{resolved:K,isExternal:U}=R_($,X,Q,J),L=Z.importKind==="type",C=Z.specifiers,q={dstFilePath:K,specifier:X};if(C.length===0){let w={};if(L)w.isType=!0;if(U)w.isExternal=!0;if(K===null&&!U)w.isUnresolved=!0;W.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...q,dstSymbolName:null,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}else for(let w of C){let S=w.type,F=L||S==="ImportSpecifier"&&w.importKind==="type",G={};if(F)G.isType=!0;if(U)G.isExternal=!0;if(K===null&&!U)G.isUnresolved=!0;let E,u;if(S==="ImportDefaultSpecifier")E="default",u=w.local.name;else if(S==="ImportNamespaceSpecifier")E="*",u=w.local.name,G.importKind="namespace";else E=t_(w.imported),u=w.local.name;W.push({type:F?"type-references":"imports",srcFilePath:$,srcSymbolName:u,...q,dstSymbolName:E,...Object.keys(G).length>0?{metaJson:JSON.stringify(G)}:{}})}continue}if(Y.type==="ExportAllDeclaration"){let Z=Y,X=Z.source.value,{resolved:K,isExternal:U}=R_($,X,Q,J),L=Z.exportKind==="type",C=Z.exported,q=C?t_(C):null,w={isReExport:!0};if(L)w.isType=!0;if(U)w.isExternal=!0;if(K===null&&!U)w.isUnresolved=!0;if(q)w.namespaceAlias=q;W.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:q,specifier:X,metaJson:JSON.stringify(w)});continue}if(Y.type==="ExportNamedDeclaration"){let Z=Y;if(!Z.source)continue;let X=Z.source.value,{resolved:K,isExternal:U}=R_($,X,Q,J),L=Z.exportKind==="type",C=Z.specifiers??[];for(let q of C){let w=L||q.exportKind==="type",S=t_(q.local),F=t_(q.exported),G={isReExport:!0,specifiers:[{local:S,exported:F}]};if(w)G.isType=!0;if(U)G.isExternal=!0;if(K===null&&!U)G.isUnresolved=!0;W.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:K,dstSymbolName:S,specifier:X,metaJson:JSON.stringify(G)})}}}}function IQ(_,$,Q,J,W){new KQ({ImportExpression(Y){let Z=Y.source;if(Z.type!=="Literal"||typeof Z.value!=="string")return;let X=Z.value,{resolved:K,isExternal:U}=R_($,X,Q,J),L={isDynamic:!0};if(U)L.isExternal=!0;if(K===null&&!U)L.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(L)})},CallExpression(Y){let Z=Y.callee,X=!1;if(Z.type==="Identifier"&&Z.name==="require");else if(Z.type==="MemberExpression"&&!Z.computed){let S=Z,F=S.object,G=S.property;if(F.type==="Identifier"&&F.name==="require"&&G.name==="resolve")X=!0;else return}else return;let K=Y.arguments;if(K.length===0)return;let U=K[0];if(U.type!=="Literal"||typeof U.value!=="string")return;let L=U.value,{resolved:C,isExternal:q}=R_($,L,Q,J),w={isRequire:!0};if(X)w.isRequireResolve=!0;if(q)w.isExternal=!0;if(C===null&&!q)w.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:C,dstSymbolName:null,specifier:L,metaJson:JSON.stringify(w)})}}).visit(_)}function e0(_,$,Q,J=q_,W){let z=[];if(W)BQ(W,$,Q,J,z),wQ(W,$,Q,J,z);else DQ(_,$,Q,J,z);return IQ(_,$,Q,J,z),z}import{walk as CQ}from"oxc-walker";function u_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let Q=$.name;return{root:Q,parts:[],full:Q}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let Q=[],J=$;while(J.type==="MemberExpression"){let Y=J.property;if(!Y||typeof Y.name!=="string")return null;Q.push(Y.name),J=J.object}let W;if(J.type==="Identifier")W=J.name;else if(J.type==="ThisExpression")W="this";else if(J.type==="Super")W="super";else return null;Q.reverse();let z=[W,...Q].join(".");return{root:W,parts:Q,full:z}}return null}function _1(_,$,Q){let J=[],W=[],z=[];function Y(){if(W.length>0)return W[W.length-1]??null;return null}function Z(U){if(!U)return null;let L=Q.get(U.root);if(U.parts.length===0){if(L)return{dstFilePath:L.path,dstSymbolName:L.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:U.root,resolution:"local"}}else{if(L&&L.importedName==="*"){let C=U.parts[U.parts.length-1];return{dstFilePath:L.path,dstSymbolName:C,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:U.full,resolution:"local-member"}}}function X(U,L){let C=u_(U.callee),q=Z(C);if(q){let w=Y(),S={};if(L)S.isNew=!0;if(w===null)S.scope="module";J.push({type:"calls",srcFilePath:$,srcSymbolName:w,dstFilePath:q.dstFilePath,dstSymbolName:q.dstSymbolName,...Object.keys(S).length>0?{metaJson:JSON.stringify(S)}:{}})}}function K(U,L){if(U.type==="FunctionDeclaration"){W.push(U.id?.name??"anonymous");return}if(U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){if(L?.type==="VariableDeclarator"){let w=L.id,S=w.type==="Identifier"?w.name:"anonymous";W.push(S);return}if(L?.type==="MethodDefinition"||L?.type==="TSAbstractMethodDefinition"){let w=L.key,S=z[z.length-1]??"",F="name"in w?w.name:"anonymous",G=S?`${S}.${F}`:F;W.push(G);return}let C=Y(),q=C?`${C}.<anonymous>`:"<anonymous>";W.push(q)}}return CQ(_,{enter(U,L){if(U.type==="ClassDeclaration"||U.type==="ClassExpression"){z.push(U.id?.name??"AnonymousClass");return}if(U.type==="FunctionDeclaration"||U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){K(U,L);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"){z.pop();return}if(U.type==="FunctionDeclaration"||U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){W.pop();return}}}),J}import{Visitor as AQ}from"oxc-parser";function $1(_,$,Q){let J=[];function W(Y){let Z=Y.id?.name??"AnonymousClass";if(Y.superClass){let K=u_(Y.superClass);if(K){let U=I0(K,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...U})}}let X=Y.implements??[];for(let K of X){let U=u_(K.expression);if(!U)continue;let L=I0(U,$,Q);J.push({type:"implements",srcFilePath:$,srcSymbolName:Z,...L})}}return new AQ({TSInterfaceDeclaration(Y){let Z=Y.id.name??"AnonymousInterface",X=Y.extends;for(let K of X){let U=u_(K.expression);if(!U)continue;let L=I0(U,$,Q);J.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...L})}},ClassDeclaration(Y){W(Y)},ClassExpression(Y){W(Y)}}).visit(_),J}function I0(_,$,Q){let J=Q.get(_.root);if(J){if(J.importedName==="*"){let W=_.parts[_.parts.length-1]??_.root;return{dstFilePath:J.path,dstSymbolName:W,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 n_(_,$,Q,J=q_,W){let z=t0(_,$,Q,J),Y=e0(_,$,Q,J,W),Z=_1(_,$,z),X=$1(_,$,z);return[...Y,...Z,...X]}function C0(_){let{ast:$,project:Q,filePath:J,relationRepo:W,projectRoot:z,tsconfigPaths:Y,knownFiles:Z,boundaries:X,module:K}=_,U=g_(z,J),C=n_($,U,Y,Z?(w,S,F)=>{let G=q_(w,S,F);for(let E of G){let u=f_(z,E);if(X){let y=l(u,X);if(Z.has(`${y}::${u}`))return[E]}else if(Z.has(`${Q}::${u}`))return[E]}return[]}:void 0,K),q=[];for(let w of C){if(w.dstFilePath===null){let E=f_(z,w.srcFilePath),u;if(w.metaJson)try{u=JSON.parse(w.metaJson)}catch{}let y=u?.isExternal===!0;q.push({project:Q,type:w.type,srcFilePath:E,srcSymbolName:w.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:y?1:0});continue}let S=f_(z,w.dstFilePath);if(S.startsWith(".."))continue;let F=f_(z,w.srcFilePath),G=X?l(S,X):Q;q.push({project:Q,type:w.type,srcFilePath:F,srcSymbolName:w.srcSymbolName??null,dstProject:G,dstFilePath:S,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:0})}return W.replaceFileRelations(Q,J,q),q.length}import{isErr as NQ}from"@zipbul/result";var Q1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function qQ(_){let $=N_(_),Q=[];for(let J of $){Q.push({name:J.name,startLine:J.span.start.line});for(let W of J.members??[])Q.push({name:`${J.name}.${W.name}`,startLine:W.span.start.line})}return Q.sort((J,W)=>J.startLine-W.startLine),Q}function A0(_,$,Q){let J=0,W=_.length-1;while(J<=W){let z=J+W>>1;if(_[z].startLine<=$)J=z+1;else W=z-1}if(J<_.length){let z=_[J];if(z.startLine-$<=Q)return z.name}return null}function e_(_,$,Q){let J=V_(_,$),W=V_(_,Q);return{start:J,end:W}}function J1(_){let{comments:$,sourceText:Q}=_;if(!$.length)return[];let J=h_(Q),W=qQ(_),z=[],Y=[...$].sort((X,K)=>X.start-K.start),Z=null;for(let X of Y)if(X.type==="Block"&&X.value.startsWith("*")){Z=null;let K=`/*${X.value}*/`,U=r_(K);if(NQ(U))continue;let L=U;if(!L.tags?.length)continue;let C=V_(J,X.end),q=A0(W,C.line,3),w=Q.slice(X.start,X.end);for(let S of L.tags){let F=[S.name,S.description].filter(Boolean).join(" "),G=`@${S.tag}`,E=w.indexOf(G),u;if(E>=0){let y=X.start+E,d=Q.indexOf(`
4
+ `,y),p=d>=0?Math.min(d,X.end):X.end;u=e_(J,y,p)}else u=e_(J,X.start,X.end);z.push({tag:S.tag,value:F,source:"jsdoc",span:u,symbolName:q})}}else if(X.type==="Block"){Z=null;let K=X.value.split(`
5
+ `),U=0;for(let L of K){let C=L.replace(/^\s*\*?\s?/,""),q=Q1.exec(C);if(q){let w=q[1],S=q[2]?.trim()??"",F=`@${w}`,G=L.indexOf(F),E=X.start+2+U+(G>=0?G:0),u=X.start+2+U+L.length,y=e_(J,E,u),d=V_(J,X.end),p=A0(W,d.line,3);z.push({tag:w,value:S,source:"block",span:y,symbolName:p})}U+=L.length+1}}else{let K=X.value,U=Q1.exec(K),L=V_(J,X.start),C=V_(J,X.end);if(U){let q=U[1],w=U[2]?.trim()??"",S=`@${q}`,F=K.indexOf(S),G=X.start+2+(F>=0?F:0),E=e_(J,G,X.end),u=A0(W,C.line,3),y={tag:q,value:w,source:"line",span:E,symbolName:u};z.push(y),Z={annotation:y,endLine:C.line}}else if(Z&&L.line===Z.endLine+1){let q=K.trim();if(q)Z.annotation.value+=" "+q,Z.annotation.span.end=V_(J,X.end),Z.endLine=C.line}else Z=null}return z}function N0(_){let{parsed:$,project:Q,filePath:J,annotationRepo:W}=_,z=J1($);if(W.deleteFileAnnotations(Q,J),!z.length)return 0;let Y=new Date().toISOString(),Z=z.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:Y}));return W.insertBatch(Q,J,Z),z.length}function W1(_,$){let Q=[],J=[],W=[];for(let[U,L]of $)if(!_.has(U))Q.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});for(let[U,L]of _)if(!$.has(U))J.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});if(!Q.length||!J.length)return{renamed:W,added:Q,removed:J};let z=new Map,Y=new Map;for(let U of Q){let L=z.get(U.filePath)??[];L.push(U),z.set(U.filePath,L)}for(let U of J){let L=Y.get(U.filePath)??[];L.push(U),Y.set(U.filePath,L)}let Z=new Set,X=new Set;for(let[U,L]of z){let C=Y.get(U);if(!C)continue;for(let q of new Set(L.map((w)=>w.kind))){let w=L.filter((u)=>u.kind===q&&!Z.has(u)),S=C.filter((u)=>u.kind===q&&!X.has(u));if(!w.length||!S.length)continue;let F=(u,y)=>{return y.get(`${u.filePath}::${u.name}`)?.structuralFingerprint??null},G=(u,y)=>{return y.get(`${u.filePath}::${u.name}`)?.startLine??0},E=new Map;for(let u of S){let y=F(u,_);if(!y)continue;let d=E.get(y)??[];d.push(u),E.set(y,d)}for(let u of w){if(Z.has(u))continue;let y=F(u,$);if(!y)continue;let d=E.get(y);if(!d)continue;let p=d.filter((Z_)=>!X.has(Z_));if(!p.length)continue;let J_=p[0];if(p.length>1){let Z_=G(u,$),O_=Math.abs(G(J_,_)-Z_);for(let Y_=1;Y_<p.length;Y_++){let W_=Math.abs(G(p[Y_],_)-Z_);if(W_<O_)O_=W_,J_=p[Y_]}}W.push({oldName:J_.name,newName:u.name,filePath:U,kind:q}),Z.add(u),X.add(J_)}}}let K=W.filter((U)=>!U.oldName.includes("."));for(let U of K){let L=`${U.oldName}.`,C=`${U.newName}.`,q=J.filter((S)=>S.filePath===U.filePath&&S.name.startsWith(L)&&!X.has(S)),w=Q.filter((S)=>S.filePath===U.filePath&&S.name.startsWith(C)&&!Z.has(S));for(let S of q){let F=S.name.slice(L.length),G=w.find((E)=>E.name.slice(C.length)===F);if(G)W.push({oldName:S.name,newName:G.name,filePath:U.filePath,kind:S.kind}),Z.add(G),X.add(S)}}return{renamed:W,added:Q.filter((U)=>!Z.has(U)),removed:J.filter((U)=>!X.has(U))}}var RQ=100,Z1=50;class q0{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=x_(_.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")){s_(this.opts.projectRoot),this.tsconfigPathsRaw=x_(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??a_;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()},RQ)}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,W)=>{this.pendingFullIndexWaiters.push({resolve:J,reject:W})});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((W)=>{for(let z of J)z.resolve(W)}).catch((W)=>{for(let z of J)z.reject(W)})}else if(this.pendingEvents.length>0){let J=this.pendingEvents.splice(0);this.startIndex(J,!1).catch((W)=>this.logger.error("[IndexCoordinator] incremental drain error",W))}});return this.currentIndexing=Q,Q}async doIndex(_,$){let Q=Date.now(),{fileRepo:J,symbolRepo:W,relationRepo:z,dbConnection:Y}=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 M of this.opts.boundaries)for(let[B,A]of J.getFilesMap(M.project))V.set(B,A);let H=await r0({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>V}});Z=H.changed,X=H.deleted}let K=await this.tsconfigPathsRaw??void 0,U=new Map;for(let V of X){let H=l(V,this.opts.boundaries),M=W.getFileSymbols(H,V);U.set(V,M)}let L=crypto.randomUUID(),C=new Map,q=new Map,w=(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 H of J.getAllFiles(V.project))for(let M of W.getFileSymbols(V.project,H.filePath))C.set(`${M.filePath}::${M.name}`,w(M));else{for(let V of Z){let H=l(V.filePath,this.opts.boundaries);for(let M of W.getFileSymbols(H,V.filePath))C.set(`${M.filePath}::${M.name}`,w(M))}for(let[,V]of U)for(let H of V)C.set(`${H.filePath}::${H.name}`,w(H))}let S=(V)=>`${V.type}|${V.srcFilePath}|${V.dstFilePath??""}|${V.srcSymbolName??""}|${V.dstSymbolName??""}|${U_(V.metaJson??"")}`,F=new Map;if($)for(let V of this.opts.boundaries)for(let H of J.getAllFiles(V.project))for(let M of z.getOutgoing(V.project,H.filePath))F.set(S(M),M);else{for(let V of Z){let H=l(V.filePath,this.opts.boundaries);for(let M of z.getOutgoing(H,V.filePath))F.set(S(M),M)}for(let V of X){let H=l(V,this.opts.boundaries);for(let M of z.getOutgoing(H,V))F.set(S(M),M)}}let{annotationRepo:G,changelogRepo:E}=this.opts,u=()=>{for(let V of X){let H=l(V,this.opts.boundaries);if(W.deleteFileSymbols(H,V),z.deleteFileRelations(H,V),z.deleteIncomingRelations(H,V),G)G.deleteFileAnnotations(H,V);J.deleteFile(H,V)}},y=0,d=async()=>{let{projectRoot:V,boundaries:H}=this.opts,{parseCache:M}=this.opts,B=0,A=0,D=0,T=[],R=[];for(let j of Z)try{let v=g_(V,j.filePath),m=Bun.file(v),__=await m.text(),X_=j.contentHash||U_(__),K_=l(j.filePath,H);J.upsertFile({project:K_,filePath:j.filePath,mtimeMs:m.lastModified,size:m.size,contentHash:X_,updatedAt:new Date().toISOString(),lineCount:__.split(`
6
+ `).length});let D_=(this.opts.parseSourceFn??j_)(v,__);if(z1(D_))throw D_.data;let G$=D_;R.push({filePath:j.filePath,text:__,contentHash:X_,parsed:G$,project:K_})}catch(v){this.logger.error(`[IndexCoordinator] Failed to prepare ${j.filePath}:`,v),T.push(j.filePath)}let g=new Set;for(let j of H)for(let[v]of J.getFilesMap(j.project))g.add(`${j.project}::${v}`);return Y.transaction(()=>{for(let j of R){if(w0({parsed:j.parsed,project:j.project,filePath:j.filePath,contentHash:j.contentHash,symbolRepo:W}),A+=C0({ast:j.parsed.program,project:j.project,filePath:j.filePath,relationRepo:z,projectRoot:V,tsconfigPaths:K,knownFiles:g,boundaries:H,module:j.parsed.module}),G)D+=N0({parsed:j.parsed,project:j.project,filePath:j.filePath,annotationRepo:G});M.set(j.filePath,j.parsed),B+=W.getFileSymbols(j.project,j.filePath).length}}),{symbols:B,relations:A,annotations:D,failedFiles:T}},p=0,J_=0,Z_=[];if($){let{projectRoot:V,boundaries:H}=this.opts,{parseCache:M}=this.opts,B=[];for(let D=0;D<Z.length;D+=Z1){let T=Z.slice(D,D+Z1),R=await Promise.allSettled(T.map(async(g)=>{let j=g_(V,g.filePath),v=Bun.file(j),m=await v.text(),__=g.contentHash||U_(m);return{filePath:g.filePath,text:m,contentHash:__,mtimeMs:v.lastModified,size:v.size}}));for(let g=0;g<R.length;g++){let j=R[g];if(j.status==="fulfilled")B.push(j.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",j.reason),Z_.push(T[g].filePath)}}let A=[];Y.transaction(()=>{for(let R of B){let g=l(R.filePath,H);J.deleteFile(g,R.filePath)}for(let R of X){let g=l(R,H);if(W.deleteFileSymbols(g,R),z.deleteFileRelations(g,R),z.deleteIncomingRelations(g,R),G)G.deleteFileAnnotations(g,R);J.deleteFile(g,R)}for(let R of B){let g=l(R.filePath,H);J.upsertFile({project:g,filePath:R.filePath,mtimeMs:R.mtimeMs,size:R.size,contentHash:R.contentHash,updatedAt:new Date().toISOString(),lineCount:R.text.split(`
7
+ `).length})}let D=new Set;for(let R of H)for(let[g]of J.getFilesMap(R.project))D.add(`${R.project}::${g}`);let T=this.opts.parseSourceFn??j_;for(let R of B){let g=l(R.filePath,H),j=T(g_(V,R.filePath),R.text);if(z1(j))throw j.data;let v=j;if(A.push({filePath:R.filePath,parsed:v}),w0({parsed:v,project:g,filePath:R.filePath,contentHash:R.contentHash,symbolRepo:W}),G)y+=N0({parsed:v,project:g,filePath:R.filePath,annotationRepo:G});J_+=C0({ast:v.program,project:g,filePath:R.filePath,relationRepo:z,projectRoot:V,tsconfigPaths:K,knownFiles:D,boundaries:H,module:v.module}),p+=W.getFileSymbols(g,R.filePath).length}});for(let D of A)M.set(D.filePath,D.parsed)}else{u();let V=await d();p=V.symbols,J_=V.relations,y=V.annotations,Z_=V.failedFiles}for(let V of Z){let H=l(V.filePath,this.opts.boundaries);for(let M of W.getFileSymbols(H,V.filePath))q.set(`${M.filePath}::${M.name}`,w(M))}let O_=new Map;for(let V of Z){let H=l(V.filePath,this.opts.boundaries);for(let M of z.getOutgoing(H,V.filePath))O_.set(S(M),M)}let Y_=(V)=>({type:V.type,srcFilePath:V.srcFilePath,dstFilePath:V.dstFilePath,srcSymbolName:V.srcSymbolName,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,metaJson:V.metaJson}),W_={added:[...O_.entries()].filter(([V])=>!F.has(V)).map(([,V])=>Y_(V)),removed:[...F.entries()].filter(([V])=>!O_.has(V)).map(([,V])=>Y_(V))},i={added:[],modified:[],removed:[]};for(let[V,H]of q){let M=C.get(V);if(!M)i.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let B=M.fingerprint!==H.fingerprint,A=M.isExported!==H.isExported,D=M.structuralFingerprint!==null&&H.structuralFingerprint!==null&&M.structuralFingerprint!==H.structuralFingerprint;if(B||A||D)i.modified.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)})}}for(let[V,H]of C)if(!q.has(V))i.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let c=W1(C,q),w_=new Set(c.renamed.map((V)=>`${V.filePath}::${V.oldName}`)),I=new Set(c.renamed.map((V)=>`${V.filePath}::${V.newName}`));i.added=i.added.filter((V)=>!I.has(`${V.filePath}::${V.name}`)),i.removed=i.removed.filter((V)=>!w_.has(`${V.filePath}::${V.name}`));let N=[];if(!$){for(let[H,M]of U)for(let B of M){if(!B.fingerprint)continue;let A=l(H,this.opts.boundaries),D=W.getByFingerprint(A,B.fingerprint);if(D.length===1){let T=D[0];z.retargetRelations({dstProject:A,oldFile:H,oldSymbol:B.name,newFile:T.filePath,newSymbol:T.name}),N.push({name:T.name,filePath:T.filePath,kind:T.kind,oldFilePath:H,isExported:T.isExported??0})}}let V=new Set(N.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of c.removed){if(V.has(`${H.filePath}::${H.name}`))continue;let B=C.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!B)continue;let A=l(H.filePath,this.opts.boundaries),D=W.getByFingerprint(A,B);if(D.length===1){let T=D[0];if(T.filePath!==H.filePath||T.name!==H.name)z.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:T.filePath,newSymbol:T.name}),N.push({name:T.name,filePath:T.filePath,kind:T.kind,oldFilePath:H.filePath,isExported:T.isExported??0})}}}if(N.length){let V=new Set(N.map((M)=>`${M.filePath}::${M.name}`)),H=new Set(N.map((M)=>`${M.oldFilePath}::${M.name}`));i.added=i.added.filter((M)=>!V.has(`${M.filePath}::${M.name}`)),i.removed=i.removed.filter((M)=>!H.has(`${M.filePath}::${M.name}`))}if(E){let V=new Date().toISOString(),H=$?1:0,M=[];for(let B of i.added){let A=`${B.filePath}::${B.name}`,D=q.get(A),T=l(B.filePath,this.opts.boundaries);M.push({project:T,changeType:"added",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:D?.fingerprint??null,changedAt:V,isFullIndex:H,indexRunId:L})}for(let B of i.modified){let A=q.get(`${B.filePath}::${B.name}`),D=l(B.filePath,this.opts.boundaries);M.push({project:D,changeType:"modified",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:V,isFullIndex:H,indexRunId:L})}for(let B of i.removed){let A=`${B.filePath}::${B.name}`,D=C.get(A),T=l(B.filePath,this.opts.boundaries);M.push({project:T,changeType:"removed",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:D?.fingerprint??null,changedAt:V,isFullIndex:H,indexRunId:L})}for(let B of c.renamed){let A=q.get(`${B.filePath}::${B.newName}`),D=l(B.filePath,this.opts.boundaries);M.push({project:D,changeType:"renamed",symbolName:B.newName,symbolKind:B.kind,filePath:B.filePath,oldName:B.oldName,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:V,isFullIndex:H,indexRunId:L})}for(let B of N){let A=q.get(`${B.filePath}::${B.name}`),D=l(B.filePath,this.opts.boundaries);M.push({project:D,changeType:"moved",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:B.oldFilePath,fingerprint:A?.fingerprint??null,changedAt:V,isFullIndex:H,indexRunId:L})}if(M.length)try{Y.transaction(()=>{E.insertBatch(M)})}catch(B){this.logger.error("[IndexCoordinator] changelog insert failed:",B)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let B=new Date(Date.now()-2592000000).toISOString();try{for(let A of this.opts.boundaries)E.pruneOlderThan(A.project,B)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Z.length,removedFiles:X.length,totalSymbols:p,totalRelations:J_,totalAnnotations:y,durationMs:Date.now()-Q,changedFiles:Z.map((V)=>V.filePath),deletedFiles:[...X],failedFiles:Z_,changedSymbols:i,renamedSymbols:c.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:N.map((V)=>({name:V.name,oldFilePath:V.oldFilePath,newFilePath:V.filePath,kind:V.kind,isExported:Boolean(V.isExported)})),changedRelations:W_}}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 SQ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function TQ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function Y1(_,$,Q={}){let J=Q.now??Date.now,W=Q.isAlive??SQ,z=Q.staleAfterSeconds??60,Y=Q.instanceId;return _.immediateTransaction(()=>{let Z=_.selectOwner();if(!Z)return _.insertOwner($,Y),"owner";let X=Math.floor((J()-TQ(Z.heartbeat_at))/1000),K=W(Z.pid);if(K&&Y&&Z.instance_id&&Z.instance_id!==Y&&Z.pid===$)return _.replaceOwner($,Y),"owner";if(K&&X<z)return"reader";return _.replaceOwner($,Y),"owner"})}function X1(_,$){_.deleteOwner($)}function V1(_,$){_.touchOwner($)}class m_{#_;#$=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 R0{lru;constructor(_=500){this.lru=new m_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function S0(_){let{symbolRepo:$,project:Q,query:J}=_,W=J.project??Q,z={kind:J.kind,filePath:J.filePath,isExported:J.isExported,project:W,limit:J.limit,resolvedType:J.resolvedType};if(J.text)if(J.exact)z.exactName=J.text;else{let Z=F_(J.text);if(Z)z.ftsQuery=Z}if(J.decorator)z.decorator=J.decorator;if(J.regex)z.regex=J.regex;return $.searchByQuery(z).map((Z)=>{let X=Z.name.indexOf(".");return{id:Z.id,filePath:Z.filePath,kind:Z.kind,name:Z.name,memberName:X>=0?Z.name.slice(X+1):null,span:{start:{line:Z.startLine,column:Z.startColumn},end:{line:Z.endLine,column:Z.endColumn}},isExported:Z.isExported===1,signature:Z.signature,fingerprint:Z.fingerprint,detail:Z.detailJson?(()=>{try{return JSON.parse(Z.detailJson)}catch{return{}}})():{}}})}function T0(_){let{relationRepo:$,project:Q,query:J}=_;if(J.srcFilePath&&J.srcFilePathPattern)throw new O("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(J.dstFilePath&&J.dstFilePathPattern)throw new O("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let W=J.project??Q,z=J.limit,Y=!!(J.srcFilePathPattern||J.dstFilePathPattern),Z=Y?void 0:z,K=$.searchRelations({srcFilePath:J.srcFilePath,srcSymbolName:J.srcSymbolName,dstFilePath:J.dstFilePath,dstSymbolName:J.dstSymbolName,dstProject:J.dstProject,type:J.type,project:W,specifier:J.specifier,isExternal:J.isExternal,limit:Z}).map((U)=>{let L;if(U.metaJson)try{L=JSON.parse(U.metaJson)}catch{}return{type:U.type,srcFilePath:U.srcFilePath,srcSymbolName:U.srcSymbolName,dstFilePath:U.dstFilePath,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,isExternal:U.isExternal===1,specifier:U.specifier,metaJson:U.metaJson??void 0,meta:L}});if(J.srcFilePathPattern||J.dstFilePathPattern){let U=J.srcFilePathPattern?new Bun.Glob(J.srcFilePathPattern):null,L=J.dstFilePathPattern?new Bun.Glob(J.dstFilePathPattern):null;K=K.filter((C)=>(!U||U.match(C.srcFilePath))&&(!L||C.dstFilePath===null||L.match(C.dstFilePath)))}if(Y&&z!==void 0&&K.length>z)K=K.slice(0,z);return K}import{findInFiles as GQ,Lang as FQ}from"@ast-grep/napi";function gQ(_){let $=new Set,Q=/\${1,3}([A-Z_][A-Z_0-9]*)/g,J;while((J=Q.exec(_))!==null)$.add(J[0]);return[...$]}function jQ(_){return _.replace(/^\$+/,"")}function kQ(_,$){if($.length===0)return;let Q={},J=!1;for(let W of $){let z=jQ(W),Y=_.getMatch(z);if(Y){let X=Y.range();Q[W]={text:Y.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(z);if(Z.length>0){let X=Z[0].range(),K=Z[Z.length-1].range();Q[W]={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 G0(_){if(_.filePaths.length===0)return[];let $=gQ(_.pattern),Q=[];return await GQ(FQ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,W)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let z of W){let Y=z.range(),Z={filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,startColumn:Y.start.column,endColumn:Y.end.column,startOffset:Y.start.index,endOffset:Y.end.index,matchedText:z.text()},X=kQ(z,$);if(X)Z.captures=X;Q.push(Z)}}),Q}import o from"typescript";import{isErr as iQ}from"@zipbul/result";import L_ from"typescript";import uQ from"path";import{err as F0}from"@zipbul/result";function EQ(_){try{return x0("fs").readFileSync(_,"utf-8")}catch{return}}function vQ(_){try{return x0("fs").readFileSync(_,"utf-8")}catch{return}}class _0{#_;#$;#Q=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let Q=$.readConfigFile??EQ,J=$.resolveNonTrackedFile??vQ,W=uQ.dirname(_),z=Q(_);if(z===void 0)return F0(new O("semantic",`tsconfig not found: ${_}`));let Y=L_.parseJsonText(_,z),Z=Y.parseDiagnostics;if(Z&&Z.length>0){let L=Z.map((C)=>L_.flattenDiagnosticMessageText(C.messageText,`
8
+ `)).join("; ");return F0(new O("semantic",`tsconfig parse error: ${L}`))}let X=L_.parseJsonSourceFileConfigFileContent(Y,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(L)=>Q(L)!==void 0||J(L)!==void 0,readFile:(L)=>Q(L)??J(L)},W);if(X.errors.length>0){let L=X.errors.filter((C)=>C.category===L_.DiagnosticCategory.Error&&C.code!==18003);if(L.length>0){let C=L.map((q)=>L_.flattenDiagnosticMessageText(q.messageText,`
9
+ `)).join("; ");return F0(new O("semantic",`tsconfig compile error: ${C}`))}}let K=new U1(X.fileNames,X.options,W,J),U=L_.createLanguageService(K);return new _0(U,K)}get isDisposed(){return this.#Q}getProgram(){this.#Z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#Z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#Z(),this.#_}notifyFileChanged(_,$){if(this.#Q)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#Q)return;this.#$.removeFile(_)}dispose(){if(this.#Q)return;this.#Q=!0,this.#_.dispose()}#Z(){if(this.#Q)throw Error("TscProgram is disposed")}}class U1{#_;#$;#Q;#Z;#W=new Map;#z=new Map;#J=new Map;constructor(_,$,Q,J){this.#_=new Set(_),this.#$=$,this.#Q=Q,this.#Z=J}updateFile(_,$){let Q=this.#W.get(_);if(Q)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 W=`${_}:${$.version}`,z=this.#z.get(W);if(!z)z=L_.ScriptSnapshot.fromString($.content),this.#z.set(W,z);return z}let Q=this.#J.get(_);if(Q)return Q;let J=this.#Z(_);if(J!==void 0)return Q=L_.ScriptSnapshot.fromString(J),this.#J.set(_,Q),Q;return}getCurrentDirectory(){return this.#Q}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return L_.getDefaultLibFilePath(_)}fileExists(_){if(this.#W.has(_))return!0;return this.#Z(_)!==void 0}readFile(_){let $=this.#W.get(_);if($)return $.content;return this.#Z(_)}}import n from"typescript";import bQ from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let Q=bQ.getTokenAtPosition(_,$);if(Q.getStart(_,!1)>$)return;return Q}var $0=8;function PQ(_){return!!(_.flags&n.TypeFlags.Object)&&!!(_.objectFlags&n.ObjectFlags.Reference)}function M_(_,$,Q=0,J){if(J){let w=J.get($);if(w)return w}let W=_.typeToString($),z=$.flags,Y=!!(z&n.TypeFlags.Union),Z=!!(z&n.TypeFlags.Intersection),X;if(Q<$0&&PQ($)){let w=_.getTypeArguments($);if(w.length>0)X=w}let K=!!(z&n.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,U;if(Y&&Q<$0)U=$.types.map((w)=>M_(_,w,Q+1,J));else if(Z&&Q<$0)U=$.types.map((w)=>M_(_,w,Q+1,J));let L;if(X&&X.length>0)L=X.map((w)=>M_(_,w,Q+1,J));let C;if(Q<$0&&!!(z&n.TypeFlags.Object)&&!Y&&!Z){let w=_.getPropertiesOfType($);if(w.length>0&&w.length<=50){let S=$.symbol?.declarations?.[0];C=[];for(let F of w){let G=F.declarations?.[0]??S;if(!G)continue;try{let E=_.getTypeOfSymbolAtLocation(F,G);C.push({name:F.getName(),type:M_(_,E,Q+1,J)})}catch{}}if(C.length===0)C=void 0}}let q={text:W,flags:z,isUnion:Y,isIntersection:Z,isGeneric:K,members:U,typeArguments:L,properties:C};if(J)J.set($,q);return q}function fQ(_){return n.isFunctionDeclaration(_)||n.isVariableDeclaration(_)||n.isClassDeclaration(_)||n.isInterfaceDeclaration(_)||n.isTypeAliasDeclaration(_)||n.isEnumDeclaration(_)||n.isMethodDeclaration(_)||n.isPropertyDeclaration(_)||n.isPropertySignature(_)||n.isMethodSignature(_)}var g0="/__gildash_type_probe__.ts";class j0{program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(g0,`declare const __gildash_probe__: ${_};`),this.#_=_}#Q(_,$){let Q=_.getSourceFile(g0);if(!Q)return null;let J=Q.statements[0];if(!J||!n.isVariableStatement(J))return null;let W=J.declarationList.declarations[0];if(!W)return null;return $.getTypeAtLocation(W.name)}clearProbe(){if(this.#_!==null)this.program.removeFile(g0),this.#_=null}collectAt(_,$){let Q=this.program.getProgram(),J=Q.getTypeChecker();if($<0)return null;let W=Q.getSourceFile(_);if(!W)return null;if($>=W.getEnd())return null;let z=e(W,$);if(!z)return null;if(!n.isIdentifier(z)&&!n.isTypeNode(z))return null;try{let Y=J.getTypeAtLocation(z);return M_(J,Y,0,new Map)}catch{return null}}isAssignableTo(_,$,Q,J){let W=this.program.getProgram(),z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!n.isIdentifier(Z))return null;let X=W.getSourceFile(Q);if(!X)return null;let K=e(X,J);if(!K||!n.isIdentifier(K))return null;try{let U=z.getTypeAtLocation(Z),L=z.getTypeAtLocation(K);return z.isTypeAssignableTo(U,L)}catch{return null}}isAssignableToType(_,$,Q,J){this.#$(Q);let W=this.program.getProgram(),z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!n.isIdentifier(Z)&&!n.isTypeNode(Z))return null;try{let X=this.#Q(W,z);if(!X)return null;let K=z.getTypeAtLocation(Z);if(J?.anyConstituent&&K.isUnion())return K.types.some((U)=>z.isTypeAssignableTo(U,X));return z.isTypeAssignableTo(K,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,Q,J){let W=new Map;if($.length===0)return W;this.#$(Q);let z=this.program.getProgram(),Y=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return W;try{let X=this.#Q(z,Y);if(!X)return W;let K=Z.getEnd();for(let U of $){if(U<0||U>=K)continue;let L=e(Z,U);if(!L||!n.isIdentifier(L)&&!n.isTypeNode(L))continue;try{let C=Y.getTypeAtLocation(L);if(J?.anyConstituent&&C.isUnion())W.set(U,C.types.some((q)=>Y.isTypeAssignableTo(q,X)));else W.set(U,Y.isTypeAssignableTo(C,X))}catch{}}}catch{}return W}collectAtPositions(_,$){let Q=new Map;if($.length===0)return Q;let J=this.program.getProgram(),W=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return Q;let Y=z.getEnd(),Z=new Map;for(let X of $){if(X<0||X>=Y)continue;let K=e(z,X);if(!K)continue;if(!n.isIdentifier(K)&&!n.isTypeNode(K))continue;try{let U=W.getTypeAtLocation(K);Q.set(X,M_(W,U,0,Z))}catch{}}return Q}collectFile(_){let $=new Map,Q=this.program.getProgram(),J=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return $;let z=new Map;function Y(Z){if(fQ(Z)&&Z.name&&n.isIdentifier(Z.name)){let X=Z.name;try{let K=J.getTypeAtLocation(X),U=X.getStart(W);$.set(U,M_(J,K,0,z))}catch{}}n.forEachChild(Z,Y)}return Y(W),$}}import B_ from"typescript";var yQ=1000,xQ=1;function hQ(_){let $=_.declarations?.[0],Q=$?.getSourceFile(),J=$?B_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:Q?.fileName??"",position:J?.getStart(Q,!1)??$?.getStart(Q,!1)??0}}function Q0(_,$=0,Q){let J=_.declarations?.[0],W=J?.getSourceFile(),z=J?B_.getNameOfDeclaration(J):void 0,Y=W?.fileName??"",Z=z?.getStart(W,!1)??J?.getStart(W,!1)??0,X={name:_.getName(),filePath:Y,position:Z},K=_;if(K.parent)X.parent=hQ(K.parent);let U=Q&&!!(_.flags&B_.SymbolFlags.Alias)?Q.getAliasedSymbol(_):_;if($<xQ){let L=U.flags,C=!!(L&B_.SymbolFlags.Enum),q=!!(L&(B_.SymbolFlags.NamespaceModule|B_.SymbolFlags.ValueModule)),w=!!(L&(B_.SymbolFlags.Class|B_.SymbolFlags.Interface));if(C&&U.exports&&U.exports.size>0){let S=[];U.exports.forEach((F)=>{S.push(Q0(F,$+1,Q))}),X.members=S}else if(w&&U.members&&U.members.size>0){let S=[];U.members.forEach((F)=>{S.push(Q0(F,$+1,Q))}),X.members=S}if(q&&U.exports&&U.exports.size>0){let S=[];U.exports.forEach((F)=>{S.push(Q0(F,$+1,Q))}),X.exports=S}}return X}class k0{#_;#$;#Q=new Map;constructor(_,$=yQ){this.#_=_,this.#$=new m_($)}get(_,$){if(this.#_.isDisposed)return null;let Q=`${_}:${$}`,J=this.#$.get(Q);if(J!==void 0)return J;let W=this.#_.getProgram(),z=W.getSourceFile(_);if(!z)return null;let Y=e(z,$);if(!Y||!B_.isIdentifier(Y))return null;let Z=W.getTypeChecker(),X=Z.getSymbolAtLocation(Y);if(!X)return null;let K=Q0(X,0,Z);this.#$.set(Q,K);let U=this.#Q.get(_);if(!U)U=new Set,this.#Q.set(_,U);return U.add(Q),K}invalidate(_){let $=this.#Q.get(_);if($){for(let Q of $)this.#$.delete(Q);this.#Q.delete(_)}}clear(){this.#$.clear(),this.#Q.clear()}}import nQ from"typescript";class u0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let Q=this.#_.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let W=e(J,$);if(!W||!nQ.isIdentifier(W))return[];let Y=this.#_.getLanguageService().findReferences(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y)for(let K of X.references){let U=Q.getSourceFile(K.fileName);if(!U)continue;let{line:L,character:C}=U.getLineAndCharacterOfPosition(K.textSpan.start);Z.push({filePath:K.fileName,position:K.textSpan.start,line:L+1,column:C,isDefinition:K.isDefinition??!1,isWrite:K.isWriteAccess??!1})}return Z}}import x from"typescript";function mQ(_,$){let Q=e(_,$);if(!Q)return;if(O1(Q))return Q;let J=Q.parent;for(let W=0;W<5&&J;W++){if(O1(J))return J;J=J.parent}return Q}function O1(_){return x.isClassDeclaration(_)||x.isClassExpression(_)||x.isFunctionDeclaration(_)||x.isFunctionExpression(_)||x.isArrowFunction(_)||x.isVariableDeclaration(_)||x.isObjectLiteralExpression(_)}function H1(_){if(x.isClassDeclaration(_)||x.isClassExpression(_))return"class";if(x.isFunctionDeclaration(_)||x.isFunctionExpression(_)||x.isArrowFunction(_))return"function";if(x.isObjectLiteralExpression(_))return"object";if(x.isVariableDeclaration(_)&&_.initializer)return H1(_.initializer);return"class"}function dQ(_,$){if(x.isClassDeclaration(_)||x.isFunctionDeclaration(_))return _.name?.getText($)??"";if(x.isClassExpression(_))return _.name?.getText($)??"";if(x.isVariableDeclaration(_)&&x.isIdentifier(_.name))return _.name.getText($);if(x.isFunctionExpression(_))return _.name?.getText($)??"";if(x.isArrowFunction(_)&&_.parent&&x.isVariableDeclaration(_.parent)){if(x.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(x.isObjectLiteralExpression(_)&&_.parent&&x.isVariableDeclaration(_.parent)){if(x.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function pQ(_){if(!x.isClassDeclaration(_)&&!x.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((Q)=>Q.token===x.SyntaxKind.ImplementsKeyword)}class E0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let Q=this.#_.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let W=e(J,$);if(!W||!x.isIdentifier(W))return[];let Y=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y){if(X.kind===x.ScriptElementKind.interfaceElement||X.kind===x.ScriptElementKind.typeElement)continue;let K=Q.getSourceFile(X.fileName);if(!K)continue;let U=mQ(K,X.textSpan.start);if(!U)continue;let L=H1(U),C=dQ(U,K),q=pQ(U);Z.push({filePath:X.fileName,symbolName:C,position:X.textSpan.start,kind:L,isExplicit:q})}return Z}}function lQ(_){if(o.isFunctionDeclaration(_))return"function";if(o.isClassDeclaration(_))return"class";if(o.isInterfaceDeclaration(_))return"interface";if(o.isTypeAliasDeclaration(_))return"type";if(o.isEnumDeclaration(_))return"enum";if(o.isVariableDeclaration(_))return"const";if(o.isVariableStatement(_))return"const";return"unknown"}function M1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class J0{#_;#$;#Q;#Z;#W;#z=!1;constructor(_,$,Q,J,W){this.#_=_,this.#$=$,this.#Q=Q,this.#Z=J,this.#W=W}static create(_,$={}){let Q=_0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(iQ(Q))return Q;let J=Q,W=$.typeCollector??new j0(J),z=$.symbolGraph??new k0(J),Y=$.referenceResolver??new u0(J),Z=$.implementationFinder??new E0(J);return new J0(J,W,z,Y,Z)}get isDisposed(){return this.#z}collectTypeAt(_,$){return this.#J(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#J(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#J(),this.#$.collectAtPositions(_,$)}findReferences(_,$){return this.#J(),this.#Z.findAt(_,$)}findImplementations(_,$){return this.#J(),this.#W.findAt(_,$)}isTypeAssignableTo(_,$,Q,J){return this.#J(),this.#$.isAssignableTo(_,$,Q,J)}isTypeAssignableToType(_,$,Q,J){return this.#J(),this.#$.isAssignableToType(_,$,Q,J)}isTypeAssignableToTypeAtPositions(_,$,Q,J){return this.#J(),this.#$.isAssignableToTypeAtPositions(_,$,Q,J)}getSymbolNode(_,$){return this.#J(),this.#Q.get(_,$)}getBaseTypes(_,$){this.#J();let Q=this.#_.getProgram(),J=Q.getSourceFile(_);if(!J)return null;let W=e(J,$);if(!W)return null;let z=Q.getTypeChecker(),Y=z.getTypeAtLocation(W);if(!(Y.flags&o.TypeFlags.Object)||!(Y.objectFlags&o.ObjectFlags.ClassOrInterface))return null;let Z=z.getBaseTypes(Y);if(!Z||Z.length===0)return[];let X=new Map;return Z.map((K)=>M_(z,K,0,X))}getModuleInterface(_){this.#J();let $=[],Q=this.#_.getProgram(),J=Q.getSourceFile(_);if(!J)return{filePath:_,exports:$};let W=Q.getTypeChecker(),z=W.getSymbolAtLocation(J);if(z){let Y=W.getExportsOfModule(z),Z=new Map;for(let X of Y){let K=X.getName(),U=X.declarations?.[0],L="unknown";if(U){if(L=lQ(U),L==="unknown"&&o.isExportAssignment(U))L="const"}let C=null;try{let q=W.getTypeOfSymbolAtLocation(X,U??J);C=M_(W,q,0,Z)}catch{}$.push({name:K,kind:L,resolvedType:C})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#z)return;this.#_.notifyFileChanged(_,$),this.#Q.invalidate(_)}notifyFileDeleted(_){if(this.#z)return;this.#_.removeFile(_),this.#Q.invalidate(_)}lineColumnToPosition(_,$,Q){this.#J();let J=this.#_.getProgram().getSourceFile(_);if(!J)return null;try{return o.getPositionOfLineAndCharacter(J,$-1,Q)}catch{return null}}findNamePosition(_,$,Q){this.#J();let J=this.#_.getProgram().getSourceFile(_);if(!J)return null;let W=J.getFullText(),z=$;while(z<W.length){let Y=W.indexOf(Q,z);if(Y<0)return null;let Z=Y>0?W.charCodeAt(Y-1):32,X=Y+Q.length<W.length?W.charCodeAt(Y+Q.length):32;if(!M1(Z)&&!M1(X))return Y;z=Y+1}return null}getDiagnostics(_,$){this.#J();let Q=this.#_.getProgram(),J=Q.getSourceFile(_);if(!J)return[];let W={[o.DiagnosticCategory.Error]:"error",[o.DiagnosticCategory.Warning]:"warning",[o.DiagnosticCategory.Suggestion]:"suggestion",[o.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?o.getPreEmitDiagnostics(Q,J):Q.getSemanticDiagnostics(J)).map((Y)=>{let Z=1,X=0;if(Y.file&&Y.start!==void 0){let K=o.getLineAndCharacterOfPosition(Y.file,Y.start);Z=K.line+1,X=K.character}return{filePath:Y.file?.fileName??_,line:Z,column:X,message:o.flattenDiagnosticMessageText(Y.messageText,`
10
+ `),code:Y.code,category:W[Y.category]??"error"}})}dispose(){if(this.#z)return;this.#z=!0,this.#$.clearProbe(),this.#_.dispose(),this.#Q.clear()}#J(){if(this.#z)throw Error("SemanticLayer is disposed")}}import{eq as S_,and as K1,sql as cQ}from"drizzle-orm";var L1=80;class v0{db;constructor(_){this.db=_}insertBatch(_,$,Q){if(!Q.length)return;let J=Q.map((W)=>({project:_,filePath:$,tag:W.tag,value:W.value,source:W.source,symbolName:W.symbolName,startLine:W.startLine,startColumn:W.startColumn,endLine:W.endLine,endColumn:W.endColumn,indexedAt:W.indexedAt}));for(let W=0;W<J.length;W+=L1)this.db.drizzleDb.insert(z_).values(J.slice(W,W+L1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(z_).where(K1(S_(z_.project,_),S_(z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(z_).where(K1(_.project?S_(z_.project,_.project):void 0,_.tag?S_(z_.tag,_.tag):void 0,_.filePath?S_(z_.filePath,_.filePath):void 0,_.symbolName?S_(z_.symbolName,_.symbolName):void 0,_.source?S_(z_.source,_.source):void 0,_.ftsQuery?cQ`${z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as E_,and as B1,sql as d_,gt as aQ,gte as sQ}from"drizzle-orm";var w1=80;class b0{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+=w1)this.db.drizzleDb.insert(t).values($.slice(Q,Q+w1)).run()}getSince(_){return this.db.drizzleDb.select().from(t).where(B1(E_(t.project,_.project),sQ(t.changedAt,_.since),_.symbolName?E_(t.symbolName,_.symbolName):void 0,_.changeTypes?.length?d_`${t.changeType} IN (${d_.join(_.changeTypes.map(($)=>d_`${$}`),d_`, `)})`:void 0,_.filePath?E_(t.filePath,_.filePath):void 0,_.includeFullIndex?void 0:E_(t.isFullIndex,0),_.indexRunId?E_(t.indexRunId,_.indexRunId):void 0,_.afterId?aQ(t.id,_.afterId):void 0)).orderBy(t.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(t).where(B1(E_(t.project,_),d_`${t.changedAt} < ${$}`)).run().changes}}function D1(_){let{annotationRepo:$,project:Q,query:J}=_,W=J.project??Q,z;if(J.text){let Z=F_(J.text);if(Z)z=Z}return $.search({project:W,tag:J.tag,filePath:J.filePath,symbolName:J.symbolName,source:J.source,ftsQuery:z,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}}}))}class W0{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:W}=Q;if(W===null)continue;if(!this.adjacencyList.has(J))this.adjacencyList.set(J,new Set);if(this.adjacencyList.get(J).add(W),!this.adjacencyList.has(W))this.adjacencyList.set(W,new Set);if(!this.reverseAdjacencyList.has(W))this.reverseAdjacencyList.set(W,new Set);this.reverseAdjacencyList.get(W).add(J)}}patchFiles(_,$,Q){let J=new Set([..._,...$]);for(let W of J){let z=this.adjacencyList.get(W);if(z){for(let Z of z)this.reverseAdjacencyList.get(Z)?.delete(W);z.clear()}let Y=this.reverseAdjacencyList.get(W);if(Y){for(let Z of Y)this.adjacencyList.get(Z)?.delete(W);Y.clear()}}for(let W of $)this.adjacencyList.delete(W),this.reverseAdjacencyList.delete(W);for(let W of _){let z=Q(W);for(let Y of z){if(!this.adjacencyList.has(Y.srcFilePath))this.adjacencyList.set(Y.srcFilePath,new Set);if(this.adjacencyList.get(Y.srcFilePath).add(Y.dstFilePath),!this.adjacencyList.has(Y.dstFilePath))this.adjacencyList.set(Y.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Y.dstFilePath))this.reverseAdjacencyList.set(Y.dstFilePath,new Set);this.reverseAdjacencyList.get(Y.dstFilePath).add(Y.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 W of this.reverseAdjacencyList.get(J)??[])if(!$.has(W))$.add(W),Q.push(W)}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 W=J.pop();if(W.entered){$.delete(W.node);continue}if($.has(W.node))return!0;if(_.has(W.node))continue;_.add(W.node),$.add(W.node),J.push({node:W.node,entered:!0});for(let z of this.adjacencyList.get(W.node)??[]){if($.has(z))return!0;if(!_.has(z))J.push({node:z,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 W of this.adjacencyList.get(J)??[])if(!$.has(W))$.add(W),Q.push(W)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let Q=new Map;for(let[J,W]of this.adjacencyList)Q.set(J,Array.from(W));return _J(Q,$)}}var rQ=(_,$)=>_.localeCompare($);function oQ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let Q=$;for(let J=1;J<$.length;J++){let W=$.slice(J).concat($.slice(0,J));if(W.join("::")<Q.join("::"))Q=W}return[...Q]}function P0(_,$,Q){let J=oQ(Q);if(J.length===0)return!1;let W=J.join("->");if(_.has(W))return!1;return _.add(W),$.push(J),!0}function tQ(_){let $=0,Q=[],J=new Set,W=new Map,z=new Map,Y=[],Z=(X)=>{W.set(X,$),z.set(X,$),$+=1,Q.push(X),J.add(X);for(let K of _.get(X)??[])if(!W.has(K))Z(K),z.set(X,Math.min(z.get(X)??0,z.get(K)??0));else if(J.has(K))z.set(X,Math.min(z.get(X)??0,W.get(K)??0));if(z.get(X)===W.get(X)){let K=[],U="";do U=Q.pop()??"",J.delete(U),K.push(U);while(U!==X&&Q.length>0);Y.push(K)}};for(let X of _.keys())if(!W.has(X))Z(X);return{components:Y}}function eQ(_,$,Q){let J=[],W=new Set,z=[..._].sort(rQ),Y=(Z,X,K)=>{X.delete(Z);let U=K.get(Z);if(!U)return;for(let L of U)if(X.has(L))Y(L,X,K);U.clear()};for(let Z=0;Z<z.length&&J.length<Q;Z++){let X=z[Z]??"",K=new Set(z.slice(Z)),U=new Set,L=new Map,C=[],q=(S)=>($.get(S)??[]).filter((F)=>K.has(F)),w=(S)=>{if(J.length>=Q)return!0;let F=!1;C.push(S),U.add(S);for(let G of q(S)){if(J.length>=Q)break;if(G===X)P0(W,J,C.concat(X)),F=!0;else if(!U.has(G)){if(w(G))F=!0}}if(F)Y(S,U,L);else for(let G of q(S)){let E=L.get(G)??new Set;E.add(S),L.set(G,E)}return C.pop(),F};w(X)}return J}function _J(_,$){let{components:Q}=tQ(_),J=[],W=new Set;for(let z of Q){if(J.length>=$)break;if(z.length===0)continue;if(z.length===1){let X=z[0]??"";if((_.get(X)??[]).includes(X))P0(W,J,[X,X]);continue}let Y=$-J.length,Z=eQ(z,_,Y);for(let X of Z){if(J.length>=$)break;P0(W,J,X)}}return J}var $J=15000;function z0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function T_(_,$){let Q=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>$J)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===Q)return _.graphCache;let J=new W0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((W)=>W.project)});return J.build(),_.graphCache=J,_.graphCacheKey=Q,_.graphCacheBuiltAt=Date.now(),J}function I1(_,$,Q,J=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:Q??_.defaultProject,query:{srcFilePath:$,type:"imports",project:Q??_.defaultProject,limit:J}}).filter((W)=>W.dstFilePath!==null).map((W)=>W.dstFilePath)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getDependencies failed",{cause:W})}}function C1(_,$,Q,J=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:Q??_.defaultProject,query:{dstFilePath:$,type:"imports",project:Q??_.defaultProject,limit:J}}).map((W)=>W.srcFilePath)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getDependents failed",{cause:W})}}async function A1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,Q).getAffectedByChange($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getAffected failed",{cause:J})}}async function N1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,$).hasCycle()}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: hasCycle failed",{cause:Q})}}async function q1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,$).getAdjacencyList()}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getImportGraph failed",{cause:Q})}}async function R1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,Q).getTransitiveDependencies($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getTransitiveDependencies failed",{cause:J})}}async function S1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,Q).getTransitiveDependents($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getTransitiveDependents failed",{cause:J})}}async function T1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return T_(_,$).getCyclePaths(Q)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getCyclePaths failed",{cause:J})}}async function G1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let J=T_(_,Q);return{filePath:$,fanIn:J.getDependents($).length,fanOut:J.getDependencies($).length}}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getFanMetrics failed",{cause:J})}}var WJ=30000,F1=15000,zJ=10;function ZJ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??v_.basename(_.projectRoot)}function YJ(_,$){return(Q)=>{for(let J of _.onFileChangedCallbacks)try{J(Q)}catch(W){_.logger.error("[Gildash] onFileChanged callback threw:",W)}if($.handleWatcherEvent?.(Q),_.semanticLayer)if(Q.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(Q.filePath)}catch(J){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",J);for(let W of _.onErrorCallbacks)try{W(J instanceof O?J:new O("semantic","semantic notifyFileDeleted failed",{cause:J}))}catch{}}else _.readFileFn(Q.filePath).then((J)=>{try{_.semanticLayer?.notifyFileChanged(Q.filePath,J)}catch(W){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",W);for(let z of _.onErrorCallbacks)try{z(W instanceof O?W:new O("semantic","semantic notifyFileChanged failed",{cause:W}))}catch{}}}).catch((J)=>{_.logger.error("[Gildash] failed to read file for semantic layer",Q.filePath,J);try{_.semanticLayer?.notifyFileDeleted(Q.filePath)}catch(W){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",W)}})}}async function XJ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(Q)=>{try{let J=v_.resolve(_.projectRoot,Q.filePath),W=await _.readFileFn(J);_.semanticLayer?.notifyFileChanged(J,W)}catch{}}))}async function g1(_,$){let Q=_.coordinatorFactory?_.coordinatorFactory():new q0({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)=>ZJ(_,J),logger:_.logger});_.coordinator=Q;for(let J of _.onIndexedCallbacks)Q.onIndexed(J);if(Q.onIndexed((J)=>{let W=J.changedFiles.length+J.deletedFiles.length;if(_.graphCache&&W>0&&W<100){let z=_.relationRepo;_.graphCache.patchFiles(J.changedFiles,J.deletedFiles,(Y)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>z.getByType(X,"imports").concat(z.getByType(X,"type-references")).concat(z.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Y||X.dstFilePath===Y)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else z0(_)}),$.isWatchMode){let J=_.watcherFactory?_.watcherFactory():new L0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await J.start(YJ(_,Q)).then((W)=>{if(p_(W))throw W.data}),_.watcher=J,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},WJ)}await Q.fullIndex(),await XJ(_)}function VJ(_,$){let Q=["SIGTERM","SIGINT","beforeExit"];for(let J of Q){let W=()=>{$().catch((z)=>_.logger.error("[Gildash] close error during signal",J,z))};if(J==="beforeExit")process.on("beforeExit",W);else process.on(J,W);_.signalHandlers.push([J,W])}}async function j1(_){let{projectRoot:$,extensions:Q=[".ts",".mts",".cts"],ignorePatterns:J=["**/node_modules/**"],parseCacheCapacity:W=500,logger:z=console,existsSyncFn:Y=JJ,dbConnectionFactory:Z,watcherFactory:X,coordinatorFactory:K,repositoryFactory:U,acquireWatcherRoleFn:L=Y1,releaseWatcherRoleFn:C=X1,updateHeartbeatFn:q=V1,discoverProjectsFn:w=a_,parseSourceFn:S=j_,extractSymbolsFn:F=N_,extractRelationsFn:G=n_,symbolSearchFn:E=S0,relationSearchFn:u=T0,patternSearchFn:y=G0,loadTsconfigPathsFn:d=x_,readFileFn:p=async(c)=>Bun.file(c).text(),unlinkFn:J_=async(c)=>{await Bun.file(c).unlink()},watchMode:Z_,semantic:O_,semanticLayerFactory:Y_}=_;if(!v_.isAbsolute($))throw new O("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Y($))throw new O("validation",`Gildash: projectRoot does not exist: "${$}"`);let W_=Z?Z():new U0({projectRoot:$}),i=W_.open();if(p_(i))throw i.data;try{let c=await w($),w_=c[0]?.project??v_.basename($),I=U?U():(()=>{let T=W_;return{fileRepo:new O0(T),symbolRepo:new H0(T),relationRepo:new M0(T),parseCache:new R0(W)}})(),N=U?null:W_,V=N?new v0(N):null,H=N?new b0(N):null,M=Z_??!0,B=crypto.randomUUID(),A;if(M)A=await Promise.resolve(L(W_,process.pid,{instanceId:B}));else A="owner";let D={projectRoot:$,extensions:Q,ignorePatterns:J,logger:z,defaultProject:w_,role:A,db:W_,symbolRepo:I.symbolRepo,relationRepo:I.relationRepo,fileRepo:I.fileRepo,parseCache:I.parseCache,annotationRepo:V,changelogRepo:H,annotationSearchFn:D1,releaseWatcherRoleFn:C,parseSourceFn:S,extractSymbolsFn:F,extractRelationsFn:G,symbolSearchFn:E,relationSearchFn:u,patternSearchFn:y,readFileFn:p,unlinkFn:J_,existsSyncFn:Y,acquireWatcherRoleFn:L,updateHeartbeatFn:q,watcherFactory:X,coordinatorFactory:K,instanceId:B,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:c,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(s_($),D.tsconfigPaths=await d($),O_){let T=v_.join($,"tsconfig.json");try{if(Y_)D.semanticLayer=Y_(T);else{let R=J0.create(T);if(p_(R))throw R.data;D.semanticLayer=R}}catch(R){if(R instanceof O)throw R;throw new O("semantic","Gildash: semantic layer creation failed",{cause:R})}}if(A==="owner")await g1(D,{isWatchMode:M});else{let T=0,R=async()=>{try{let g=await Promise.resolve(D.acquireWatcherRoleFn(D.db,process.pid,{instanceId:D.instanceId}));if(T=0,g==="owner"){D.role="owner";for(let j of D.onRoleChangedCallbacks)try{j("owner")}catch(v){D.logger.error("[Gildash] onRoleChanged callback threw:",v)}clearInterval(D.timer),D.timer=null;try{await g1(D,{isWatchMode:!0})}catch(j){if(D.logger.error("[Gildash] owner promotion failed, reverting to reader",j),D.role="reader",D.timer!==null)clearInterval(D.timer),D.timer=null;if(D.watcher){let v=await D.watcher.close();if(p_(v))D.logger.error("[Gildash] watcher close error during promotion rollback",v.data);D.watcher=null}if(D.coordinator)await D.coordinator.shutdown().catch((v)=>D.logger.error("[Gildash] coordinator shutdown error during promotion rollback",v)),D.coordinator=null;try{D.releaseWatcherRoleFn(D.db,process.pid)}catch(v){D.logger.error("[Gildash] failed to release watcher role during promotion rollback",v)}D.timer=setInterval(R,F1)}}}catch(g){T++;let j=g instanceof O?g:new O("watcher","Gildash: healthcheck error",{cause:g});for(let v of D.onErrorCallbacks)try{v(j)}catch(m){D.logger.error("[Gildash] onError callback threw:",m)}if(D.logger.error("[Gildash] healthcheck error",g),T>=zJ)D.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(D.timer),D.timer=null,Z0(D).catch((v)=>D.logger.error("[Gildash] close error during healthcheck shutdown",v))}};D.timer=setInterval(R,F1)}if(M)VJ(D,()=>Z0(D));return D}catch(c){if(W_.close(),c instanceof O)throw c;throw new O("store","Gildash: initialization failed",{cause:c})}}async function Z0(_,$){if(_.closed)return;_.closed=!0;let Q=[];for(let[J,W]of _.signalHandlers)if(J==="beforeExit")process.off("beforeExit",W);else process.off(J,W);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(p_(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(v_.join(_.projectRoot,I_,l_+J))}catch{}if(Q.length>0)throw new O("close","Gildash: one or more errors occurred during close()",{cause:Q})}import{isErr as k1}from"@zipbul/result";function u1(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");let W=_.parseSourceFn($,Q,J);if(k1(W))throw W.data;return _.parseCache.set($,W),W}async function E1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let J=new Map,W=[];return await Promise.all($.map(async(z)=>{try{let Y=await _.readFileFn(z),Z=_.parseSourceFn(z,Y,Q);if(!k1(Z))J.set(z,Z);else W.push({filePath:z,error:Z.data})}catch(Y){W.push({filePath:z,error:Y instanceof Error?Y:Error(String(Y))})}})),{parsed:J,failures:W}}function v1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.parseCache.get($)}function b1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function P1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import f1 from"path";function y1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getStats failed",{cause:Q})}}function f0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: searchSymbols failed",{cause:Q})}}function x1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: searchRelations failed",{cause:Q})}}function h1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: searchAllSymbols failed",{cause:Q})}}function n1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: searchAllRelations failed",{cause:Q})}}function m1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: listIndexedFiles failed",{cause:Q})}}function d1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:Q??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getInternalRelations failed",{cause:J})}}function p1(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=J??_.defaultProject,z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:W,query:{text:$,exact:!0,filePath:Q,limit:1}});if(z.length===0)return null;let Y=z[0],Z=Y.detail,X={...Y,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=f1.isAbsolute(Q)?Q:f1.resolve(_.projectRoot,Q),U=_.semanticLayer.lineColumnToPosition(K,Y.span.start.line,Y.span.start.column);if(U!==null){let L=_.semanticLayer.findNamePosition(K,U,Y.name)??U,C=_.semanticLayer.collectTypeAt(K,L);if(C)X.resolvedType=C}}catch{}return X}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getFullSymbol failed",{cause:W})}}function i1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let J=Q??_.defaultProject,W=_.fileRepo.getFile(J,$);if(!W)throw new O("search",`Gildash: file '${$}' is not in the index`);let z=_.symbolRepo.getFileSymbols(J,$),Y=_.relationRepo.getOutgoing(J,$);return{filePath:W.filePath,lineCount:W.lineCount??0,size:W.size,symbolCount:z.length,exportedSymbolCount:z.filter((Z)=>Z.isExported).length,relationCount:Y.length}}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getFileStats failed",{cause:J})}}function l1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(Q??_.defaultProject,$)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getFileInfo failed",{cause:J})}}function c1(_,$,Q){return f0(_,{filePath:$,project:Q??void 0,limit:1e4})}function a1(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:Q??_.defaultProject,query:{filePath:$,isExported:!0}}).map((z)=>({name:z.name,kind:z.kind,parameters:z.detail.parameters?`(${z.detail.parameters.map((Y)=>`${Y.name}${Y.isOptional?"?":""}: ${Y.type??"unknown"}`).join(", ")})`:void 0,returnType:z.detail.returnType??void 0,jsDoc:z.detail.jsDoc?.description??void 0}));return{filePath:$,exports:W}}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getModuleInterface failed",{cause:J})}}import P from"path";function i_(_,$,Q,J){let W=J??_.defaultProject,z=P.isAbsolute(Q)?P.relative(_.projectRoot,Q):Q,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:W,query:{text:$,exact:!0,filePath:z,limit:1}});if(Y.length===0)return null;let Z=Y[0],X=P.isAbsolute(Q)?Q:P.resolve(_.projectRoot,Q),K=_.semanticLayer.lineColumnToPosition(X,Z.span.start.line,Z.span.start.column);if(K===null)return null;let U=_.semanticLayer.findNamePosition(X,K,Z.name)??K;return{sym:Z,position:U,absPath:X}}function s1(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,Q,J);if(!W)return null;return _.semanticLayer.collectTypeAt(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getResolvedType failed",{cause:W})}}function r1(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,Q,J);if(!W)throw new O("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findReferences(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getSemanticReferences failed",{cause:W})}}function o1(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,Q,J);if(!W)throw new O("search",`Gildash: symbol '${$}' not found in '${Q}'`);return _.semanticLayer.findImplementations(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getImplementations failed",{cause:W})}}function t1(_,$,Q,J,W,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Y=i_(_,$,Q,z);if(!Y)throw new O("search",`Gildash: source symbol '${$}' not found in '${Q}'`);let Z=i_(_,J,W,z);if(!Z)throw new O("search",`Gildash: target symbol '${J}' not found in '${W}'`);return _.semanticLayer.isTypeAssignableTo(Y.absPath,Y.position,Z.absPath,Z.position)}catch(Y){if(Y instanceof O)throw Y;throw new O("semantic","Gildash: isTypeAssignableTo failed",{cause:Y})}}function e1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(Q)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getFileTypes failed",{cause:Q})}}function _$(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$),z=_.semanticLayer.lineColumnToPosition(W,Q,J);if(z===null)return null;return _.semanticLayer.collectTypeAt(W,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: getResolvedTypeAt failed",{cause:W})}}function $$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($.source.filePath)?$.source.filePath:P.resolve(_.projectRoot,$.source.filePath),J=P.isAbsolute($.target.filePath)?$.target.filePath:P.resolve(_.projectRoot,$.target.filePath),W=_.semanticLayer.lineColumnToPosition(Q,$.source.line,$.source.column);if(W===null)return null;let z=_.semanticLayer.lineColumnToPosition(J,$.target.line,$.target.column);if(z===null)return null;return _.semanticLayer.isTypeAssignableTo(Q,W,J,z)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: isTypeAssignableToAt failed",{cause:Q})}}function Q$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getSemanticModuleInterface failed",{cause:Q})}}function J$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getBaseTypes failed",{cause:J})}}function W$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:J})}}function z$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:J})}}function Z$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:J})}}function Y$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getImplementationsAtPosition failed",{cause:J})}}function X$(_,$,Q,J,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$),Y=P.isAbsolute(J)?J:P.resolve(_.projectRoot,J);return _.semanticLayer.isTypeAssignableTo(z,Q,Y,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:z})}}function V$(_,$,Q,J,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(z,Q,J,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToType failed",{cause:z})}}function U$(_,$,Q,J,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(z,Q,J,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:z})}}function O$(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(W,Q,J)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: lineColumnToPosition failed",{cause:W})}}function H$(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(W,Q,J)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: findNamePosition failed",{cause:W})}}function M$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getSymbolNode failed",{cause:J})}}function K$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(J,Q)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getSemanticDiagnostics failed",{cause:J})}}function L$(_,$){let Q=new Map(_.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),J=new Map($.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),W=[],z=[],Y=[];for(let[Z,X]of J){let K=Q.get(Z);if(!K)W.push(X);else if(K.fingerprint!==X.fingerprint)Y.push({before:K,after:X})}for(let[Z,X]of Q)if(!J.has(Z))z.push(X);return{added:W,removed:z,modified:Y}}function B$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let Q=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),Q()}}async function w$(_){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.coordinator)throw new O("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return z0(_),$}catch($){if($ instanceof O)throw $;throw new O("index","Gildash: reindex failed",{cause:$})}}function D$(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");let W=J??_.defaultProject,z=new Set,Y=[],Z=$,X=Q;for(;;){let K=`${X}::${Z}`;if(z.has(K))return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!0};z.add(K);let U=_.relationSearchFn({relationRepo:_.relationRepo,project:W,query:{type:"re-exports",srcFilePath:X,limit:500}}),L,C;for(let q of U){let w;if(q.metaJson)try{let F=JSON.parse(q.metaJson);if(Array.isArray(F.specifiers))w=F.specifiers}catch{}if(!w)continue;let S=w.find((F)=>F.exported===Z);if(!S)continue;L=q.dstFilePath??void 0,C=S.local;break}if(!L||!C)return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!1};Y.push({filePath:X,exportedAs:Z}),X=L,Z=C}}function I$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function C$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function A$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function N$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let J=Q?.project??_.defaultProject,W=Q?.filePaths?Q.filePaths:_.fileRepo.getAllFiles(J).map((z)=>z.filePath);return await _.patternSearchFn({pattern:$,filePaths:W})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: findPattern failed",{cause:J})}}async function q$(_,$,Q,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=J??_.defaultProject,z=new Set,Y=(Z,X,K)=>{let U=`${Z}::${X}`;if(z.has(U))return{symbolName:Z,filePath:X,kind:K,children:[]};z.add(U);let q=_.relationSearchFn({relationRepo:_.relationRepo,project:W,query:{srcFilePath:X,srcSymbolName:Z,limit:1000}}).filter((w)=>w.type==="extends"||w.type==="implements").filter((w)=>w.dstSymbolName!=null&&w.dstFilePath!=null).map((w)=>Y(w.dstSymbolName,w.dstFilePath,w.type));return{symbolName:Z,filePath:X,kind:K,children:q}};return Y($,Q)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getHeritageChain failed",{cause:W})}}function R$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function S$(_,$,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let J=$ instanceof Date?$.toISOString():$,W=Q?.project??_.defaultProject,z=Q?.limit??1000;return _.changelogRepo.getSince({project:W,since:J,symbolName:Q?.symbolName,changeTypes:Q?.changeTypes,filePath:Q?.filePath,includeFullIndex:Q?.includeFullIndex,indexRunId:Q?.indexRunId,afterId:Q?.afterId,limit:z}).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 T$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let Q=$ instanceof Date?$.toISOString():$,J=0,W=[_.defaultProject,..._.boundaries.map((Y)=>Y.project)],z=[...new Set(W)];for(let Y of z)J+=_.changelogRepo.pruneOlderThan(Y,Q);return J}class y0{_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 j1(_);return new y0($)}async close(_){return Z0(this._ctx,_)}parseSource(_,$,Q){return u1(this._ctx,_,$,Q)}async batchParse(_,$){return E1(this._ctx,_,$)}getParsedAst(_){return v1(this._ctx,_)}extractSymbols(_){return b1(this._ctx,_)}extractRelations(_){return P1(this._ctx,_)}getStats(_){return y1(this._ctx,_)}searchSymbols(_){return f0(this._ctx,_)}searchRelations(_){return x1(this._ctx,_)}searchAllSymbols(_){return h1(this._ctx,_)}searchAllRelations(_){return n1(this._ctx,_)}listIndexedFiles(_){return m1(this._ctx,_)}getInternalRelations(_,$){return d1(this._ctx,_,$)}getFullSymbol(_,$,Q){return p1(this._ctx,_,$,Q)}getFileStats(_,$){return i1(this._ctx,_,$)}getFileInfo(_,$){return l1(this._ctx,_,$)}getSymbolsByFile(_,$){return c1(this._ctx,_,$)}getModuleInterface(_,$){return a1(this._ctx,_,$)}getDependencies(_,$,Q=1e4){return I1(this._ctx,_,$,Q)}getDependents(_,$,Q=1e4){return C1(this._ctx,_,$,Q)}async getAffected(_,$){return A1(this._ctx,_,$)}async hasCycle(_){return N1(this._ctx,_)}async getImportGraph(_){return q1(this._ctx,_)}async getTransitiveDependencies(_,$){return R1(this._ctx,_,$)}async getTransitiveDependents(_,$){return S1(this._ctx,_,$)}async getCyclePaths(_,$){return T1(this._ctx,_,$)}async getFanMetrics(_,$){return G1(this._ctx,_,$)}getResolvedType(_,$,Q){return s1(this._ctx,_,$,Q)}getSemanticReferences(_,$,Q){return r1(this._ctx,_,$,Q)}getImplementations(_,$,Q){return o1(this._ctx,_,$,Q)}isTypeAssignableTo(_,$,Q,J,W){return t1(this._ctx,_,$,Q,J,W)}getSemanticModuleInterface(_){return Q$(this._ctx,_)}getFileTypes(_){return e1(this._ctx,_)}getResolvedTypeAt(_,$,Q){return _$(this._ctx,_,$,Q)}isTypeAssignableToAt(_){return $$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return z$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return W$(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return Z$(this._ctx,_,$)}getImplementationsAtPosition(_,$){return Y$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,Q,J){return X$(this._ctx,_,$,Q,J)}isTypeAssignableToType(_,$,Q,J){return V$(this._ctx,_,$,Q,J)}isTypeAssignableToTypeAtPositions(_,$,Q,J){return U$(this._ctx,_,$,Q,J)}lineColumnToPosition(_,$,Q){return O$(this._ctx,_,$,Q)}findNamePosition(_,$,Q){return H$(this._ctx,_,$,Q)}getSymbolNode(_,$){return M$(this._ctx,_,$)}getBaseTypes(_,$){return J$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return K$(this._ctx,_,$)}diffSymbols(_,$){return L$(_,$)}onIndexed(_){return B$(this._ctx,_)}async reindex(){return w$(this._ctx)}resolveSymbol(_,$,Q){return D$(this._ctx,_,$,Q)}async findPattern(_,$){return N$(this._ctx,_,$)}async getHeritageChain(_,$,Q){return q$(this._ctx,_,$,Q)}onFileChanged(_){return I$(this._ctx,_)}onError(_){return C$(this._ctx,_)}onRoleChanged(_){return A$(this._ctx,_)}searchAnnotations(_){return R$(this._ctx,_)}getSymbolChanges(_,$){return S$(this._ctx,_,$)}pruneChangelog(_){return T$(this._ctx,_)}}import{Visitor as O5,visitorKeys as H5}from"oxc-parser";export{H5 as visitorKeys,S0 as symbolSearch,T0 as relationSearch,G0 as patternSearch,j_ as parseSource,Q_ as normalizePath,V_ as getLineColumn,N_ as extractSymbols,n_ as extractRelations,h_ as buildLineOffsets,O5 as Visitor,O as GildashError,y0 as Gildash,W0 as DependencyGraph};