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