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