@zipbul/gildash 0.19.0 → 0.20.0
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 +9 -9
- package/dist/src/extractor/index.d.ts +1 -1
- package/dist/src/extractor/types.d.ts +68 -2
- package/dist/src/gildash/types.d.ts +3 -1
- package/dist/src/index.d.ts +2 -2
- package/dist/src/search/index.d.ts +1 -1
- package/dist/src/search/pattern-search.d.ts +13 -0
- package/dist/src/search/symbol-search.d.ts +7 -1
- package/dist/src/semantic/type-collector.d.ts +3 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var R1=Object.defineProperty;var S1=(_)=>_;function T1(_,$){this[_]=S1.bind(null,$)}var k1=(_,$)=>{for(var J in $)R1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:T1.bind($,J)})};var P$=import.meta.require;import{isErr as m_}from"@zipbul/result";import F_ from"path";import{existsSync as sJ}from"fs";import{err as f$,isErr as b1}from"@zipbul/result";import{Database as y1}from"bun:sqlite";import{mkdirSync as P1,unlinkSync as n$,existsSync as m$}from"fs";import{dirname as f1,join as x$}from"path";import{drizzle as n1}from"drizzle-orm/bun-sqlite";import{migrate as m1}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};k1(Y$,{watcherOwner:()=>v1,symbols:()=>h,symbolChangelog:()=>Q_,relations:()=>E,files:()=>__,annotations:()=>Z_});import{sql as F1}from"drizzle-orm";import{sqliteTable as N_,text as y,integer as e,real as j1,index as W_,primaryKey as G1,foreignKey as W$,check as E1}from"drizzle-orm/sqlite-core";var __=N_("files",{project:y("project").notNull(),filePath:y("file_path").notNull(),mtimeMs:j1("mtime_ms").notNull(),size:e("size").notNull(),contentHash:y("content_hash").notNull(),updatedAt:y("updated_at").notNull(),lineCount:e("line_count")},(_)=>[G1({columns:[_.project,_.filePath]})]),h=N_("symbols",{id:e("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),filePath:y("file_path").notNull(),kind:y("kind").notNull(),name:y("name").notNull(),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),isExported:e("is_exported").notNull().default(0),signature: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")},(_)=>[W_("idx_symbols_project_file").on(_.project,_.filePath),W_("idx_symbols_project_kind").on(_.project,_.kind),W_("idx_symbols_project_name").on(_.project,_.name),W_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),E=N_("relations",{id:e("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:e("is_external").notNull().default(0)},(_)=>[W_("idx_relations_src").on(_.project,_.srcFilePath),W_("idx_relations_dst").on(_.dstProject,_.dstFilePath),W_("idx_relations_type").on(_.project,_.type),W_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),W_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Z_=N_("annotations",{id:e("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:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),indexedAt:y("indexed_at").notNull()},(_)=>[W_("idx_annotations_project_file").on(_.project,_.filePath),W_("idx_annotations_project_tag").on(_.project,_.tag),W_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Q_=N_("symbol_changelog",{id:e("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:e("is_full_index").notNull().default(0),indexRunId:y("index_run_id").notNull()},(_)=>[W_("idx_changelog_project_changed_at").on(_.project,_.changedAt),W_("idx_changelog_project_name").on(_.project,_.symbolName),W_("idx_changelog_project_run").on(_.project,_.indexRunId)]),v1=N_("watcher_owner",{id:e("id").primaryKey(),pid:e("pid").notNull(),startedAt:y("started_at").notNull(),heartbeatAt:y("heartbeat_at").notNull(),instanceId:y("instance_id")},(_)=>[E1("watcher_owner_singleton",F1`${_.id} = 1`)]);class Z${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=x$(_.projectRoot,L_,h_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{P1(f1(this.dbPath),{recursive:!0}),this.client=new y1(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=n1(this.client,{schema:Y$}),m1(this.drizzle,{migrationsFolder:x$(import.meta.dirname,"migrations")});let _=this.client.prepare("PRAGMA foreign_key_check").all();if(_.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(_.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(_){if(this.isCorruptionError(_)&&m$(this.dbPath)){this.closeClient(),n$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(m$(Q))n$(Q)}let $=this.open();if(b1($))return f$(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return f$(new V("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as j_,and as h$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(__).where(h$(j_(__.project,_),j_(__.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(__).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[__.project,__.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(__).where(j_(__.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(__).where(h$(j_(__.project,_),j_(__.filePath,$))).run()}}import{eq as $_,and as B_,sql as p_,count as x1}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var p$=50;class O${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(h).where(B_($_(h.project,_),$_(h.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),Y=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<Y.length;Z+=p$)this.db.drizzleDb.insert(h).values(Y.slice(Z,Z+p$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(h).where(B_($_(h.project,_),$_(h.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(h).where(B_(p_`${h.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,$_(h.project,_),J.kind?$_(h.kind,J.kind):void 0)).orderBy(h.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(h).where(B_($_(h.project,_),$_(h.kind,$))).orderBy(h.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:x1(),fileCount:p_`COUNT(DISTINCT ${h.filePath})`}).from(h).where($_(h.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(h).where(B_($_(h.project,_),$_(h.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(h).where(B_($_(h.project,_),$_(h.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(h).where(B_(_.ftsQuery?p_`${h.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?$_(h.name,_.exactName):void 0,_.project!==void 0?$_(h.project,_.project):void 0,_.kind?$_(h.kind,_.kind):void 0,_.filePath!==void 0?$_(h.filePath,_.filePath):void 0,_.isExported!==void 0?$_(h.isExported,_.isExported?1:0):void 0,_.decorator?p_`${h.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?$_(h.resolvedType,_.resolvedType):void 0)).orderBy(h.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new V("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((Y)=>J.test(Y.name));let Q=[];for(let z of[5,20,100]){let Y=_.limit*z,Z=$.limit(Y).all();if(Q=Z.filter((W)=>J.test(W.name)),Q.length>=_.limit||Z.length<Y)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as s,and as V_,isNull as d$,or as h1}from"drizzle-orm";var G_={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(V_(s(E.project,_),s(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(G_).from(E).where(V_(s(E.project,_),s(E.srcFilePath,$),h1(s(E.srcSymbolName,J),d$(E.srcSymbolName)))).all();return this.db.drizzleDb.select(G_).from(E).where(V_(s(E.project,_),s(E.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(G_).from(E).where(V_(s(E.dstProject,$),s(E.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(G_).from(E).where(V_(s(E.project,_),s(E.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(E).where(V_(s(E.project,_),s(E.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(E).where(V_(s(E.dstProject,_),s(E.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(G_).from(E).where(V_(_.project!==void 0?s(E.project,_.project):void 0,_.srcFilePath!==void 0?s(E.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?s(E.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?s(E.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?s(E.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?s(E.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?s(E.type,_.type):void 0,_.specifier!==void 0?s(E.specifier,_.specifier):void 0,_.isExternal!==void 0?s(E.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:Y,newDstProject:Z}=_,W=Q===null?V_(s(E.dstProject,$),s(E.dstFilePath,J),d$(E.dstSymbolName)):V_(s(E.dstProject,$),s(E.dstFilePath,J),s(E.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:Y};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(E).set(X).where(W).run()}}import{err as l$}from"@zipbul/result";import{subscribe as p1}from"@parcel/watcher";import U$ from"path";import i$ from"path";function Y_(_){return _.replaceAll("\\","/")}function E_(_,$){return Y_(i$.relative(_,$))}function q_(_,$){return Y_(i$.resolve(_,$))}var d1=["**/.git/**",`**/${L_}/**`,"**/dist/**","**/node_modules/**"],i1=new Set(["package.json","tsconfig.json"]);function l1(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class H${#_;#$;#J;#z;#Q;#Y;constructor(_,$=p1,J=console){this.#$=_.projectRoot,this.#J=[...d1,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#Q=$,this.#Y=J}async start(_){try{this.#_=await this.#Q(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=Y_(U$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let Y=U$.basename(z),Z=U$.extname(z).toLowerCase();if(!i1.has(Y)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:l1(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return l$(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return l$(new V("watcher","Failed to close watcher",{cause:_}))}}}import M$ from"path";import{promises as c1}from"fs";var a1=["**/node_modules/**","**/.git/**",`**/${L_}/**`,"**/dist/**"];async function d_(_){let $=[];for await(let J of c1.glob("**/package.json",{cwd:_,exclude:a1})){let Q=Y_(M$.dirname(J)),z=M$.join(_,J),Y=await Bun.file(z).json(),Z=typeof Y?.name==="string"&&Y.name.length>0?Y.name:M$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function t(_,$,J="default"){let Q=Y_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import v_ from"path";var w_=new Map;async function s1(_){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 r1(_,$){if($.startsWith(".")){let J=v_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return v_.resolve(_,"node_modules",$)}async function c$(_,$=5){if($<=0)return null;let J=await s1(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=r1(v_.dirname(_),Q),Y=await c$(z,$-1);if(!Y)return J;let Z=typeof Y.compilerOptions==="object"&&Y.compilerOptions!==null?Y.compilerOptions:{},W=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...Y,...J,compilerOptions:{...Z,...W}}}async function b_(_){if(w_.has(_))return w_.get(_)??null;let $=v_.join(_,"tsconfig.json"),J=await c$($);if(!J)return w_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return w_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,Y=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!Y)return w_.set(_,null),null;let Z=z?v_.resolve(_,z):_,W=new Map;if(Y)for(let[H,O]of Object.entries(Y)){if(!Array.isArray(O))continue;let U=O.filter((L)=>typeof L==="string");W.set(H,U)}let X={baseUrl:Z,paths:W};return w_.set(_,X),X}function i_(_){if(_){w_.delete(_);return}w_.clear()}function O_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Q0}from"@zipbul/result";import{err as o1}from"@zipbul/result";import{parseSync as t1}from"oxc-parser";function y_(_,$,J,Q=t1){try{let z={preserveParens:!1,...J},Y=Q(_,$,z);return{filePath:_,program:Y.program,errors:Y.errors,comments:Y.comments,sourceText:$,module:Y.module}}catch(z){return o1(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{promises as e1}from"fs";import{join as _J}from"path";async function a$(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z}=_,Y=z.getFilesMap(),Z=new Set,W=[],X=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of e1.glob("**/*",{cwd:$})){let L=Y_(U);if(!J.some((f)=>L.endsWith(f)))continue;if(L.startsWith("node_modules/")||L.includes("/node_modules/"))continue;if(H.some((f)=>f.match(L)))continue;Z.add(L);let D=_J($,L),K=Bun.file(D),{size:B,lastModified:S}=K,R=Y.get(L);if(!R){let f=await K.text(),o=O_(f);W.push({filePath:L,contentHash:o,mtimeMs:S,size:B});continue}if(R.mtimeMs===S&&R.size===B){X.push({filePath:L,contentHash:R.contentHash,mtimeMs:S,size:B});continue}let v=await K.text(),j=O_(v);if(j===R.contentHash)X.push({filePath:L,contentHash:j,mtimeMs:S,size:B});else W.push({filePath:L,contentHash:j,mtimeMs:S,size:B})}let O=[];for(let U of Y.keys())if(!Z.has(U))O.push(U);return{changed:W,unchanged:X,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 $J}from"@zipbul/result";import{parse as JJ}from"comment-parser";function l_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=JJ(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((z)=>({tag:z.tag??"",name:z.name??"",type:z.type??"",description:z.description??"",optional:z.optional??!1,...z.default!==void 0?{default:z.default}:{}}))}}catch($){return $J(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as QJ}from"@zipbul/result";function c_(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _&&typeof _.value==="string")return _.value;return"unknown"}function R_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...R_(J.argument));else $.push(...R_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...R_(J.argument));else $.push(...R_(J))}return $}if(_.type==="AssignmentPattern")return R_(_.left);return[]}function S_(_){let{program:$,sourceText:J,comments:Q}=_,z=P_(J),Y=Q.filter((w)=>w.type==="Block"&&w.value.startsWith("*")).sort((w,N)=>w.end-N.end),Z=$.body.map((w)=>w.start).sort((w,N)=>w-N);function W(w,N){return{start:X_(z,w),end:X_(z,N)}}function X(w){let N=0,I=Y.length-1,A=-1;while(N<=I){let q=N+I>>>1;if(Y[q].end<=w)A=q,N=q+1;else I=q-1}if(A<0)return;let u=Y[A];N=0,I=Z.length-1;while(N<=I){let q=N+I>>>1,T=Z[q];if(T<=u.end)N=q+1;else if(T>=w)I=q-1;else return}return`/*${u.value}*/`}function H(w){if(!w)return;let N="typeAnnotation"in w&&w.typeAnnotation?w.typeAnnotation:w;return J.slice(N.start,N.end)}function O(w){if(!w||w.length===0)return[];return w.map((N)=>{let I=N.expression;if(I.type==="CallExpression"){let A=I,u=A.callee,q="name"in u&&typeof u.name==="string"?u.name:("property"in u)&&u.property&&typeof u.property.name==="string"?u.property.name:"unknown",T=A.arguments.map((G)=>J.slice(G.start,G.end));return{name:q,arguments:T.length>0?T:void 0}}if(I.type==="Identifier")return{name:I.name??"unknown"};return{name:J.slice(I.start,I.end)}})}function U(w){if(w.type==="TSParameterProperty"){let I=w;return L(I.parameter,I.parameter.decorators)}if(w.type==="RestElement"){let I=w,A=I.argument,q=`...${"name"in A&&typeof A.name==="string"?A.name:"unknown"}`,T=I.typeAnnotation,G=T?H(T):void 0,p={name:q,isOptional:!1};if(G)p.type=G;return p}let N=w;return L(N,N.decorators)}function L(w,N){if(w.type==="AssignmentPattern"){let{left:p,right:d}=w,r="name"in p&&typeof p.name==="string"?p.name:"unknown",M="typeAnnotation"in p?p.typeAnnotation:null,C=M?H(M):void 0,k=J.slice(d.start,d.end),F="decorators"in p&&Array.isArray(p.decorators)?p.decorators:[],x=O(F),g={name:r,isOptional:!0,defaultValue:k};if(C)g.type=C;if(x.length>0)g.decorators=x;return g}let I="name"in w&&typeof w.name==="string"?w.name:("pattern"in w)&&w.pattern&&typeof w.pattern.name==="string"?w.pattern.name:"unknown",A=!!(("optional"in w)&&w.optional),u="typeAnnotation"in w?w.typeAnnotation:null,q=u?H(u):void 0,T=O(N??[]),G={name:I,isOptional:A};if(q)G.type=q;if(T.length>0)G.decorators=T;return G}function D(w,N){let I=[];if(N?.async)I.push("async");if(w.static)I.push("static");if(w.abstract)I.push("abstract");if(w.readonly)I.push("readonly");if(w.override)I.push("override");if(w.declare)I.push("declare");if(w.const)I.push("const");let A=w.accessibility;if(A==="private")I.push("private");else if(A==="protected")I.push("protected");else if(A==="public")I.push("public");return I}function K(w){if(!w)return;let N=w.params.flatMap((I)=>{let A=I.name.name;return A?[A]:[]});return N.length>0?N:void 0}function B(w){let N=[];if(w.superClass){let A=J.slice(w.superClass.start,w.superClass.end);N.push({kind:"extends",name:A})}let I=w.implements??[];for(let A of I){let u=A.expression,q=J.slice(u.start,u.end);N.push({kind:"implements",name:q})}return N}function S(w){let N=[],I=w.extends;for(let A of I){let u=A.expression,q=J.slice(u.start,u.end);N.push({kind:"extends",name:q})}return N}function R(w){let N=[];for(let I of w)if(I.type==="MethodDefinition"||I.type==="TSAbstractMethodDefinition"){let A=I,u=c_(A.key),q=A.value,T=A.kind,G=T==="constructor"?"constructor":T==="get"?"getter":T==="set"?"setter":"method",p=D(A,q);if(I.type==="TSAbstractMethodDefinition"&&!p.includes("abstract"))p.push("abstract");let d=q.params.map(U),r=H(q.returnType),M={kind:"method",name:u,span:W(I.start,I.end),isExported:!1,methodKind:G,modifiers:p,parameters:d.length>0?d:void 0,returnType:r};N.push(M)}else if(I.type==="PropertyDefinition"||I.type==="TSAbstractPropertyDefinition"){let A=I,u=c_(A.key),q=D(A);if(I.type==="TSAbstractPropertyDefinition"&&!q.includes("abstract"))q.push("abstract");let T={kind:"property",name:u,span:W(I.start,I.end),isExported:!1,modifiers:q};N.push(T)}return N}function v(w){let N=[];for(let I of w)if(I.type==="TSMethodSignature"){let A=I,u=c_(A.key),q=A.params.map(U),T=H(A.returnType);N.push({kind:"method",name:u,span:W(I.start,I.end),isExported:!1,modifiers:[],methodKind:"method",parameters:q.length>0?q:void 0,returnType:T})}else if(I.type==="TSPropertySignature"){let A=I,u=c_(A.key),q=H(A.typeAnnotation),T={kind:"property",name:u,span:W(I.start,I.end),isExported:!1,modifiers:A.readonly?["readonly"]:[],returnType:q};N.push(T)}return N}function j(w,N){let I=w.type;if(I==="FunctionDeclaration"||I==="FunctionExpression"||I==="TSDeclareFunction"||I==="TSEmptyBodyFunctionExpression"){let A=w,u=A.id?.name??"default",q=A.params.map(U),T=H(A.returnType),G=D(A,A),p=O(A.decorators??[]),d=K(A.typeParameters),r={kind:"function",name:u,span:W(w.start,w.end),isExported:N,modifiers:G,parameters:q.length>0?q:void 0,returnType:T,decorators:p.length>0?p:void 0};if(d&&d.length>0)r.typeParameters=d;return r}if(I==="ClassDeclaration"||I==="ClassExpression"){let A=w,u=A.id?.name??"default",q=B(A),T=R(A.body.body),G=O(A.decorators),p=D(A),d=K(A.typeParameters),r={kind:"class",name:u,span:W(w.start,w.end),isExported:N,modifiers:p,heritage:q.length>0?q:void 0,members:T.length>0?T:void 0,decorators:G.length>0?G:void 0};if(d&&d.length>0)r.typeParameters=d;return r}if(I==="VariableDeclaration"){let A=w,u=[];for(let q of A.declarations){let{id:T,init:G}=q;if(T.type==="ObjectPattern"||T.type==="ArrayPattern"){let k=R_(T);for(let F of k)u.push({kind:"variable",name:F.name,span:W(F.start,F.end),isExported:N,modifiers:[]});continue}let p="name"in T&&typeof T.name==="string"?T.name:"unknown",d="variable",r,M;if(G){if(G.type==="FunctionExpression"||G.type==="ArrowFunctionExpression"){d="function";let k=G;r=k.params.map(U),M=H(k.returnType)}}let C=[];u.push({kind:d,name:p,span:W(q.start,q.end),isExported:N,modifiers:C,parameters:r,returnType:M})}if(u.length===0)return null;if(u.length===1)return u[0];return u}if(I==="TSTypeAliasDeclaration")return{kind:"type",name:w.id.name,span:W(w.start,w.end),isExported:N,modifiers:[]};if(I==="TSInterfaceDeclaration"){let A=w,u=A.id.name,q=S(A),T=v(A.body.body),G=K(A.typeParameters),p={kind:"interface",name:u,span:W(w.start,w.end),isExported:N,modifiers:[],heritage:q.length>0?q:void 0,members:T.length>0?T:void 0};if(G&&G.length>0)p.typeParameters=G;return p}if(I==="TSEnumDeclaration"){let A=w,u=A.id.name,q=D(A),G=A.body.members.map((p)=>{let d=p.id;return{kind:"property",name:"name"in d&&typeof d.name==="string"?d.name:("value"in d)&&typeof d.value==="string"?d.value:"unknown",span:W(p.start,p.end),isExported:!1,modifiers:[]}});return{kind:"enum",name:u,span:W(w.start,w.end),isExported:N,modifiers:q,members:G.length>0?G:void 0}}if(I==="TSModuleDeclaration"){let A=w,u=A.id.name??A.id.value??"unknown",q=D(A),T=[];if(A.body?.type==="TSModuleBlock")for(let G of A.body.body??[]){if(G.type!=="ExportNamedDeclaration")continue;let p=G.declaration;if(!p)continue;let d=j(p,!1);if(d)if(Array.isArray(d))T.push(...d);else T.push(d)}return{kind:"namespace",name:u,span:W(w.start,w.end),isExported:N,modifiers:q,members:T.length>0?T:void 0}}return null}let f=[],o=new Set;for(let w of $.body){let N=null,I=w;if(I.type==="ExportNamedDeclaration"){let u=I;if(u.declaration){if(N=j(u.declaration,!0),N&&!Array.isArray(N))N.span=W(u.start,u.end)}else if(!u.source&&u.specifiers)for(let q of u.specifiers){let T=q.local,G="name"in T?T.name:T.value;if(G)o.add(G)}}else if(I.type==="ExportDefaultDeclaration"){let u=I,q=u.declaration;if(q){if(N=j(q,!0),N&&!Array.isArray(N))N.name="id"in q&&q.id&&typeof q.id.name==="string"?q.id.name:"default",N.isExported=!0,N.span=W(u.start,u.end);else if(!N&&"type"in q&&q.type==="Identifier"){let T=q.name;if(T)o.add(T)}}}else{let u=I.type;if(u==="FunctionDeclaration"||u==="TSDeclareFunction"||u==="ClassDeclaration"||u==="VariableDeclaration"||u==="TSTypeAliasDeclaration"||u==="TSInterfaceDeclaration"||u==="TSEnumDeclaration"||u==="TSModuleDeclaration")N=j(I,!1)}let A=Array.isArray(N)?N:N?[N]:[];for(let u of A){let q=w.start,T=X(q);if(T){let G=l_(T);if(!QJ(G))u.jsDoc=G}f.push(u)}}if(o.size>0){for(let w of f)if(!w.isExported&&o.has(w.name))w.isExported=!0}return f}function zJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function WJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((z)=>z==="private"||z==="protected"||z==="public");return{name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0}});return Object.keys($).length>0?JSON.stringify($):null}function YJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${O_(J)}`)}return O_($.join("|"))}function s$(_,$,J,Q,z){let Y=zJ(_),Z=O_(`${$}|${_.kind}|${Y??""}`),W=YJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:Y,fingerprint:Z,detailJson:WJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:W}}function K$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:Y}=_,Z=S_($),W=[];for(let X of Z){W.push(s$(X,X.name,J,Q,z));for(let H of X.members??[])W.push(s$(H,`${X.name}.${H.name}`,J,Q,z))}Y.replaceFileSymbols(J,Q,z,W)}import{resolve as L$,dirname as ZJ,extname as XJ}from"path";function D_(_,$,J){let Q=(z)=>{let Y=XJ(z);if(Y===".js")return[z.slice(0,-3)+".ts"];if(Y===".mjs")return[z.slice(0,-4)+".mts"];if(Y===".cjs")return[z.slice(0,-4)+".cts"];if(Y===".ts"||Y===".mts"||Y===".cts"||Y===".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=Y_(L$(ZJ(_),$));return Q(z)}if(J)for(let[z,Y]of J.paths){if(Y.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let W=[];for(let X of Y)W.push(...Q(Y_(L$(J.baseUrl,X))));return W}}else{let W=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(W)&&(X===""||$.endsWith(X))){let H=$.slice(W.length,X===""?void 0:$.length-X.length),O=[];for(let U of Y)O.push(...Q(Y_(L$(J.baseUrl,U.replace("*",H)))));return O}}}return[]}function r$(_,$,J,Q=D_){let z=new Map,Y=_.body??[];for(let Z of Y){if(Z.type!=="ImportDeclaration")continue;let W=Z.source?.value??"",X=Q($,W,J);if(X.length===0)continue;let H=X[0],O=Z.specifiers??[];for(let U of O)switch(U.type){case"ImportSpecifier":z.set(U.local.name,{path:H,importedName:U.imported.name});break;case"ImportDefaultSpecifier":z.set(U.local.name,{path:H,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(U.local.name,{path:H,importedName:"*"});break}}return z}import{Visitor as OJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function VJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function I_(_,$,J,Q){let z=Q(_,$,J),Y=z.length>0?z[0]:null,Z=Y===null&&VJ($);return{resolved:Y,isExternal:Z}}function UJ(_,$,J,Q,z){for(let Y of _.staticImports){let Z=Y.moduleRequest.value,{resolved:W,isExternal:X}=I_($,Z,J,Q),H=W===null?{dstFilePath:null,specifier:Z}:{dstFilePath:W};if(Y.entries.length===0){let O={};if(X)O.isExternal=!0;if(W===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of Y.entries){let U=O.isType,L={};if(U)L.isType=!0;if(X)L.isExternal=!0;if(W===null&&!X)L.isUnresolved=!0;let D,K,B=O.importName.kind;if(B==="Default")D="default",K=O.localName.value;else if(B==="NamespaceObject")D="*",K=O.localName.value,L.importKind="namespace";else D=O.importName.name??"unknown",K=O.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:K,...H,dstSymbolName:D,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}}}function HJ(_,$,J,Q,z){let Y=new Map;for(let Z of _.staticImports)for(let W of Z.entries)Y.set(W.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let W of Z.entries){let X=null;if(W.moduleRequest)X=W.moduleRequest.value;else if(W.localName.name)X=Y.get(W.localName.name)??null;if(!X)continue;let{resolved:H,isExternal:O}=I_($,X,J,Q),U=W.exportName.name??"default",L=W.exportName.kind,D=W.localName.name??W.importName.name??U,K=W.isType,B={isReExport:!0};if(L==="None");else B.specifiers=[{local:D,exported:U}];if(K)B.isType=!0;if(O)B.isExternal=!0;if(H===null&&!O)B.isUnresolved=!0;let S=null,R=null,v=W.importName.kind;if(v==="All"||v==="AllButDefault"){if(L==="Name"&&U)R=U,B.namespaceAlias=U}else R=D,S=U;z.push({type:K?"type-references":"re-exports",srcFilePath:$,srcSymbolName:S,dstFilePath:H,dstSymbolName:R,metaJson:JSON.stringify(B),...H===null?{specifier:X}:{}})}}function MJ(_,$,J,Q,z){for(let Y of _.body){let Z=Y;if(Z.type==="ImportDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=I_($,X,J,Q),U=W.importKind==="type",L=W.specifiers,D=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(L.length===0){let K={};if(U)K.isType=!0;if(O)K.isExternal=!0;if(H===null&&!O)K.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...D,dstSymbolName:null,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}else for(let K of L){let B=K.type,S=U||B==="ImportSpecifier"&&K.importKind==="type",R={};if(S)R.isType=!0;if(O)R.isExternal=!0;if(H===null&&!O)R.isUnresolved=!0;let v,j;if(B==="ImportDefaultSpecifier")v="default",j=K.local.name;else if(B==="ImportNamespaceSpecifier")v="*",j=K.local.name,R.importKind="namespace";else v=a_(K.imported),j=K.local.name;z.push({type:S?"type-references":"imports",srcFilePath:$,srcSymbolName:j,...D,dstSymbolName:v,...Object.keys(R).length>0?{metaJson:JSON.stringify(R)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=I_($,X,J,Q),U=W.exportKind==="type",L=W.exported,D=L?a_(L):null,K={isReExport:!0};if(U)K.isType=!0;if(O)K.isExternal=!0;if(H===null&&!O)K.isUnresolved=!0;if(D)K.namespaceAlias=D;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:D,metaJson:JSON.stringify(K),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let W=Z;if(!W.source)continue;let X=W.source.value,{resolved:H,isExternal:O}=I_($,X,J,Q),U=W.exportKind==="type",L=W.specifiers??[];for(let D of L){let K=U||D.exportKind==="type",B=a_(D.local),S=a_(D.exported),R={isReExport:!0,specifiers:[{local:B,exported:S}]};if(K)R.isType=!0;if(O)R.isExternal=!0;if(H===null&&!O)R.isUnresolved=!0;z.push({type:K?"type-references":"re-exports",srcFilePath:$,srcSymbolName:S,dstFilePath:H,dstSymbolName:B,metaJson:JSON.stringify(R),...H===null?{specifier:X}:{}})}}}}function KJ(_,$,J,Q,z){new OJ({ImportExpression(Z){let W=Z.source;if(W.type!=="Literal"||typeof W.value!=="string")return;let X=W.value,{resolved:H,isExternal:O}=I_($,X,J,Q),U={isDynamic:!0};if(O)U.isExternal=!0;if(H===null&&!O)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(U),...H===null?{specifier:X}:{}})},CallExpression(Z){let W=Z.callee,X=!1;if(W.type==="Identifier"&&W.name==="require");else if(W.type==="MemberExpression"&&!W.computed){let B=W,S=B.object,R=B.property;if(S.type==="Identifier"&&S.name==="require"&&R.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let O=H[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let U=O.value,{resolved:L,isExternal:D}=I_($,U,J,Q),K={isRequire:!0};if(X)K.isRequireResolve=!0;if(D)K.isExternal=!0;if(L===null&&!D)K.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:L,dstSymbolName:null,metaJson:JSON.stringify(K),...L===null?{specifier:U}:{}})}}).visit(_)}function o$(_,$,J,Q=D_,z){let Y=[];if(z)UJ(z,$,J,Q,Y),HJ(z,$,J,Q,Y);else MJ(_,$,J,Q,Y);return KJ(_,$,J,Q,Y),Y}import{walk as LJ}from"oxc-walker";function T_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let Y=[z,...J].join(".");return{root:z,parts:J,full:Y}}return null}function t$(_,$,J){let Q=[],z=[],Y=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function W(O){if(!O)return null;let U=J.get(O.root);if(O.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let L=O.parts[O.parts.length-1];return{dstFilePath:U.path,dstSymbolName:L,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,U){let L=T_(O.callee),D=W(L);if(D){let K=Z(),B={};if(U)B.isNew=!0;if(K===null)B.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:K,dstFilePath:D.dstFilePath,dstSymbolName:D.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}}function H(O,U){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let K=U.id,B=K.type==="Identifier"?K.name:"anonymous";z.push(B);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let K=U.key,B=Y[Y.length-1]??"",S="name"in K?K.name:"anonymous",R=B?`${B}.${S}`:S;z.push(R);return}let L=Z(),D=L?`${L}.<anonymous>`:"<anonymous>";z.push(D)}}return LJ(_,{enter(O,U){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){H(O,U);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as wJ}from"oxc-parser";function e$(_,$,J){let Q=[];function z(Z){let W=Z.id?.name??"AnonymousClass";if(Z.superClass){let H=T_(Z.superClass);if(H){let O=w$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...O})}}let X=Z.implements??[];for(let H of X){let O=T_(H.expression);if(!O)continue;let U=w$(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:W,...U})}}return new wJ({TSInterfaceDeclaration(Z){let W=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let O=T_(H.expression);if(!O)continue;let U=w$(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...U})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).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 s_(_,$,J,Q=D_,z){let Y=r$(_,$,J,Q),Z=o$(_,$,J,Q,z),W=t$(_,$,Y),X=e$(_,$,Y);return[...Z,...W,...X]}function B$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:Y,tsconfigPaths:Z,knownFiles:W,boundaries:X,module:H}=_,O=q_(Y,Q),L=s_($,O,Z,W?(K,B,S)=>{let R=D_(K,B,S);for(let v of R){let j=E_(Y,v);if(X){let f=t(j,X);if(W.has(`${f}::${j}`))return[v]}else if(W.has(`${J}::${j}`))return[v]}return[]}:void 0,H),D=[];for(let K of L){if(K.dstFilePath===null){let v=E_(Y,K.srcFilePath),j;if(K.metaJson)try{j=JSON.parse(K.metaJson)}catch{}let f=j?.isExternal===!0;D.push({project:J,type:K.type,srcFilePath:v,srcSymbolName:K.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:K.dstSymbolName??null,metaJson:K.metaJson??null,specifier:K.specifier??null,isExternal:f?1:0});continue}let B=E_(Y,K.dstFilePath);if(B.startsWith(".."))continue;let S=E_(Y,K.srcFilePath),R=X?t(B,X):J;D.push({project:J,type:K.type,srcFilePath:S,srcSymbolName:K.srcSymbolName??null,dstProject:R,dstFilePath:B,dstSymbolName:K.dstSymbolName??null,metaJson:K.metaJson??null,specifier:K.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,D),D.length}import{isErr as BJ}from"@zipbul/result";var _0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function DJ(_){let $=S_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function D$(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let Y=Q+z>>1;if(_[Y].startLine<=$)Q=Y+1;else z=Y-1}if(Q<_.length){let Y=_[Q];if(Y.startLine-$<=J)return Y.name}return null}function r_(_,$,J){let Q=X_(_,$),z=X_(_,J);return{start:Q,end:z}}function $0(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=P_(J),z=DJ(_),Y=[],Z=[...$].sort((X,H)=>X.start-H.start),W=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){W=null;let H=`/*${X.value}*/`,O=l_(H);if(BJ(O))continue;let U=O;if(!U.tags?.length)continue;let L=X_(Q,X.end),D=D$(z,L.line,3),K=J.slice(X.start,X.end);for(let B of U.tags){let S=[B.name,B.description].filter(Boolean).join(" "),R=`@${B.tag}`,v=K.indexOf(R),j;if(v>=0){let f=X.start+v,o=J.indexOf(`
|
|
4
|
-
`,
|
|
5
|
-
`),
|
|
6
|
-
`).length});let z$=(this.opts.parseSourceFn??
|
|
7
|
-
`).length})}let g=new Set;for(let b of C)for(let[i]of Q.getFilesMap(b.project))g.add(`${b.project}::${i}`);let n=this.opts.parseSourceFn??y_;for(let b of F){let i=t(b.filePath,C),P=n(q_(M,b.filePath),b.text);if(Q0(P))throw P.data;let a=P;if(x.push({filePath:b.filePath,parsed:a}),K$({parsed:a,project:i,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:z}),R)f+=I$({parsed:a,project:i,filePath:b.filePath,annotationRepo:R});N+=B$({ast:a.program,project:i,filePath:b.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:g,boundaries:C,module:a.module}),w+=z.getFileSymbols(i,b.filePath).length}});for(let g of x)k.set(g.filePath,g.parsed)}else{j();let M=await o();w=M.symbols,N=M.relations,f=M.annotations,I=M.failedFiles}for(let M of W){let C=t(M.filePath,this.opts.boundaries);for(let k of z.getFileSymbols(C,M.filePath))D.set(`${k.filePath}::${k.name}`,K(k))}let A=new Map;for(let M of W){let C=t(M.filePath,this.opts.boundaries);for(let k of Y.getOutgoing(C,M.filePath))A.set(B(k),k)}let u=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),q={added:[...A.entries()].filter(([M])=>!S.has(M)).map(([,M])=>u(M)),removed:[...S.entries()].filter(([M])=>!A.has(M)).map(([,M])=>u(M))},T={added:[],modified:[],removed:[]};for(let[M,C]of D){let k=L.get(M);if(!k)T.added.push({name:C.name,filePath:C.filePath,kind:C.kind,isExported:Boolean(C.isExported)});else{let F=k.fingerprint!==C.fingerprint,x=k.isExported!==C.isExported,g=k.structuralFingerprint!==null&&C.structuralFingerprint!==null&&k.structuralFingerprint!==C.structuralFingerprint;if(F||x||g)T.modified.push({name:C.name,filePath:C.filePath,kind:C.kind,isExported:Boolean(C.isExported)})}}for(let[M,C]of L)if(!D.has(M))T.removed.push({name:C.name,filePath:C.filePath,kind:C.kind,isExported:Boolean(C.isExported)});let G=J0(L,D),p=new Set(G.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),d=new Set(G.renamed.map((M)=>`${M.filePath}::${M.newName}`));T.added=T.added.filter((M)=>!d.has(`${M.filePath}::${M.name}`)),T.removed=T.removed.filter((M)=>!p.has(`${M.filePath}::${M.name}`));let r=[];if(!$){for(let[C,k]of O)for(let F of k){if(!F.fingerprint)continue;let x=t(C,this.opts.boundaries),g=z.getByFingerprint(x,F.fingerprint);if(g.length===1){let n=g[0];Y.retargetRelations({dstProject:x,oldFile:C,oldSymbol:F.name,newFile:n.filePath,newSymbol:n.name}),r.push({name:n.name,filePath:n.filePath,kind:n.kind,oldFilePath:C,isExported:n.isExported??0})}}let M=new Set(r.map((C)=>`${C.oldFilePath}::${C.name}`));for(let C of G.removed){if(M.has(`${C.filePath}::${C.name}`))continue;let F=L.get(`${C.filePath}::${C.name}`)?.fingerprint;if(!F)continue;let x=t(C.filePath,this.opts.boundaries),g=z.getByFingerprint(x,F);if(g.length===1){let n=g[0];if(n.filePath!==C.filePath||n.name!==C.name)Y.retargetRelations({dstProject:x,oldFile:C.filePath,oldSymbol:C.name,newFile:n.filePath,newSymbol:n.name}),r.push({name:n.name,filePath:n.filePath,kind:n.kind,oldFilePath:C.filePath,isExported:n.isExported??0})}}}if(r.length){let M=new Set(r.map((k)=>`${k.filePath}::${k.name}`)),C=new Set(r.map((k)=>`${k.oldFilePath}::${k.name}`));T.added=T.added.filter((k)=>!M.has(`${k.filePath}::${k.name}`)),T.removed=T.removed.filter((k)=>!C.has(`${k.filePath}::${k.name}`))}if(v){let M=new Date().toISOString(),C=$?1:0,k=[];for(let F of T.added){let x=`${F.filePath}::${F.name}`,g=D.get(x),n=t(F.filePath,this.opts.boundaries);k.push({project:n,changeType:"added",symbolName:F.name,symbolKind:F.kind,filePath:F.filePath,oldName:null,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:M,isFullIndex:C,indexRunId:U})}for(let F of T.modified){let x=D.get(`${F.filePath}::${F.name}`),g=t(F.filePath,this.opts.boundaries);k.push({project:g,changeType:"modified",symbolName:F.name,symbolKind:F.kind,filePath:F.filePath,oldName:null,oldFilePath:null,fingerprint:x?.fingerprint??null,changedAt:M,isFullIndex:C,indexRunId:U})}for(let F of T.removed){let x=`${F.filePath}::${F.name}`,g=L.get(x),n=t(F.filePath,this.opts.boundaries);k.push({project:n,changeType:"removed",symbolName:F.name,symbolKind:F.kind,filePath:F.filePath,oldName:null,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:M,isFullIndex:C,indexRunId:U})}for(let F of G.renamed){let x=D.get(`${F.filePath}::${F.newName}`),g=t(F.filePath,this.opts.boundaries);k.push({project:g,changeType:"renamed",symbolName:F.newName,symbolKind:F.kind,filePath:F.filePath,oldName:F.oldName,oldFilePath:null,fingerprint:x?.fingerprint??null,changedAt:M,isFullIndex:C,indexRunId:U})}for(let F of r){let x=D.get(`${F.filePath}::${F.name}`),g=t(F.filePath,this.opts.boundaries);k.push({project:g,changeType:"moved",symbolName:F.name,symbolKind:F.kind,filePath:F.filePath,oldName:null,oldFilePath:F.oldFilePath,fingerprint:x?.fingerprint??null,changedAt:M,isFullIndex:C,indexRunId:U})}if(k.length)try{Z.transaction(()=>{v.insertBatch(k)})}catch(F){this.logger.error("[IndexCoordinator] changelog insert failed:",F)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let F=new Date(Date.now()-2592000000).toISOString();try{for(let x of this.opts.boundaries)v.pruneOlderThan(x.project,F)}catch(x){this.logger.error("[IndexCoordinator] changelog pruning failed:",x)}}}return{indexedFiles:W.length,removedFiles:X.length,totalSymbols:w,totalRelations:N,totalAnnotations:f,durationMs:Date.now()-J,changedFiles:W.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:I,changedSymbols:T,renamedSymbols:G.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(D.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:r.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:q}}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 CJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function AJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function W0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??CJ,Y=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let W=_.selectOwner();if(!W)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-AJ(W.heartbeat_at))/1000),H=z(W.pid);if(H&&Z&&W.instance_id&&W.instance_id!==Z&&W.pid===$)return _.replaceOwner($,Z),"owner";if(H&&X<Y)return"reader";return _.replaceOwner($,Z),"owner"})}function Y0(_,$){_.deleteOwner($)}function Z0(_,$){_.touchOwner($)}class f_{#_;#$=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 f_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function u$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,Y={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)Y.exactName=Q.text;else{let W=g_(Q.text);if(W)Y.ftsQuery=W}if(Q.decorator)Y.decorator=Q.decorator;if(Q.regex)Y.regex=Q.regex;return $.searchByQuery(Y).map((W)=>{let X=W.name.indexOf(".");return{id:W.id,filePath:W.filePath,kind:W.kind,name:W.name,memberName:X>=0?W.name.slice(X+1):null,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}},isExported:W.isExported===1,signature:W.signature,fingerprint:W.fingerprint,detail:W.detailJson?(()=>{try{return JSON.parse(W.detailJson)}catch{return{}}})():{}}})}function N$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,Y=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),W=Z?void 0:Y,H=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:W}).map((O)=>{let U;if(O.metaJson)try{U=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,isExternal:O.isExternal===1,specifier:O.specifier,metaJson:O.metaJson??void 0,meta:U}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((L)=>(!O||O.match(L.srcFilePath))&&(!U||L.dstFilePath===null||U.match(L.dstFilePath)))}if(Z&&Y!==void 0&&H.length>Y)H=H.slice(0,Y);return H}import{findInFiles as uJ,Lang as NJ}from"@ast-grep/napi";async function g$(_){if(_.filePaths.length===0)return[];let $=[];return await uJ(NJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,Q)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let z of Q){let Y=z.range();$.push({filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,matchedText:z.text()})}}),$}import J_ from"typescript";import{isErr as PJ}from"@zipbul/result";import H_ from"typescript";import gJ from"path";import{err as q$}from"@zipbul/result";function qJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}function RJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}class o_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??qJ,Q=$.resolveNonTrackedFile??RJ,z=gJ.dirname(_),Y=J(_);if(Y===void 0)return q$(new V("semantic",`tsconfig not found: ${_}`));let Z=H_.parseJsonText(_,Y),W=Z.parseDiagnostics;if(W&&W.length>0){let U=W.map((L)=>H_.flattenDiagnosticMessageText(L.messageText,`
|
|
8
|
-
`)).join("; ");return
|
|
9
|
-
`)).join("; ");return q$(new V("semantic",`tsconfig compile error: ${L}`))}}let H=new X0(X.fileNames,X.options,z,Q),O=H_.createLanguageService(H);return new o_(O,H)}get isDisposed(){return this.#J}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#z(){if(this.#J)throw Error("TscProgram is disposed")}}class X0{#_;#$;#J;#z;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#Q.get(_);if(J)J.version+=1,J.content=$;else this.#Q.set(_,{version:1,content:$})}removeFile(_){this.#Q.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#Q.keys()];return[...[...this.#_].filter((J)=>!this.#Q.has(J)),..._]}getScriptVersion(_){let $=this.#Q.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#Q.get(_);if($)return H_.ScriptSnapshot.fromString($.content);let J=this.#z(_);if(J!==void 0)return H_.ScriptSnapshot.fromString(J);return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return H_.getDefaultLibFilePath(_)}fileExists(_){if(this.#Q.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#Q.get(_);if($)return $.content;return this.#z(_)}}import c from"typescript";import SJ from"typescript";function z_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),Y=Q.getEnd();if($<z||$>=Y)return;let Z;return SJ.forEachChild(Q,(W)=>{if(!Z)Z=J(W)}),Z??Q}return J(_)}var t_=8;function TJ(_){return!!(_.flags&c.TypeFlags.Object)&&!!(_.objectFlags&c.ObjectFlags.Reference)}function U_(_,$,J=0,Q){if(Q){let K=Q.get($);if(K)return K}let z=_.typeToString($),Y=$.flags,Z=!!(Y&c.TypeFlags.Union),W=!!(Y&c.TypeFlags.Intersection),X;if(J<t_&&TJ($)){let K=_.getTypeArguments($);if(K.length>0)X=K}let H=!!(Y&c.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,O;if(Z&&J<t_)O=$.types.map((K)=>U_(_,K,J+1,Q));else if(W&&J<t_)O=$.types.map((K)=>U_(_,K,J+1,Q));let U;if(X&&X.length>0)U=X.map((K)=>U_(_,K,J+1,Q));let L;if(J<t_&&!!(Y&c.TypeFlags.Object)&&!Z&&!W){let K=_.getPropertiesOfType($);if(K.length>0&&K.length<=50){let B=$.symbol?.declarations?.[0];L=[];for(let S of K){let R=S.declarations?.[0]??B;if(!R)continue;try{let v=_.getTypeOfSymbolAtLocation(S,R);L.push({name:S.getName(),type:U_(_,v,J+1,Q)})}catch{}}if(L.length===0)L=void 0}}let D={text:z,flags:Y,isUnion:Z,isIntersection:W,isGeneric:H,members:O,typeArguments:U,properties:L};if(Q)Q.set($,D);return D}function kJ(_){return c.isFunctionDeclaration(_)||c.isVariableDeclaration(_)||c.isClassDeclaration(_)||c.isInterfaceDeclaration(_)||c.isTypeAliasDeclaration(_)||c.isEnumDeclaration(_)||c.isMethodDeclaration(_)||c.isPropertyDeclaration(_)||c.isPropertySignature(_)||c.isMethodSignature(_)}class R${program;constructor(_){this.program=_}collectAt(_,$){let J=this.program.getProgram(),Q=this.program.getChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let Y=z_(z,$);if(!Y)return null;if(!c.isIdentifier(Y)&&!c.isTypeNode(Y))return null;try{let Z=Q.getTypeAtLocation(Y);return U_(Q,Z,0,new Map)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getChecker(),Y=this.program.getProgram(),Z=Y.getSourceFile(_);if(!Z)return null;let W=z_(Z,$);if(!W||!c.isIdentifier(W))return null;let X=Y.getSourceFile(J);if(!X)return null;let H=z_(X,Q);if(!H||!c.isIdentifier(H))return null;try{let O=z.getTypeAtLocation(W),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(O,U)}catch{return null}}isAssignableToType(_,$,J,Q){let z=this.program.getChecker(),Z=this.program.getProgram().getSourceFile(_);if(!Z)return null;let W=z_(Z,$);if(!W||!c.isIdentifier(W)&&!c.isTypeNode(W))return null;let X=`${_}.__gildash_probe__.ts`,H=`declare const __gildash_probe__: ${J};`;this.program.notifyFileChanged(X,H);try{let O=z.getTypeAtLocation(W),L=this.program.getProgram().getSourceFile(X);if(!L)return null;let D=this.program.getChecker(),K=L.statements[0];if(!K||!c.isVariableStatement(K))return null;let B=K.declarationList.declarations[0];if(!B)return null;let S=D.getTypeAtLocation(B.name);if(Q?.anyConstituent&&O.isUnion())return O.types.some((R)=>D.isTypeAssignableTo(R,S));return D.isTypeAssignableTo(O,S)}catch{return null}finally{this.program.removeFile(X)}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;if(!this.program.getProgram().getSourceFile(_))return z;let W=`${_}.__gildash_probe__.ts`,X=`declare const __gildash_probe__: ${J};`;this.program.notifyFileChanged(W,X);try{let H=this.program.getProgram(),O=H.getSourceFile(W);if(!O)return z;let U=this.program.getChecker(),L=O.statements[0];if(!L||!c.isVariableStatement(L))return z;let D=L.declarationList.declarations[0];if(!D)return z;let K=U.getTypeAtLocation(D.name),B=H.getSourceFile(_);if(!B)return z;let S=B.getEnd();for(let R of $){if(R<0||R>=S)continue;let v=z_(B,R);if(!v||!c.isIdentifier(v)&&!c.isTypeNode(v))continue;try{let j=U.getTypeAtLocation(v);if(Q?.anyConstituent&&j.isUnion())z.set(R,j.types.some((f)=>U.isTypeAssignableTo(f,K)));else z.set(R,U.isTypeAssignableTo(j,K))}catch{}}}catch{}finally{this.program.removeFile(W)}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=this.program.getChecker(),Y=Q.getSourceFile(_);if(!Y)return J;let Z=Y.getEnd(),W=new Map;for(let X of $){if(X<0||X>=Z)continue;let H=z_(Y,X);if(!H)continue;if(!c.isIdentifier(H)&&!c.isTypeNode(H))continue;try{let O=z.getTypeAtLocation(H);J.set(X,U_(z,O,0,W))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=this.program.getChecker(),z=J.getSourceFile(_);if(!z)return $;let Y=new Map;function Z(W){if(kJ(W)&&W.name&&c.isIdentifier(W.name)){let X=W.name;try{let H=Q.getTypeAtLocation(X),O=X.getStart(z);$.set(O,U_(Q,H,0,Y))}catch{}}c.forEachChild(W,Z)}return Z(z),$}}import M_ from"typescript";var FJ=1000,jJ=1;function GJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?M_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function e_(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),Y=Q?M_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",W=Y?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:W},H=_;if(H.parent)X.parent=GJ(H.parent);let O=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<jJ){let U=O.flags,L=!!(U&M_.SymbolFlags.Enum),D=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),K=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(L&&O.exports&&O.exports.size>0){let B=[];O.exports.forEach((S)=>{B.push(e_(S,$+1,J))}),X.members=B}else if(K&&O.members&&O.members.size>0){let B=[];O.members.forEach((S)=>{B.push(e_(S,$+1,J))}),X.members=B}if(D&&O.exports&&O.exports.size>0){let B=[];O.exports.forEach((S)=>{B.push(e_(S,$+1,J))}),X.exports=B}}return X}class S${#_;#$;#J=new Map;constructor(_,$=FJ){this.#_=_,this.#$=new f_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let Y=this.#_.getProgram().getSourceFile(_);if(!Y)return null;let Z=z_(Y,$);if(!Z||!M_.isIdentifier(Z))return null;let W=this.#_.getChecker(),X=W.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,W);this.#$.set(J,H);let O=this.#J.get(_);if(!O)O=new Set,this.#J.set(_,O);return O.add(J),H}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import EJ from"typescript";class T${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=z_(Q,$);if(!z||!EJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z)for(let H of X.references){let O=J.getSourceFile(H.fileName);if(!O)continue;let{line:U,character:L}=O.getLineAndCharacterOfPosition(H.textSpan.start);W.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:L,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return W}}import l from"typescript";function vJ(_,$){let J=z_(_,$);if(!J)return;if(O0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(O0(Q))return Q;Q=Q.parent}return J}function O0(_){return l.isClassDeclaration(_)||l.isClassExpression(_)||l.isFunctionDeclaration(_)||l.isFunctionExpression(_)||l.isArrowFunction(_)||l.isVariableDeclaration(_)||l.isObjectLiteralExpression(_)}function V0(_){if(l.isClassDeclaration(_)||l.isClassExpression(_))return"class";if(l.isFunctionDeclaration(_)||l.isFunctionExpression(_)||l.isArrowFunction(_))return"function";if(l.isObjectLiteralExpression(_))return"object";if(l.isVariableDeclaration(_)&&_.initializer)return V0(_.initializer);return"class"}function bJ(_,$){if(l.isClassDeclaration(_)||l.isFunctionDeclaration(_))return _.name?.getText($)??"";if(l.isClassExpression(_))return _.name?.getText($)??"";if(l.isVariableDeclaration(_)&&l.isIdentifier(_.name))return _.name.getText($);if(l.isFunctionExpression(_))return _.name?.getText($)??"";if(l.isArrowFunction(_)&&_.parent&&l.isVariableDeclaration(_.parent)){if(l.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(l.isObjectLiteralExpression(_)&&_.parent&&l.isVariableDeclaration(_.parent)){if(l.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function yJ(_){if(!l.isClassDeclaration(_)&&!l.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===l.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=z_(Q,$);if(!z||!l.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z){if(X.kind===l.ScriptElementKind.interfaceElement||X.kind===l.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let O=vJ(H,X.textSpan.start);if(!O)continue;let U=V0(O),L=bJ(O,H),D=yJ(O);W.push({filePath:X.fileName,symbolName:L,position:X.textSpan.start,kind:U,isExplicit:D})}return W}}function fJ(_){if(J_.isFunctionDeclaration(_))return"function";if(J_.isClassDeclaration(_))return"class";if(J_.isInterfaceDeclaration(_))return"interface";if(J_.isTypeAliasDeclaration(_))return"type";if(J_.isEnumDeclaration(_))return"enum";if(J_.isVariableDeclaration(_))return"const";if(J_.isVariableStatement(_))return"const";return"unknown"}function U0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class _${#_;#$;#J;#z;#Q;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#Q=z}static create(_,$={}){let J=o_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(PJ(J))return J;let Q=J,z=$.typeCollector??new R$(Q),Y=$.symbolGraph??new S$(Q),Z=$.referenceResolver??new T$(Q),W=$.implementationFinder??new k$(Q);return new _$(Q,z,Y,Z,W)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#W(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#W(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#W(),this.#$.collectAtPositions(_,$)}findReferences(_,$){return this.#W(),this.#z.findAt(_,$)}findImplementations(_,$){return this.#W(),this.#Q.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#W(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#W(),this.#$.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#W(),this.#$.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#W(),this.#J.get(_,$)}getBaseTypes(_,$){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=z_(Q,$);if(!z)return null;let Y=this.#_.getChecker(),Z=Y.getTypeAtLocation(z);if(!(Z.flags&J_.TypeFlags.Object)||!(Z.objectFlags&J_.ObjectFlags.ClassOrInterface))return null;let W=Y.getBaseTypes(Z);if(!W||W.length===0)return[];let X=new Map;return W.map((H)=>U_(Y,H,0,X))}getModuleInterface(_){this.#W();let $=[],Q=this.#_.getProgram().getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=this.#_.getChecker(),Y=z.getSymbolAtLocation(Q);if(Y){let Z=z.getExportsOfModule(Y),W=new Map;for(let X of Z){let H=X.getName(),O=X.declarations?.[0],U="unknown";if(O){if(U=fJ(O),U==="unknown"&&J_.isExportAssignment(O))U="const"}let L=null;try{let D=z.getTypeOfSymbolAtLocation(X,O??Q);L=U_(z,D,0,W)}catch{}$.push({name:H,kind:U,resolvedType:L})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return J_.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),Y=$;while(Y<z.length){let Z=z.indexOf(J,Y);if(Z<0)return null;let W=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!U0(W)&&!U0(X))return Z;Y=Z+1}return null}getDiagnostics(_,$){this.#W();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[J_.DiagnosticCategory.Error]:"error",[J_.DiagnosticCategory.Warning]:"warning",[J_.DiagnosticCategory.Suggestion]:"suggestion",[J_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?J_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let W=1,X=0;if(Z.file&&Z.start!==void 0){let H=J_.getLineAndCharacterOfPosition(Z.file,Z.start);W=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:W,column:X,message:J_.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
-
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#_.dispose(),this.#J.clear()}#W(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as C_,and as H0,sql as nJ}from"drizzle-orm";var M0=80;class F${db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((z)=>({project:_,filePath:$,tag:z.tag,value:z.value,source:z.source,symbolName:z.symbolName,startLine:z.startLine,startColumn:z.startColumn,endLine:z.endLine,endColumn:z.endColumn,indexedAt:z.indexedAt}));for(let z=0;z<Q.length;z+=M0)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(H0(C_(Z_.project,_),C_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(H0(_.project?C_(Z_.project,_.project):void 0,_.tag?C_(Z_.tag,_.tag):void 0,_.filePath?C_(Z_.filePath,_.filePath):void 0,_.symbolName?C_(Z_.symbolName,_.symbolName):void 0,_.source?C_(Z_.source,_.source):void 0,_.ftsQuery?nJ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as k_,and as K0,sql as n_,gt as mJ,gte as xJ}from"drizzle-orm";var L0=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+=L0)this.db.drizzleDb.insert(Q_).values($.slice(J,J+L0)).run()}getSince(_){return this.db.drizzleDb.select().from(Q_).where(K0(k_(Q_.project,_.project),xJ(Q_.changedAt,_.since),_.symbolName?k_(Q_.symbolName,_.symbolName):void 0,_.changeTypes?.length?n_`${Q_.changeType} IN (${n_.join(_.changeTypes.map(($)=>n_`${$}`),n_`, `)})`:void 0,_.filePath?k_(Q_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:k_(Q_.isFullIndex,0),_.indexRunId?k_(Q_.indexRunId,_.indexRunId):void 0,_.afterId?mJ(Q_.id,_.afterId):void 0)).orderBy(Q_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(Q_).where(K0(k_(Q_.project,_),n_`${Q_.changedAt} < ${$}`)).run().changes}}function w0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,Y;if(Q.text){let W=g_(Q.text);if(W)Y=W}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:Y,limit:Q.limit}).map((W)=>({tag:W.tag,value:W.value,source:W.source,filePath:W.filePath,symbolName:W.symbolName,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}}}))}class $${options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let Y=this.adjacencyList.get(z);if(Y){for(let W of Y)this.reverseAdjacencyList.get(W)?.delete(z);Y.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let W of Z)this.adjacencyList.get(W)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let Y=J(z);for(let Z of Y){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let Y of this.adjacencyList.get(z.node)??[]){if($.has(Y))return!0;if(!_.has(Y))Q.push({node:Y,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return lJ(J,$)}}var hJ=(_,$)=>_.localeCompare($);function pJ(_){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 G$(_,$,J){let Q=pJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function dJ(_){let $=0,J=[],Q=new Set,z=new Map,Y=new Map,Z=[],W=(X)=>{z.set(X,$),Y.set(X,$),$+=1,J.push(X),Q.add(X);for(let H of _.get(X)??[])if(!z.has(H))W(H),Y.set(X,Math.min(Y.get(X)??0,Y.get(H)??0));else if(Q.has(H))Y.set(X,Math.min(Y.get(X)??0,z.get(H)??0));if(Y.get(X)===z.get(X)){let H=[],O="";do O=J.pop()??"",Q.delete(O),H.push(O);while(O!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))W(X);return{components:Z}}function iJ(_,$,J){let Q=[],z=new Set,Y=[..._].sort(hJ),Z=(W,X,H)=>{X.delete(W);let O=H.get(W);if(!O)return;for(let U of O)if(X.has(U))Z(U,X,H);O.clear()};for(let W=0;W<Y.length&&Q.length<J;W++){let X=Y[W]??"",H=new Set(Y.slice(W)),O=new Set,U=new Map,L=[],D=(B)=>($.get(B)??[]).filter((S)=>H.has(S)),K=(B)=>{if(Q.length>=J)return!0;let S=!1;L.push(B),O.add(B);for(let R of D(B)){if(Q.length>=J)break;if(R===X)G$(z,Q,L.concat(X)),S=!0;else if(!O.has(R)){if(K(R))S=!0}}if(S)Z(B,O,U);else for(let R of D(B)){let v=U.get(R)??new Set;v.add(B),U.set(R,v)}return L.pop(),S};K(X)}return Q}function lJ(_,$){let{components:J}=dJ(_),Q=[],z=new Set;for(let Y of J){if(Q.length>=$)break;if(Y.length===0)continue;if(Y.length===1){let X=Y[0]??"";if((_.get(X)??[]).includes(X))G$(z,Q,[X,X]);continue}let Z=$-Q.length,W=iJ(Y,_,Z);for(let X of W){if(Q.length>=$)break;G$(z,Q,X)}}return Q}var cJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function A_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>cJ)_.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 B0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependencies failed",{cause:z})}}function D0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependents failed",{cause:z})}}async function I0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function C0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function A0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function u0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function N0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return A_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function q0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=A_(_,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 rJ=30000,R0=15000,oJ=10;function tJ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??F_.basename(_.projectRoot)}function eJ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let Y of _.onErrorCallbacks)try{Y(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function _Q(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=F_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function S0(_,$){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)=>tJ(_,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 Y=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>Y.getByType(X,"imports").concat(Y.getByType(X,"type-references")).concat(Y.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else J$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new H$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(eJ(_,J)).then((z)=>{if(m_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},rJ)}await J.fullIndex(),await _Q(_)}function $Q(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((Y)=>_.logger.error("[Gildash] close error during signal",Q,Y))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function T0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:Y=console,existsSyncFn:Z=sJ,dbConnectionFactory:W,watcherFactory:X,coordinatorFactory:H,repositoryFactory:O,acquireWatcherRoleFn:U=W0,releaseWatcherRoleFn:L=Y0,updateHeartbeatFn:D=Z0,discoverProjectsFn:K=d_,parseSourceFn:B=y_,extractSymbolsFn:S=S_,extractRelationsFn:R=s_,symbolSearchFn:v=u$,relationSearchFn:j=N$,patternSearchFn:f=g$,loadTsconfigPathsFn:o=b_,readFileFn:w=async(G)=>Bun.file(G).text(),unlinkFn:N=async(G)=>{await Bun.file(G).unlink()},watchMode:I,semantic:A,semanticLayerFactory:u}=_;if(!F_.isAbsolute($))throw new V("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new V("validation",`Gildash: projectRoot does not exist: "${$}"`);let q=W?W():new Z$({projectRoot:$}),T=q.open();if(m_(T))throw T.data;try{let G=await K($),p=G[0]?.project??F_.basename($),d=O?O():(()=>{let n=q;return{fileRepo:new X$(n),symbolRepo:new O$(n),relationRepo:new V$(n),parseCache:new A$(z)}})(),r=O?null:q,M=r?new F$(r):null,C=r?new j$(r):null,k=I??!0,F=crypto.randomUUID(),x;if(k)x=await Promise.resolve(U(q,process.pid,{instanceId:F}));else x="owner";let g={projectRoot:$,extensions:J,ignorePatterns:Q,logger:Y,defaultProject:p,role:x,db:q,symbolRepo:d.symbolRepo,relationRepo:d.relationRepo,fileRepo:d.fileRepo,parseCache:d.parseCache,annotationRepo:M,changelogRepo:C,annotationSearchFn:w0,releaseWatcherRoleFn:L,parseSourceFn:B,extractSymbolsFn:S,extractRelationsFn:R,symbolSearchFn:v,relationSearchFn:j,patternSearchFn:f,readFileFn:w,unlinkFn:N,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:D,watcherFactory:X,coordinatorFactory:H,instanceId:F,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:G,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(i_($),g.tsconfigPaths=await o($),A){let n=F_.join($,"tsconfig.json");try{if(u)g.semanticLayer=u(n);else{let b=_$.create(n);if(m_(b))throw b.data;g.semanticLayer=b}}catch(b){if(b instanceof V)throw b;throw new V("semantic","Gildash: semantic layer creation failed",{cause:b})}}if(x==="owner")await S0(g,{isWatchMode:k});else{let n=0,b=async()=>{try{let i=await Promise.resolve(g.acquireWatcherRoleFn(g.db,process.pid,{instanceId:g.instanceId}));if(n=0,i==="owner"){g.role="owner";for(let P of g.onRoleChangedCallbacks)try{P("owner")}catch(a){g.logger.error("[Gildash] onRoleChanged callback threw:",a)}clearInterval(g.timer),g.timer=null;try{await S0(g,{isWatchMode:!0})}catch(P){if(g.logger.error("[Gildash] owner promotion failed, reverting to reader",P),g.role="reader",g.timer!==null)clearInterval(g.timer),g.timer=null;if(g.watcher){let a=await g.watcher.close();if(m_(a))g.logger.error("[Gildash] watcher close error during promotion rollback",a.data);g.watcher=null}if(g.coordinator)await g.coordinator.shutdown().catch((a)=>g.logger.error("[Gildash] coordinator shutdown error during promotion rollback",a)),g.coordinator=null;try{g.releaseWatcherRoleFn(g.db,process.pid)}catch(a){g.logger.error("[Gildash] failed to release watcher role during promotion rollback",a)}g.timer=setInterval(b,R0)}}}catch(i){n++;let P=i instanceof V?i:new V("watcher","Gildash: healthcheck error",{cause:i});for(let a of g.onErrorCallbacks)try{a(P)}catch(K_){g.logger.error("[Gildash] onError callback threw:",K_)}if(g.logger.error("[Gildash] healthcheck error",i),n>=oJ)g.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(g.timer),g.timer=null,Q$(g).catch((a)=>g.logger.error("[Gildash] close error during healthcheck shutdown",a))}};g.timer=setInterval(b,R0)}if(k)$Q(g,()=>Q$(g));return g}catch(G){if(q.close(),G instanceof V)throw G;throw new V("store","Gildash: initialization failed",{cause:G})}}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(m_(Q))J.push(Q.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}try{_.db.close()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if($?.cleanup)for(let Q of["","-wal","-shm"])try{await _.unlinkFn(F_.join(_.projectRoot,L_,h_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function F0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(k0(z))throw z.data;return _.parseCache.set($,z),z}async function j0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(Y)=>{try{let Z=await _.readFileFn(Y),W=_.parseSourceFn(Y,Z,J);if(!k0(W))Q.set(Y,W);else z.push({filePath:Y,error:W.data})}catch(Z){z.push({filePath:Y,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function G0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function E0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function v0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import b0 from"path";function y0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: getStats failed",{cause:J})}}function E$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchSymbols failed",{cause:J})}}function P0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchRelations failed",{cause:J})}}function f0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllSymbols failed",{cause:J})}}function n0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllRelations failed",{cause:J})}}function m0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: listIndexedFiles failed",{cause:J})}}function x0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getInternalRelations failed",{cause:Q})}}function h0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(Y.length===0)return null;let Z=Y[0],W=Z.detail,X={...Z,members:W.members,jsDoc:W.jsDoc,parameters:W.parameters,returnType:W.returnType,heritage:W.heritage,decorators:W.decorators,typeParameters:W.typeParameters};if(_.semanticLayer)try{let H=b0.isAbsolute(J)?J:b0.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(O!==null){let U=_.semanticLayer.findNamePosition(H,O,Z.name)??O,L=_.semanticLayer.collectTypeAt(H,U);if(L)X.resolvedType=L}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function p0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let Y=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:Y.length,exportedSymbolCount:Y.filter((W)=>W.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function d0(_,$,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 i0(_,$,J){return E$(_,{filePath:$,project:J??void 0,limit:1e4})}function l0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((Y)=>({name:Y.name,kind:Y.kind,parameters:Y.detail.parameters?`(${Y.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:Y.detail.returnType??void 0,jsDoc:Y.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import m from"path";function x_(_,$,J,Q){let z=Q??_.defaultProject,Y=m.isAbsolute(J)?m.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:Y,limit:1}});if(Z.length===0)return null;let W=Z[0],X=m.isAbsolute(J)?J:m.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,W.span.start.line,W.span.start.column);if(H===null)return null;let O=_.semanticLayer.findNamePosition(X,H,W.name)??H;return{sym:W,position:O,absPath:X}}function c0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getResolvedType failed",{cause:z})}}function a0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getSemanticReferences failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getImplementations failed",{cause:z})}}function r0(_,$,J,Q,z,Y){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=x_(_,$,J,Y);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let W=x_(_,Q,z,Y);if(!W)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,W.absPath,W.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function o0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=m.isAbsolute($)?$:m.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function t0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=m.isAbsolute($)?$:m.resolve(_.projectRoot,$),Y=_.semanticLayer.lineColumnToPosition(z,J,Q);if(Y===null)return null;return _.semanticLayer.collectTypeAt(z,Y)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function e0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=m.isAbsolute($.source.filePath)?$.source.filePath:m.resolve(_.projectRoot,$.source.filePath),Q=m.isAbsolute($.target.filePath)?$.target.filePath:m.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let Y=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(Y===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,Y)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function _1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function $1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=m.isAbsolute($)?$:m.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function J1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=m.isAbsolute($)?$:m.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 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=m.isAbsolute($)?$:m.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 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=m.isAbsolute($)?$:m.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 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=m.isAbsolute($)?$:m.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 Y=m.isAbsolute($)?$:m.resolve(_.projectRoot,$),Z=m.isAbsolute(Q)?Q:m.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(Y,J,Z,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:Y})}}function Z1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=m.isAbsolute($)?$:m.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(Y,J,Q,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:Y})}}function 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 Y=m.isAbsolute($)?$:m.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(Y,J,Q,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:Y})}}function O1(_,$,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=m.isAbsolute($)?$:m.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 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=m.isAbsolute($)?$:m.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 U1(_,$,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=m.isAbsolute($)?$:m.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 H1(_,$,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=m.isAbsolute($)?$:m.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((W)=>[`${W.name}::${W.filePath}`,W])),Q=new Map($.map((W)=>[`${W.name}::${W.filePath}`,W])),z=[],Y=[],Z=[];for(let[W,X]of Q){let H=J.get(W);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,after:X})}for(let[W,X]of J)if(!Q.has(W))Y.push(X);return{added:z,removed:Y,modified:Z}}function K1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function L1(_){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 w1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,Y=new Set,Z=[],W=$,X=J;for(;;){let H=`${X}::${W}`;if(Y.has(H))return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!0};Y.add(H);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,L;for(let D of O){let K;if(D.metaJson)try{let S=JSON.parse(D.metaJson);if(Array.isArray(S.specifiers))K=S.specifiers}catch{}if(!K)continue;let B=K.find((S)=>S.exported===W);if(!B)continue;U=D.dstFilePath??void 0,L=B.local;break}if(!U||!L)return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:W}),X=U,W=L}}function B1(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function D1(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function I1(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function C1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((Y)=>Y.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function A1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=new Set,Z=(W,X,H)=>{let O=`${W}::${X}`;if(Y.has(O))return{symbolName:W,filePath:X,kind:H,children:[]};Y.add(O);let D=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:W,limit:1000}}).filter((K)=>K.type==="extends"||K.type==="implements").filter((K)=>K.dstSymbolName!=null&&K.dstFilePath!=null).map((K)=>Z(K.dstSymbolName,K.dstFilePath,K.type));return{symbolName:W,filePath:X,kind:H,children:D}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function u1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function N1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,Y=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:Y}).map((W)=>({changeType:W.changeType,symbolName:W.symbolName,symbolKind:W.symbolKind,filePath:W.filePath,oldName:W.oldName,oldFilePath:W.oldFilePath,fingerprint:W.fingerprint,changedAt:W.changedAt,isFullIndex:W.isFullIndex===1,indexRunId:W.indexRunId}))}function g1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],Y=[...new Set(z)];for(let Z of Y)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class v${_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(_){this._ctx=_}static async open(_){let $=await T0(_);return new v$($)}async close(_){return Q$(this._ctx,_)}parseSource(_,$,J){return F0(this._ctx,_,$,J)}async batchParse(_,$){return j0(this._ctx,_,$)}getParsedAst(_){return G0(this._ctx,_)}extractSymbols(_){return E0(this._ctx,_)}extractRelations(_){return v0(this._ctx,_)}getStats(_){return y0(this._ctx,_)}searchSymbols(_){return E$(this._ctx,_)}searchRelations(_){return P0(this._ctx,_)}searchAllSymbols(_){return f0(this._ctx,_)}searchAllRelations(_){return n0(this._ctx,_)}listIndexedFiles(_){return m0(this._ctx,_)}getInternalRelations(_,$){return x0(this._ctx,_,$)}getFullSymbol(_,$,J){return h0(this._ctx,_,$,J)}getFileStats(_,$){return p0(this._ctx,_,$)}getFileInfo(_,$){return d0(this._ctx,_,$)}getSymbolsByFile(_,$){return i0(this._ctx,_,$)}getModuleInterface(_,$){return l0(this._ctx,_,$)}getDependencies(_,$,J=1e4){return B0(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return D0(this._ctx,_,$,J)}async getAffected(_,$){return I0(this._ctx,_,$)}async hasCycle(_){return C0(this._ctx,_)}async getImportGraph(_){return A0(this._ctx,_)}async getTransitiveDependencies(_,$){return u0(this._ctx,_,$)}async getTransitiveDependents(_,$){return N0(this._ctx,_,$)}async getCyclePaths(_,$){return g0(this._ctx,_,$)}async getFanMetrics(_,$){return q0(this._ctx,_,$)}getResolvedType(_,$,J){return c0(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return a0(this._ctx,_,$,J)}getImplementations(_,$,J){return s0(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return r0(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return _1(this._ctx,_)}getFileTypes(_){return o0(this._ctx,_)}getResolvedTypeAt(_,$,J){return t0(this._ctx,_,$,J)}isTypeAssignableToAt(_){return e0(this._ctx,_)}getResolvedTypeAtPosition(_,$){return Q1(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return J1(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return z1(this._ctx,_,$)}getImplementationsAtPosition(_,$){return W1(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return Y1(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return Z1(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return X1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return O1(this._ctx,_,$,J)}findNamePosition(_,$,J){return V1(this._ctx,_,$,J)}getSymbolNode(_,$){return U1(this._ctx,_,$)}getBaseTypes(_,$){return $1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return H1(this._ctx,_,$)}diffSymbols(_,$){return M1(_,$)}onIndexed(_){return K1(this._ctx,_)}async reindex(){return L1(this._ctx)}resolveSymbol(_,$,J){return w1(this._ctx,_,$,J)}async findPattern(_,$){return C1(this._ctx,_,$)}async getHeritageChain(_,$,J){return A1(this._ctx,_,$,J)}onFileChanged(_){return B1(this._ctx,_)}onError(_){return D1(this._ctx,_)}onRoleChanged(_){return I1(this._ctx,_)}searchAnnotations(_){return u1(this._ctx,_)}getSymbolChanges(_,$){return N1(this._ctx,_,$)}pruneChangelog(_){return g1(this._ctx,_)}}import{Visitor as Q3,visitorKeys as z3}from"oxc-parser";export{z3 as visitorKeys,u$ as symbolSearch,N$ as relationSearch,g$ as patternSearch,Y_ as normalizePath,X_ as getLineColumn,P_ as buildLineOffsets,Q3 as Visitor,V as GildashError,v$ as Gildash,$$ as DependencyGraph};
|
|
2
|
+
var R1=Object.defineProperty;var T1=(_)=>_;function F1(_,$){this[_]=T1.bind(null,$)}var k1=(_,$)=>{for(var J in $)R1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:F1.bind($,J)})};var y$=import.meta.require;import{isErr as m_}from"@zipbul/result";import k_ from"path";import{existsSync as tJ}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 O extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};k1(Y$,{watcherOwner:()=>b1,symbols:()=>h,symbolChangelog:()=>J_,relations:()=>E,files:()=>e,annotations:()=>Z_});import{sql as G1}from"drizzle-orm";import{sqliteTable as q_,text as P,integer as t,real as j1,index as W_,primaryKey as E1,foreignKey as W$,check as v1}from"drizzle-orm/sqlite-core";var e=q_("files",{project:P("project").notNull(),filePath:P("file_path").notNull(),mtimeMs:j1("mtime_ms").notNull(),size:t("size").notNull(),contentHash:P("content_hash").notNull(),updatedAt:P("updated_at").notNull(),lineCount:t("line_count")},(_)=>[E1({columns:[_.project,_.filePath]})]),h=q_("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),kind:P("kind").notNull(),name:P("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:P("signature"),fingerprint:P("fingerprint"),detailJson:P("detail_json"),contentHash:P("content_hash").notNull(),indexedAt:P("indexed_at").notNull(),resolvedType:P("resolved_type"),structuralFingerprint:P("structural_fingerprint")},(_)=>[W_("idx_symbols_project_file").on(_.project,_.filePath),W_("idx_symbols_project_kind").on(_.project,_.kind),W_("idx_symbols_project_name").on(_.project,_.name),W_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),E=q_("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),type:P("type").notNull(),srcFilePath:P("src_file_path").notNull(),srcSymbolName:P("src_symbol_name"),dstProject:P("dst_project"),dstFilePath:P("dst_file_path"),dstSymbolName:P("dst_symbol_name"),metaJson:P("meta_json"),specifier:P("specifier"),isExternal:t("is_external").notNull().default(0)},(_)=>[W_("idx_relations_src").on(_.project,_.srcFilePath),W_("idx_relations_dst").on(_.dstProject,_.dstFilePath),W_("idx_relations_type").on(_.project,_.type),W_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),W_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),Z_=q_("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),tag:P("tag").notNull(),value:P("value").notNull().default(""),source:P("source").notNull(),symbolName:P("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:P("indexed_at").notNull()},(_)=>[W_("idx_annotations_project_file").on(_.project,_.filePath),W_("idx_annotations_project_tag").on(_.project,_.tag),W_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[e.project,e.filePath]}).onDelete("cascade")]),J_=q_("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),changeType:P("change_type").notNull(),symbolName:P("symbol_name").notNull(),symbolKind:P("symbol_kind").notNull(),filePath:P("file_path").notNull(),oldName:P("old_name"),oldFilePath:P("old_file_path"),fingerprint:P("fingerprint"),changedAt:P("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:P("index_run_id").notNull()},(_)=>[W_("idx_changelog_project_changed_at").on(_.project,_.changedAt),W_("idx_changelog_project_name").on(_.project,_.symbolName),W_("idx_changelog_project_run").on(_.project,_.indexRunId)]),b1=q_("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:P("started_at").notNull(),heartbeatAt:P("heartbeat_at").notNull(),instanceId:P("instance_id")},(_)=>[v1("watcher_owner_singleton",G1`${_.id} = 1`)]);class Z${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=h$(_.projectRoot,L_,h_)}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 O("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return x$(new O("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let 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 G_,and as p$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(e).where(p$(G_(e.project,_),G_(e.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(e).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[e.project,e.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(e).where(G_(e.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(e).where(p$(G_(e.project,_),G_(e.filePath,$))).run()}}import{eq as __,and as B_,sql as p_,count as h1}from"drizzle-orm";function u_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i$=50;class V${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(h).where(B_(__(h.project,_),__(h.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),W=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<W.length;Z+=i$)this.db.drizzleDb.insert(h).values(W.slice(Z,Z+i$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(h).where(B_(__(h.project,_),__(h.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=u_($);if(!z)return[];return this.db.drizzleDb.select().from(h).where(B_(p_`${h.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,__(h.project,_),J.kind?__(h.kind,J.kind):void 0)).orderBy(h.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(h).where(B_(__(h.project,_),__(h.kind,$))).orderBy(h.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:h1(),fileCount:p_`COUNT(DISTINCT ${h.filePath})`}).from(h).where(__(h.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(h).where(B_(__(h.project,_),__(h.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(h).where(B_(__(h.project,_),__(h.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(h).where(B_(_.ftsQuery?p_`${h.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?__(h.name,_.exactName):void 0,_.project!==void 0?__(h.project,_.project):void 0,_.kind?__(h.kind,_.kind):void 0,_.filePath!==void 0?__(h.filePath,_.filePath):void 0,_.isExported!==void 0?__(h.isExported,_.isExported?1:0):void 0,_.decorator?p_`${h.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?__(h.resolvedType,_.resolvedType):void 0)).orderBy(h.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new O("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Z=$.limit(W).all();if(Q=Z.filter((Y)=>J.test(Y.name)),Q.length>=_.limit||Z.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as c,and as O_,isNull as d$,or as p1}from"drizzle-orm";var j_={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 O${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(E).where(O_(c(E.project,_),c(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(j_).from(E).where(O_(c(E.project,_),c(E.srcFilePath,$),p1(c(E.srcSymbolName,J),d$(E.srcSymbolName)))).all();return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.project,_),c(E.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.dstProject,$),c(E.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.project,_),c(E.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(E).where(O_(c(E.project,_),c(E.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(E).where(O_(c(E.dstProject,_),c(E.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(j_).from(E).where(O_(_.project!==void 0?c(E.project,_.project):void 0,_.srcFilePath!==void 0?c(E.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?c(E.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?c(E.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?c(E.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?c(E.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?c(E.type,_.type):void 0,_.specifier!==void 0?c(E.specifier,_.specifier):void 0,_.isExternal!==void 0?c(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:Z}=_,Y=Q===null?O_(c(E.dstProject,$),c(E.dstFilePath,J),d$(E.dstSymbolName)):O_(c(E.dstProject,$),c(E.dstFilePath,J),c(E.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(E).set(X).where(Y).run()}}import{err as c$}from"@zipbul/result";import{subscribe as i1}from"@parcel/watcher";import U$ from"path";import l$ from"path";function Y_(_){return _.replaceAll("\\","/")}function E_(_,$){return Y_(l$.relative(_,$))}function S_(_,$){return Y_(l$.resolve(_,$))}var d1=["**/.git/**",`**/${L_}/**`,"**/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;#z;#Q;#Y;constructor(_,$=i1,J=console){this.#$=_.projectRoot,this.#J=[...d1,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#Q=$,this.#Y=J}async start(_){try{this.#_=await this.#Q(this.#$,($,J)=>{if($){this.#Y.error(new O("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=Y_(U$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let W=U$.basename(z),Z=U$.extname(z).toLowerCase();if(!l1.has(W)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:c1(Q.type),filePath:z})}}catch(Q){this.#Y.error(new O("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return c$(new O("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return c$(new O("watcher","Failed to close watcher",{cause:_}))}}}import M$ from"path";import{promises as a1}from"fs";var s1=["**/node_modules/**","**/.git/**",`**/${L_}/**`,"**/dist/**"];async function i_(_){let $=[];for await(let J of a1.glob("**/package.json",{cwd:_,exclude:s1})){let Q=Y_(M$.dirname(J)),z=M$.join(_,J),W=await Bun.file(z).json(),Z=typeof W?.name==="string"&&W.name.length>0?W.name:M$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function r(_,$,J="default"){let Q=Y_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import v_ from"path";var w_=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=v_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return v_.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(v_.dirname(_),Q),W=await a$(z,$-1);if(!W)return J;let Z=typeof W.compilerOptions==="object"&&W.compilerOptions!==null?W.compilerOptions:{},Y=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...W,...J,compilerOptions:{...Z,...Y}}}async function b_(_){if(w_.has(_))return w_.get(_)??null;let $=v_.join(_,"tsconfig.json"),J=await a$($);if(!J)return w_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return w_.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 w_.set(_,null),null;let Z=z?v_.resolve(_,z):_,Y=new Map;if(W)for(let[H,V]of Object.entries(W)){if(!Array.isArray(V))continue;let U=V.filter((B)=>typeof B==="string");Y.set(H,U)}let X={baseUrl:Z,paths:Y};return w_.set(_,X),X}function d_(_){if(_){w_.delete(_);return}w_.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 f_(_,$,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 O("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(),Z=new Set,Y=[],X=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of _J.glob("**/*",{cwd:$})){let B=Y_(U);if(!J.some((p)=>B.endsWith(p)))continue;if(B.startsWith("node_modules/")||B.includes("/node_modules/"))continue;if(H.some((p)=>p.match(B)))continue;Z.add(B);let q=$J($,B),L=Bun.file(q),{size:C,lastModified:T}=L,F=W.get(B);if(!F){let p=await L.text(),s=V_(p);Y.push({filePath:B,contentHash:s,mtimeMs:T,size:C});continue}if(F.mtimeMs===T&&F.size===C){X.push({filePath:B,contentHash:F.contentHash,mtimeMs:T,size:C});continue}let x=await L.text(),b=V_(x);if(b===F.contentHash)X.push({filePath:B,contentHash:b,mtimeMs:T,size:C});else Y.push({filePath:B,contentHash:b,mtimeMs:T,size:C})}let V=[];for(let U of W.keys())if(!Z.has(U))V.push(U);return{changed:Y,unchanged:X,deleted:V}}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 l_(_){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 O("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as zJ}from"@zipbul/result";function c_(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _&&typeof _.value==="string")return _.value;return"unknown"}function g_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...g_(J.argument));else $.push(...g_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...g_(J.argument));else $.push(...g_(J))}return $}if(_.type==="AssignmentPattern")return g_(_.left);return[]}function R_(_){let{program:$,sourceText:J,comments:Q}=_,z=P_(J),W=Q.filter((K)=>K.type==="Block"&&K.value.startsWith("*")).sort((K,u)=>K.end-u.end),Z=$.body.map((K)=>K.start).sort((K,u)=>K-u);function Y(K,u){return{start:X_(z,K),end:X_(z,u)}}function X(K){let u=0,D=W.length-1,w=-1;while(u<=D){let N=u+D>>>1;if(W[N].end<=K)w=N,u=N+1;else D=N-1}if(w<0)return;let A=W[w];u=0,D=Z.length-1;while(u<=D){let N=u+D>>>1,k=Z[N];if(k<=A.end)u=N+1;else if(k>=K)D=N-1;else return}return`/*${A.value}*/`}function H(K){if(!K)return;let u="typeAnnotation"in K&&K.typeAnnotation?K.typeAnnotation:K;return J.slice(u.start,u.end)}let V=8;function U(K,u=0){if(u>=V)return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)};let D=K.type;if(D==="Literal"){let w=K.value;if(w===null)return{kind:"null",value:null};if(typeof w==="string")return{kind:"string",value:w};if(typeof w==="number")return{kind:"number",value:w};if(typeof w==="boolean")return{kind:"boolean",value:w};return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}if(D==="Identifier"){let w=K.name;if(w==="undefined")return{kind:"undefined",value:null};return{kind:"identifier",name:w}}if(D==="MemberExpression"){if(K.computed)return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)};let w=J.slice(K.object.start,K.object.end),A=K.property.name??J.slice(K.property.start,K.property.end);return{kind:"member",object:w,property:A}}if(D==="CallExpression"){let w=K.callee,A=J.slice(w.start,w.end),k=(K.arguments??[]).map((j)=>U(j,u+1));return{kind:"call",callee:A,arguments:k}}if(D==="NewExpression"){let w=K.callee,A=J.slice(w.start,w.end),k=(K.arguments??[]).map((j)=>U(j,u+1));return{kind:"new",callee:A,arguments:k}}if(D==="ObjectExpression")return{kind:"object",properties:(K.properties??[]).map((N)=>{if(N.type==="SpreadElement"){let R=N.argument;return{key:"...",value:{kind:"spread",argument:U(R,u+1)}}}let k=N.key,j=k.name??k.value,v=j!=null?String(j):J.slice(k.start,k.end),M=N.value,I=N.computed||void 0,g=N.shorthand||void 0;return{key:v,value:U(M,u+1),computed:I,shorthand:g}})};if(D==="ArrayExpression")return{kind:"array",elements:(K.elements??[]).map((N)=>{if(!N)return{kind:"undefined",value:null};return U(N,u+1)})};if(D==="SpreadElement"){let w=K.argument;return{kind:"spread",argument:U(w,u+1)}}if(D==="ArrowFunctionExpression"||D==="FunctionExpression")return{kind:"function",sourceText:J.slice(K.start,K.end)};if(D==="TemplateLiteral"||D==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(K.start,K.end)};if(D==="UnaryExpression"){let{operator:w,argument:A}=K;if(w==="-"&&A.type==="Literal"&&typeof A.value==="number")return{kind:"number",value:-A.value};if(w==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}if(D==="TSAsExpression"||D==="TSSatisfiesExpression"||D==="TSNonNullExpression"||D==="TSTypeAssertion"||D==="TSInstantiationExpression"||D==="ParenthesizedExpression"){let w=K.expression;if(w)return U(w,u)}return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}function B(K){if(!K||K.length===0)return[];return K.map((u)=>{let D=u.expression;if(D.type==="CallExpression"){let w=D,A=w.callee,N="name"in A&&typeof A.name==="string"?A.name:("property"in A)&&A.property&&typeof A.property.name==="string"?A.property.name:"unknown",k=w.arguments.map((j)=>U(j));return{name:N,arguments:k.length>0?k:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function q(K){if(K.type==="TSParameterProperty"){let D=K;return L(D.parameter,D.parameter.decorators)}if(K.type==="RestElement"){let D=K,w=D.argument,N=`...${"name"in w&&typeof w.name==="string"?w.name:"unknown"}`,k=D.typeAnnotation,j=k?H(k):void 0,v={name:N,isOptional:!1};if(j)v.type=j;return v}let u=K;return L(u,u.decorators)}function L(K,u){if(K.type==="AssignmentPattern"){let{left:v,right:M}=K,I="name"in v&&typeof v.name==="string"?v.name:"unknown",g="typeAnnotation"in v?v.typeAnnotation:null,R=g?H(g):void 0,m=J.slice(M.start,M.end),S="decorators"in v&&Array.isArray(v.decorators)?v.decorators:[],f=B(S),G={name:I,isOptional:!0,defaultValue:m};if(R)G.type=R;if(f.length>0)G.decorators=f;return G}let D="name"in K&&typeof K.name==="string"?K.name:("pattern"in K)&&K.pattern&&typeof K.pattern.name==="string"?K.pattern.name:"unknown",w=!!(("optional"in K)&&K.optional),A="typeAnnotation"in K?K.typeAnnotation:null,N=A?H(A):void 0,k=B(u??[]),j={name:D,isOptional:w};if(N)j.type=N;if(k.length>0)j.decorators=k;return j}function C(K,u){let D=[];if(u?.async)D.push("async");if(K.static)D.push("static");if(K.abstract)D.push("abstract");if(K.readonly)D.push("readonly");if(K.override)D.push("override");if(K.declare)D.push("declare");if(K.const)D.push("const");let w=K.accessibility;if(w==="private")D.push("private");else if(w==="protected")D.push("protected");else if(w==="public")D.push("public");return D}function T(K){if(!K)return;let u=K.params.flatMap((D)=>{let w=D.name.name;return w?[w]:[]});return u.length>0?u:void 0}function F(K){let u=[];if(K.superClass){let w=J.slice(K.superClass.start,K.superClass.end);u.push({kind:"extends",name:w})}let D=K.implements??[];for(let w of D){let A=w.expression,N=J.slice(A.start,A.end);u.push({kind:"implements",name:N})}return u}function x(K){let u=[],D=K.extends;for(let w of D){let A=w.expression,N=J.slice(A.start,A.end);u.push({kind:"extends",name:N})}return u}function b(K){let u=[];for(let D of K)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let w=D,A=c_(w.key),N=w.value,k=w.kind,j=k==="constructor"?"constructor":k==="get"?"getter":k==="set"?"setter":"method",v=C(w,N);if(D.type==="TSAbstractMethodDefinition"&&!v.includes("abstract"))v.push("abstract");let M=N.params.map(q),I=H(N.returnType),g={kind:"method",name:A,span:Y(D.start,D.end),isExported:!1,methodKind:j,modifiers:v,parameters:M.length>0?M:void 0,returnType:I};u.push(g)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let w=D,A=c_(w.key),N=C(w);if(D.type==="TSAbstractPropertyDefinition"&&!N.includes("abstract"))N.push("abstract");let k=H(w.typeAnnotation),j=w.value,v=j?U(j):void 0,M=B(w.decorators??[]),I={kind:"property",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:N,returnType:k,initializer:v};if(M.length>0)I.decorators=M;u.push(I)}return u}function p(K){let u=[];for(let D of K)if(D.type==="TSMethodSignature"){let w=D,A=c_(w.key),N=w.params.map(q),k=H(w.returnType);u.push({kind:"method",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:N.length>0?N:void 0,returnType:k})}else if(D.type==="TSPropertySignature"){let w=D,A=c_(w.key),N=H(w.typeAnnotation),k={kind:"property",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:w.readonly?["readonly"]:[],returnType:N};u.push(k)}return u}function s(K,u){let D=K.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let w=K,A=w.id?.name??"default",N=w.params.map(q),k=H(w.returnType),j=C(w,w),v=B(w.decorators??[]),M=T(w.typeParameters),I={kind:"function",name:A,span:Y(K.start,K.end),isExported:u,modifiers:j,parameters:N.length>0?N:void 0,returnType:k,decorators:v.length>0?v:void 0};if(M&&M.length>0)I.typeParameters=M;return I}if(D==="ClassDeclaration"||D==="ClassExpression"){let w=K,A=w.id?.name??"default",N=F(w),k=b(w.body.body),j=B(w.decorators),v=C(w),M=T(w.typeParameters),I={kind:"class",name:A,span:Y(K.start,K.end),isExported:u,modifiers:v,heritage:N.length>0?N:void 0,members:k.length>0?k:void 0,decorators:j.length>0?j:void 0};if(M&&M.length>0)I.typeParameters=M;return I}if(D==="VariableDeclaration"){let w=K,A=[];for(let N of w.declarations){let{id:k,init:j}=N;if(k.type==="ObjectPattern"||k.type==="ArrayPattern"){let f=g_(k);for(let G of f)A.push({kind:"variable",name:G.name,span:Y(G.start,G.end),isExported:u,modifiers:[]});continue}let v="name"in k&&typeof k.name==="string"?k.name:"unknown",M="variable",I,g,R;if(j)if(j.type==="FunctionExpression"||j.type==="ArrowFunctionExpression"){M="function";let f=j;I=f.params.map(q),g=H(f.returnType)}else R=U(j);let m=[],S={kind:M,name:v,span:Y(N.start,N.end),isExported:u,modifiers:m,parameters:I,returnType:g};if(R)S.initializer=R;A.push(S)}if(A.length===0)return null;if(A.length===1)return A[0];return A}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:K.id.name,span:Y(K.start,K.end),isExported:u,modifiers:[]};if(D==="TSInterfaceDeclaration"){let w=K,A=w.id.name,N=x(w),k=p(w.body.body),j=T(w.typeParameters),v={kind:"interface",name:A,span:Y(K.start,K.end),isExported:u,modifiers:[],heritage:N.length>0?N:void 0,members:k.length>0?k:void 0};if(j&&j.length>0)v.typeParameters=j;return v}if(D==="TSEnumDeclaration"){let w=K,A=w.id.name,N=C(w),j=w.body.members.map((v)=>{let M=v.id,I="name"in M&&typeof M.name==="string"?M.name:("value"in M)&&typeof M.value==="string"?M.value:"unknown",g=v.initializer,R=g?U(g):void 0,m={kind:"property",name:I,span:Y(v.start,v.end),isExported:!1,modifiers:[]};if(R)m.initializer=R;return m});return{kind:"enum",name:A,span:Y(K.start,K.end),isExported:u,modifiers:N,members:j.length>0?j:void 0}}if(D==="TSModuleDeclaration"){let w=K,A=w.id.name??w.id.value??"unknown",N=C(w),k=[];if(w.body?.type==="TSModuleBlock")for(let j of w.body.body??[]){if(j.type!=="ExportNamedDeclaration")continue;let v=j.declaration;if(!v)continue;let M=s(v,!1);if(M)if(Array.isArray(M))k.push(...M);else k.push(M)}return{kind:"namespace",name:A,span:Y(K.start,K.end),isExported:u,modifiers:N,members:k.length>0?k:void 0}}return null}let o=[],z_=new Set;for(let K of $.body){let u=null,D=K;if(D.type==="ExportNamedDeclaration"){let A=D;if(A.declaration){if(u=s(A.declaration,!0),u&&!Array.isArray(u))u.span=Y(A.start,A.end)}else if(!A.source&&A.specifiers)for(let N of A.specifiers){let k=N.local,j="name"in k?k.name:k.value;if(j)z_.add(j)}}else if(D.type==="ExportDefaultDeclaration"){let A=D,N=A.declaration;if(N){if(u=s(N,!0),u&&!Array.isArray(u))u.name="id"in N&&N.id&&typeof N.id.name==="string"?N.id.name:"default",u.isExported=!0,u.span=Y(A.start,A.end);else if(!u&&"type"in N&&N.type==="Identifier"){let k=N.name;if(k)z_.add(k)}}}else{let A=D.type;if(A==="FunctionDeclaration"||A==="TSDeclareFunction"||A==="ClassDeclaration"||A==="VariableDeclaration"||A==="TSTypeAliasDeclaration"||A==="TSInterfaceDeclaration"||A==="TSEnumDeclaration"||A==="TSModuleDeclaration")u=s(D,!1)}let w=Array.isArray(u)?u:u?[u]:[];for(let A of w){let N=K.start,k=X(N);if(k){let j=l_(k);if(!zJ(j))A.jsDoc=j}o.push(A)}}if(z_.size>0){for(let K of o)if(!K.isExported&&z_.has(K.name))K.isExported=!0}return o}function WJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function YJ(_){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 ZJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${V_(J)}`)}return V_($.join("|"))}function r$(_,$,J,Q,z){let W=WJ(_),Z=V_(`${$}|${_.kind}|${W??""}`),Y=ZJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:W,fingerprint:Z,detailJson:YJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function K$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Z=R_($),Y=[];for(let X of Z){Y.push(r$(X,X.name,J,Q,z));for(let H of X.members??[])Y.push(r$(H,`${X.name}.${H.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as L$,dirname as XJ,extname as VJ}from"path";function D_(_,$,J){let Q=(z)=>{let W=VJ(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=Y_(L$(XJ(_),$));return Q(z)}if(J)for(let[z,W]of J.paths){if(W.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let Y=[];for(let X of W)Y.push(...Q(Y_(L$(J.baseUrl,X))));return Y}}else{let Y=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(Y)&&(X===""||$.endsWith(X))){let H=$.slice(Y.length,X===""?void 0:$.length-X.length),V=[];for(let U of W)V.push(...Q(Y_(L$(J.baseUrl,U.replace("*",H)))));return V}}}return[]}function o$(_,$,J,Q=D_){let z=new Map,W=_.body??[];for(let Z of W){if(Z.type!=="ImportDeclaration")continue;let Y=Z.source?.value??"",X=Q($,Y,J);if(X.length===0)continue;let H=X[0],V=Z.specifiers??[];for(let U of V)switch(U.type){case"ImportSpecifier":z.set(U.local.name,{path:H,importedName:U.imported.name});break;case"ImportDefaultSpecifier":z.set(U.local.name,{path:H,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(U.local.name,{path:H,importedName:"*"});break}}return z}import{Visitor as OJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function UJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function I_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&UJ($);return{resolved:W,isExternal:Z}}function HJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=I_($,Z,J,Q),H=Y===null?{dstFilePath:null,specifier:Z}:{dstFilePath:Y};if(W.entries.length===0){let V={};if(X)V.isExternal=!0;if(Y===null&&!X)V.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of W.entries){let U=V.isType,B={};if(U)B.isType=!0;if(X)B.isExternal=!0;if(Y===null&&!X)B.isUnresolved=!0;let q,L,C=V.importName.kind;if(C==="Default")q="default",L=V.localName.value;else if(C==="NamespaceObject")q="*",L=V.localName.value,B.importKind="namespace";else q=V.importName.name??"unknown",L=V.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:L,...H,dstSymbolName:q,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}}}function MJ(_,$,J,Q,z){let W=new Map;for(let Z of _.staticImports)for(let Y of Z.entries)W.set(Y.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let Y of Z.entries){let X=null;if(Y.moduleRequest)X=Y.moduleRequest.value;else if(Y.localName.name)X=W.get(Y.localName.name)??null;if(!X)continue;let{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.exportName.name??"default",B=Y.exportName.kind,q=Y.localName.name??Y.importName.name??U,L=Y.isType,C={isReExport:!0};if(B==="None");else C.specifiers=[{local:q,exported:U}];if(L)C.isType=!0;if(V)C.isExternal=!0;if(H===null&&!V)C.isUnresolved=!0;let T=null,F=null,x=Y.importName.kind;if(x==="All"||x==="AllButDefault"){if(B==="Name"&&U)F=U,C.namespaceAlias=U}else F=q,T=U;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:H,dstSymbolName:F,metaJson:JSON.stringify(C),...H===null?{specifier:X}:{}})}}function KJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.importKind==="type",B=Y.specifiers,q=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(B.length===0){let L={};if(U)L.isType=!0;if(V)L.isExternal=!0;if(H===null&&!V)L.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...q,dstSymbolName:null,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}else for(let L of B){let C=L.type,T=U||C==="ImportSpecifier"&&L.importKind==="type",F={};if(T)F.isType=!0;if(V)F.isExternal=!0;if(H===null&&!V)F.isUnresolved=!0;let x,b;if(C==="ImportDefaultSpecifier")x="default",b=L.local.name;else if(C==="ImportNamespaceSpecifier")x="*",b=L.local.name,F.importKind="namespace";else x=a_(L.imported),b=L.local.name;z.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:b,...q,dstSymbolName:x,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.exportKind==="type",B=Y.exported,q=B?a_(B):null,L={isReExport:!0};if(U)L.isType=!0;if(V)L.isExternal=!0;if(H===null&&!V)L.isUnresolved=!0;if(q)L.namespaceAlias=q;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:q,metaJson:JSON.stringify(L),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.exportKind==="type",B=Y.specifiers??[];for(let q of B){let L=U||q.exportKind==="type",C=a_(q.local),T=a_(q.exported),F={isReExport:!0,specifiers:[{local:C,exported:T}]};if(L)F.isType=!0;if(V)F.isExternal=!0;if(H===null&&!V)F.isUnresolved=!0;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:H,dstSymbolName:C,metaJson:JSON.stringify(F),...H===null?{specifier:X}:{}})}}}}function LJ(_,$,J,Q,z){new OJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U={isDynamic:!0};if(V)U.isExternal=!0;if(H===null&&!V)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(U),...H===null?{specifier:X}:{}})},CallExpression(Z){let Y=Z.callee,X=!1;if(Y.type==="Identifier"&&Y.name==="require");else if(Y.type==="MemberExpression"&&!Y.computed){let C=Y,T=C.object,F=C.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let V=H[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let U=V.value,{resolved:B,isExternal:q}=I_($,U,J,Q),L={isRequire:!0};if(X)L.isRequireResolve=!0;if(q)L.isExternal=!0;if(B===null&&!q)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:B,dstSymbolName:null,metaJson:JSON.stringify(L),...B===null?{specifier:U}:{}})}}).visit(_)}function t$(_,$,J,Q=D_,z){let W=[];if(z)HJ(z,$,J,Q,W),MJ(z,$,J,Q,W);else KJ(_,$,J,Q,W);return LJ(_,$,J,Q,W),W}import{walk as wJ}from"oxc-walker";function T_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let W=[z,...J].join(".");return{root:z,parts:J,full:W}}return null}function e$(_,$,J){let Q=[],z=[],W=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function Y(V){if(!V)return null;let U=J.get(V.root);if(V.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let B=V.parts[V.parts.length-1];return{dstFilePath:U.path,dstSymbolName:B,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,U){let B=T_(V.callee),q=Y(B);if(q){let L=Z(),C={};if(U)C.isNew=!0;if(L===null)C.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:L,dstFilePath:q.dstFilePath,dstSymbolName:q.dstSymbolName,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}function H(V,U){if(V.type==="FunctionDeclaration"){z.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let L=U.id,C=L.type==="Identifier"?L.name:"anonymous";z.push(C);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let L=U.key,C=W[W.length-1]??"",T="name"in L?L.name:"anonymous",F=C?`${C}.${T}`:T;z.push(F);return}let B=Z(),q=B?`${B}.<anonymous>`:"<anonymous>";z.push(q)}}return wJ(_,{enter(V,U){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){H(V,U);return}if(V.type==="CallExpression"){X(V,!1);return}if(V.type==="NewExpression"){X(V,!0);return}},leave(V){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.pop();return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as BJ}from"oxc-parser";function _0(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let H=T_(Z.superClass);if(H){let V=w$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...V})}}let X=Z.implements??[];for(let H of X){let V=T_(H.expression);if(!V)continue;let U=w$(V,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...U})}}return new BJ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let V=T_(H.expression);if(!V)continue;let U=w$(V,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...U})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).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 s_(_,$,J,Q=D_,z){let W=o$(_,$,J,Q),Z=t$(_,$,J,Q,z),Y=e$(_,$,W),X=_0(_,$,W);return[...Z,...Y,...X]}function B$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Z,knownFiles:Y,boundaries:X,module:H}=_,V=S_(W,Q),B=s_($,V,Z,Y?(L,C,T)=>{let F=D_(L,C,T);for(let x of F){let b=E_(W,x);if(X){let p=r(b,X);if(Y.has(`${p}::${b}`))return[x]}else if(Y.has(`${J}::${b}`))return[x]}return[]}:void 0,H),q=[];for(let L of B){if(L.dstFilePath===null){let x=E_(W,L.srcFilePath),b;if(L.metaJson)try{b=JSON.parse(L.metaJson)}catch{}let p=b?.isExternal===!0;q.push({project:J,type:L.type,srcFilePath:x,srcSymbolName:L.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:p?1:0});continue}let C=E_(W,L.dstFilePath);if(C.startsWith(".."))continue;let T=E_(W,L.srcFilePath),F=X?r(C,X):J;q.push({project:J,type:L.type,srcFilePath:T,srcSymbolName:L.srcSymbolName??null,dstProject:F,dstFilePath:C,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,q),q.length}import{isErr as DJ}from"@zipbul/result";var $0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function IJ(_){let $=R_(_),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=IJ(_),W=[],Z=[...$].sort((X,H)=>X.start-H.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let H=`/*${X.value}*/`,V=l_(H);if(DJ(V))continue;let U=V;if(!U.tags?.length)continue;let B=X_(Q,X.end),q=D$(z,B.line,3),L=J.slice(X.start,X.end);for(let C of U.tags){let T=[C.name,C.description].filter(Boolean).join(" "),F=`@${C.tag}`,x=L.indexOf(F),b;if(x>=0){let p=X.start+x,s=J.indexOf(`
|
|
4
|
+
`,p),o=s>=0?Math.min(s,X.end):X.end;b=r_(Q,p,o)}else b=r_(Q,X.start,X.end);W.push({tag:C.tag,value:T,source:"jsdoc",span:b,symbolName:q})}}else if(X.type==="Block"){Y=null;let H=X.value.split(`
|
|
5
|
+
`),V=0;for(let U of H){let B=U.replace(/^\s*\*?\s?/,""),q=$0.exec(B);if(q){let L=q[1],C=q[2]?.trim()??"",T=`@${L}`,F=U.indexOf(T),x=X.start+2+V+(F>=0?F:0),b=X.start+2+V+U.length,p=r_(Q,x,b),s=X_(Q,X.end),o=D$(z,s.line,3);W.push({tag:L,value:C,source:"block",span:p,symbolName:o})}V+=U.length+1}}else{let H=X.value,V=$0.exec(H),U=X_(Q,X.start),B=X_(Q,X.end);if(V){let q=V[1],L=V[2]?.trim()??"",C=`@${q}`,T=H.indexOf(C),F=X.start+2+(T>=0?T:0),x=r_(Q,F,X.end),b=D$(z,B.line,3),p={tag:q,value:L,source:"line",span:x,symbolName:b};W.push(p),Y={annotation:p,endLine:B.line}}else if(Y&&U.line===Y.endLine+1){let q=H.trim();if(q)Y.annotation.value+=" "+q,Y.annotation.span.end=X_(Q,X.end),Y.endLine=B.line}else Y=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 Z=new Date().toISOString(),Y=W.map((X)=>({project:J,filePath:Q,tag:X.tag,value:X.value,source:X.source,symbolName:X.symbolName,startLine:X.span.start.line,startColumn:X.span.start.column,endLine:X.span.end.line,endColumn:X.span.end.column,indexedAt:Z}));return z.insertBatch(J,Q,Y),W.length}function Q0(_,$){let J=[],Q=[],z=[];for(let[V,U]of $)if(!_.has(V))J.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[V,U]of _)if(!$.has(V))Q.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Z=new Map;for(let V of J){let U=W.get(V.filePath)??[];U.push(V),W.set(V.filePath,U)}for(let V of Q){let U=Z.get(V.filePath)??[];U.push(V),Z.set(V.filePath,U)}let Y=new Set,X=new Set;for(let[V,U]of W){let B=Z.get(V);if(!B)continue;for(let q of new Set(U.map((L)=>L.kind))){let L=U.filter((b)=>b.kind===q&&!Y.has(b)),C=B.filter((b)=>b.kind===q&&!X.has(b));if(!L.length||!C.length)continue;let T=(b,p)=>{return p.get(`${b.filePath}::${b.name}`)?.structuralFingerprint??null},F=(b,p)=>{return p.get(`${b.filePath}::${b.name}`)?.startLine??0},x=new Map;for(let b of C){let p=T(b,_);if(!p)continue;let s=x.get(p)??[];s.push(b),x.set(p,s)}for(let b of L){if(Y.has(b))continue;let p=T(b,$);if(!p)continue;let s=x.get(p);if(!s)continue;let o=s.filter((K)=>!X.has(K));if(!o.length)continue;let z_=o[0];if(o.length>1){let K=F(b,$),u=Math.abs(F(z_,_)-K);for(let D=1;D<o.length;D++){let w=Math.abs(F(o[D],_)-K);if(w<u)u=w,z_=o[D]}}z.push({oldName:z_.name,newName:b.name,filePath:V,kind:q}),Y.add(b),X.add(z_)}}}let H=z.filter((V)=>!V.oldName.includes("."));for(let V of H){let U=`${V.oldName}.`,B=`${V.newName}.`,q=Q.filter((C)=>C.filePath===V.filePath&&C.name.startsWith(U)&&!X.has(C)),L=J.filter((C)=>C.filePath===V.filePath&&C.name.startsWith(B)&&!Y.has(C));for(let C of q){let T=C.name.slice(U.length),F=L.find((x)=>x.name.slice(B.length)===T);if(F)z.push({oldName:C.name,newName:F.name,filePath:V.filePath,kind:C.kind}),Y.add(F),X.add(C)}}return{renamed:z,added:J.filter((V)=>!Y.has(V)),removed:Q.filter((V)=>!X.has(V))}}var CJ=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=b_(_.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(_){return this.startIndex(_,!1)}onIndexed(_){return this.callbacks.add(_),()=>this.callbacks.delete(_)}handleWatcherEvent(_){if(_.filePath.endsWith("tsconfig.json")){d_(this.opts.projectRoot),this.tsconfigPathsRaw=b_(this.opts.projectRoot),this.fullIndex().catch(($)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",$)});return}if(_.filePath.endsWith("package.json")){let $=this.opts.discoverProjectsFn??i_;this.boundariesRefresh=$(this.opts.projectRoot).then((J)=>{this.opts.boundaries=J,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()},CJ)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(_,$){if(this.indexingLock){if($)return this.pendingFullIndex=!0,new Promise((Q,z)=>{this.pendingFullIndexWaiters.push({resolve:Q,reject:z})});return this.currentIndexing}this.indexingLock=!0;let J=this.doIndex(_,$).then((Q)=>{return this.fireCallbacks(Q),Q}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let Q=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((z)=>{for(let W of Q)W.resolve(z)}).catch((z)=>{for(let W of Q)W.reject(z)})}else if(this.pendingEvents.length>0){let Q=this.pendingEvents.splice(0);this.startIndex(Q,!1).catch((z)=>this.logger.error("[IndexCoordinator] incremental drain error",z))}});return this.currentIndexing=J,J}async doIndex(_,$){let J=Date.now(),{fileRepo:Q,symbolRepo:z,relationRepo:W,dbConnection:Z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Y,X;if(_!==void 0)Y=_.filter((M)=>M.eventType==="create"||M.eventType==="change").map((M)=>({filePath:M.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((M)=>M.eventType==="delete").map((M)=>M.filePath);else{let M=new Map;for(let g of this.opts.boundaries)for(let[R,m]of Q.getFilesMap(g.project))M.set(R,m);let I=await s$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>M}});Y=I.changed,X=I.deleted}let H=await this.tsconfigPathsRaw??void 0,V=new Map;for(let M of X){let I=r(M,this.opts.boundaries),g=z.getFileSymbols(I,M);V.set(M,g)}let U=crypto.randomUUID(),B=new Map,q=new Map,L=(M)=>({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint,structuralFingerprint:M.structuralFingerprint??null,startLine:M.startLine,isExported:M.isExported??0});if($)for(let M of this.opts.boundaries)for(let I of Q.getAllFiles(M.project))for(let g of z.getFileSymbols(M.project,I.filePath))B.set(`${g.filePath}::${g.name}`,L(g));else{for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of z.getFileSymbols(I,M.filePath))B.set(`${g.filePath}::${g.name}`,L(g))}for(let[,M]of V)for(let I of M)B.set(`${I.filePath}::${I.name}`,L(I))}let C=(M)=>`${M.type}|${M.srcFilePath}|${M.dstFilePath??""}|${M.srcSymbolName??""}|${M.dstSymbolName??""}|${V_(M.metaJson??"")}`,T=new Map;if($)for(let M of this.opts.boundaries)for(let I of Q.getAllFiles(M.project))for(let g of W.getOutgoing(M.project,I.filePath))T.set(C(g),g);else{for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of W.getOutgoing(I,M.filePath))T.set(C(g),g)}for(let M of X){let I=r(M,this.opts.boundaries);for(let g of W.getOutgoing(I,M))T.set(C(g),g)}}let{annotationRepo:F,changelogRepo:x}=this.opts,b=()=>{for(let M of X){let I=r(M,this.opts.boundaries);if(z.deleteFileSymbols(I,M),W.deleteFileRelations(I,M),W.deleteIncomingRelations(I,M),F)F.deleteFileAnnotations(I,M);Q.deleteFile(I,M)}},p=0,s=async()=>{let{projectRoot:M,boundaries:I}=this.opts,{parseCache:g}=this.opts,R=0,m=0,S=0,f=[],G=[];for(let y of Y)try{let l=S_(M,y.filePath),K_=Bun.file(l),N_=await K_.text(),f$=y.contentHash||V_(N_),P$=r(y.filePath,I);Q.upsertFile({project:P$,filePath:y.filePath,mtimeMs:K_.lastModified,size:K_.size,contentHash:f$,updatedAt:new Date().toISOString(),lineCount:N_.split(`
|
|
6
|
+
`).length});let z$=(this.opts.parseSourceFn??f_)(l,N_);if(z0(z$))throw z$.data;let g1=z$;G.push({filePath:y.filePath,text:N_,contentHash:f$,parsed:g1,project:P$})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${y.filePath}:`,l),f.push(y.filePath)}let i=new Set;for(let y of I)for(let[l]of Q.getFilesMap(y.project))i.add(`${y.project}::${l}`);return Z.transaction(()=>{for(let y of G){if(K$({parsed:y.parsed,project:y.project,filePath:y.filePath,contentHash:y.contentHash,symbolRepo:z}),m+=B$({ast:y.parsed.program,project:y.project,filePath:y.filePath,relationRepo:W,projectRoot:M,tsconfigPaths:H,knownFiles:i,boundaries:I,module:y.parsed.module}),F)S+=I$({parsed:y.parsed,project:y.project,filePath:y.filePath,annotationRepo:F});g.set(y.filePath,y.parsed),R+=z.getFileSymbols(y.project,y.filePath).length}}),{symbols:R,relations:m,annotations:S,failedFiles:f}},o=0,z_=0,K=[];if($){let{projectRoot:M,boundaries:I}=this.opts,{parseCache:g}=this.opts,R=[];for(let S=0;S<Y.length;S+=W0){let f=Y.slice(S,S+W0),G=await Promise.allSettled(f.map(async(i)=>{let y=S_(M,i.filePath),l=Bun.file(y),K_=await l.text(),N_=i.contentHash||V_(K_);return{filePath:i.filePath,text:K_,contentHash:N_,mtimeMs:l.lastModified,size:l.size}}));for(let i=0;i<G.length;i++){let y=G[i];if(y.status==="fulfilled")R.push(y.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",y.reason),K.push(f[i].filePath)}}let m=[];Z.transaction(()=>{for(let G of R){let i=r(G.filePath,I);Q.deleteFile(i,G.filePath)}for(let G of X){let i=r(G,I);if(z.deleteFileSymbols(i,G),W.deleteFileRelations(i,G),W.deleteIncomingRelations(i,G),F)F.deleteFileAnnotations(i,G);Q.deleteFile(i,G)}for(let G of R){let i=r(G.filePath,I);Q.upsertFile({project:i,filePath:G.filePath,mtimeMs:G.mtimeMs,size:G.size,contentHash:G.contentHash,updatedAt:new Date().toISOString(),lineCount:G.text.split(`
|
|
7
|
+
`).length})}let S=new Set;for(let G of I)for(let[i]of Q.getFilesMap(G.project))S.add(`${G.project}::${i}`);let f=this.opts.parseSourceFn??f_;for(let G of R){let i=r(G.filePath,I),y=f(S_(M,G.filePath),G.text);if(z0(y))throw y.data;let l=y;if(m.push({filePath:G.filePath,parsed:l}),K$({parsed:l,project:i,filePath:G.filePath,contentHash:G.contentHash,symbolRepo:z}),F)p+=I$({parsed:l,project:i,filePath:G.filePath,annotationRepo:F});z_+=B$({ast:l.program,project:i,filePath:G.filePath,relationRepo:W,projectRoot:M,tsconfigPaths:H,knownFiles:S,boundaries:I,module:l.module}),o+=z.getFileSymbols(i,G.filePath).length}});for(let S of m)g.set(S.filePath,S.parsed)}else{b();let M=await s();o=M.symbols,z_=M.relations,p=M.annotations,K=M.failedFiles}for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of z.getFileSymbols(I,M.filePath))q.set(`${g.filePath}::${g.name}`,L(g))}let u=new Map;for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of W.getOutgoing(I,M.filePath))u.set(C(g),g)}let D=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),w={added:[...u.entries()].filter(([M])=>!T.has(M)).map(([,M])=>D(M)),removed:[...T.entries()].filter(([M])=>!u.has(M)).map(([,M])=>D(M))},A={added:[],modified:[],removed:[]};for(let[M,I]of q){let g=B.get(M);if(!g)A.added.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)});else{let R=g.fingerprint!==I.fingerprint,m=g.isExported!==I.isExported,S=g.structuralFingerprint!==null&&I.structuralFingerprint!==null&&g.structuralFingerprint!==I.structuralFingerprint;if(R||m||S)A.modified.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)})}}for(let[M,I]of B)if(!q.has(M))A.removed.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)});let N=Q0(B,q),k=new Set(N.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),j=new Set(N.renamed.map((M)=>`${M.filePath}::${M.newName}`));A.added=A.added.filter((M)=>!j.has(`${M.filePath}::${M.name}`)),A.removed=A.removed.filter((M)=>!k.has(`${M.filePath}::${M.name}`));let v=[];if(!$){for(let[I,g]of V)for(let R of g){if(!R.fingerprint)continue;let m=r(I,this.opts.boundaries),S=z.getByFingerprint(m,R.fingerprint);if(S.length===1){let f=S[0];W.retargetRelations({dstProject:m,oldFile:I,oldSymbol:R.name,newFile:f.filePath,newSymbol:f.name}),v.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:I,isExported:f.isExported??0})}}let M=new Set(v.map((I)=>`${I.oldFilePath}::${I.name}`));for(let I of N.removed){if(M.has(`${I.filePath}::${I.name}`))continue;let R=B.get(`${I.filePath}::${I.name}`)?.fingerprint;if(!R)continue;let m=r(I.filePath,this.opts.boundaries),S=z.getByFingerprint(m,R);if(S.length===1){let f=S[0];if(f.filePath!==I.filePath||f.name!==I.name)W.retargetRelations({dstProject:m,oldFile:I.filePath,oldSymbol:I.name,newFile:f.filePath,newSymbol:f.name}),v.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:I.filePath,isExported:f.isExported??0})}}}if(v.length){let M=new Set(v.map((g)=>`${g.filePath}::${g.name}`)),I=new Set(v.map((g)=>`${g.oldFilePath}::${g.name}`));A.added=A.added.filter((g)=>!M.has(`${g.filePath}::${g.name}`)),A.removed=A.removed.filter((g)=>!I.has(`${g.filePath}::${g.name}`))}if(x){let M=new Date().toISOString(),I=$?1:0,g=[];for(let R of A.added){let m=`${R.filePath}::${R.name}`,S=q.get(m),f=r(R.filePath,this.opts.boundaries);g.push({project:f,changeType:"added",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of A.modified){let m=q.get(`${R.filePath}::${R.name}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"modified",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of A.removed){let m=`${R.filePath}::${R.name}`,S=B.get(m),f=r(R.filePath,this.opts.boundaries);g.push({project:f,changeType:"removed",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of N.renamed){let m=q.get(`${R.filePath}::${R.newName}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"renamed",symbolName:R.newName,symbolKind:R.kind,filePath:R.filePath,oldName:R.oldName,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of v){let m=q.get(`${R.filePath}::${R.name}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"moved",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:R.oldFilePath,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}if(g.length)try{Z.transaction(()=>{x.insertBatch(g)})}catch(R){this.logger.error("[IndexCoordinator] changelog insert failed:",R)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let R=new Date(Date.now()-2592000000).toISOString();try{for(let m of this.opts.boundaries)x.pruneOlderThan(m.project,R)}catch(m){this.logger.error("[IndexCoordinator] changelog pruning failed:",m)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:o,totalRelations:z_,totalAnnotations:p,durationMs:Date.now()-J,changedFiles:Y.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:K,changedSymbols:A,renamedSymbols:N.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(q.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:v.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:w}}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 AJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function NJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function Y0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??AJ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-NJ(Y.heartbeat_at))/1000),H=z(Y.pid);if(H&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(H&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function Z0(_,$){_.deleteOwner($)}function X0(_,$){_.touchOwner($)}class y_{#_;#$=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 y_(_)}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 X=Y.name.indexOf(".");return{id:Y.id,filePath:Y.filePath,kind:Y.kind,name:Y.name,memberName:X>=0?Y.name.slice(X+1):null,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}},isExported:Y.isExported===1,signature:Y.signature,fingerprint:Y.fingerprint,detail:Y.detailJson?(()=>{try{return JSON.parse(Y.detailJson)}catch{return{}}})():{}}})}function q$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new O("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new O("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,W=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Y=Z?void 0:W,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((V)=>{let U;if(V.metaJson)try{U=JSON.parse(V.metaJson)}catch{}return{type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,isExternal:V.isExternal===1,specifier:V.specifier,metaJson:V.metaJson??void 0,meta:U}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let V=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((B)=>(!V||V.match(B.srcFilePath))&&(!U||B.dstFilePath===null||U.match(B.dstFilePath)))}if(Z&&W!==void 0&&H.length>W)H=H.slice(0,W);return H}import{findInFiles as qJ,Lang as uJ}from"@ast-grep/napi";function SJ(_){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(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=_.getMatch(z);if(W){let Y=W.range();J[z]={text:W.text(),startLine:Y.start.line+1,endLine:Y.end.line+1},Q=!0;continue}let Z=_.getMultipleMatches(z);if(Z.length>0){let Y=Z[0].range(),X=Z[Z.length-1].range();J[z]={text:Z.map((H)=>H.text()).join(", "),startLine:Y.start.line+1,endLine:X.end.line+1},Q=!0}}return Q?J:void 0}async function u$(_){if(_.filePaths.length===0)return[];let $=SJ(_.pattern),J=[];return await qJ(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 Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,matchedText:W.text()},X=gJ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import $_ from"typescript";import{isErr as mJ}from"@zipbul/result";import H_ from"typescript";import RJ from"path";import{err as S$}from"@zipbul/result";function TJ(_){try{return y$("fs").readFileSync(_,"utf-8")}catch{return}}function FJ(_){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??TJ,Q=$.resolveNonTrackedFile??FJ,z=RJ.dirname(_),W=J(_);if(W===void 0)return S$(new O("semantic",`tsconfig not found: ${_}`));let Z=H_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let U=Y.map((B)=>H_.flattenDiagnosticMessageText(B.messageText,`
|
|
8
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig parse error: ${U}`))}let X=H_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>J(U)!==void 0||Q(U)!==void 0,readFile:(U)=>J(U)??Q(U)},z);if(X.errors.length>0){let U=X.errors.filter((B)=>B.category===H_.DiagnosticCategory.Error&&B.code!==18003);if(U.length>0){let B=U.map((q)=>H_.flattenDiagnosticMessageText(q.messageText,`
|
|
9
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig compile error: ${B}`))}}let H=new V0(X.fileNames,X.options,z,Q),V=H_.createLanguageService(H);return new o_(V,H)}get isDisposed(){return this.#J}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#z(){if(this.#J)throw Error("TscProgram is disposed")}}class V0{#_;#$;#J;#z;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#Q.get(_);if(J)J.version+=1,J.content=$;else this.#Q.set(_,{version:1,content:$})}removeFile(_){this.#Q.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#Q.keys()];return[...[...this.#_].filter((J)=>!this.#Q.has(J)),..._]}getScriptVersion(_){let $=this.#Q.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#Q.get(_);if($)return H_.ScriptSnapshot.fromString($.content);let J=this.#z(_);if(J!==void 0)return H_.ScriptSnapshot.fromString(J);return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return H_.getDefaultLibFilePath(_)}fileExists(_){if(this.#Q.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#Q.get(_);if($)return $.content;return this.#z(_)}}import a from"typescript";import kJ from"typescript";function Q_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),W=Q.getEnd();if($<z||$>=W)return;let Z;return kJ.forEachChild(Q,(Y)=>{if(!Z)Z=J(Y)}),Z??Q}return J(_)}var t_=8;function GJ(_){return!!(_.flags&a.TypeFlags.Object)&&!!(_.objectFlags&a.ObjectFlags.Reference)}function U_(_,$,J=0,Q){if(Q){let L=Q.get($);if(L)return L}let z=_.typeToString($),W=$.flags,Z=!!(W&a.TypeFlags.Union),Y=!!(W&a.TypeFlags.Intersection),X;if(J<t_&&GJ($)){let L=_.getTypeArguments($);if(L.length>0)X=L}let H=!!(W&a.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(Z&&J<t_)V=$.types.map((L)=>U_(_,L,J+1,Q));else if(Y&&J<t_)V=$.types.map((L)=>U_(_,L,J+1,Q));let U;if(X&&X.length>0)U=X.map((L)=>U_(_,L,J+1,Q));let B;if(J<t_&&!!(W&a.TypeFlags.Object)&&!Z&&!Y){let L=_.getPropertiesOfType($);if(L.length>0&&L.length<=50){let C=$.symbol?.declarations?.[0];B=[];for(let T of L){let F=T.declarations?.[0]??C;if(!F)continue;try{let x=_.getTypeOfSymbolAtLocation(T,F);B.push({name:T.getName(),type:U_(_,x,J+1,Q)})}catch{}}if(B.length===0)B=void 0}}let q={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:H,members:V,typeArguments:U,properties:B};if(Q)Q.set($,q);return q}function jJ(_){return a.isFunctionDeclaration(_)||a.isVariableDeclaration(_)||a.isClassDeclaration(_)||a.isInterfaceDeclaration(_)||a.isTypeAliasDeclaration(_)||a.isEnumDeclaration(_)||a.isMethodDeclaration(_)||a.isPropertyDeclaration(_)||a.isPropertySignature(_)||a.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||!a.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=this.program.getChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let W=Q_(z,$);if(!W)return null;if(!a.isIdentifier(W)&&!a.isTypeNode(W))return null;try{let Z=Q.getTypeAtLocation(W);return U_(Q,Z,0,new Map)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getChecker(),W=this.program.getProgram(),Z=W.getSourceFile(_);if(!Z)return null;let Y=Q_(Z,$);if(!Y||!a.isIdentifier(Y))return null;let X=W.getSourceFile(J);if(!X)return null;let H=Q_(X,Q);if(!H||!a.isIdentifier(H))return null;try{let V=z.getTypeAtLocation(Y),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(V,U)}catch{return null}}isAssignableToType(_,$,J,Q){this.#$(J);let z=this.program.getProgram(),W=this.program.getChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=Q_(Z,$);if(!Y||!a.isIdentifier(Y)&&!a.isTypeNode(Y))return null;try{let X=this.#J(z,W);if(!X)return null;let H=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&H.isUnion())return H.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(H,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#$(J);let W=this.program.getProgram(),Z=this.program.getChecker(),Y=W.getSourceFile(_);if(!Y)return z;try{let X=this.#J(W,Z);if(!X)return z;let H=Y.getEnd();for(let V of $){if(V<0||V>=H)continue;let U=Q_(Y,V);if(!U||!a.isIdentifier(U)&&!a.isTypeNode(U))continue;try{let B=Z.getTypeAtLocation(U);if(Q?.anyConstituent&&B.isUnion())z.set(V,B.types.some((q)=>Z.isTypeAssignableTo(q,X)));else z.set(V,Z.isTypeAssignableTo(B,X))}catch{}}}catch{}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=this.program.getChecker(),W=Q.getSourceFile(_);if(!W)return J;let Z=W.getEnd(),Y=new Map;for(let X of $){if(X<0||X>=Z)continue;let H=Q_(W,X);if(!H)continue;if(!a.isIdentifier(H)&&!a.isTypeNode(H))continue;try{let V=z.getTypeAtLocation(H);J.set(X,U_(z,V,0,Y))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=this.program.getChecker(),z=J.getSourceFile(_);if(!z)return $;let W=new Map;function Z(Y){if(jJ(Y)&&Y.name&&a.isIdentifier(Y.name)){let X=Y.name;try{let H=Q.getTypeAtLocation(X),V=X.getStart(z);$.set(V,U_(Q,H,0,W))}catch{}}a.forEachChild(Y,Z)}return Z(z),$}}import M_ from"typescript";var EJ=1000,vJ=1;function bJ(_){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,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},H=_;if(H.parent)X.parent=bJ(H.parent);let V=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<vJ){let U=V.flags,B=!!(U&M_.SymbolFlags.Enum),q=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),L=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(B&&V.exports&&V.exports.size>0){let C=[];V.exports.forEach((T)=>{C.push(e_(T,$+1,J))}),X.members=C}else if(L&&V.members&&V.members.size>0){let C=[];V.members.forEach((T)=>{C.push(e_(T,$+1,J))}),X.members=C}if(q&&V.exports&&V.exports.size>0){let C=[];V.exports.forEach((T)=>{C.push(e_(T,$+1,J))}),X.exports=C}}return X}class T${#_;#$;#J=new Map;constructor(_,$=EJ){this.#_=_,this.#$=new y_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let W=this.#_.getProgram().getSourceFile(_);if(!W)return null;let Z=Q_(W,$);if(!Z||!M_.isIdentifier(Z))return null;let Y=this.#_.getChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,Y);this.#$.set(J,H);let V=this.#J.get(_);if(!V)V=new Set,this.#J.set(_,V);return V.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 fJ from"typescript";class F${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Q_(Q,$);if(!z||!fJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z)for(let H of X.references){let V=J.getSourceFile(H.fileName);if(!V)continue;let{line:U,character:B}=V.getLineAndCharacterOfPosition(H.textSpan.start);Y.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:B,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return Y}}import d from"typescript";function PJ(_,$){let J=Q_(_,$);if(!J)return;if(O0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(O0(Q))return Q;Q=Q.parent}return J}function O0(_){return d.isClassDeclaration(_)||d.isClassExpression(_)||d.isFunctionDeclaration(_)||d.isFunctionExpression(_)||d.isArrowFunction(_)||d.isVariableDeclaration(_)||d.isObjectLiteralExpression(_)}function U0(_){if(d.isClassDeclaration(_)||d.isClassExpression(_))return"class";if(d.isFunctionDeclaration(_)||d.isFunctionExpression(_)||d.isArrowFunction(_))return"function";if(d.isObjectLiteralExpression(_))return"object";if(d.isVariableDeclaration(_)&&_.initializer)return U0(_.initializer);return"class"}function yJ(_,$){if(d.isClassDeclaration(_)||d.isFunctionDeclaration(_))return _.name?.getText($)??"";if(d.isClassExpression(_))return _.name?.getText($)??"";if(d.isVariableDeclaration(_)&&d.isIdentifier(_.name))return _.name.getText($);if(d.isFunctionExpression(_))return _.name?.getText($)??"";if(d.isArrowFunction(_)&&_.parent&&d.isVariableDeclaration(_.parent)){if(d.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(d.isObjectLiteralExpression(_)&&_.parent&&d.isVariableDeclaration(_.parent)){if(d.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function xJ(_){if(!d.isClassDeclaration(_)&&!d.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===d.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Q_(Q,$);if(!z||!d.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===d.ScriptElementKind.interfaceElement||X.kind===d.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let V=PJ(H,X.textSpan.start);if(!V)continue;let U=U0(V),B=yJ(V,H),q=xJ(V);Y.push({filePath:X.fileName,symbolName:B,position:X.textSpan.start,kind:U,isExplicit:q})}return Y}}function nJ(_){if($_.isFunctionDeclaration(_))return"function";if($_.isClassDeclaration(_))return"class";if($_.isInterfaceDeclaration(_))return"interface";if($_.isTypeAliasDeclaration(_))return"type";if($_.isEnumDeclaration(_))return"enum";if($_.isVariableDeclaration(_))return"const";if($_.isVariableStatement(_))return"const";return"unknown"}function H0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class _${#_;#$;#J;#z;#Q;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#Q=z}static create(_,$={}){let J=o_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(mJ(J))return J;let Q=J,z=$.typeCollector??new R$(Q),W=$.symbolGraph??new T$(Q),Z=$.referenceResolver??new F$(Q),Y=$.implementationFinder??new k$(Q);return new _$(Q,z,W,Z,Y)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#W(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#W(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#W(),this.#$.collectAtPositions(_,$)}findReferences(_,$){return this.#W(),this.#z.findAt(_,$)}findImplementations(_,$){return this.#W(),this.#Q.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#W(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#W(),this.#$.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#W(),this.#$.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#W(),this.#J.get(_,$)}getBaseTypes(_,$){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q_(Q,$);if(!z)return null;let W=this.#_.getChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&$_.TypeFlags.Object)||!(Z.objectFlags&$_.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((H)=>U_(W,H,0,X))}getModuleInterface(_){this.#W();let $=[],Q=this.#_.getProgram().getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=this.#_.getChecker(),W=z.getSymbolAtLocation(Q);if(W){let Z=z.getExportsOfModule(W),Y=new Map;for(let X of Z){let H=X.getName(),V=X.declarations?.[0],U="unknown";if(V){if(U=nJ(V),U==="unknown"&&$_.isExportAssignment(V))U="const"}let B=null;try{let q=z.getTypeOfSymbolAtLocation(X,V??Q);B=U_(z,q,0,Y)}catch{}$.push({name:H,kind:U,resolvedType:B})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return $_.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),W=$;while(W<z.length){let Z=z.indexOf(J,W);if(Z<0)return null;let Y=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!H0(Y)&&!H0(X))return Z;W=Z+1}return null}getDiagnostics(_,$){this.#W();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[$_.DiagnosticCategory.Error]:"error",[$_.DiagnosticCategory.Warning]:"warning",[$_.DiagnosticCategory.Suggestion]:"suggestion",[$_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?$_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let H=$_.getLineAndCharacterOfPosition(Z.file,Z.start);Y=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:$_.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
+
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#$.clearProbe(),this.#_.dispose(),this.#J.clear()}#W(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as C_,and as M0,sql as hJ}from"drizzle-orm";var K0=80;class G${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+=K0)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+K0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(M0(C_(Z_.project,_),C_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(M0(_.project?C_(Z_.project,_.project):void 0,_.tag?C_(Z_.tag,_.tag):void 0,_.filePath?C_(Z_.filePath,_.filePath):void 0,_.symbolName?C_(Z_.symbolName,_.symbolName):void 0,_.source?C_(Z_.source,_.source):void 0,_.ftsQuery?hJ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as F_,and as L0,sql as x_,gt as pJ,gte as iJ}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(J_).values($.slice(J,J+w0)).run()}getSince(_){return this.db.drizzleDb.select().from(J_).where(L0(F_(J_.project,_.project),iJ(J_.changedAt,_.since),_.symbolName?F_(J_.symbolName,_.symbolName):void 0,_.changeTypes?.length?x_`${J_.changeType} IN (${x_.join(_.changeTypes.map(($)=>x_`${$}`),x_`, `)})`:void 0,_.filePath?F_(J_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:F_(J_.isFullIndex,0),_.indexRunId?F_(J_.indexRunId,_.indexRunId):void 0,_.afterId?pJ(J_.id,_.afterId):void 0)).orderBy(J_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(J_).where(L0(F_(J_.project,_),x_`${J_.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 Z=this.reverseAdjacencyList.get(z);if(Z){for(let Y of Z)this.adjacencyList.get(Y)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let W=J(z);for(let Z of W){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let W of this.adjacencyList.get(z.node)??[]){if($.has(W))return!0;if(!_.has(W))Q.push({node:W,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return sJ(J,$)}}var dJ=(_,$)=>_.localeCompare($);function lJ(_){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=lJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function cJ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Z=[],Y=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let H of _.get(X)??[])if(!z.has(H))Y(H),W.set(X,Math.min(W.get(X)??0,W.get(H)??0));else if(Q.has(H))W.set(X,Math.min(W.get(X)??0,z.get(H)??0));if(W.get(X)===z.get(X)){let H=[],V="";do V=J.pop()??"",Q.delete(V),H.push(V);while(V!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function aJ(_,$,J){let Q=[],z=new Set,W=[..._].sort(dJ),Z=(Y,X,H)=>{X.delete(Y);let V=H.get(Y);if(!V)return;for(let U of V)if(X.has(U))Z(U,X,H);V.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",H=new Set(W.slice(Y)),V=new Set,U=new Map,B=[],q=(C)=>($.get(C)??[]).filter((T)=>H.has(T)),L=(C)=>{if(Q.length>=J)return!0;let T=!1;B.push(C),V.add(C);for(let F of q(C)){if(Q.length>=J)break;if(F===X)E$(z,Q,B.concat(X)),T=!0;else if(!V.has(F)){if(L(F))T=!0}}if(T)Z(C,V,U);else for(let F of q(C)){let x=U.get(F)??new Set;x.add(C),U.set(F,x)}return B.pop(),T};L(X)}return Q}function sJ(_,$){let{components:J}=cJ(_),Q=[],z=new Set;for(let W of J){if(Q.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))E$(z,Q,[X,X]);continue}let Z=$-Q.length,Y=aJ(W,_,Z);for(let X of Y){if(Q.length>=$)break;E$(z,Q,X)}}return Q}var rJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function A_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>rJ)_.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 O("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 O)throw z;throw new O("search","Gildash: getDependencies failed",{cause:z})}}function I0(_,$,J,Q=1e4){if(_.closed)throw new O("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 O)throw z;throw new O("search","Gildash: getDependents failed",{cause:z})}}async function C0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getAffected failed",{cause:Q})}}async function A0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).hasCycle()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: hasCycle failed",{cause:J})}}async function N0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).getAdjacencyList()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getImportGraph failed",{cause:J})}}async function q0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function u0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function S0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getCyclePaths failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=A_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getFanMetrics failed",{cause:Q})}}var eJ=30000,R0=15000,_Q=10;function $Q(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??k_.basename(_.projectRoot)}function JQ(_,$){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 O?Q:new O("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 O?z:new O("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 QQ(_){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)=>$Q(_,Q),logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let W=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>W.getByType(X,"imports").concat(W.getByType(X,"type-references")).concat(W.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else J$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new H$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(JQ(_,J)).then((z)=>{if(m_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},eJ)}await J.fullIndex(),await QQ(_)}function zQ(_,$){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:Z=tJ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:H,repositoryFactory:V,acquireWatcherRoleFn:U=Y0,releaseWatcherRoleFn:B=Z0,updateHeartbeatFn:q=X0,discoverProjectsFn:L=i_,parseSourceFn:C=f_,extractSymbolsFn:T=R_,extractRelationsFn:F=s_,symbolSearchFn:x=N$,relationSearchFn:b=q$,patternSearchFn:p=u$,loadTsconfigPathsFn:s=b_,readFileFn:o=async(N)=>Bun.file(N).text(),unlinkFn:z_=async(N)=>{await Bun.file(N).unlink()},watchMode:K,semantic:u,semanticLayerFactory:D}=_;if(!k_.isAbsolute($))throw new O("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new O("validation",`Gildash: projectRoot does not exist: "${$}"`);let w=Y?Y():new Z$({projectRoot:$}),A=w.open();if(m_(A))throw A.data;try{let N=await L($),k=N[0]?.project??k_.basename($),j=V?V():(()=>{let f=w;return{fileRepo:new X$(f),symbolRepo:new V$(f),relationRepo:new O$(f),parseCache:new A$(z)}})(),v=V?null:w,M=v?new G$(v):null,I=v?new j$(v):null,g=K??!0,R=crypto.randomUUID(),m;if(g)m=await Promise.resolve(U(w,process.pid,{instanceId:R}));else m="owner";let S={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:k,role:m,db:w,symbolRepo:j.symbolRepo,relationRepo:j.relationRepo,fileRepo:j.fileRepo,parseCache:j.parseCache,annotationRepo:M,changelogRepo:I,annotationSearchFn:B0,releaseWatcherRoleFn:B,parseSourceFn:C,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:x,relationSearchFn:b,patternSearchFn:p,readFileFn:o,unlinkFn:z_,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:q,watcherFactory:X,coordinatorFactory:H,instanceId:R,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:N,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),S.tsconfigPaths=await s($),u){let f=k_.join($,"tsconfig.json");try{if(D)S.semanticLayer=D(f);else{let G=_$.create(f);if(m_(G))throw G.data;S.semanticLayer=G}}catch(G){if(G instanceof O)throw G;throw new O("semantic","Gildash: semantic layer creation failed",{cause:G})}}if(m==="owner")await T0(S,{isWatchMode:g});else{let f=0,G=async()=>{try{let i=await Promise.resolve(S.acquireWatcherRoleFn(S.db,process.pid,{instanceId:S.instanceId}));if(f=0,i==="owner"){S.role="owner";for(let y of S.onRoleChangedCallbacks)try{y("owner")}catch(l){S.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(S.timer),S.timer=null;try{await T0(S,{isWatchMode:!0})}catch(y){if(S.logger.error("[Gildash] owner promotion failed, reverting to reader",y),S.role="reader",S.timer!==null)clearInterval(S.timer),S.timer=null;if(S.watcher){let l=await S.watcher.close();if(m_(l))S.logger.error("[Gildash] watcher close error during promotion rollback",l.data);S.watcher=null}if(S.coordinator)await S.coordinator.shutdown().catch((l)=>S.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),S.coordinator=null;try{S.releaseWatcherRoleFn(S.db,process.pid)}catch(l){S.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}S.timer=setInterval(G,R0)}}}catch(i){f++;let y=i instanceof O?i:new O("watcher","Gildash: healthcheck error",{cause:i});for(let l of S.onErrorCallbacks)try{l(y)}catch(K_){S.logger.error("[Gildash] onError callback threw:",K_)}if(S.logger.error("[Gildash] healthcheck error",i),f>=_Q)S.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(S.timer),S.timer=null,Q$(S).catch((l)=>S.logger.error("[Gildash] close error during healthcheck shutdown",l))}};S.timer=setInterval(G,R0)}if(g)zQ(S,()=>Q$(S));return S}catch(N){if(w.close(),N instanceof O)throw N;throw new O("store","Gildash: initialization failed",{cause:N})}}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(m_(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,L_,h_+Q))}catch{}if(J.length>0)throw new O("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function G0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(k0(z))throw z.data;return _.parseCache.set($,z),z}async function j0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Z=await _.readFileFn(W),Y=_.parseSourceFn(W,Z,J);if(!k0(Y))Q.set(W,Y);else z.push({filePath:W,error:Y.data})}catch(Z){z.push({filePath:W,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function E0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.parseCache.get($)}function v0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function b0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import f0 from"path";function P0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getStats failed",{cause:J})}}function v$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchSymbols failed",{cause:J})}}function y0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchRelations failed",{cause:J})}}function x0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllSymbols failed",{cause:J})}}function m0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllRelations failed",{cause:J})}}function n0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: listIndexedFiles failed",{cause:J})}}function h0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getInternalRelations failed",{cause:Q})}}function p0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Z=W[0],Y=Z.detail,X={...Z,members:Y.members,jsDoc:Y.jsDoc,parameters:Y.parameters,returnType:Y.returnType,heritage:Y.heritage,decorators:Y.decorators,typeParameters:Y.typeParameters,initializer:Y.initializer};if(_.semanticLayer)try{let H=f0.isAbsolute(J)?J:f0.resolve(_.projectRoot,J),V=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(V!==null){let U=_.semanticLayer.findNamePosition(H,V,Z.name)??V,B=_.semanticLayer.collectTypeAt(H,U);if(B)X.resolvedType=B}}catch{}return X}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getFullSymbol failed",{cause:z})}}function i0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new O("search",`Gildash: file '${$}' is not in the index`);let W=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Y)=>Y.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileStats failed",{cause:Q})}}function d0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof O)throw Q;throw new O("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 O("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getModuleInterface failed",{cause:Q})}}import n from"path";function n_(_,$,J,Q){let z=Q??_.defaultProject,W=n.isAbsolute(J)?n.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:W,limit:1}});if(Z.length===0)return null;let Y=Z[0],X=n.isAbsolute(J)?J:n.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(H===null)return null;let V=_.semanticLayer.findNamePosition(X,H,Y.name)??H;return{sym:Y,position:V,absPath:X}}function a0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getResolvedType failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getSemanticReferences failed",{cause:z})}}function r0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getImplementations failed",{cause:z})}}function o0(_,$,J,Q,z,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Z=n_(_,$,J,W);if(!Z)throw new O("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=n_(_,Q,z,W);if(!Y)throw new O("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,Y.absPath,Y.position)}catch(Z){if(Z instanceof O)throw Z;throw new O("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function t0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getFileTypes failed",{cause:J})}}function e0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function _1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=n.isAbsolute($.source.filePath)?$.source.filePath:n.resolve(_.projectRoot,$.source.filePath),Q=n.isAbsolute($.target.filePath)?$.target.filePath:n.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 O)throw J;throw new O("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function $1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function J1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function W1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function Y1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function Z1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$),Z=n.isAbsolute(Q)?Q:n.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function X1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function V1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function O1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function U1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: findNamePosition failed",{cause:z})}}function H1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function M1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function K1(_,$){let J=new Map(_.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),Q=new Map($.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),z=[],W=[],Z=[];for(let[Y,X]of Q){let H=J.get(Y);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,after:X})}for(let[Y,X]of J)if(!Q.has(Y))W.push(X);return{added:z,removed:W,modified:Z}}function L1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function w1(_){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.coordinator)throw new O("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return J$(_),$}catch($){if($ instanceof O)throw $;throw new O("index","Gildash: reindex failed",{cause:$})}}function B1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let H=`${X}::${Y}`;if(W.has(H))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(H);let V=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,B;for(let q of V){let L;if(q.metaJson)try{let T=JSON.parse(q.metaJson);if(Array.isArray(T.specifiers))L=T.specifiers}catch{}if(!L)continue;let C=L.find((T)=>T.exported===Y);if(!C)continue;U=q.dstFilePath??void 0,B=C.local;break}if(!U||!B)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=U,Y=B}}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 O("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 O)throw Q;throw new O("search","Gildash: findPattern failed",{cause:Q})}}async function N1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(Y,X,H)=>{let V=`${Y}::${X}`;if(W.has(V))return{symbolName:Y,filePath:X,kind:H,children:[]};W.add(V);let q=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((L)=>L.type==="extends"||L.type==="implements").filter((L)=>L.dstSymbolName!=null&&L.dstFilePath!=null).map((L)=>Z(L.dstSymbolName,L.dstFilePath,L.type));return{symbolName:Y,filePath:X,kind:H,children:q}};return Z($,J)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getHeritageChain failed",{cause:z})}}function q1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function u1(_,$,J){if(_.closed)throw new O("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 S1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],W=[...new Set(z)];for(let Z of W)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class 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 G0(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 p0(this._ctx,_,$,J)}getFileStats(_,$){return i0(this._ctx,_,$)}getFileInfo(_,$){return d0(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 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 V1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return O1(this._ctx,_,$,J)}findNamePosition(_,$,J){return U1(this._ctx,_,$,J)}getSymbolNode(_,$){return H1(this._ctx,_,$)}getBaseTypes(_,$){return J1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return M1(this._ctx,_,$)}diffSymbols(_,$){return K1(_,$)}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 Y3,visitorKeys as Z3}from"oxc-parser";export{Z3 as visitorKeys,N$ as symbolSearch,q$ as relationSearch,u$ as patternSearch,Y_ as normalizePath,X_ as getLineColumn,P_ as buildLineOffsets,Y3 as Visitor,O as GildashError,b$ as Gildash,$$ as DependencyGraph};
|
|
@@ -5,4 +5,4 @@ export { extractImports } from './imports-extractor';
|
|
|
5
5
|
export { extractCalls } from './calls-extractor';
|
|
6
6
|
export { extractHeritage } from './heritage-extractor';
|
|
7
7
|
export { resolveImport, buildImportMap } from './extractor-utils';
|
|
8
|
-
export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, JsDocBlock, JsDocTag, ImportReference, QualifiedName, AnnotationSource, ExtractedAnnotation, } from './types';
|
|
8
|
+
export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, ExpressionValue, ExpressionLiteral, ExpressionIdentifier, ExpressionMember, ExpressionCall, ExpressionNew, ExpressionObject, ExpressionObjectProperty, ExpressionArray, ExpressionSpread, ExpressionFunction, ExpressionTemplate, ExpressionUnresolvable, JsDocBlock, JsDocTag, ImportReference, QualifiedName, AnnotationSource, ExtractedAnnotation, } from './types';
|
|
@@ -1,4 +1,68 @@
|
|
|
1
1
|
import type { SourcePosition, SourceSpan } from '../parser/types';
|
|
2
|
+
/**
|
|
3
|
+
* A structured representation of a JavaScript/TypeScript expression.
|
|
4
|
+
*
|
|
5
|
+
* Used for decorator arguments, variable initializers, enum member values,
|
|
6
|
+
* and property initializers — anywhere an expression's structure matters
|
|
7
|
+
* beyond its raw source text.
|
|
8
|
+
*
|
|
9
|
+
* The extractor does **not** resolve imports; use relation queries for that.
|
|
10
|
+
*/
|
|
11
|
+
export type ExpressionValue = ExpressionLiteral | ExpressionIdentifier | ExpressionMember | ExpressionCall | ExpressionNew | ExpressionObject | ExpressionArray | ExpressionSpread | ExpressionFunction | ExpressionTemplate | ExpressionUnresolvable;
|
|
12
|
+
export interface ExpressionLiteral {
|
|
13
|
+
kind: 'string' | 'number' | 'boolean' | 'null' | 'undefined';
|
|
14
|
+
value: string | number | boolean | null;
|
|
15
|
+
}
|
|
16
|
+
export interface ExpressionIdentifier {
|
|
17
|
+
kind: 'identifier';
|
|
18
|
+
name: string;
|
|
19
|
+
}
|
|
20
|
+
export interface ExpressionMember {
|
|
21
|
+
kind: 'member';
|
|
22
|
+
/** Full dot-separated expression text, e.g. `'HttpMethod.Get'`. */
|
|
23
|
+
object: string;
|
|
24
|
+
property: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ExpressionCall {
|
|
27
|
+
kind: 'call';
|
|
28
|
+
callee: string;
|
|
29
|
+
arguments: ExpressionValue[];
|
|
30
|
+
}
|
|
31
|
+
export interface ExpressionNew {
|
|
32
|
+
kind: 'new';
|
|
33
|
+
callee: string;
|
|
34
|
+
arguments: ExpressionValue[];
|
|
35
|
+
}
|
|
36
|
+
export interface ExpressionObject {
|
|
37
|
+
kind: 'object';
|
|
38
|
+
properties: ExpressionObjectProperty[];
|
|
39
|
+
}
|
|
40
|
+
export interface ExpressionObjectProperty {
|
|
41
|
+
key: string;
|
|
42
|
+
value: ExpressionValue;
|
|
43
|
+
computed?: boolean;
|
|
44
|
+
shorthand?: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface ExpressionArray {
|
|
47
|
+
kind: 'array';
|
|
48
|
+
elements: ExpressionValue[];
|
|
49
|
+
}
|
|
50
|
+
export interface ExpressionSpread {
|
|
51
|
+
kind: 'spread';
|
|
52
|
+
argument: ExpressionValue;
|
|
53
|
+
}
|
|
54
|
+
export interface ExpressionFunction {
|
|
55
|
+
kind: 'function';
|
|
56
|
+
sourceText: string;
|
|
57
|
+
}
|
|
58
|
+
export interface ExpressionTemplate {
|
|
59
|
+
kind: 'template';
|
|
60
|
+
sourceText: string;
|
|
61
|
+
}
|
|
62
|
+
export interface ExpressionUnresolvable {
|
|
63
|
+
kind: 'unresolvable';
|
|
64
|
+
sourceText: string;
|
|
65
|
+
}
|
|
2
66
|
/**
|
|
3
67
|
* The kind of a symbol extracted from TypeScript source.
|
|
4
68
|
*
|
|
@@ -49,8 +113,8 @@ export interface Heritage {
|
|
|
49
113
|
export interface Decorator {
|
|
50
114
|
/** Decorator name without `@`. */
|
|
51
115
|
name: string;
|
|
52
|
-
/**
|
|
53
|
-
arguments?:
|
|
116
|
+
/** Structured decorator call arguments. */
|
|
117
|
+
arguments?: ExpressionValue[];
|
|
54
118
|
}
|
|
55
119
|
/**
|
|
56
120
|
* A single JSDoc tag parsed from a documentation comment.
|
|
@@ -113,6 +177,8 @@ export interface ExtractedSymbol {
|
|
|
113
177
|
heritage?: Heritage[];
|
|
114
178
|
/** Decorators applied to this symbol. */
|
|
115
179
|
decorators?: Decorator[];
|
|
180
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
181
|
+
initializer?: ExpressionValue;
|
|
116
182
|
/** Nested members (class fields, methods, interface properties, enum members). */
|
|
117
183
|
members?: ExtractedSymbol[];
|
|
118
184
|
/** Parsed JSDoc comment associated with this symbol. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ParsedFile } from '../parser/types';
|
|
2
2
|
import type { SymbolSearchResult, SymbolDetail } from '../search/symbol-search';
|
|
3
|
-
import type { SymbolKind, Decorator } from '../extractor/types';
|
|
3
|
+
import type { SymbolKind, Decorator, ExpressionValue } from '../extractor/types';
|
|
4
4
|
import type { ResolvedType } from '../semantic/types';
|
|
5
5
|
/**
|
|
6
6
|
* Minimal logger interface accepted by {@link Gildash}.
|
|
@@ -70,6 +70,8 @@ export interface FullSymbol extends SymbolSearchResult {
|
|
|
70
70
|
decorators?: Decorator[];
|
|
71
71
|
/** Generic type parameter names. */
|
|
72
72
|
typeParameters?: string[];
|
|
73
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
74
|
+
initializer?: ExpressionValue;
|
|
73
75
|
/** Resolved type from the Semantic Layer (available when `semantic: true`). */
|
|
74
76
|
resolvedType?: ResolvedType;
|
|
75
77
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -8,10 +8,10 @@ export { relationSearch } from "./search/relation-search";
|
|
|
8
8
|
export type { RelationSearchQuery, StoredCodeRelation } from "./search/relation-search";
|
|
9
9
|
export { DependencyGraph } from "./search/dependency-graph";
|
|
10
10
|
export { patternSearch } from "./search/pattern-search";
|
|
11
|
-
export type { PatternMatch } from "./search/pattern-search";
|
|
11
|
+
export type { PatternMatch, PatternCapture } from "./search/pattern-search";
|
|
12
12
|
export type { IndexResult } from "./indexer/index-coordinator";
|
|
13
13
|
export type { ProjectBoundary } from "./common/project-discovery";
|
|
14
|
-
export type { CodeRelation, ExtractedSymbol, SymbolKind, Decorator, Parameter, Heritage, Modifier, JsDocBlock, JsDocTag } from "./extractor/types";
|
|
14
|
+
export type { CodeRelation, ExtractedSymbol, SymbolKind, Decorator, Parameter, Heritage, Modifier, JsDocBlock, JsDocTag, ExpressionValue, ExpressionLiteral, ExpressionIdentifier, ExpressionMember, ExpressionCall, ExpressionNew, ExpressionObject, ExpressionObjectProperty, ExpressionArray, ExpressionSpread, ExpressionFunction, ExpressionTemplate, ExpressionUnresolvable } from "./extractor/types";
|
|
15
15
|
export type { SymbolStats } from "./store/repositories/symbol.repository";
|
|
16
16
|
export type { WatcherRole, FileChangeEvent } from "./watcher/types";
|
|
17
17
|
export type { ParsedFile } from "./parser/types";
|
|
@@ -5,6 +5,6 @@ export type { RelationSearchQuery, IRelationRepo } from './relation-search';
|
|
|
5
5
|
export { DependencyGraph } from './dependency-graph';
|
|
6
6
|
export type { IDependencyGraphRepo } from './dependency-graph';
|
|
7
7
|
export { patternSearch } from './pattern-search';
|
|
8
|
-
export type { PatternMatch, PatternSearchOptions } from './pattern-search';
|
|
8
|
+
export type { PatternMatch, PatternCapture, PatternSearchOptions } from './pattern-search';
|
|
9
9
|
export { annotationSearch } from './annotation-search';
|
|
10
10
|
export type { AnnotationSearchQuery, AnnotationSearchResult, IAnnotationRepo } from './annotation-search';
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A captured metavariable from an ast-grep pattern match.
|
|
3
|
+
*/
|
|
4
|
+
export interface PatternCapture {
|
|
5
|
+
/** Source text of the captured node. */
|
|
6
|
+
text: string;
|
|
7
|
+
/** 1-based start line number. */
|
|
8
|
+
startLine: number;
|
|
9
|
+
/** 1-based end line number. */
|
|
10
|
+
endLine: number;
|
|
11
|
+
}
|
|
1
12
|
/**
|
|
2
13
|
* A single structural-pattern match found in a source file.
|
|
3
14
|
*/
|
|
@@ -10,6 +21,8 @@ export interface PatternMatch {
|
|
|
10
21
|
endLine: number;
|
|
11
22
|
/** Source text of the matched node. */
|
|
12
23
|
matchedText: string;
|
|
24
|
+
/** Named captures from metavariables in the pattern (e.g. `$METHOD`, `$$$ARGS`). */
|
|
25
|
+
captures?: Record<string, PatternCapture>;
|
|
13
26
|
}
|
|
14
27
|
/**
|
|
15
28
|
* Options for {@link patternSearch}.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SymbolKind, Modifier, Decorator, JsDocBlock } from '../extractor/types';
|
|
1
|
+
import type { SymbolKind, Modifier, Decorator, JsDocBlock, ExpressionValue } from '../extractor/types';
|
|
2
2
|
import type { SymbolRecord } from '../store/repositories/symbol.repository';
|
|
3
3
|
/**
|
|
4
4
|
* Filters for {@link symbolSearch}.
|
|
@@ -66,6 +66,8 @@ export interface SymbolDetail {
|
|
|
66
66
|
typeParameters?: string[];
|
|
67
67
|
/** Declaration modifiers. */
|
|
68
68
|
modifiers?: Modifier[];
|
|
69
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
70
|
+
initializer?: ExpressionValue;
|
|
69
71
|
/** Class/interface members. */
|
|
70
72
|
members?: Array<{
|
|
71
73
|
name: string;
|
|
@@ -74,6 +76,10 @@ export interface SymbolDetail {
|
|
|
74
76
|
visibility?: string;
|
|
75
77
|
isStatic?: boolean;
|
|
76
78
|
isReadonly?: boolean;
|
|
79
|
+
/** Member initializer expression. */
|
|
80
|
+
initializer?: ExpressionValue;
|
|
81
|
+
/** Decorators applied to this member. */
|
|
82
|
+
decorators?: Decorator[];
|
|
77
83
|
}>;
|
|
78
84
|
/** Parsed JSDoc comment associated with this symbol. */
|
|
79
85
|
jsDoc?: JsDocBlock;
|
|
@@ -16,8 +16,11 @@ import type { TscProgram } from "./tsc-program";
|
|
|
16
16
|
*/
|
|
17
17
|
export declare function buildResolvedType(checker: ts.TypeChecker, type: ts.Type, depth?: number, seen?: Map<ts.Type, ResolvedType>): ResolvedType;
|
|
18
18
|
export declare class TypeCollector {
|
|
19
|
+
#private;
|
|
19
20
|
private readonly program;
|
|
20
21
|
constructor(program: TscProgram);
|
|
22
|
+
/** 캐시된 probe 파일을 제거한다. dispose 시 호출. */
|
|
23
|
+
clearProbe(): void;
|
|
21
24
|
/**
|
|
22
25
|
* `filePath`의 `position` 위치(0-based 문자 오프셋)에 있는 노드의 타입을 수집한다.
|
|
23
26
|
*
|