@zipbul/gildash 0.5.1 → 0.6.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.
Files changed (40) hide show
  1. package/README.ko.md +28 -6
  2. package/README.md +29 -5
  3. package/dist/index.js +7 -5
  4. package/dist/index.js.map +42 -28
  5. package/dist/migrations/0003_majestic_mongu.sql +1 -0
  6. package/dist/migrations/0004_cool_firestar.sql +23 -0
  7. package/dist/migrations/meta/0003_snapshot.json +422 -0
  8. package/dist/migrations/meta/0004_snapshot.json +429 -0
  9. package/dist/migrations/meta/_journal.json +14 -0
  10. package/dist/src/errors.d.ts +1 -1
  11. package/dist/src/extractor/relation-extractor.d.ts +2 -1
  12. package/dist/src/gildash/context.d.ts +91 -0
  13. package/dist/src/gildash/extract-api.d.ts +9 -0
  14. package/dist/src/gildash/graph-api.d.ts +30 -0
  15. package/dist/src/gildash/index.d.ts +92 -0
  16. package/dist/src/gildash/lifecycle.d.ts +62 -0
  17. package/dist/src/gildash/misc-api.d.ts +22 -0
  18. package/dist/src/gildash/parse-api.d.ts +11 -0
  19. package/dist/src/gildash/query-api.d.ts +35 -0
  20. package/dist/src/gildash/semantic-api.d.ts +22 -0
  21. package/dist/src/gildash/types.d.ts +160 -0
  22. package/dist/src/index.d.ts +2 -1
  23. package/dist/src/indexer/index-coordinator.d.ts +8 -2
  24. package/dist/src/indexer/relation-indexer.d.ts +6 -0
  25. package/dist/src/search/dependency-graph.d.ts +1 -0
  26. package/dist/src/search/relation-search.d.ts +11 -1
  27. package/dist/src/search/symbol-search.d.ts +6 -0
  28. package/dist/src/semantic/ast-node-utils.d.ts +9 -0
  29. package/dist/src/semantic/implementation-finder.d.ts +22 -0
  30. package/dist/src/semantic/index.d.ts +68 -0
  31. package/dist/src/semantic/reference-resolver.d.ts +19 -0
  32. package/dist/src/semantic/symbol-graph.d.ts +36 -0
  33. package/dist/src/semantic/tsc-program.d.ts +67 -0
  34. package/dist/src/semantic/type-collector.d.ts +27 -0
  35. package/dist/src/semantic/types.d.ts +103 -0
  36. package/dist/src/store/repositories/relation.repository.d.ts +14 -2
  37. package/dist/src/store/repositories/symbol.repository.d.ts +2 -0
  38. package/dist/src/store/schema.d.ts +38 -0
  39. package/package.json +3 -2
  40. package/dist/src/gildash.d.ts +0 -821
package/README.ko.md CHANGED
@@ -32,9 +32,8 @@ gildash는 TypeScript 코드베이스를 로컬 SQLite 데이터베이스에 인
32
32
  - **심볼 레벨 diff** — `IndexResult`의 `changedSymbols`로 인덱싱 사이클 당 추가/수정/삭제된 심볼 추적
33
33
  - **멀티 프로세스 안전** — owner/reader 역할 분리로 단일 writer 보장
34
34
  - **스캔 전용 모드** — `watchMode: false`로 파일 워처 없이 1회성 인덱싱
35
- - **외부 패키지 인덱싱** — `node_modules`의 `.d.ts` 타입 선언 인덱싱
36
35
  - **tsconfig.json JSONC** — `tsconfig.json`의 주석(`//`, `/* */`)과 트레일링 콤마를 지원하는 경로 별칭 파싱
37
-
36
+ - **시맨틱 레이어 (opt-in)** — tsc TypeChecker 통합으로 resolved type, 참조, 구현체, 모듈 인터페이스 분석
38
37
  <br>
39
38
 
40
39
  ## 📋 요구사항
@@ -229,9 +228,12 @@ if (isErr(result)) {
229
228
  | `parseCacheCapacity` | `number` | `500` | LRU 파싱 캐시 최대 크기 |
230
229
  | `logger` | `Logger` | `console` | 커스텀 로거 (`{ error(...args): void }`) |
231
230
  | `watchMode` | `boolean` | `true` | `false`이면 파일 워처 비활성화 (스캔 전용 모드) |
231
+ | `semantic` | `boolean` | `false` | tsc TypeChecker 기반 시맨틱 분석 활성화 |
232
232
 
233
233
  **반환**: `Promise<Gildash>` (`Result`로 래핑됨)
234
234
 
235
+ > **참고:** `semantic: true`는 프로젝트 루트에 `tsconfig.json`이 필요합니다. 없으면 `Gildash.open()`이 `GildashError`를 반환합니다.
236
+
235
237
  <br>
236
238
 
237
239
  ## 🔍 API 레퍼런스
@@ -241,9 +243,9 @@ if (isErr(result)) {
241
243
  | 메서드 | 반환 타입 | 설명 |
242
244
  |--------|-----------|------|
243
245
  | `searchSymbols(query)` | `Result<SymbolSearchResult[]>` | FTS5 전문검색 + exact/regex/decorator 필터 |
244
- | `searchRelations(query)` | `Result<CodeRelation[]>` | 파일, 심볼, 관계 유형 필터 |
246
+ | `searchRelations(query)` | `Result<StoredCodeRelation[]>` | 파일, 심볼, 관계 유형 필터 |
245
247
  | `searchAllSymbols(query)` | `Result<SymbolSearchResult[]>` | 전체 프로젝트 심볼 검색 |
246
- | `searchAllRelations(query)` | `Result<CodeRelation[]>` | 전체 프로젝트 관계 검색 |
248
+ | `searchAllRelations(query)` | `Result<StoredCodeRelation[]>` | 전체 프로젝트 관계 검색 |
247
249
  | `listIndexedFiles(project?)` | `Result<FileRecord[]>` | 인덱싱된 파일 목록 |
248
250
  | `getSymbolsByFile(filePath)` | `Result<SymbolSearchResult[]>` | 단일 파일의 모든 심볼 |
249
251
 
@@ -267,9 +269,23 @@ if (isErr(result)) {
267
269
  | `getFileStats(filePath)` | `Result<FileStats>` | 라인 수, 심볼 수, 파일 크기 |
268
270
  | `getFanMetrics(filePath)` | `Promise<Result<FanMetrics>>` | fan-in/fan-out 결합도 |
269
271
  | `getModuleInterface(filePath)` | `Result<ModuleInterface>` | 공개 export와 메타데이터 |
270
- | `getInternalRelations(filePath)` | `Result<CodeRelation[]>` | 파일 내부 관계 |
272
+ | `getInternalRelations(filePath)` | `Result<StoredCodeRelation[]>` | 파일 내부 관계 |
271
273
  | `diffSymbols(before, after)` | `SymbolDiff` | 스냅샷 diff (추가/삭제/수정) |
272
274
 
275
+ ### 시맨틱 (opt-in)
276
+
277
+ `semantic: true`로 열어야 사용 가능.
278
+
279
+ | 메서드 | 반환 타입 | 설명 |
280
+ |--------|-----------|------|
281
+ | `getResolvedType(name, filePath)` | `Result<ResolvedType \| null>` | tsc TypeChecker로 resolved type 조회 |
282
+ | `getSemanticReferences(name, filePath)` | `Result<SemanticReference[]>` | 심볼의 모든 참조 위치 |
283
+ | `getImplementations(name, filePath)` | `Result<Implementation[]>` | 인터페이스/추상 클래스 구현체 |
284
+ | `getSemanticModuleInterface(filePath)` | `Result<SemanticModuleInterface>` | 모듈 export 목록 + resolved type |
285
+
286
+ `getFullSymbol()`은 semantic 활성 시 자동으로 `resolvedType` 필드를 보강합니다.
287
+ `searchSymbols({ resolvedType })`로 resolved type 문자열 기반 필터링이 가능합니다.
288
+
273
289
  ### 고급
274
290
 
275
291
  | 메서드 | 반환 타입 | 설명 |
@@ -277,7 +293,6 @@ if (isErr(result)) {
277
293
  | `findPattern(pattern, opts?)` | `Promise<Result<PatternMatch[]>>` | AST 구조적 검색 (ast-grep) |
278
294
  | `resolveSymbol(name, filePath)` | `Result<ResolvedSymbol>` | re-export 체인을 따라 원본 추적 |
279
295
  | `getHeritageChain(name, filePath)` | `Promise<Result<HeritageNode>>` | extends/implements 트리 |
280
- | `indexExternalPackages(packages)` | `Promise<Result<IndexResult[]>>` | `node_modules`의 `.d.ts` 인덱싱 |
281
296
  | `batchParse(filePaths, opts?)` | `Promise<Result<Map>>` | 다중 파일 동시 파싱. `opts`: oxc-parser `ParserOptions`. |
282
297
 
283
298
  ### 라이프사이클 & 저수준
@@ -326,6 +341,11 @@ interface CodeRelation {
326
341
  meta?: Record<string, unknown>;
327
342
  }
328
343
 
344
+ /** 목적지 프로젝트 식별자가 추가된 CodeRelation */
345
+ interface StoredCodeRelation extends CodeRelation {
346
+ dstProject: string;
347
+ }
348
+
329
349
  interface IndexResult {
330
350
  indexedFiles: number;
331
351
  removedFiles: number;
@@ -364,6 +384,7 @@ interface GildashError {
364
384
  | `store` | DB 연산 실패 |
365
385
  | `search` | 검색 쿼리 실패 |
366
386
  | `closed` | 종료된 인스턴스에서 연산 시도 |
387
+ | `semantic` | 시맨틱 레이어 미활성화 또는 tsc 에러 |
367
388
  | `validation` | 잘못된 입력 (e.g. `node_modules`에 패키지 없음) |
368
389
  | `close` | 종료 중 에러 |
369
390
 
@@ -378,6 +399,7 @@ Gildash (파사드)
378
399
  ├── Store — bun:sqlite + drizzle-orm (files · symbols · relations · FTS5), `.gildash/gildash.db`에 저장
379
400
  ├── Indexer — 파일 변경 → 파싱 → 추출 → 저장 파이프라인, 심볼 레벨 diff
380
401
  ├── Search — FTS + regex + decorator 검색, 관계 쿼리, 의존성 그래프, ast-grep
402
+ ├── Semantic — tsc TypeChecker 통합 (opt-in): 타입, 참조, 구현체
381
403
  └── Watcher — @parcel/watcher + owner/reader 역할 관리
382
404
  ```
383
405
 
package/README.md CHANGED
@@ -32,8 +32,8 @@ gildash indexes your TypeScript codebase into a local SQLite database, then lets
32
32
  - **Symbol-level diff** — `changedSymbols` in `IndexResult` tracks added/modified/removed symbols per index cycle
33
33
  - **Multi-process safe** — Owner/reader role separation guarantees a single writer per database
34
34
  - **Scan-only mode** — `watchMode: false` for one-shot indexing without file watcher overhead
35
- - **External package indexing** — Index `.d.ts` type declarations from `node_modules`
36
35
  - **tsconfig.json JSONC** — Path alias resolution parses comments and trailing commas in `tsconfig.json`
36
+ - **Semantic layer (opt-in)** — tsc TypeChecker integration for resolved types, references, implementations, and module interface analysis
37
37
 
38
38
  <br>
39
39
 
@@ -229,9 +229,12 @@ if (isErr(result)) {
229
229
  | `parseCacheCapacity` | `number` | `500` | LRU parse-cache capacity |
230
230
  | `logger` | `Logger` | `console` | Custom logger (`{ error(...args): void }`) |
231
231
  | `watchMode` | `boolean` | `true` | `false` disables the file watcher (scan-only mode) |
232
+ | `semantic` | `boolean` | `false` | Enable tsc TypeChecker-backed semantic analysis |
232
233
 
233
234
  Returns `Promise<Gildash>` (wrapped in `Result`).
234
235
 
236
+ > **Note:** `semantic: true` requires a `tsconfig.json` in the project root. If not found, `Gildash.open()` returns a `GildashError`.
237
+
235
238
  <br>
236
239
 
237
240
  ## 🔍 API Reference
@@ -241,9 +244,9 @@ Returns `Promise<Gildash>` (wrapped in `Result`).
241
244
  | Method | Returns | Description |
242
245
  |--------|---------|-------------|
243
246
  | `searchSymbols(query)` | `Result<SymbolSearchResult[]>` | FTS5 full-text + exact / regex / decorator filters |
244
- | `searchRelations(query)` | `Result<CodeRelation[]>` | Filter by file, symbol, or relation type |
247
+ | `searchRelations(query)` | `Result<StoredCodeRelation[]>` | Filter by file, symbol, or relation type |
245
248
  | `searchAllSymbols(query)` | `Result<SymbolSearchResult[]>` | Cross-project symbol search |
246
- | `searchAllRelations(query)` | `Result<CodeRelation[]>` | Cross-project relation search |
249
+ | `searchAllRelations(query)` | `Result<StoredCodeRelation[]>` | Cross-project relation search |
247
250
  | `listIndexedFiles(project?)` | `Result<FileRecord[]>` | All indexed files for a project |
248
251
  | `getSymbolsByFile(filePath)` | `Result<SymbolSearchResult[]>` | All symbols in a single file |
249
252
 
@@ -267,9 +270,23 @@ Returns `Promise<Gildash>` (wrapped in `Result`).
267
270
  | `getFileStats(filePath)` | `Result<FileStats>` | Line count, symbol count, size |
268
271
  | `getFanMetrics(filePath)` | `Promise<Result<FanMetrics>>` | Fan-in / fan-out coupling |
269
272
  | `getModuleInterface(filePath)` | `Result<ModuleInterface>` | Public exports with metadata |
270
- | `getInternalRelations(filePath)` | `Result<CodeRelation[]>` | Intra-file relations |
273
+ | `getInternalRelations(filePath)` | `Result<StoredCodeRelation[]>` | Intra-file relations |
271
274
  | `diffSymbols(before, after)` | `SymbolDiff` | Snapshot diff (added / removed / modified) |
272
275
 
276
+ ### Semantic (opt-in)
277
+
278
+ Requires `semantic: true` at open time.
279
+
280
+ | Method | Returns | Description |
281
+ |--------|---------|-------------|
282
+ | `getResolvedType(name, filePath)` | `Result<ResolvedType \| null>` | Resolved type via tsc TypeChecker |
283
+ | `getSemanticReferences(name, filePath)` | `Result<SemanticReference[]>` | All references to a symbol |
284
+ | `getImplementations(name, filePath)` | `Result<Implementation[]>` | Interface / abstract class implementations |
285
+ | `getSemanticModuleInterface(filePath)` | `Result<SemanticModuleInterface>` | Module exports with resolved types |
286
+
287
+ `getFullSymbol()` automatically enriches the result with a `resolvedType` field when semantic is enabled.
288
+ `searchSymbols({ resolvedType })` filters symbols by their resolved type string.
289
+
273
290
  ### Advanced
274
291
 
275
292
  | Method | Returns | Description |
@@ -277,7 +294,6 @@ Returns `Promise<Gildash>` (wrapped in `Result`).
277
294
  | `findPattern(pattern, opts?)` | `Promise<Result<PatternMatch[]>>` | AST structural search (ast-grep) |
278
295
  | `resolveSymbol(name, filePath)` | `Result<ResolvedSymbol>` | Follow re-export chain to original |
279
296
  | `getHeritageChain(name, filePath)` | `Promise<Result<HeritageNode>>` | extends / implements tree |
280
- | `indexExternalPackages(packages)` | `Promise<Result<IndexResult[]>>` | Index `.d.ts` from `node_modules` |
281
297
  | `batchParse(filePaths, opts?)` | `Promise<Result<Map>>` | Concurrent multi-file parsing. `opts`: oxc-parser `ParserOptions`. |
282
298
 
283
299
  ### Lifecycle & Low-level
@@ -332,6 +348,7 @@ interface RelationSearchQuery {
332
348
  srcSymbolName?: string;
333
349
  dstFilePath?: string;
334
350
  dstSymbolName?: string;
351
+ dstProject?: string; // filter by destination project
335
352
  type?: 'imports' | 'type-references' | 're-exports' | 'calls' | 'extends' | 'implements';
336
353
  project?: string;
337
354
  limit?: number; // default: 500
@@ -347,6 +364,11 @@ interface CodeRelation {
347
364
  meta?: Record<string, unknown>; // auto-parsed from metaJson
348
365
  }
349
366
 
367
+ /** CodeRelation enriched with the destination project identifier. */
368
+ interface StoredCodeRelation extends CodeRelation {
369
+ dstProject: string;
370
+ }
371
+
350
372
  // ── Analysis ────────────────────────────────────────────────────────────
351
373
 
352
374
  interface FullSymbol extends SymbolSearchResult {
@@ -472,6 +494,7 @@ interface GildashError {
472
494
  | `store` | Database operation failure |
473
495
  | `search` | Search query failure |
474
496
  | `closed` | Operation on a closed instance |
497
+ | `semantic` | Semantic layer not enabled or tsc error |
475
498
  | `validation` | Invalid input (e.g. missing `node_modules` package) |
476
499
  | `close` | Error during shutdown |
477
500
 
@@ -486,6 +509,7 @@ Gildash (Facade)
486
509
  ├── Store — bun:sqlite + drizzle-orm (files · symbols · relations · FTS5) at `.gildash/gildash.db`
487
510
  ├── Indexer — File change → parse → extract → store pipeline, symbol-level diff
488
511
  ├── Search — FTS + regex + decorator search, relation queries, dependency graph, ast-grep
512
+ ├── Semantic — tsc TypeChecker integration (opt-in): types, references, implementations
489
513
  └── Watcher — @parcel/watcher + owner/reader role management
490
514
  ```
491
515
 
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  // @bun
2
- var wt=Object.defineProperty;var St=(n,t)=>{for(var i in t)wt(n,i,{get:t[i],enumerable:!0,configurable:!0,set:(e)=>t[i]=()=>e})};import{err as O,isErr as rn}from"@zipbul/result";import Nn from"path";import{existsSync as mi}from"fs";import{err as bt}from"@zipbul/result";import{parseSync as Ot}from"oxc-parser";function y(n,t,i){return i!==void 0?{type:n,message:t,cause:i}:{type:n,message:t}}function un(n,t,i,e=Ot){try{let{program:r,errors:s,comments:m}=e(n,t,i);return{filePath:n,program:r,errors:s,comments:m,sourceText:t}}catch(r){return bt(y("parse",`Failed to parse file: ${n}`,r))}}class An{#t;#n=new Map;constructor(n){this.#t=Math.max(1,n)}get size(){return this.#n.size}has(n){return this.#n.has(n)}get(n){if(!this.#n.has(n))return;let t=this.#n.get(n);return this.#n.delete(n),this.#n.set(n,t),t}set(n,t){if(this.#n.has(n))this.#n.delete(n);if(this.#n.set(n,t),this.#n.size>this.#t){let i=this.#n.keys().next().value;if(i!==void 0)this.#n.delete(i)}}delete(n){return this.#n.delete(n)}clear(){this.#n.clear()}}class Dn{lru;constructor(n=500){this.lru=new An(n)}get(n){return this.lru.get(n)}set(n,t){this.lru.set(n,t)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Yn(n){let t=[0];for(let i=0;i<n.length;i++)if(n[i]===`
3
- `)t.push(i+1);return t}function kn(n,t){let i=0,e=n.length-1;while(i<e){let r=i+e+1>>1;if(n[r]<=t)i=r;else e=r-1}return{line:i+1,column:t-n[i]}}import{err as Nt}from"@zipbul/result";import{parse as ht}from"comment-parser";function Zn(n){try{let t=n.trim();if(t.startsWith("/**"))t=t.slice(3);if(t.endsWith("*/"))t=t.slice(0,-2);let e=ht(`/** ${t} */`)[0]??{description:"",tags:[]};return{description:(e.description??"").trim(),tags:(e.tags??[]).map((r)=>({tag:r.tag??"",name:r.name??"",type:r.type??"",description:r.description??"",optional:r.optional??!1,...r.default!==void 0?{default:r.default}:{}}))}}catch(t){return Nt(y("parse","Failed to parse JSDoc comment",t))}}import{isErr as At}from"@zipbul/result";function ln(n){let{program:t,sourceText:i,comments:e}=n,r=Yn(i);function s(c,g){return{start:kn(r,c),end:kn(r,g)}}function m(c){let g=null;for(let o of e){if(o.type!=="Block")continue;if(o.end>c)continue;if(!o.value.startsWith("*"))continue;if(!g||o.end>g.end)g={value:`/*${o.value}*/`,end:o.end}}if(!g)return;for(let o of t.body){let f=o.start??0;if(f===c)continue;if(f>g.end&&f<c)return}return g.value}function u(c){if(!c)return;let g=c.typeAnnotation??c;return i.slice(g.start,g.end)}function a(c){if(!c||c.length===0)return[];return c.map((g)=>{let o=g.expression;if(!o)return{name:"unknown"};if(o.type==="CallExpression"){let f=o.callee?.name??o.callee?.property?.name??"unknown",x=(o.arguments??[]).map((b)=>i.slice(b.start,b.end));return{name:f,arguments:x.length>0?x:void 0}}if(o.type==="Identifier")return{name:o.name??"unknown"};return{name:i.slice(o.start,o.end)}})}function p(c){let g=c.type==="TSParameterProperty"?c.parameter:c;if(g?.type==="RestElement"){let h=`...${g.argument?.name??"unknown"}`,M=g.typeAnnotation,C=M?u(M):void 0,I={name:h,isOptional:!1};if(C)I.type=C;return I}if(g?.type==="AssignmentPattern"){let{left:k,right:h}=g,M=k?.name??"unknown",C=k?.typeAnnotation,I=C?u(C):void 0,L=i.slice(h.start,h.end),sn=a(k?.decorators??[]),Z={name:M,isOptional:!0,defaultValue:L};if(I)Z.type=I;if(sn.length>0)Z.decorators=sn;return Z}let o=g?.name??g?.pattern?.name??"unknown",f=!!g?.optional,x=g?.typeAnnotation,b=x?u(x):void 0,D=a(g?.decorators??[]),$={name:o,isOptional:f};if(b)$.type=b;if(D.length>0)$.decorators=D;return $}function l(c,g){let o=[];if(g?.async)o.push("async");if(c.static)o.push("static");if(c.abstract)o.push("abstract");if(c.readonly)o.push("readonly");if(c.override)o.push("override");if(c.declare)o.push("declare");if(c.const)o.push("const");let f=c.accessibility;if(f==="private")o.push("private");else if(f==="protected")o.push("protected");else if(f==="public")o.push("public");return o}function d(c){let g=[];if(c.superClass){let f=i.slice(c.superClass.start,c.superClass.end);g.push({kind:"extends",name:f})}let o=c.implements??[];for(let f of o){let x=f.expression??f,b=i.slice(x.start,x.end);g.push({kind:"implements",name:b})}return g}function S(c){let g=[];for(let o of c.extends??[]){let f=o.expression??o,x=i.slice(f.start,f.end);g.push({kind:"extends",name:x})}return g}function N(c){let g=[];for(let o of c)if(o.type==="MethodDefinition"){let f=o.key?.name??"unknown",x=o.value,b=o.kind??"method",D=b==="constructor"?"constructor":b==="get"?"getter":b==="set"?"setter":"method",$=l(o,x),k=(x?.params??[]).map(p),h=u(x?.returnType),M={kind:"method",name:f,span:s(o.start,o.end),isExported:!1,methodKind:D,modifiers:$,parameters:k.length>0?k:void 0,returnType:h};g.push(M)}else if(o.type==="PropertyDefinition"){let f=o.key?.name??"unknown",x=l(o),b={kind:"property",name:f,span:s(o.start,o.end),isExported:!1,modifiers:x};g.push(b)}return g}function J(c){let g=[];for(let o of c)if(o.type==="TSMethodSignature"){let f=o.key?.name??"unknown",x=(o.params??[]).map(p),b=u(o.returnType);g.push({kind:"method",name:f,span:s(o.start,o.end),isExported:!1,modifiers:[],methodKind:"method",parameters:x.length>0?x:void 0,returnType:b})}else if(o.type==="TSPropertySignature"){let f=o.key?.name??"unknown",x=u(o.typeAnnotation),b={kind:"property",name:f,span:s(o.start,o.end),isExported:!1,modifiers:o.readonly?["readonly"]:[],returnType:x};g.push(b)}return g}function A(c,g){let o=c.type??"";if(o==="FunctionDeclaration"){let f=c.id?.name??"default",x=(c.params??[]).map(p),b=u(c.returnType),D=l(c,c),$=a(c.decorators??[]),k=c.typeParameters?.params?.map((M)=>M.name?.name).filter(Boolean)||void 0,h={kind:"function",name:f,span:s(c.start,c.end),isExported:g,modifiers:D,parameters:x.length>0?x:void 0,returnType:b,decorators:$.length>0?$:void 0};if(k&&k.length>0)h.typeParameters=k;return h}if(o==="ClassDeclaration"||o==="ClassExpression"){let f=c.id?.name??"default",x=d(c),b=N(c.body?.body??[]),D=a(c.decorators??[]),$=l(c,c),k=c.typeParameters?.params?.map((M)=>M.name?.name).filter(Boolean)||void 0,h={kind:"class",name:f,span:s(c.start,c.end),isExported:g,modifiers:$,heritage:x.length>0?x:void 0,members:b.length>0?b:void 0,decorators:D.length>0?D:void 0};if(k&&k.length>0)h.typeParameters=k;return h}if(o==="VariableDeclaration"){let f=[];for(let x of c.declarations??[]){let{id:b,init:D}=x;if(b?.type==="ObjectPattern"){for(let I of b.properties??[]){let L=I.value?.name??I.key?.name??"unknown";f.push({kind:"variable",name:L,span:s(I.start??x.start,I.end??x.end),isExported:g,modifiers:[]})}continue}if(b?.type==="ArrayPattern"){for(let I of b.elements??[]){if(!I||I.type!=="Identifier")continue;let L=I.name??"unknown";f.push({kind:"variable",name:L,span:s(I.start??x.start,I.end??x.end),isExported:g,modifiers:[]})}continue}let $=b?.name??"unknown",k="variable",h,M;if(D?.type==="FunctionExpression"||D?.type==="ArrowFunctionExpression")k="function",h=(D.params??[]).map(p),M=u(D.returnType);let C=[];f.push({kind:k,name:$,span:s(x.start,x.end),isExported:g,modifiers:C,parameters:h,returnType:M})}if(f.length===0)return null;if(f.length===1)return f[0];return f}if(o==="TSTypeAliasDeclaration")return{kind:"type",name:c.id?.name??"unknown",span:s(c.start,c.end),isExported:g,modifiers:[]};if(o==="TSInterfaceDeclaration"){let f=c.id?.name??"unknown",x=S(c),b=J(c.body?.body??[]),D=c.typeParameters?.params?.map((k)=>k.name?.name).filter(Boolean)||void 0,$={kind:"interface",name:f,span:s(c.start,c.end),isExported:g,modifiers:[],heritage:x.length>0?x:void 0,members:b.length>0?b:void 0};if(D&&D.length>0)$.typeParameters=D;return $}if(o==="TSEnumDeclaration"){let f=c.id?.name??"unknown",x=l(c),D=(c.body?.members??[]).map(($)=>({kind:"property",name:$.id?.name??$.id?.value??"unknown",span:s($.start,$.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:f,span:s(c.start,c.end),isExported:g,modifiers:x,members:D.length>0?D:void 0}}return null}let F=[];for(let c of t.body){let g=null,o=c,f=typeof o.type==="string"?o.type:"";if(f==="ExportNamedDeclaration"){let b=c;if(b.declaration){if(g=A(b.declaration,!0),g&&!Array.isArray(g))g.span=s(b.start,b.end);else if(Array.isArray(g))for(let D of g)D.span=s(b.start,b.end)}}else if(f==="ExportDefaultDeclaration"){let b=c,D=b.declaration;if(D){if(g=A(D,!0),g&&!Array.isArray(g))g.name=D.id?.name??"default",g.isExported=!0,g.span=s(b.start,b.end)}}else g=A(c,!1);let x=Array.isArray(g)?g:g?[g]:[];for(let b of x){let D=c.start??0,$=m(D);if($){let k=Zn($);if(!At(k))b.jsDoc=k}F.push(b)}}return F}import{resolve as Fn,dirname as Dt,extname as kt}from"path";function _n(n,t,i){let e=(r)=>{let s=kt(r);if(s==="")return[r+".ts",r+"/index.ts",r+".mts",r+"/index.mts",r+".cts",r+"/index.cts"];if(s===".js")return[r.slice(0,-3)+".ts"];if(s===".mjs")return[r.slice(0,-4)+".mts"];if(s===".cjs")return[r.slice(0,-4)+".cts"];return[r]};if(t.startsWith(".")){let r=Fn(Dt(n),t);return e(r)}if(i)for(let[r,s]of i.paths){if(s.length===0)continue;let m=r.indexOf("*");if(m===-1){if(t===r){let u=[];for(let a of s)u.push(...e(Fn(i.baseUrl,a)));return u}}else{let u=r.slice(0,m),a=r.slice(m+1);if(t.startsWith(u)&&(a===""||t.endsWith(a))){let p=t.slice(u.length,a===""?void 0:t.length-a.length),l=[];for(let d of s)l.push(...e(Fn(i.baseUrl,d.replace("*",p))));return l}}}return[]}function vn(n,t,i,e=_n){let r=new Map,s=n.body??[];for(let m of s){if(m.type!=="ImportDeclaration")continue;let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.specifiers??[];for(let d of l)switch(d.type){case"ImportSpecifier":r.set(d.local.name,{path:p,importedName:d.imported.name});break;case"ImportDefaultSpecifier":r.set(d.local.name,{path:p,importedName:"default"});break;case"ImportNamespaceSpecifier":r.set(d.local.name,{path:p,importedName:"*"});break}}return r}var Ft=new Set(["loc","start","end","scope"]);function an(n,t){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let e of n)an(e,t);return}let i=n;t(i);for(let e of Object.keys(i)){if(Ft.has(e))continue;let r=i[e];if(r&&typeof r==="object")an(r,t)}}function Xn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if((t.type==="StringLiteral"||t.type==="Literal")&&typeof t.value==="string")return t.value;return null}function nn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.type==="Identifier"){let i=t.name;return{root:i,parts:[],full:i}}if(t.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(t.type==="Super")return{root:"super",parts:[],full:"super"};if(t.type==="MemberExpression"){let i=[],e=t;while(e.type==="MemberExpression"){let m=e.property;if(!m||typeof m.name!=="string")return null;i.unshift(m.name),e=e.object}let r;if(e.type==="Identifier")r=e.name;else if(e.type==="ThisExpression")r="this";else if(e.type==="Super")r="super";else return null;let s=[r,...i].join(".");return{root:r,parts:i,full:s}}return null}function Pn(n,t,i,e=_n){let r=[],s=n.body??[];for(let m of s){if(m.type==="ImportDeclaration"){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.importKind==="type",d=m.specifiers??[];if(d.length===0){let S={};if(l)S.isType=!0;r.push({type:l?"type-references":"imports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,...Object.keys(S).length>0?{metaJson:JSON.stringify(S)}:{}})}else for(let S of d){let N=S.type,J=l||S.importKind==="type",A={};if(J)A.isType=!0;let F,c;if(N==="ImportDefaultSpecifier")F="default",c=S.local.name;else if(N==="ImportNamespaceSpecifier")F="*",c=S.local.name,A.importKind="namespace";else F=S.imported.name,c=S.local.name;r.push({type:J?"type-references":"imports",srcFilePath:t,srcSymbolName:c,dstFilePath:p,dstSymbolName:F,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}continue}if(m.type==="ExportAllDeclaration"&&m.source){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.exportKind==="type",d={isReExport:!0};if(l)d.isType=!0;r.push({type:l?"type-references":"re-exports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify(d)});continue}if(m.type==="ExportNamedDeclaration"&&m.source){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.exportKind==="type",N={isReExport:!0,specifiers:(m.specifiers??[]).map((J)=>({local:J.local.name,exported:J.exported.name}))};if(l)N.isType=!0;r.push({type:l?"type-references":"re-exports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify(N)})}}return an(n,(m)=>{if(m.type!=="ImportExpression")return;let u=Xn(m.source);if(!u)return;let a=e(t,u,i);if(a.length===0)return;let p=a[0];r.push({type:"imports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),r}function En(n,t,i){let e=[],r=[],s=[];function m(){if(r.length>0)return r[r.length-1]??null;return null}function u(p){if(!p)return null;let l=i.get(p.root);if(p.parts.length===0){if(l)return{dstFilePath:l.path,dstSymbolName:l.importedName,resolution:"import"};return{dstFilePath:t,dstSymbolName:p.root,resolution:"local"}}else{if(l&&l.importedName==="*"){let d=p.parts[p.parts.length-1];return{dstFilePath:l.path,dstSymbolName:d,resolution:"namespace"}}return{dstFilePath:t,dstSymbolName:p.full,resolution:"local-member"}}}function a(p){if(!p||typeof p!=="object")return;if(Array.isArray(p)){for(let S of p)a(S);return}let l=p,d=typeof l.type==="string"?l.type:"";if(d==="ClassDeclaration"||d==="ClassExpression"){let S=l,N=S.id?.name??"AnonymousClass";s.push(N),a(S.body),s.pop();return}if(d==="FunctionDeclaration"){let S=l,N=S.id?.name??"anonymous";r.push(N),a(S.body),r.pop();return}if(d==="VariableDeclarator"&&l.init&&(l.init?.type==="FunctionExpression"||l.init?.type==="ArrowFunctionExpression")){let S=l,N=S.id?.name??"anonymous";r.push(N),a(S.init?.body??S.init),r.pop();return}if(d==="MethodDefinition"&&l.value){let S=l,N=s[s.length-1]??"",J=S.key?.name??"anonymous",A=N?`${N}.${J}`:J;r.push(A),a(S.value?.body),r.pop();return}if(d==="FunctionExpression"||d==="ArrowFunctionExpression"){let S=m(),N=S?`${S}.<anonymous>`:"<anonymous>";r.push(N),a(l.body),r.pop();return}if(d==="CallExpression"){let S=l,N=nn(S.callee),J=u(N);if(J){let A=m(),F={};if(A===null)F.scope="module";e.push({type:"calls",srcFilePath:t,srcSymbolName:A,dstFilePath:J.dstFilePath,dstSymbolName:J.dstSymbolName,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}a(S.callee);for(let A of S.arguments??[])a(A);return}if(d==="NewExpression"){let S=l,N=nn(S.callee),J=u(N);if(J){let A=m(),F={isNew:!0};if(A===null)F.scope="module";e.push({type:"calls",srcFilePath:t,srcSymbolName:A,dstFilePath:J.dstFilePath,dstSymbolName:J.dstSymbolName,metaJson:JSON.stringify(F)})}for(let A of S.arguments??[])a(A);return}for(let S of Object.keys(l)){if(S==="loc"||S==="start"||S==="end"||S==="scope")continue;let N=l[S];if(N&&typeof N==="object")a(N)}}return a(n),e}function jn(n,t,i){let e=[];return an(n,(r)=>{if(r.type==="TSInterfaceDeclaration"){let u=r.id?.name??"AnonymousInterface",a=r.extends??[];for(let p of a){let l=p.expression??p,d=nn(l);if(!d)continue;let S=Jn(d,t,i);e.push({type:"extends",srcFilePath:t,srcSymbolName:u,...S})}return}if(r.type!=="ClassDeclaration"&&r.type!=="ClassExpression")return;let s=r.id?.name??"AnonymousClass";if(r.superClass){let u=nn(r.superClass);if(u){let a=Jn(u,t,i);e.push({type:"extends",srcFilePath:t,srcSymbolName:s,...a})}}let m=r.implements??[];for(let u of m){let a=u.expression??u,p=nn(a);if(!p)continue;let l=Jn(p,t,i);e.push({type:"implements",srcFilePath:t,srcSymbolName:s,...l})}}),e}function Jn(n,t,i){let e=i.get(n.root);if(e){if(e.importedName==="*"){let r=n.parts[n.parts.length-1]??n.root;return{dstFilePath:e.path,dstSymbolName:r,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:e.path,dstSymbolName:n.parts.length>0?n.full:e.importedName}}return{dstFilePath:t,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function pn(n,t,i){let e=vn(n,t,i),r=Pn(n,t,i),s=En(n,t,e),m=jn(n,t,e);return[...r,...s,...m]}import{err as qn,isErr as It}from"@zipbul/result";import{Database as Kt}from"bun:sqlite";import{mkdirSync as Rt,unlinkSync as nt,existsSync as tt}from"fs";import{dirname as Tt,join as it}from"path";import{drizzle as zt}from"drizzle-orm/bun-sqlite";import{migrate as Lt}from"drizzle-orm/bun-sqlite/migrator";var X=".gildash",gn="gildash.db";var $n={};St($n,{watcherOwner:()=>Ct,symbols:()=>_,relations:()=>w,files:()=>z});import{sql as _t}from"drizzle-orm";import{sqliteTable as xn,text as T,integer as H,real as Jt,index as tn,primaryKey as Mt,foreignKey as Mn,check as $t}from"drizzle-orm/sqlite-core";var z=xn("files",{project:T("project").notNull(),filePath:T("file_path").notNull(),mtimeMs:Jt("mtime_ms").notNull(),size:H("size").notNull(),contentHash:T("content_hash").notNull(),updatedAt:T("updated_at").notNull(),lineCount:H("line_count")},(n)=>[Mt({columns:[n.project,n.filePath]})]),_=xn("symbols",{id:H("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),kind:T("kind").notNull(),name:T("name").notNull(),startLine:H("start_line").notNull(),startColumn:H("start_column").notNull(),endLine:H("end_line").notNull(),endColumn:H("end_column").notNull(),isExported:H("is_exported").notNull().default(0),signature:T("signature"),fingerprint:T("fingerprint"),detailJson:T("detail_json"),contentHash:T("content_hash").notNull(),indexedAt:T("indexed_at").notNull()},(n)=>[tn("idx_symbols_project_file").on(n.project,n.filePath),tn("idx_symbols_project_kind").on(n.project,n.kind),tn("idx_symbols_project_name").on(n.project,n.name),tn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Mn({columns:[n.project,n.filePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade")]),w=xn("relations",{id:H("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),type:T("type").notNull(),srcFilePath:T("src_file_path").notNull(),srcSymbolName:T("src_symbol_name"),dstFilePath:T("dst_file_path").notNull(),dstSymbolName:T("dst_symbol_name"),metaJson:T("meta_json")},(n)=>[tn("idx_relations_src").on(n.project,n.srcFilePath),tn("idx_relations_dst").on(n.project,n.dstFilePath),tn("idx_relations_type").on(n.project,n.type),Mn({columns:[n.project,n.srcFilePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade"),Mn({columns:[n.project,n.dstFilePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade")]),Ct=xn("watcher_owner",{id:H("id").primaryKey(),pid:H("pid").notNull(),startedAt:T("started_at").notNull(),heartbeatAt:T("heartbeat_at").notNull()},(n)=>[$t("watcher_owner_singleton",_t`${n.id} = 1`)]);class Cn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=it(n.projectRoot,X,gn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Rt(Tt(this.dbPath),{recursive:!0}),this.client=new Kt(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = ON"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=zt(this.client,{schema:$n}),Lt(this.drizzle,{migrationsFolder:it(import.meta.dirname,"migrations")});let n=this.client;if(typeof n.function==="function")n.function.call(this.client,"regexp",(t,i)=>{try{return new RegExp(t).test(i)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&tt(this.dbPath)){this.closeClient(),nt(this.dbPath);for(let i of["-wal","-shm"]){let e=this.dbPath+i;if(tt(e))nt(e)}let t=this.open();if(It(t))return qn(y("store",`Failed to recover database at ${this.dbPath}`,t.data));return t}return qn(y("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let t=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return t.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;t.run(`SAVEPOINT "${i}"`);try{let e=n(this);return t.run(`RELEASE SAVEPOINT "${i}"`),e}catch(e){throw t.run(`ROLLBACK TO SAVEPOINT "${i}"`),t.run(`RELEASE SAVEPOINT "${i}"`),e}finally{this.txDepth--}}immediateTransaction(n){let t=this.requireClient();this.txDepth++,t.run("BEGIN IMMEDIATE");try{let i=n();return t.run("COMMIT"),i}catch(i){throw t.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let t=this.requireClient().prepare(n).get();if(!t)return null;return Object.values(t)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((t)=>t.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let t=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,t,t)}replaceOwner(n){let t=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,t,t)}touchOwner(n){let t=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(t,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}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(n){if(!(n instanceof Error))return!1;let t=n.message.toLowerCase();return t.includes("malformed")||t.includes("corrupt")||t.includes("not a database")||t.includes("disk i/o error")||t.includes("sqlite_corrupt")}}import{eq as mn,and as et}from"drizzle-orm";class In{db;constructor(n){this.db=n}getFile(n,t){return this.db.drizzleDb.select().from(z).where(et(mn(z.project,n),mn(z.filePath,t))).get()??null}upsertFile(n){this.db.drizzleDb.insert(z).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[z.project,z.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(z).where(mn(z.project,n)).all()}getFilesMap(n){let t=this.getAllFiles(n),i=new Map;for(let e of t)i.set(e.filePath,e);return i}deleteFile(n,t){this.db.drizzleDb.delete(z).where(et(mn(z.project,n),mn(z.filePath,t))).run()}}import{eq as G,and as en,sql as yn,count as Gt}from"drizzle-orm";function dn(n){return n.trim().split(/\s+/).map((t)=>t.trim()).filter((t)=>t.length>0).map((t)=>`"${t.replaceAll('"','""')}"*`).join(" ")}class Kn{db;constructor(n){this.db=n}replaceFileSymbols(n,t,i,e){if(this.db.drizzleDb.delete(_).where(en(G(_.project,n),G(_.filePath,t))).run(),!e.length)return;let r=new Date().toISOString();for(let s of e)this.db.drizzleDb.insert(_).values({project:n,filePath:t,kind:s.kind??"unknown",name:s.name??"",startLine:s.startLine??0,startColumn:s.startColumn??0,endLine:s.endLine??0,endColumn:s.endColumn??0,isExported:s.isExported??0,signature:s.signature??null,fingerprint:s.fingerprint??null,detailJson:s.detailJson??null,contentHash:i,indexedAt:s.indexedAt??r}).run()}getFileSymbols(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.filePath,t))).all()}searchByName(n,t,i={}){let e=i.limit??50,r=dn(t);if(!r)return[];return this.db.drizzleDb.select().from(_).where(en(yn`${_.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${r})`,G(_.project,n),i.kind?G(_.kind,i.kind):void 0)).orderBy(_.name).limit(e).all()}searchByKind(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.kind,t))).orderBy(_.name).all()}getStats(n){let t=this.db.drizzleDb.select({symbolCount:Gt(),fileCount:yn`COUNT(DISTINCT ${_.filePath})`}).from(_).where(G(_.project,n)).get();return{symbolCount:t?.symbolCount??0,fileCount:t?.fileCount??0}}getByFingerprint(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.fingerprint,t))).all()}deleteFileSymbols(n,t){this.db.drizzleDb.delete(_).where(en(G(_.project,n),G(_.filePath,t))).run()}searchByQuery(n){let t=this.db.drizzleDb.select().from(_).where(en(n.ftsQuery?yn`${_.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?G(_.name,n.exactName):void 0,n.project!==void 0?G(_.project,n.project):void 0,n.kind?G(_.kind,n.kind):void 0,n.filePath!==void 0?G(_.filePath,n.filePath):void 0,n.isExported!==void 0?G(_.isExported,n.isExported?1:0):void 0,n.decorator?yn`${_.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0)).orderBy(_.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return t;try{let i=new RegExp(n.regex);return t.filter((e)=>i.test(e.name)).slice(0,n.limit)}catch{return[]}}}import{eq as R,and as Y,isNull as rt,or as Bt}from"drizzle-orm";class Rn{db;constructor(n){this.db=n}replaceFileRelations(n,t,i){if(this.db.drizzleDb.delete(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).run(),!i.length)return;for(let e of i)this.db.drizzleDb.insert(w).values({project:n,type:e.type??"unknown",srcFilePath:e.srcFilePath??t,srcSymbolName:e.srcSymbolName??null,dstFilePath:e.dstFilePath??"",dstSymbolName:e.dstSymbolName??null,metaJson:e.metaJson??null}).run()}getOutgoing(n,t,i){if(i!==void 0)return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.srcFilePath,t),Bt(R(w.srcSymbolName,i),rt(w.srcSymbolName)))).all();return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).all()}getIncoming(n,t){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.dstFilePath,t))).all()}getByType(n,t){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.type,t))).all()}deleteFileRelations(n,t){this.db.drizzleDb.delete(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).run()}searchRelations(n){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(n.project!==void 0?R(w.project,n.project):void 0,n.srcFilePath!==void 0?R(w.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?R(w.srcSymbolName,n.srcSymbolName):void 0,n.dstFilePath!==void 0?R(w.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?R(w.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?R(w.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n,t,i,e,r){let s=i===null?Y(R(w.project,n),R(w.dstFilePath,t),rt(w.dstSymbolName)):Y(R(w.project,n),R(w.dstFilePath,t),R(w.dstSymbolName,i));this.db.drizzleDb.update(w).set({dstFilePath:e,dstSymbolName:r}).where(s).run()}}import{err as st}from"@zipbul/result";import{subscribe as Wt}from"@parcel/watcher";import Tn from"path";var Ht=["**/.git/**",`**/${X}/**`,"**/dist/**","**/node_modules/**"],Ut=new Set(["package.json","tsconfig.json"]);function Vt(n){return n.replaceAll("\\","/")}function Qt(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class wn{#t;#n;#e;#r;#s;#i;constructor(n,t=Wt,i=console){this.#n=n.projectRoot,this.#e=[...Ht,...n.ignorePatterns??[]],this.#r=new Set((n.extensions??[".ts",".mts",".cts"]).map((e)=>e.toLowerCase())),this.#s=t,this.#i=i}async start(n){try{this.#t=await this.#s(this.#n,(t,i)=>{if(t){this.#i.error(y("watcher","Callback error",t));return}try{for(let e of i){let r=Vt(Tn.relative(this.#n,e.path));if(r.startsWith(".."))continue;let s=Tn.basename(r),m=Tn.extname(r).toLowerCase();if(!Ut.has(s)&&!this.#r.has(m))continue;if(r.endsWith(".d.ts"))continue;n({eventType:Qt(e.type),filePath:r})}}catch(e){this.#i.error(y("watcher","Callback error",e))}},{ignore:this.#e})}catch(t){return st(y("watcher","Failed to subscribe watcher",t))}}async close(){if(!this.#t)return;try{await this.#t.unsubscribe(),this.#t=void 0}catch(n){return st(y("watcher","Failed to close watcher",n))}}}import zn from"path";import{promises as Yt}from"fs";var Zt=["**/node_modules/**","**/.git/**",`**/${X}/**`,"**/dist/**"];async function Sn(n){let t=[];for await(let i of Yt.glob("**/package.json",{cwd:n,exclude:Zt})){let e=zn.dirname(i).replaceAll("\\","/"),r=zn.join(n,i),s=await Bun.file(r).json(),m=typeof s?.name==="string"&&s.name.length>0?s.name:zn.basename(e==="."?n:e);t.push({dir:e,project:m})}return t.sort((i,e)=>e.dir.length-i.dir.length),t}function U(n,t,i="default"){let e=n.replaceAll("\\","/");for(let r of t){if(r.dir===".")return r.project;if(e===r.dir||e.startsWith(`${r.dir}/`))return r.project}return i}import at from"path";var P=new Map;async function vt(n){let t=Bun.file(n);if(!await t.exists())return null;try{let i=await t.text(),e=Bun.JSONC.parse(i);return typeof e==="object"&&e!==null?e:null}catch{return null}}async function cn(n){if(P.has(n))return P.get(n)??null;let t=at.join(n,"tsconfig.json"),i=await vt(t);if(!i)return P.set(n,null),null;let e=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!e)return P.set(n,null),null;let r=typeof e.baseUrl==="string"?e.baseUrl:null,s=typeof e.paths==="object"&&e.paths!==null?e.paths:null;if(!r&&!s)return P.set(n,null),null;let m=r?at.resolve(n,r):n,u=new Map;if(s)for(let[p,l]of Object.entries(s)){if(!Array.isArray(l))continue;let d=l.filter((S)=>typeof S==="string");u.set(p,d)}let a={baseUrl:m,paths:u};return P.set(n,a),a}function bn(n){if(n){P.delete(n);return}P.clear()}import ot from"path";function Ln(n,t){return ot.relative(n,t).replaceAll("\\","/")}function on(n,t){return ot.resolve(n,t)}function E(n){let t=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(t)).toString(16).padStart(16,"0")}import{isErr as ct}from"@zipbul/result";import{promises as Xt}from"fs";import{join as Pt}from"path";async function ut(n){let{projectRoot:t,extensions:i,ignorePatterns:e,fileRepo:r}=n,s=r.getFilesMap(),m=new Set,u=[],a=[],p=e.map((d)=>new Bun.Glob(d));for await(let d of Xt.glob("**/*",{cwd:t})){if(!i.some((o)=>d.endsWith(o)))continue;if(p.some((o)=>o.match(d)))continue;m.add(d);let S=Pt(t,d),N=Bun.file(S),{size:J,lastModified:A}=N,F=s.get(d);if(!F){let o=await N.text(),f=E(o);u.push({filePath:d,contentHash:f,mtimeMs:A,size:J});continue}if(F.mtimeMs===A&&F.size===J){a.push({filePath:d,contentHash:F.contentHash,mtimeMs:A,size:J});continue}let c=await N.text(),g=E(c);if(g===F.contentHash)a.push({filePath:d,contentHash:g,mtimeMs:A,size:J});else u.push({filePath:d,contentHash:g,mtimeMs:A,size:J})}let l=[];for(let d of s.keys())if(!m.has(d))l.push(d);return{changed:u,unchanged:a,deleted:l}}function Et(n){if(n.kind==="function"||n.kind==="method"){let t=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${t}|async:${i}`}return null}function jt(n){let t={};if(n.jsDoc)t.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)t.parameters=n.parameters;if(n.returnType!==void 0)t.returnType=n.returnType}if(n.heritage?.length)t.heritage=n.heritage;if(n.decorators?.length)t.decorators=n.decorators;if(n.typeParameters?.length)t.typeParameters=n.typeParameters;if(n.modifiers?.length)t.modifiers=n.modifiers;if(n.members?.length)t.members=n.members.map((i)=>{let e=i.modifiers.find((r)=>r==="private"||r==="protected"||r==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:e,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(t).length>0?JSON.stringify(t):null}function mt(n,t,i,e,r){let s=Et(n),m=E(`${t}|${n.kind}|${s??""}`);return{project:i,filePath:e,kind:n.kind,name:t,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:s,fingerprint:m,detailJson:jt(n),contentHash:r,indexedAt:new Date().toISOString()}}function Gn(n){let{parsed:t,project:i,filePath:e,contentHash:r,symbolRepo:s}=n,m=ln(t),u=[];for(let a of m){u.push(mt(a,a.name,i,e,r));for(let p of a.members??[])u.push(mt(p,`${a.name}.${p.name}`,i,e,r))}s.replaceFileSymbols(i,e,r,u)}function Bn(n){let{ast:t,project:i,filePath:e,relationRepo:r,projectRoot:s,tsconfigPaths:m}=n,u=on(s,e),a=pn(t,u,m),p=[];for(let l of a){let d=Ln(s,l.dstFilePath);if(d.startsWith(".."))continue;let S=Ln(s,l.srcFilePath);p.push({project:i,type:l.type,srcFilePath:S,srcSymbolName:l.srcSymbolName??null,dstFilePath:d,dstSymbolName:l.dstSymbolName??null,metaJson:l.metaJson??null})}return r.replaceFileRelations(i,e,p),p.length}var qt=100;class fn{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=cn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){bn(this.opts.projectRoot),this.tsconfigPathsRaw=cn(this.opts.projectRoot),this.fullIndex().catch((t)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",t)});return}if(n.filePath.endsWith("package.json")){let t=this.opts.discoverProjectsFn??Sn;this.boundariesRefresh=t(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},qt)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,t){if(this.indexingLock){if(t)return this.pendingFullIndex=!0,new Promise((e,r)=>{this.pendingFullIndexWaiters.push({resolve:e,reject:r})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,t).then((e)=>{return this.fireCallbacks(e),e}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let e=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((r)=>{for(let s of e)s.resolve(r)}).catch((r)=>{for(let s of e)s.reject(r)})}else if(this.pendingEvents.length>0){let e=this.pendingEvents.splice(0);this.startIndex(e,!1).catch((r)=>this.logger.error("[IndexCoordinator] incremental drain error",r))}});return this.currentIndexing=i,i}async doIndex(n,t){let i=Date.now(),{fileRepo:e,symbolRepo:r,relationRepo:s,dbConnection:m}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let u,a;if(n!==void 0)u=n.filter((o)=>o.eventType==="create"||o.eventType==="change").map((o)=>({filePath:o.filePath,contentHash:"",mtimeMs:0,size:0})),a=n.filter((o)=>o.eventType==="delete").map((o)=>o.filePath);else{let o=new Map;for(let x of this.opts.boundaries)for(let[b,D]of e.getFilesMap(x.project))o.set(b,D);let f=await ut({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>o}});u=f.changed,a=f.deleted}let p=await this.tsconfigPathsRaw??void 0,l=new Map;for(let o of a){let f=U(o,this.opts.boundaries),x=r.getFileSymbols(f,o);l.set(o,x)}let d=new Map,S=new Map;if(t)for(let o of this.opts.boundaries)for(let f of e.getAllFiles(o.project))for(let x of r.getFileSymbols(o.project,f.filePath))d.set(`${x.filePath}::${x.name}`,{name:x.name,filePath:x.filePath,kind:x.kind,fingerprint:x.fingerprint});else{for(let o of u){let f=U(o.filePath,this.opts.boundaries);for(let x of r.getFileSymbols(f,o.filePath))d.set(`${x.filePath}::${x.name}`,{name:x.name,filePath:x.filePath,kind:x.kind,fingerprint:x.fingerprint})}for(let[,o]of l)for(let f of o)d.set(`${f.filePath}::${f.name}`,{name:f.name,filePath:f.filePath,kind:f.kind,fingerprint:f.fingerprint})}let N=()=>{for(let o of a){let f=U(o,this.opts.boundaries);r.deleteFileSymbols(f,o),s.deleteFileRelations(f,o),e.deleteFile(f,o)}},J=async()=>{let o=0,f=0,x=[];for(let b of u)try{let D=await this.processFile(b.filePath,b.contentHash||void 0,p);o+=D.symbolCount,f+=D.relCount}catch(D){this.logger.error(`[IndexCoordinator] Failed to index ${b.filePath}:`,D),x.push(b.filePath)}return{symbols:o,relations:f,failedFiles:x}},A=0,F=0,c=[];if(t){let{projectRoot:o,boundaries:f}=this.opts,{parseCache:x}=this.opts,b=await Promise.allSettled(u.map(async(k)=>{let h=on(o,k.filePath),M=Bun.file(h),C=await M.text(),I=k.contentHash||E(C);return{filePath:k.filePath,text:C,contentHash:I,mtimeMs:M.lastModified,size:M.size}})),D=b.filter((k)=>k.status==="fulfilled").map((k)=>k.value);for(let k of b)if(k.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",k.reason);let $=[];m.transaction(()=>{for(let h of D){let M=U(h.filePath,f);e.deleteFile(M,h.filePath)}for(let h of a){let M=U(h,f);r.deleteFileSymbols(M,h),s.deleteFileRelations(M,h),e.deleteFile(M,h)}for(let h of D){let M=U(h.filePath,f);e.upsertFile({project:M,filePath:h.filePath,mtimeMs:h.mtimeMs,size:h.size,contentHash:h.contentHash,updatedAt:new Date().toISOString(),lineCount:h.text.split(`
4
- `).length})}let k=this.opts.parseSourceFn??un;for(let h of D){let M=U(h.filePath,f),C=k(on(o,h.filePath),h.text);if(ct(C))throw C.data;let I=C;$.push({filePath:h.filePath,parsed:I}),Gn({parsed:I,project:M,filePath:h.filePath,contentHash:h.contentHash,symbolRepo:r}),F+=Bn({ast:I.program,project:M,filePath:h.filePath,relationRepo:s,projectRoot:o,tsconfigPaths:p}),A+=r.getFileSymbols(M,h.filePath).length}});for(let k of $)x.set(k.filePath,k.parsed)}else{N();let o=await J();A=o.symbols,F=o.relations,c=o.failedFiles}for(let o of u){let f=U(o.filePath,this.opts.boundaries);for(let x of r.getFileSymbols(f,o.filePath))S.set(`${x.filePath}::${x.name}`,{name:x.name,filePath:x.filePath,kind:x.kind,fingerprint:x.fingerprint})}let g={added:[],modified:[],removed:[]};for(let[o,f]of S){let x=d.get(o);if(!x)g.added.push({name:f.name,filePath:f.filePath,kind:f.kind});else if(x.fingerprint!==f.fingerprint)g.modified.push({name:f.name,filePath:f.filePath,kind:f.kind})}for(let[o,f]of d)if(!S.has(o))g.removed.push({name:f.name,filePath:f.filePath,kind:f.kind});if(!t)for(let[o,f]of l)for(let x of f){if(!x.fingerprint)continue;let b=U(o,this.opts.boundaries),D=r.getByFingerprint(b,x.fingerprint);if(D.length===1){let $=D[0];s.retargetRelations(b,o,x.name,$.filePath,$.name)}}return{indexedFiles:u.length,removedFiles:a.length,totalSymbols:A,totalRelations:F,durationMs:Date.now()-i,changedFiles:u.map((o)=>o.filePath),deletedFiles:[...a],failedFiles:c,changedSymbols:g}}async processFile(n,t,i){let{projectRoot:e,boundaries:r}=this.opts,{fileRepo:s,symbolRepo:m,relationRepo:u,parseCache:a}=this.opts,p=on(e,n),l=Bun.file(p),d=await l.text(),S=t||E(d),N=U(n,r),A=(this.opts.parseSourceFn??un)(p,d);if(ct(A))throw A.data;let F=A;a.set(n,F),s.upsertFile({project:N,filePath:n,mtimeMs:l.lastModified,size:l.size,contentHash:S,updatedAt:new Date().toISOString(),lineCount:d.split(`
5
- `).length}),Gn({parsed:F,project:N,filePath:n,contentHash:S,symbolRepo:m});let c=Bn({ast:F.program,project:N,filePath:n,relationRepo:u,projectRoot:e,tsconfigPaths:i});return{symbolCount:m.getFileSymbols(N,n).length,relCount:c}}fireCallbacks(n){for(let t of this.callbacks)try{t(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((t)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",t))}}}function ni(n){try{return process.kill(n,0),!0}catch(t){if(typeof t==="object"&&t&&"code"in t)return t.code!=="ESRCH";return!0}}function ti(n){let t=new Date(n).getTime();return Number.isNaN(t)?0:t}function ft(n,t,i={}){let e=i.now??Date.now,r=i.isAlive??ni,s=i.staleAfterSeconds??90;return n.immediateTransaction(()=>{let m=n.selectOwner();if(!m)return n.insertOwner(t),"owner";let u=Math.floor((e()-ti(m.heartbeat_at))/1000);if(r(m.pid)&&u<s)return"reader";return n.replaceOwner(t),"owner"})}function lt(n,t){n.deleteOwner(t)}function pt(n,t){n.touchOwner(t)}function Wn(n){let{symbolRepo:t,project:i,query:e}=n,r=e.project??i,s=e.limit??100,m={kind:e.kind,filePath:e.filePath,isExported:e.isExported,project:r,limit:s};if(e.text)if(e.exact)m.exactName=e.text;else{let a=dn(e.text);if(a)m.ftsQuery=a}if(e.decorator)m.decorator=e.decorator;if(e.regex)m.regex=e.regex;return t.searchByQuery(m).map((a)=>({id:a.id,filePath:a.filePath,kind:a.kind,name:a.name,span:{start:{line:a.startLine,column:a.startColumn},end:{line:a.endLine,column:a.endColumn}},isExported:a.isExported===1,signature:a.signature,fingerprint:a.fingerprint,detail:a.detailJson?(()=>{try{return JSON.parse(a.detailJson)}catch{return{}}})():{}}))}function Hn(n){let{relationRepo:t,project:i,query:e}=n,r=e.project??i,s=e.limit??500;return t.searchRelations({srcFilePath:e.srcFilePath,srcSymbolName:e.srcSymbolName,dstFilePath:e.dstFilePath,dstSymbolName:e.dstSymbolName,type:e.type,project:r,limit:s}).map((u)=>{let a;if(u.metaJson)try{a=JSON.parse(u.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",u.metaJson)}return{type:u.type,srcFilePath:u.srcFilePath,srcSymbolName:u.srcSymbolName,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,metaJson:u.metaJson??void 0,meta:a}})}class On{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let n=[...this.options.relationRepo.getByType(this.options.project,"imports"),...this.options.relationRepo.getByType(this.options.project,"type-references"),...this.options.relationRepo.getByType(this.options.project,"re-exports")];for(let t of n){let{srcFilePath:i,dstFilePath:e}=t;if(!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(this.adjacencyList.get(i).add(e),!this.adjacencyList.has(e))this.adjacencyList.set(e,new Set);if(!this.reverseAdjacencyList.has(e))this.reverseAdjacencyList.set(e,new Set);this.reverseAdjacencyList.get(e).add(i)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let t=new Set,i=[n];while(i.length>0){let e=i.shift();for(let r of this.reverseAdjacencyList.get(e)??[])if(!t.has(r))t.add(r),i.push(r)}return Array.from(t)}hasCycle(){let n=new Set,t=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let e=[{node:i,entered:!1}];while(e.length>0){let r=e.pop();if(r.entered){t.delete(r.node);continue}if(t.has(r.node))return!0;if(n.has(r.node))continue;n.add(r.node),t.add(r.node),e.push({node:r.node,entered:!0});for(let s of this.adjacencyList.get(r.node)??[]){if(t.has(s))return!0;if(!n.has(s))e.push({node:s,entered:!1})}}}return!1}getAffectedByChange(n){let t=new Set;for(let i of n)for(let e of this.getTransitiveDependents(i))t.add(e);return Array.from(t)}getAdjacencyList(){let n=new Map;for(let[t,i]of this.adjacencyList)n.set(t,Array.from(i));return n}getTransitiveDependencies(n){let t=new Set,i=[n];while(i.length>0){let e=i.shift();for(let r of this.adjacencyList.get(e)??[])if(!t.has(r))t.add(r),i.push(r)}return Array.from(t)}getCyclePaths(n){let t=n?.maxCycles??1/0;if(t<=0)return[];let i=new Map;for(let[e,r]of this.adjacencyList)i.set(e,Array.from(r));return ai(i,t)}}var ii=(n,t)=>n.localeCompare(t);function ei(n){let t=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(t.length===0)return[];let i=t;for(let e=1;e<t.length;e++){let r=t.slice(e).concat(t.slice(0,e));if(r.join("::")<i.join("::"))i=r}return[...i]}function Un(n,t,i){let e=ei(i);if(e.length===0)return!1;let r=e.join("->");if(n.has(r))return!1;return n.add(r),t.push(e),!0}function ri(n){let t=0,i=[],e=new Set,r=new Map,s=new Map,m=[],u=(a)=>{r.set(a,t),s.set(a,t),t+=1,i.push(a),e.add(a);for(let p of n.get(a)??[])if(!r.has(p))u(p),s.set(a,Math.min(s.get(a)??0,s.get(p)??0));else if(e.has(p))s.set(a,Math.min(s.get(a)??0,r.get(p)??0));if(s.get(a)===r.get(a)){let p=[],l="";do l=i.pop()??"",e.delete(l),p.push(l);while(l!==a&&i.length>0);m.push(p)}};for(let a of n.keys())if(!r.has(a))u(a);return{components:m}}function si(n,t,i){let e=[],r=new Set,s=[...n].sort(ii),m=(u,a,p)=>{a.delete(u);let l=p.get(u);if(!l)return;for(let d of l)if(a.has(d))m(d,a,p);l.clear()};for(let u=0;u<s.length&&e.length<i;u++){let a=s[u]??"",p=new Set(s.slice(u)),l=new Set,d=new Map,S=[],N=(A)=>(t.get(A)??[]).filter((F)=>p.has(F)),J=(A)=>{if(e.length>=i)return!0;let F=!1;S.push(A),l.add(A);for(let c of N(A)){if(e.length>=i)break;if(c===a)Un(r,e,S.concat(a)),F=!0;else if(!l.has(c)){if(J(c))F=!0}}if(F)m(A,l,d);else for(let c of N(A)){let g=d.get(c)??new Set;g.add(A),d.set(c,g)}return S.pop(),F};J(a)}return e}function ai(n,t){let{components:i}=ri(n),e=[],r=new Set;for(let s of i){if(e.length>=t)break;if(s.length===0)continue;if(s.length===1){let a=s[0]??"";if((n.get(a)??[]).includes(a))Un(r,e,[a,a]);continue}let m=t-e.length,u=si(s,n,m);for(let a of u){if(e.length>=t)break;Un(r,e,a)}}return e}import{findInFiles as oi,Lang as ui}from"@ast-grep/napi";async function Vn(n){if(n.filePaths.length===0)return[];let t=[];return await oi(ui.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,e)=>{if(i)return;for(let r of e){let s=r.range();t.push({filePath:r.getRoot().filename(),startLine:s.start.line+1,endLine:s.end.line+1,matchedText:r.text()})}}),t}var gt=30000,xt=60000,ci=10;class Qn{projectRoot;db;symbolRepo;relationRepo;fileRepo;parseCache;coordinator;watcher;releaseWatcherRoleFn;parseSourceFn;extractSymbolsFn;extractRelationsFn;symbolSearchFn;relationSearchFn;patternSearchFn;readFileFn;unlinkFn;existsSyncFn;makeExternalCoordinatorFn;logger;defaultProject;role;timer=null;signalHandlers=[];closed=!1;tsconfigPaths=null;boundaries=[];onIndexedCallbacks=new Set;graphCache=null;graphCacheKey=null;constructor(n){this.projectRoot=n.projectRoot,this.db=n.db,this.symbolRepo=n.symbolRepo,this.relationRepo=n.relationRepo,this.fileRepo=n.fileRepo,this.parseCache=n.parseCache,this.coordinator=n.coordinator,this.watcher=n.watcher,this.releaseWatcherRoleFn=n.releaseWatcherRoleFn,this.parseSourceFn=n.parseSourceFn,this.extractSymbolsFn=n.extractSymbolsFn,this.extractRelationsFn=n.extractRelationsFn,this.symbolSearchFn=n.symbolSearchFn,this.relationSearchFn=n.relationSearchFn,this.patternSearchFn=n.patternSearchFn,this.readFileFn=n.readFileFn,this.unlinkFn=n.unlinkFn,this.existsSyncFn=n.existsSyncFn,this.makeExternalCoordinatorFn=n.makeExternalCoordinatorFn,this.logger=n.logger,this.defaultProject=n.defaultProject,this.role=n.role}static async open(n){let{projectRoot:t,extensions:i=[".ts",".mts",".cts"],ignorePatterns:e=[],parseCacheCapacity:r=500,logger:s=console,existsSyncFn:m=mi,dbConnectionFactory:u,watcherFactory:a,coordinatorFactory:p,repositoryFactory:l,acquireWatcherRoleFn:d=ft,releaseWatcherRoleFn:S=lt,updateHeartbeatFn:N=pt,discoverProjectsFn:J=Sn,parseSourceFn:A=un,extractSymbolsFn:F=ln,extractRelationsFn:c=pn,symbolSearchFn:g=Wn,relationSearchFn:o=Hn,patternSearchFn:f=Vn,loadTsconfigPathsFn:x=cn,makeExternalCoordinatorFn:b,readFileFn:D=async(C)=>Bun.file(C).text(),unlinkFn:$=async(C)=>{await Bun.file(C).unlink()},watchMode:k}=n;if(!Nn.isAbsolute(t))return O(y("validation",`Gildash: projectRoot must be an absolute path, got: "${t}"`));if(!m(t))return O(y("validation",`Gildash: projectRoot does not exist: "${t}"`));let h=u?u():new Cn({projectRoot:t}),M=h.open();if(rn(M))return M;try{let C=await J(t),I=C[0]?.project??Nn.basename(t),L=l?l():(()=>{let B=h;return{fileRepo:new In(B),symbolRepo:new Kn(B),relationRepo:new Rn(B),parseCache:new Dn(r)}})(),sn=k??!0,Z;if(sn)Z=await Promise.resolve(d(h,process.pid,{}));else Z="owner";let dt=null,yt=null,K=new Qn({projectRoot:t,db:h,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,fileRepo:L.fileRepo,parseCache:L.parseCache,coordinator:dt,watcher:yt,releaseWatcherRoleFn:S,parseSourceFn:A,extractSymbolsFn:F,extractRelationsFn:c,symbolSearchFn:g,relationSearchFn:o,patternSearchFn:f,readFileFn:D,unlinkFn:$,existsSyncFn:m,makeExternalCoordinatorFn:b,logger:s,defaultProject:I,role:Z});if(bn(t),K.tsconfigPaths=await x(t),K.boundaries=C,Z==="owner"){let B=p?p():new fn({projectRoot:t,boundaries:C,extensions:i,ignorePatterns:e,dbConnection:h,parseCache:L.parseCache,fileRepo:L.fileRepo,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,logger:s});if(K.coordinator=B,B.onIndexed(()=>K.invalidateGraphCache()),sn){let V=a?a():new wn({projectRoot:t,ignorePatterns:e,extensions:i},void 0,s);K.watcher=V,await V.start((Q)=>B.handleWatcherEvent?.(Q)).then((Q)=>{if(rn(Q))throw Q.data});let j=setInterval(()=>{N(h,process.pid)},gt);K.timer=j}await B.fullIndex()}else{let B=0,V=async()=>{try{let Q=await Promise.resolve(d(h,process.pid,{}));if(B=0,Q==="owner"){clearInterval(K.timer),K.timer=null;let q=null,v=null;try{q=a?a():new wn({projectRoot:t,ignorePatterns:e,extensions:i},void 0,s),v=p?p():new fn({projectRoot:t,boundaries:C,extensions:i,ignorePatterns:e,dbConnection:h,parseCache:L.parseCache,fileRepo:L.fileRepo,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,logger:s});for(let W of K.onIndexedCallbacks)v.onIndexed(W);v.onIndexed(()=>K.invalidateGraphCache()),await q.start((W)=>v?.handleWatcherEvent?.(W)).then((W)=>{if(rn(W))throw W.data});let hn=setInterval(()=>{N(h,process.pid)},gt);K.timer=hn,K.coordinator=v,K.watcher=q,await v.fullIndex()}catch(hn){if(s.error("[Gildash] owner promotion failed, reverting to reader",hn),q){let W=await q.close();if(rn(W))s.error("[Gildash] watcher close error during promotion rollback",W.data);K.watcher=null}if(v)await v.shutdown().catch((W)=>s.error("[Gildash] coordinator shutdown error during promotion rollback",W)),K.coordinator=null;if(K.timer===null)K.timer=setInterval(V,xt)}}}catch(Q){if(B++,s.error("[Gildash] healthcheck error",Q),B>=ci)s.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(K.timer),K.timer=null,K.close().catch((q)=>s.error("[Gildash] close error during healthcheck shutdown",q))}},j=setInterval(V,xt);K.timer=j}if(sn){let B=["SIGTERM","SIGINT","beforeExit"];for(let V of B){let j=()=>{K.close().catch((Q)=>s.error("[Gildash] close error during signal",V,Q))};if(V==="beforeExit")process.on("beforeExit",j);else process.on(V,j);K.signalHandlers.push([V,j])}}return K}catch(C){return h.close(),O(y("store","Gildash: initialization failed",C))}}async close(n){if(this.closed)return;this.closed=!0;let t=[];for(let[i,e]of this.signalHandlers)if(i==="beforeExit")process.off("beforeExit",e);else process.off(i,e);if(this.signalHandlers=[],this.coordinator)try{await this.coordinator.shutdown()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(this.watcher){let i=await this.watcher.close();if(rn(i))t.push(i.data)}if(this.timer!==null)clearInterval(this.timer),this.timer=null;try{this.releaseWatcherRoleFn(this.db,process.pid)}catch(i){t.push(i instanceof Error?i:Error(String(i)))}try{this.db.close()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(n?.cleanup)for(let i of["","-wal","-shm"])try{await this.unlinkFn(Nn.join(this.projectRoot,X,gn+i))}catch{}if(t.length>0)return O(y("close","Gildash: one or more errors occurred during close()",t))}onIndexed(n){if(this.onIndexedCallbacks.add(n),!this.coordinator)return()=>{this.onIndexedCallbacks.delete(n)};let t=this.coordinator.onIndexed(n);return()=>{this.onIndexedCallbacks.delete(n),t()}}parseSource(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));let e=this.parseSourceFn(n,t,i);if(rn(e))return e;return this.parseCache.set(n,e),e}extractSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));return this.extractSymbolsFn(n)}extractRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));return this.extractRelationsFn(n.program,n.filePath,this.tsconfigPaths??void 0)}invalidateGraphCache(){this.graphCache=null,this.graphCacheKey=null}getOrBuildGraph(n){let t=n??"__cross__";if(this.graphCache&&this.graphCacheKey===t)return this.graphCache;let i=new On({relationRepo:this.relationRepo,project:n??this.defaultProject});return i.build(),this.graphCache=i,this.graphCacheKey=t,i}async reindex(){if(this.closed)return O(y("closed","Gildash: instance is closed"));if(!this.coordinator)return O(y("closed","Gildash: reindex() is not available for readers"));try{let n=await this.coordinator.fullIndex();return this.invalidateGraphCache(),n}catch(n){return O(y("index","Gildash: reindex failed",n))}}get projects(){return[...this.boundaries]}getStats(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolRepo.getStats(n??this.defaultProject)}catch(t){return O(y("store","Gildash: getStats failed",t))}}searchSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolSearchFn({symbolRepo:this.symbolRepo,project:this.defaultProject,query:n})}catch(t){return O(y("search","Gildash: searchSymbols failed",t))}}searchRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:this.defaultProject,query:n})}catch(t){return O(y("search","Gildash: searchRelations failed",t))}}searchAllSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolSearchFn({symbolRepo:this.symbolRepo,project:void 0,query:n})}catch(t){return O(y("search","Gildash: searchAllSymbols failed",t))}}searchAllRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:void 0,query:n})}catch(t){return O(y("search","Gildash: searchAllRelations failed",t))}}listIndexedFiles(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.fileRepo.getAllFiles(n??this.defaultProject)}catch(t){return O(y("store","Gildash: listIndexedFiles failed",t))}}getInternalRelations(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{srcFilePath:n,dstFilePath:n,limit:1e4}})}catch(i){return O(y("search","Gildash: getInternalRelations failed",i))}}diffSymbols(n,t){let i=new Map(n.map((u)=>[`${u.name}::${u.filePath}`,u])),e=new Map(t.map((u)=>[`${u.name}::${u.filePath}`,u])),r=[],s=[],m=[];for(let[u,a]of e){let p=i.get(u);if(!p)r.push(a);else if(p.fingerprint!==a.fingerprint)m.push({before:p,after:a})}for(let[u,a]of i)if(!e.has(u))s.push(a);return{added:r,removed:s,modified:m}}getDependencies(n,t,i=1e4){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{srcFilePath:n,type:"imports",project:t??this.defaultProject,limit:i}}).map((e)=>e.dstFilePath)}catch(e){return O(y("search","Gildash: getDependencies failed",e))}}getDependents(n,t,i=1e4){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{dstFilePath:n,type:"imports",project:t??this.defaultProject,limit:i}}).map((e)=>e.srcFilePath)}catch(e){return O(y("search","Gildash: getDependents failed",e))}}async getAffected(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(t).getAffectedByChange(n)}catch(i){return O(y("search","Gildash: getAffected failed",i))}}async hasCycle(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).hasCycle()}catch(t){return O(y("search","Gildash: hasCycle failed",t))}}async getImportGraph(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).getAdjacencyList()}catch(t){return O(y("search","Gildash: getImportGraph failed",t))}}async getTransitiveDependencies(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(t).getTransitiveDependencies(n)}catch(i){return O(y("search","Gildash: getTransitiveDependencies failed",i))}}async getCyclePaths(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).getCyclePaths(t)}catch(i){return O(y("search","Gildash: getCyclePaths failed",i))}}getFullSymbol(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=i??this.defaultProject,r=this.symbolSearchFn({symbolRepo:this.symbolRepo,project:e,query:{text:n,exact:!0,filePath:t,limit:1}});if(r.length===0)return O(y("search",`Gildash: symbol '${n}' not found in '${t}'`));let s=r[0],m=s.detail;return{...s,members:Array.isArray(m.members)?m.members:void 0,jsDoc:typeof m.jsDoc==="string"?m.jsDoc:void 0,parameters:typeof m.parameters==="string"?m.parameters:void 0,returnType:typeof m.returnType==="string"?m.returnType:void 0,heritage:Array.isArray(m.heritage)?m.heritage:void 0,decorators:Array.isArray(m.decorators)?m.decorators:void 0,typeParameters:typeof m.typeParameters==="string"?m.typeParameters:void 0}}catch(e){return O(y("search","Gildash: getFullSymbol failed",e))}}getFileStats(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=t??this.defaultProject,e=this.fileRepo.getFile(i,n);if(!e)return O(y("search",`Gildash: file '${n}' is not in the index`));let r=this.symbolRepo.getFileSymbols(i,n),s=this.relationRepo.getOutgoing(i,n);return{filePath:e.filePath,lineCount:e.lineCount??0,size:e.size,symbolCount:r.length,exportedSymbolCount:r.filter((m)=>m.isExported).length,relationCount:s.length}}catch(i){return O(y("store","Gildash: getFileStats failed",i))}}async getFanMetrics(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=this.getOrBuildGraph(t);return{filePath:n,fanIn:i.getDependents(n).length,fanOut:i.getDependencies(n).length}}catch(i){return O(y("search","Gildash: getFanMetrics failed",i))}}resolveSymbol(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));let e=i??this.defaultProject,r=new Set,s=[],m=n,u=t;for(;;){let a=`${u}::${m}`;if(r.has(a))return O(y("search","Gildash: resolveSymbol detected circular re-export chain"));r.add(a);let p=this.relationSearchFn({relationRepo:this.relationRepo,project:e,query:{type:"re-exports",srcFilePath:u,limit:500}}),l,d;for(let S of p){let N;if(S.metaJson)try{let A=JSON.parse(S.metaJson);if(Array.isArray(A.specifiers))N=A.specifiers}catch{}if(!N)continue;let J=N.find((A)=>A.exported===m);if(!J)continue;l=S.dstFilePath,d=J.local;break}if(!l||!d)return{originalName:m,originalFilePath:u,reExportChain:s};s.push({filePath:u,exportedAs:m}),u=l,m=d}}async findPattern(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=t?.project??this.defaultProject,e=t?.filePaths?t.filePaths:this.fileRepo.getAllFiles(i).map((r)=>r.filePath);return await this.patternSearchFn({pattern:n,filePaths:e})}catch(i){return O(y("search","Gildash: findPattern failed",i))}}async indexExternalPackages(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));if(this.role!=="owner")return O(y("closed","Gildash: indexExternalPackages() is not available for readers"));try{let i=[];for(let e of n){let r=Nn.resolve(this.projectRoot,"node_modules",e);if(!this.existsSyncFn(r))return O(y("validation",`Gildash: package not found in node_modules: ${e}`));let s=`@external/${e}`,u=await(this.makeExternalCoordinatorFn?this.makeExternalCoordinatorFn(r,s):new fn({projectRoot:r,boundaries:[{dir:".",project:s}],extensions:[".d.ts"],ignorePatterns:[],dbConnection:this.db,parseCache:this.parseCache,fileRepo:this.fileRepo,symbolRepo:this.symbolRepo,relationRepo:this.relationRepo,logger:this.logger})).fullIndex();i.push(u)}return i}catch(i){return O(y("store","Gildash: indexExternalPackages failed",i))}}async batchParse(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));let i=new Map;return await Promise.all(n.map(async(e)=>{try{let r=await this.readFileFn(e),s=this.parseSourceFn(e,r,t);if(!rn(s))i.set(e,s)}catch{}})),i}getModuleInterface(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=this.symbolSearchFn({symbolRepo:this.symbolRepo,project:t??this.defaultProject,query:{filePath:n,isExported:!0}}).map((r)=>({name:r.name,kind:r.kind,parameters:r.detail.parameters??void 0,returnType:r.detail.returnType??void 0,jsDoc:r.detail.jsDoc??void 0}));return{filePath:n,exports:e}}catch(i){return O(y("search","Gildash: getModuleInterface failed",i))}}async getHeritageChain(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=i??this.defaultProject,r=new Set,s=(m,u,a)=>{let p=`${m}::${u}`;if(r.has(p))return{symbolName:m,filePath:u,kind:a,children:[]};r.add(p);let S=this.relationSearchFn({relationRepo:this.relationRepo,project:e,query:{srcFilePath:u,srcSymbolName:m,limit:1000}}).filter((N)=>N.type==="extends"||N.type==="implements").filter((N)=>N.dstSymbolName!=null).map((N)=>s(N.dstSymbolName,N.dstFilePath,N.type));return{symbolName:m,filePath:u,kind:a,children:S}};return s(n,t)}catch(e){return O(y("search","Gildash: getHeritageChain failed",e))}}getParsedAst(n){if(this.closed)return;return this.parseCache.get(n)}getFileInfo(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.fileRepo.getFile(t??this.defaultProject,n)}catch(i){return O(y("store","Gildash: getFileInfo failed",i))}}getSymbolsByFile(n,t){return this.searchSymbols({filePath:n,project:t??void 0,limit:1e4})}}export{Wn as symbolSearch,Hn as relationSearch,Vn as patternSearch,y as gildashError,Qn as Gildash,On as DependencyGraph};
2
+ var Li=Object.defineProperty;var Yi=(n,u)=>{for(var i in u)Li(n,i,{get:u[i],enumerable:!0,configurable:!0,set:(t)=>u[i]=()=>t})};var Au=import.meta.require;import{isErr as ht}from"@zipbul/result";import{err as Xn,isErr as Wn}from"@zipbul/result";import Dn from"path";import{existsSync as Yt}from"fs";import{err as _u,isErr as bi}from"@zipbul/result";import{Database as Ri}from"bun:sqlite";import{mkdirSync as yi,unlinkSync as Ju,existsSync as Nu}from"fs";import{dirname as Fi,join as Mu}from"path";import{drizzle as pi}from"drizzle-orm/bun-sqlite";import{migrate as Ei}from"drizzle-orm/bun-sqlite/migrator";function J(n,u,i){return i!==void 0?{type:n,message:u,cause:i}:{type:n,message:u}}var nn=".gildash",In="gildash.db";var Fn={};Yi(Fn,{watcherOwner:()=>Ci,symbols:()=>U,relations:()=>W,files:()=>R});import{sql as Zi}from"drizzle-orm";import{sqliteTable as Hn,text as C,integer as d,real as Gi,index as gn,primaryKey as Xi,foreignKey as yn,check as Ti}from"drizzle-orm/sqlite-core";var R=Hn("files",{project:C("project").notNull(),filePath:C("file_path").notNull(),mtimeMs:Gi("mtime_ms").notNull(),size:d("size").notNull(),contentHash:C("content_hash").notNull(),updatedAt:C("updated_at").notNull(),lineCount:d("line_count")},(n)=>[Xi({columns:[n.project,n.filePath]})]),U=Hn("symbols",{id:d("id").primaryKey({autoIncrement:!0}),project:C("project").notNull(),filePath:C("file_path").notNull(),kind:C("kind").notNull(),name:C("name").notNull(),startLine:d("start_line").notNull(),startColumn:d("start_column").notNull(),endLine:d("end_line").notNull(),endColumn:d("end_column").notNull(),isExported:d("is_exported").notNull().default(0),signature:C("signature"),fingerprint:C("fingerprint"),detailJson:C("detail_json"),contentHash:C("content_hash").notNull(),indexedAt:C("indexed_at").notNull(),resolvedType:C("resolved_type")},(n)=>[gn("idx_symbols_project_file").on(n.project,n.filePath),gn("idx_symbols_project_kind").on(n.project,n.kind),gn("idx_symbols_project_name").on(n.project,n.name),gn("idx_symbols_fingerprint").on(n.project,n.fingerprint),yn({columns:[n.project,n.filePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),W=Hn("relations",{id:d("id").primaryKey({autoIncrement:!0}),project:C("project").notNull(),type:C("type").notNull(),srcFilePath:C("src_file_path").notNull(),srcSymbolName:C("src_symbol_name"),dstProject:C("dst_project").notNull(),dstFilePath:C("dst_file_path").notNull(),dstSymbolName:C("dst_symbol_name"),metaJson:C("meta_json")},(n)=>[gn("idx_relations_src").on(n.project,n.srcFilePath),gn("idx_relations_dst").on(n.dstProject,n.dstFilePath),gn("idx_relations_type").on(n.project,n.type),yn({columns:[n.project,n.srcFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade"),yn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),Ci=Hn("watcher_owner",{id:d("id").primaryKey(),pid:d("pid").notNull(),startedAt:C("started_at").notNull(),heartbeatAt:C("heartbeat_at").notNull()},(n)=>[Ti("watcher_owner_singleton",Zi`${n.id} = 1`)]);class pn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Mu(n.projectRoot,nn,In)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{yi(Fi(this.dbPath),{recursive:!0}),this.client=new Ri(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=pi(this.client,{schema:Fn}),Ei(this.drizzle,{migrationsFolder:Mu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(i,t)=>{try{return new RegExp(i).test(t)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Nu(this.dbPath)){this.closeClient(),Ju(this.dbPath);for(let i of["-wal","-shm"]){let t=this.dbPath+i;if(Nu(t))Ju(t)}let u=this.open();if(bi(u))return _u(J("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return _u(J("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${i}"`);try{let t=n(this);return u.run(`RELEASE SAVEPOINT "${i}"`),t}catch(t){throw u.run(`ROLLBACK TO SAVEPOINT "${i}"`),u.run(`RELEASE SAVEPOINT "${i}"`),t}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let i=n();return u.run("COMMIT"),i}catch(i){throw u.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}replaceOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}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(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as _n,and as $u}from"drizzle-orm";class En{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(R).where($u(_n(R.project,n),_n(R.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(R).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[R.project,R.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(R).where(_n(R.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),i=new Map;for(let t of u)i.set(t.filePath,t);return i}deleteFile(n,u){this.db.drizzleDb.delete(R).where($u(_n(R.project,n),_n(R.filePath,u))).run()}}import{eq as y,and as rn,sql as Vn,count as vi}from"drizzle-orm";function Kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class vn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,i,t){if(this.db.drizzleDb.delete(U).where(rn(y(U.project,n),y(U.filePath,u))).run(),!t.length)return;let m=new Date().toISOString();for(let g of t)this.db.drizzleDb.insert(U).values({project:n,filePath:u,kind:g.kind??"unknown",name:g.name??"",startLine:g.startLine??0,startColumn:g.startColumn??0,endLine:g.endLine??0,endColumn:g.endColumn??0,isExported:g.isExported??0,signature:g.signature??null,fingerprint:g.fingerprint??null,detailJson:g.detailJson??null,contentHash:i,indexedAt:g.indexedAt??m,resolvedType:g.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.filePath,u))).all()}searchByName(n,u,i={}){let t=i.limit??50,m=Kn(u);if(!m)return[];return this.db.drizzleDb.select().from(U).where(rn(Vn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${m})`,y(U.project,n),i.kind?y(U.kind,i.kind):void 0)).orderBy(U.name).limit(t).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.kind,u))).orderBy(U.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:vi(),fileCount:Vn`COUNT(DISTINCT ${U.filePath})`}).from(U).where(y(U.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(U).where(rn(y(U.project,n),y(U.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(U).where(rn(n.ftsQuery?Vn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?y(U.name,n.exactName):void 0,n.project!==void 0?y(U.project,n.project):void 0,n.kind?y(U.kind,n.kind):void 0,n.filePath!==void 0?y(U.filePath,n.filePath):void 0,n.isExported!==void 0?y(U.isExported,n.isExported?1:0):void 0,n.decorator?Vn`${U.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?y(U.resolvedType,n.resolvedType):void 0)).orderBy(U.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let i=new RegExp(n.regex);return u.filter((t)=>i.test(t.name)).slice(0,n.limit)}catch{return[]}}}import{eq as T,and as x,isNull as Wu,or as qi}from"drizzle-orm";class qn{db;constructor(n){this.db=n}replaceFileRelations(n,u,i){this.db.transaction((t)=>{if(t.drizzleDb.delete(W).where(x(T(W.project,n),T(W.srcFilePath,u))).run(),!i.length)return;for(let m of i)t.drizzleDb.insert(W).values({project:n,type:m.type??"unknown",srcFilePath:m.srcFilePath??u,srcSymbolName:m.srcSymbolName??null,dstProject:m.dstProject??n,dstFilePath:m.dstFilePath??"",dstSymbolName:m.dstSymbolName??null,metaJson:m.metaJson??null}).run()})}getOutgoing(n,u,i){if(i!==void 0)return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.srcFilePath,u),qi(T(W.srcSymbolName,i),Wu(W.srcSymbolName)))).all();return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:i}=n;return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.dstProject,u),T(W.dstFilePath,i))).all()}getByType(n,u){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(W).where(x(T(W.project,n),T(W.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(n.project!==void 0?T(W.project,n.project):void 0,n.srcFilePath!==void 0?T(W.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?T(W.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?T(W.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?T(W.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?T(W.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?T(W.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:i,oldSymbol:t,newFile:m,newSymbol:g,newDstProject:O}=n,r=t===null?x(T(W.dstProject,u),T(W.dstFilePath,i),Wu(W.dstSymbolName)):x(T(W.dstProject,u),T(W.dstFilePath,i),T(W.dstSymbolName,t)),w={dstFilePath:m,dstSymbolName:g};if(O!==void 0)w.dstProject=O;this.db.drizzleDb.update(W).set(w).where(r).run()}}import{err as Du}from"@zipbul/result";import{subscribe as ji}from"@parcel/watcher";import jn from"path";var Pi=["**/.git/**",`**/${nn}/**`,"**/dist/**","**/node_modules/**"],di=new Set(["package.json","tsconfig.json"]);function hi(n){return n.replaceAll("\\","/")}function oi(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class Pn{#n;#u;#i;#m;#t;#g;constructor(n,u=ji,i=console){this.#u=n.projectRoot,this.#i=[...Pi,...n.ignorePatterns??[]],this.#m=new Set((n.extensions??[".ts",".mts",".cts"]).map((t)=>t.toLowerCase())),this.#t=u,this.#g=i}async start(n){try{this.#n=await this.#t(this.#u,(u,i)=>{if(u){this.#g.error(J("watcher","Callback error",u));return}try{for(let t of i){let m=hi(jn.relative(this.#u,t.path));if(m.startsWith(".."))continue;let g=jn.basename(m),O=jn.extname(m).toLowerCase();if(!di.has(g)&&!this.#m.has(O))continue;if(m.endsWith(".d.ts"))continue;n({eventType:oi(t.type),filePath:m})}}catch(t){this.#g.error(J("watcher","Callback error",t))}},{ignore:this.#i})}catch(u){return Du(J("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Du(J("watcher","Failed to close watcher",n))}}}import dn from"path";import{promises as xi}from"fs";var li=["**/node_modules/**","**/.git/**",`**/${nn}/**`,"**/dist/**"];async function zn(n){let u=[];for await(let i of xi.glob("**/package.json",{cwd:n,exclude:li})){let t=dn.dirname(i).replaceAll("\\","/"),m=dn.join(n,i),g=await Bun.file(m).json(),O=typeof g?.name==="string"&&g.name.length>0?g.name:dn.basename(t==="."?n:t);u.push({dir:t,project:O})}return u.sort((i,t)=>t.dir.length-i.dir.length),u}function j(n,u,i="default"){let t=n.replaceAll("\\","/");for(let m of u){if(m.dir===".")return m.project;if(t===m.dir||t.startsWith(`${m.dir}/`))return m.project}return i}import ku from"path";var un=new Map;async function ci(n){let u=Bun.file(n);if(!await u.exists())return null;try{let i=await u.text(),t=Bun.JSONC.parse(i);return typeof t==="object"&&t!==null?t:null}catch{return null}}async function Jn(n){if(un.has(n))return un.get(n)??null;let u=ku.join(n,"tsconfig.json"),i=await ci(u);if(!i)return un.set(n,null),null;let t=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!t)return un.set(n,null),null;let m=typeof t.baseUrl==="string"?t.baseUrl:null,g=typeof t.paths==="object"&&t.paths!==null?t.paths:null;if(!m&&!g)return un.set(n,null),null;let O=m?ku.resolve(n,m):n,r=new Map;if(g)for(let[a,s]of Object.entries(g)){if(!Array.isArray(s))continue;let f=s.filter((M)=>typeof M==="string");r.set(a,f)}let w={baseUrl:O,paths:r};return un.set(n,w),w}function Bn(n){if(n){un.delete(n);return}un.clear()}import Iu from"path";function Un(n,u){return Iu.relative(n,u).replaceAll("\\","/")}function an(n,u){return Iu.resolve(n,u)}function tn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Zu}from"@zipbul/result";import{err as ei}from"@zipbul/result";import{parseSync as nt}from"oxc-parser";function Nn(n,u,i,t=nt){try{let{program:m,errors:g,comments:O}=t(n,u,i);return{filePath:n,program:m,errors:g,comments:O,sourceText:u}}catch(m){return ei(J("parse",`Failed to parse file: ${n}`,m))}}import{promises as ut}from"fs";import{join as it}from"path";async function Hu(n){let{projectRoot:u,extensions:i,ignorePatterns:t,fileRepo:m}=n,g=m.getFilesMap(),O=new Set,r=[],w=[],a=t.map((f)=>new Bun.Glob(f));for await(let f of ut.glob("**/*",{cwd:u})){if(!i.some((S)=>f.endsWith(S)))continue;if(f.startsWith("node_modules/")||f.includes("/node_modules/"))continue;if(a.some((S)=>S.match(f)))continue;O.add(f);let M=it(u,f),k=Bun.file(M),{size:H,lastModified:K}=k,B=g.get(f);if(!B){let S=await k.text(),_=tn(S);r.push({filePath:f,contentHash:_,mtimeMs:K,size:H});continue}if(B.mtimeMs===K&&B.size===H){w.push({filePath:f,contentHash:B.contentHash,mtimeMs:K,size:H});continue}let A=await k.text(),N=tn(A);if(N===B.contentHash)w.push({filePath:f,contentHash:N,mtimeMs:K,size:H});else r.push({filePath:f,contentHash:N,mtimeMs:K,size:H})}let s=[];for(let f of g.keys())if(!O.has(f))s.push(f);return{changed:r,unchanged:w,deleted:s}}function Ku(n){let u=[0];for(let i=0;i<n.length;i++)if(n[i]===`
3
+ `)u.push(i+1);return u}function hn(n,u){let i=0,t=n.length-1;while(i<t){let m=i+t+1>>1;if(n[m]<=u)i=m;else t=m-1}return{line:i+1,column:u-n[i]}}import{err as tt}from"@zipbul/result";import{parse as mt}from"comment-parser";function Vu(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let t=mt(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(t.description??"").trim(),tags:(t.tags??[]).map((m)=>({tag:m.tag??"",name:m.name??"",type:m.type??"",description:m.description??"",optional:m.optional??!1,...m.default!==void 0?{default:m.default}:{}}))}}catch(u){return tt(J("parse","Failed to parse JSDoc comment",u))}}import{isErr as gt}from"@zipbul/result";function Qn(n){let{program:u,sourceText:i,comments:t}=n,m=Ku(i);function g(A,N){return{start:hn(m,A),end:hn(m,N)}}function O(A){let N=null;for(let S of t){if(S.type!=="Block")continue;if(S.end>A)continue;if(!S.value.startsWith("*"))continue;if(!N||S.end>N.end)N={value:`/*${S.value}*/`,end:S.end}}if(!N)return;for(let S of u.body){let _=S.start??0;if(_===A)continue;if(_>N.end&&_<A)return}return N.value}function r(A){if(!A)return;let N=A.typeAnnotation??A;return i.slice(N.start,N.end)}function w(A){if(!A||A.length===0)return[];return A.map((N)=>{let S=N.expression;if(!S)return{name:"unknown"};if(S.type==="CallExpression"){let _=S.callee?.name??S.callee?.property?.name??"unknown",$=(S.arguments??[]).map((I)=>i.slice(I.start,I.end));return{name:_,arguments:$.length>0?$:void 0}}if(S.type==="Identifier")return{name:S.name??"unknown"};return{name:i.slice(S.start,S.end)}})}function a(A){let N=A.type==="TSParameterProperty"?A.parameter:A;if(N?.type==="RestElement"){let X=`...${N.argument?.name??"unknown"}`,D=N.typeAnnotation,Y=D?r(D):void 0,Q={name:X,isOptional:!1};if(Y)Q.type=Y;return Q}if(N?.type==="AssignmentPattern"){let{left:V,right:X}=N,D=V?.name??"unknown",Y=V?.typeAnnotation,Q=Y?r(Y):void 0,E=i.slice(X.start,X.end),h=w(V?.decorators??[]),o={name:D,isOptional:!0,defaultValue:E};if(Q)o.type=Q;if(h.length>0)o.decorators=h;return o}let S=N?.name??N?.pattern?.name??"unknown",_=!!N?.optional,$=N?.typeAnnotation,I=$?r($):void 0,z=w(N?.decorators??[]),L={name:S,isOptional:_};if(I)L.type=I;if(z.length>0)L.decorators=z;return L}function s(A,N){let S=[];if(N?.async)S.push("async");if(A.static)S.push("static");if(A.abstract)S.push("abstract");if(A.readonly)S.push("readonly");if(A.override)S.push("override");if(A.declare)S.push("declare");if(A.const)S.push("const");let _=A.accessibility;if(_==="private")S.push("private");else if(_==="protected")S.push("protected");else if(_==="public")S.push("public");return S}function f(A){let N=[];if(A.superClass){let _=i.slice(A.superClass.start,A.superClass.end);N.push({kind:"extends",name:_})}let S=A.implements??[];for(let _ of S){let $=_.expression??_,I=i.slice($.start,$.end);N.push({kind:"implements",name:I})}return N}function M(A){let N=[];for(let S of A.extends??[]){let _=S.expression??S,$=i.slice(_.start,_.end);N.push({kind:"extends",name:$})}return N}function k(A){let N=[];for(let S of A)if(S.type==="MethodDefinition"){let _=S.key?.name??"unknown",$=S.value,I=S.kind??"method",z=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",L=s(S,$),V=($?.params??[]).map(a),X=r($?.returnType),D={kind:"method",name:_,span:g(S.start,S.end),isExported:!1,methodKind:z,modifiers:L,parameters:V.length>0?V:void 0,returnType:X};N.push(D)}else if(S.type==="PropertyDefinition"){let _=S.key?.name??"unknown",$=s(S),I={kind:"property",name:_,span:g(S.start,S.end),isExported:!1,modifiers:$};N.push(I)}return N}function H(A){let N=[];for(let S of A)if(S.type==="TSMethodSignature"){let _=S.key?.name??"unknown",$=(S.params??[]).map(a),I=r(S.returnType);N.push({kind:"method",name:_,span:g(S.start,S.end),isExported:!1,modifiers:[],methodKind:"method",parameters:$.length>0?$:void 0,returnType:I})}else if(S.type==="TSPropertySignature"){let _=S.key?.name??"unknown",$=r(S.typeAnnotation),I={kind:"property",name:_,span:g(S.start,S.end),isExported:!1,modifiers:S.readonly?["readonly"]:[],returnType:$};N.push(I)}return N}function K(A,N){let S=A.type??"";if(S==="FunctionDeclaration"){let _=A.id?.name??"default",$=(A.params??[]).map(a),I=r(A.returnType),z=s(A,A),L=w(A.decorators??[]),V=A.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,X={kind:"function",name:_,span:g(A.start,A.end),isExported:N,modifiers:z,parameters:$.length>0?$:void 0,returnType:I,decorators:L.length>0?L:void 0};if(V&&V.length>0)X.typeParameters=V;return X}if(S==="ClassDeclaration"||S==="ClassExpression"){let _=A.id?.name??"default",$=f(A),I=k(A.body?.body??[]),z=w(A.decorators??[]),L=s(A,A),V=A.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,X={kind:"class",name:_,span:g(A.start,A.end),isExported:N,modifiers:L,heritage:$.length>0?$:void 0,members:I.length>0?I:void 0,decorators:z.length>0?z:void 0};if(V&&V.length>0)X.typeParameters=V;return X}if(S==="VariableDeclaration"){let _=[];for(let $ of A.declarations??[]){let{id:I,init:z}=$;if(I?.type==="ObjectPattern"){for(let Q of I.properties??[]){let E=Q.value?.name??Q.key?.name??"unknown";_.push({kind:"variable",name:E,span:g(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}if(I?.type==="ArrayPattern"){for(let Q of I.elements??[]){if(!Q||Q.type!=="Identifier")continue;let E=Q.name??"unknown";_.push({kind:"variable",name:E,span:g(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}let L=I?.name??"unknown",V="variable",X,D;if(z?.type==="FunctionExpression"||z?.type==="ArrowFunctionExpression")V="function",X=(z.params??[]).map(a),D=r(z.returnType);let Y=[];_.push({kind:V,name:L,span:g($.start,$.end),isExported:N,modifiers:Y,parameters:X,returnType:D})}if(_.length===0)return null;if(_.length===1)return _[0];return _}if(S==="TSTypeAliasDeclaration")return{kind:"type",name:A.id?.name??"unknown",span:g(A.start,A.end),isExported:N,modifiers:[]};if(S==="TSInterfaceDeclaration"){let _=A.id?.name??"unknown",$=M(A),I=H(A.body?.body??[]),z=A.typeParameters?.params?.map((V)=>V.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:_,span:g(A.start,A.end),isExported:N,modifiers:[],heritage:$.length>0?$:void 0,members:I.length>0?I:void 0};if(z&&z.length>0)L.typeParameters=z;return L}if(S==="TSEnumDeclaration"){let _=A.id?.name??"unknown",$=s(A),z=(A.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:g(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:_,span:g(A.start,A.end),isExported:N,modifiers:$,members:z.length>0?z:void 0}}return null}let B=[];for(let A of u.body){let N=null,S=A,_=typeof S.type==="string"?S.type:"";if(_==="ExportNamedDeclaration"){let I=A;if(I.declaration){if(N=K(I.declaration,!0),N&&!Array.isArray(N))N.span=g(I.start,I.end);else if(Array.isArray(N))for(let z of N)z.span=g(I.start,I.end)}}else if(_==="ExportDefaultDeclaration"){let I=A,z=I.declaration;if(z){if(N=K(z,!0),N&&!Array.isArray(N))N.name=z.id?.name??"default",N.isExported=!0,N.span=g(I.start,I.end)}}else N=K(A,!1);let $=Array.isArray(N)?N:N?[N]:[];for(let I of $){let z=A.start??0,L=O(z);if(L){let V=Vu(L);if(!gt(V))I.jsDoc=V}B.push(I)}}return B}function rt(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${u}|async:${i}`}return null}function wt(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((i)=>{let t=i.modifiers.find((m)=>m==="private"||m==="protected"||m==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:t,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function zu(n,u,i,t,m){let g=rt(n),O=tn(`${u}|${n.kind}|${g??""}`);return{project:i,filePath:t,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:g,fingerprint:O,detailJson:wt(n),contentHash:m,indexedAt:new Date().toISOString()}}function on(n){let{parsed:u,project:i,filePath:t,contentHash:m,symbolRepo:g}=n,O=Qn(u),r=[];for(let w of O){r.push(zu(w,w.name,i,t,m));for(let a of w.members??[])r.push(zu(a,`${w.name}.${a.name}`,i,t,m))}g.replaceFileSymbols(i,t,m,r)}import{resolve as xn,dirname as Ot,extname as St}from"path";function wn(n,u,i){let t=(m)=>{let g=St(m);if(g==="")return[m+".ts",m+".d.ts",m+"/index.ts",m+"/index.d.ts",m+".mts",m+"/index.mts",m+".cts",m+"/index.cts"];if(g===".js")return[m.slice(0,-3)+".ts"];if(g===".mjs")return[m.slice(0,-4)+".mts"];if(g===".cjs")return[m.slice(0,-4)+".cts"];return[m]};if(u.startsWith(".")){let m=xn(Ot(n),u);return t(m)}if(i)for(let[m,g]of i.paths){if(g.length===0)continue;let O=m.indexOf("*");if(O===-1){if(u===m){let r=[];for(let w of g)r.push(...t(xn(i.baseUrl,w)));return r}}else{let r=m.slice(0,O),w=m.slice(O+1);if(u.startsWith(r)&&(w===""||u.endsWith(w))){let a=u.slice(r.length,w===""?void 0:u.length-w.length),s=[];for(let f of g)s.push(...t(xn(i.baseUrl,f.replace("*",a))));return s}}}return[]}function Bu(n,u,i,t=wn){let m=new Map,g=n.body??[];for(let O of g){if(O.type!=="ImportDeclaration")continue;let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.specifiers??[];for(let f of s)switch(f.type){case"ImportSpecifier":m.set(f.local.name,{path:a,importedName:f.imported.name});break;case"ImportDefaultSpecifier":m.set(f.local.name,{path:a,importedName:"default"});break;case"ImportNamespaceSpecifier":m.set(f.local.name,{path:a,importedName:"*"});break}}return m}var at=new Set(["loc","start","end","scope"]);function sn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let t of n)sn(t,u);return}let i=n;u(i);for(let t of Object.keys(i)){if(at.has(t))continue;let m=i[t];if(m&&typeof m==="object")sn(m,u)}}function Uu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function On(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let i=u.name;return{root:i,parts:[],full:i}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let i=[],t=u;while(t.type==="MemberExpression"){let O=t.property;if(!O||typeof O.name!=="string")return null;i.unshift(O.name),t=t.object}let m;if(t.type==="Identifier")m=t.name;else if(t.type==="ThisExpression")m="this";else if(t.type==="Super")m="super";else return null;let g=[m,...i].join(".");return{root:m,parts:i,full:g}}return null}function Qu(n,u,i,t=wn){let m=[],g=n.body??[];for(let O of g){if(O.type==="ImportDeclaration"){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.importKind==="type",f=O.specifiers??[];if(f.length===0){let M={};if(s)M.isType=!0;m.push({type:s?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of f){let k=M.type,H=s||M.importKind==="type",K={};if(H)K.isType=!0;let B,A;if(k==="ImportDefaultSpecifier")B="default",A=M.local.name;else if(k==="ImportNamespaceSpecifier")B="*",A=M.local.name,K.importKind="namespace";else B=M.imported.name,A=M.local.name;m.push({type:H?"type-references":"imports",srcFilePath:u,srcSymbolName:A,dstFilePath:a,dstSymbolName:B,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}continue}if(O.type==="ExportAllDeclaration"&&O.source){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.exportKind==="type",f={isReExport:!0};if(s)f.isType=!0;m.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify(f)});continue}if(O.type==="ExportNamedDeclaration"&&O.source){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.exportKind==="type",k={isReExport:!0,specifiers:(O.specifiers??[]).map((H)=>({local:H.local.name,exported:H.exported.name}))};if(s)k.isType=!0;m.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify(k)})}}return sn(n,(O)=>{if(O.type!=="ImportExpression")return;let r=Uu(O.source);if(!r)return;let w=t(u,r,i);if(w.length===0)return;let a=w[0];m.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),m}function Lu(n,u,i){let t=[],m=[],g=[];function O(){if(m.length>0)return m[m.length-1]??null;return null}function r(a){if(!a)return null;let s=i.get(a.root);if(a.parts.length===0){if(s)return{dstFilePath:s.path,dstSymbolName:s.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:a.root,resolution:"local"}}else{if(s&&s.importedName==="*"){let f=a.parts[a.parts.length-1];return{dstFilePath:s.path,dstSymbolName:f,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:a.full,resolution:"local-member"}}}function w(a){if(!a||typeof a!=="object")return;if(Array.isArray(a)){for(let M of a)w(M);return}let s=a,f=typeof s.type==="string"?s.type:"";if(f==="ClassDeclaration"||f==="ClassExpression"){let M=s,k=M.id?.name??"AnonymousClass";g.push(k),w(M.body),g.pop();return}if(f==="FunctionDeclaration"){let M=s,k=M.id?.name??"anonymous";m.push(k),w(M.body),m.pop();return}if(f==="VariableDeclarator"&&s.init&&(s.init?.type==="FunctionExpression"||s.init?.type==="ArrowFunctionExpression")){let M=s,k=M.id?.name??"anonymous";m.push(k),w(M.init?.body??M.init),m.pop();return}if(f==="MethodDefinition"&&s.value){let M=s,k=g[g.length-1]??"",H=M.key?.name??"anonymous",K=k?`${k}.${H}`:H;m.push(K),w(M.value?.body),m.pop();return}if(f==="FunctionExpression"||f==="ArrowFunctionExpression"){let M=O(),k=M?`${M}.<anonymous>`:"<anonymous>";m.push(k),w(s.body),m.pop();return}if(f==="CallExpression"){let M=s,k=On(M.callee),H=r(k);if(H){let K=O(),B={};if(K===null)B.scope="module";t.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}w(M.callee);for(let K of M.arguments??[])w(K);return}if(f==="NewExpression"){let M=s,k=On(M.callee),H=r(k);if(H){let K=O(),B={isNew:!0};if(K===null)B.scope="module";t.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,metaJson:JSON.stringify(B)})}for(let K of M.arguments??[])w(K);return}for(let M of Object.keys(s)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let k=s[M];if(k&&typeof k==="object")w(k)}}return w(n),t}function Yu(n,u,i){let t=[];return sn(n,(m)=>{if(m.type==="TSInterfaceDeclaration"){let r=m.id?.name??"AnonymousInterface",w=m.extends??[];for(let a of w){let s=a.expression??a,f=On(s);if(!f)continue;let M=ln(f,u,i);t.push({type:"extends",srcFilePath:u,srcSymbolName:r,...M})}return}if(m.type!=="ClassDeclaration"&&m.type!=="ClassExpression")return;let g=m.id?.name??"AnonymousClass";if(m.superClass){let r=On(m.superClass);if(r){let w=ln(r,u,i);t.push({type:"extends",srcFilePath:u,srcSymbolName:g,...w})}}let O=m.implements??[];for(let r of O){let w=r.expression??r,a=On(w);if(!a)continue;let s=ln(a,u,i);t.push({type:"implements",srcFilePath:u,srcSymbolName:g,...s})}}),t}function ln(n,u,i){let t=i.get(n.root);if(t){if(t.importedName==="*"){let m=n.parts[n.parts.length-1]??n.root;return{dstFilePath:t.path,dstSymbolName:m,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:t.path,dstSymbolName:n.parts.length>0?n.full:t.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Ln(n,u,i,t=wn){let m=Bu(n,u,i,t),g=Qu(n,u,i,t),O=Lu(n,u,m),r=Yu(n,u,m);return[...g,...O,...r]}function cn(n){let{ast:u,project:i,filePath:t,relationRepo:m,projectRoot:g,tsconfigPaths:O,knownFiles:r,boundaries:w}=n,a=an(g,t),f=Ln(u,a,O,r?(k,H,K)=>{let B=wn(k,H,K);for(let A of B){let N=Un(g,A);if(w){let S=j(N,w);if(r.has(`${S}::${N}`))return[A]}else if(r.has(`${i}::${N}`))return[A]}return[]}:void 0),M=[];for(let k of f){let H=Un(g,k.dstFilePath);if(H.startsWith(".."))continue;let K=Un(g,k.srcFilePath),B=w?j(H,w):i;M.push({project:i,type:k.type,srcFilePath:K,srcSymbolName:k.srcSymbolName??null,dstProject:B,dstFilePath:H,dstSymbolName:k.dstSymbolName??null,metaJson:k.metaJson??null})}return m.replaceFileRelations(i,t,M),M.length}var st=100;class en{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Jn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Bn(this.opts.projectRoot),this.tsconfigPathsRaw=Jn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??zn;this.boundariesRefresh=u(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},st)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((t,m)=>{this.pendingFullIndexWaiters.push({resolve:t,reject:m})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,u).then((t)=>{return this.fireCallbacks(t),t}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let t=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((m)=>{for(let g of t)g.resolve(m)}).catch((m)=>{for(let g of t)g.reject(m)})}else if(this.pendingEvents.length>0){let t=this.pendingEvents.splice(0);this.startIndex(t,!1).catch((m)=>this.logger.error("[IndexCoordinator] incremental drain error",m))}});return this.currentIndexing=i,i}async doIndex(n,u){let i=Date.now(),{fileRepo:t,symbolRepo:m,relationRepo:g,dbConnection:O}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let r,w;if(n!==void 0)r=n.filter((S)=>S.eventType==="create"||S.eventType==="change").map((S)=>({filePath:S.filePath,contentHash:"",mtimeMs:0,size:0})),w=n.filter((S)=>S.eventType==="delete").map((S)=>S.filePath);else{let S=new Map;for(let $ of this.opts.boundaries)for(let[I,z]of t.getFilesMap($.project))S.set(I,z);let _=await Hu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>S}});r=_.changed,w=_.deleted}let a=await this.tsconfigPathsRaw??void 0,s=new Map;for(let S of w){let _=j(S,this.opts.boundaries),$=m.getFileSymbols(_,S);s.set(S,$)}let f=new Map,M=new Map;if(u)for(let S of this.opts.boundaries)for(let _ of t.getAllFiles(S.project))for(let $ of m.getFileSymbols(S.project,_.filePath))f.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint});else{for(let S of r){let _=j(S.filePath,this.opts.boundaries);for(let $ of m.getFileSymbols(_,S.filePath))f.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}for(let[,S]of s)for(let _ of S)f.set(`${_.filePath}::${_.name}`,{name:_.name,filePath:_.filePath,kind:_.kind,fingerprint:_.fingerprint})}let k=()=>{for(let S of w){let _=j(S,this.opts.boundaries);m.deleteFileSymbols(_,S),g.deleteFileRelations(_,S),t.deleteFile(_,S)}},H=async()=>{let{projectRoot:S,boundaries:_}=this.opts,{parseCache:$}=this.opts,I=0,z=0,L=[],V=[];for(let D of r)try{let Y=an(S,D.filePath),Q=Bun.file(Y),E=await Q.text(),h=D.contentHash||tn(E),o=j(D.filePath,_);t.upsertFile({project:o,filePath:D.filePath,mtimeMs:Q.lastModified,size:Q.size,contentHash:h,updatedAt:new Date().toISOString(),lineCount:E.split(`
4
+ `).length});let Z=(this.opts.parseSourceFn??Nn)(Y,E);if(Zu(Z))throw Z.data;let P=Z;V.push({filePath:D.filePath,text:E,contentHash:h,parsed:P,project:o})}catch(Y){this.logger.error(`[IndexCoordinator] Failed to prepare ${D.filePath}:`,Y),L.push(D.filePath)}let X=new Set;for(let D of _)for(let[Y]of t.getFilesMap(D.project))X.add(`${D.project}::${Y}`);return O.transaction(()=>{for(let D of V)on({parsed:D.parsed,project:D.project,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:m}),z+=cn({ast:D.parsed.program,project:D.project,filePath:D.filePath,relationRepo:g,projectRoot:S,tsconfigPaths:a,knownFiles:X,boundaries:_}),$.set(D.filePath,D.parsed),I+=m.getFileSymbols(D.project,D.filePath).length}),{symbols:I,relations:z,failedFiles:L}},K=0,B=0,A=[];if(u){let{projectRoot:S,boundaries:_}=this.opts,{parseCache:$}=this.opts,I=await Promise.allSettled(r.map(async(V)=>{let X=an(S,V.filePath),D=Bun.file(X),Y=await D.text(),Q=V.contentHash||tn(Y);return{filePath:V.filePath,text:Y,contentHash:Q,mtimeMs:D.lastModified,size:D.size}})),z=I.filter((V)=>V.status==="fulfilled").map((V)=>V.value);for(let V of I)if(V.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",V.reason);let L=[];O.transaction(()=>{for(let D of z){let Y=j(D.filePath,_);t.deleteFile(Y,D.filePath)}for(let D of w){let Y=j(D,_);m.deleteFileSymbols(Y,D),g.deleteFileRelations(Y,D),t.deleteFile(Y,D)}for(let D of z){let Y=j(D.filePath,_);t.upsertFile({project:Y,filePath:D.filePath,mtimeMs:D.mtimeMs,size:D.size,contentHash:D.contentHash,updatedAt:new Date().toISOString(),lineCount:D.text.split(`
5
+ `).length})}let V=new Set;for(let D of _)for(let[Y]of t.getFilesMap(D.project))V.add(`${D.project}::${Y}`);let X=this.opts.parseSourceFn??Nn;for(let D of z){let Y=j(D.filePath,_),Q=X(an(S,D.filePath),D.text);if(Zu(Q))throw Q.data;let E=Q;L.push({filePath:D.filePath,parsed:E}),on({parsed:E,project:Y,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:m}),B+=cn({ast:E.program,project:Y,filePath:D.filePath,relationRepo:g,projectRoot:S,tsconfigPaths:a,knownFiles:V,boundaries:_}),K+=m.getFileSymbols(Y,D.filePath).length}});for(let V of L)$.set(V.filePath,V.parsed)}else{k();let S=await H();K=S.symbols,B=S.relations,A=S.failedFiles}for(let S of r){let _=j(S.filePath,this.opts.boundaries);for(let $ of m.getFileSymbols(_,S.filePath))M.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}let N={added:[],modified:[],removed:[]};for(let[S,_]of M){let $=f.get(S);if(!$)N.added.push({name:_.name,filePath:_.filePath,kind:_.kind});else if($.fingerprint!==_.fingerprint)N.modified.push({name:_.name,filePath:_.filePath,kind:_.kind})}for(let[S,_]of f)if(!M.has(S))N.removed.push({name:_.name,filePath:_.filePath,kind:_.kind});if(!u)for(let[S,_]of s)for(let $ of _){if(!$.fingerprint)continue;let I=j(S,this.opts.boundaries),z=m.getByFingerprint(I,$.fingerprint);if(z.length===1){let L=z[0];g.retargetRelations({dstProject:I,oldFile:S,oldSymbol:$.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:r.length,removedFiles:w.length,totalSymbols:K,totalRelations:B,durationMs:Date.now()-i,changedFiles:r.map((S)=>S.filePath),deletedFiles:[...w],failedFiles:A,changedSymbols:N}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function ft(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function At(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Gu(n,u,i={}){let t=i.now??Date.now,m=i.isAlive??ft,g=i.staleAfterSeconds??90;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u),"owner";let r=Math.floor((t()-At(O.heartbeat_at))/1000);if(m(O.pid)&&r<g)return"reader";return n.replaceOwner(u),"owner"})}function Xu(n,u){n.deleteOwner(u)}function Tu(n,u){n.touchOwner(u)}class Mn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let i=this.#u.keys().next().value;if(i!==void 0)this.#u.delete(i)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class nu{lru;constructor(n=500){this.lru=new Mn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function uu(n){let{symbolRepo:u,project:i,query:t}=n,m=t.project??i,g=t.limit??100,O={kind:t.kind,filePath:t.filePath,isExported:t.isExported,project:m,limit:g,resolvedType:t.resolvedType};if(t.text)if(t.exact)O.exactName=t.text;else{let w=Kn(t.text);if(w)O.ftsQuery=w}if(t.decorator)O.decorator=t.decorator;if(t.regex)O.regex=t.regex;return u.searchByQuery(O).map((w)=>({id:w.id,filePath:w.filePath,kind:w.kind,name:w.name,span:{start:{line:w.startLine,column:w.startColumn},end:{line:w.endLine,column:w.endColumn}},isExported:w.isExported===1,signature:w.signature,fingerprint:w.fingerprint,detail:w.detailJson?(()=>{try{return JSON.parse(w.detailJson)}catch{return{}}})():{}}))}function iu(n){let{relationRepo:u,project:i,query:t}=n,m=t.project??i,g=t.limit??500;return u.searchRelations({srcFilePath:t.srcFilePath,srcSymbolName:t.srcSymbolName,dstFilePath:t.dstFilePath,dstSymbolName:t.dstSymbolName,dstProject:t.dstProject,type:t.type,project:m,limit:g}).map((r)=>{let w;if(r.metaJson)try{w=JSON.parse(r.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",r.metaJson)}return{type:r.type,srcFilePath:r.srcFilePath,srcSymbolName:r.srcSymbolName,dstFilePath:r.dstFilePath,dstSymbolName:r.dstSymbolName,dstProject:r.dstProject,metaJson:r.metaJson??void 0,meta:w}})}import{findInFiles as _t,Lang as Jt}from"@ast-grep/napi";async function tu(n){if(n.filePaths.length===0)return[];let u=[];return await _t(Jt.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,t)=>{if(i)return;for(let m of t){let g=m.range();u.push({filePath:m.getRoot().filename(),startLine:g.start.line+1,endLine:g.end.line+1,matchedText:m.text()})}}),u}import F from"typescript";import{isErr as Qt}from"@zipbul/result";import l from"typescript";import Nt from"path";import{err as mu}from"@zipbul/result";function Mt(n){try{return Au("fs").readFileSync(n,"utf-8")}catch{return}}function $t(n){try{return Au("fs").readFileSync(n,"utf-8")}catch{return}}class Yn{#n;#u;#i=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let i=u.readConfigFile??Mt,t=u.resolveNonTrackedFile??$t,m=Nt.dirname(n),g=i(n);if(g===void 0)return mu(J("semantic",`tsconfig not found: ${n}`));let O=l.parseJsonText(n,g),r=O.parseDiagnostics;if(r&&r.length>0){let f=r.map((M)=>l.flattenDiagnosticMessageText(M.messageText,`
6
+ `)).join("; ");return mu(J("semantic",`tsconfig parse error: ${f}`))}let w=l.parseJsonSourceFileConfigFileContent(O,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(f)=>i(f)!==void 0||t(f)!==void 0,readFile:(f)=>i(f)??t(f)},m);if(w.errors.length>0){let f=w.errors.filter((M)=>M.category===l.DiagnosticCategory.Error&&M.code!==18003);if(f.length>0){let M=f.map((k)=>l.flattenDiagnosticMessageText(k.messageText,`
7
+ `)).join("; ");return mu(J("semantic",`tsconfig compile error: ${M}`))}}let a=new Cu(w.fileNames,w.options,m,t),s=l.createLanguageService(a);return new Yn(s,a)}get isDisposed(){return this.#i}getProgram(){this.#m();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#m(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#m(),this.#n}notifyFileChanged(n,u){if(this.#i)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#i)return;this.#u.removeFile(n)}dispose(){if(this.#i)return;this.#i=!0,this.#n.dispose()}#m(){if(this.#i)throw Error("TscProgram is disposed")}}class Cu{#n;#u;#i;#m;#t=new Map;constructor(n,u,i,t){this.#n=[...n],this.#u=u,this.#i=i,this.#m=t}updateFile(n,u){let i=this.#t.get(n);if(i)i.version+=1,i.content=u;else this.#t.set(n,{version:1,content:u})}removeFile(n){this.#t.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#t.keys()];return[...this.#n.filter((i)=>!this.#t.has(i)),...n]}getScriptVersion(n){let u=this.#t.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#t.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let i=this.#m(n);if(i!==void 0)return l.ScriptSnapshot.fromString(i);return}getCurrentDirectory(){return this.#i}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#t.has(n))return!0;return this.#m(n)!==void 0}readFile(n){let u=this.#t.get(n);if(u)return u.content;return this.#m(n)}}import p from"typescript";import Wt from"typescript";function c(n,u){if(u<0||u>=n.getEnd())return;function i(t){let m=t.getStart(n,!1),g=t.getEnd();if(u<m||u>=g)return;let O;return Wt.forEachChild(t,(r)=>{if(!O)O=i(r)}),O??t}return i(n)}function Dt(n){return!!(n.flags&p.TypeFlags.Object)&&!!(n.objectFlags&p.ObjectFlags.Reference)}function $n(n,u,i=0){let t=n.typeToString(u),m=u.flags,g=!!(m&p.TypeFlags.Union),O=!!(m&p.TypeFlags.Intersection),r;if(i<8&&Dt(u)){let f=n.getTypeArguments(u);if(f.length>0)r=f}let w=!!(m&p.TypeFlags.TypeParameter)||r!==void 0&&r.length>0,a;if(g&&i<8)a=u.types.map((f)=>$n(n,f,i+1));else if(O&&i<8)a=u.types.map((f)=>$n(n,f,i+1));let s;if(r&&r.length>0)s=r.map((f)=>$n(n,f,i+1));return{text:t,flags:m,isUnion:g,isIntersection:O,isGeneric:w,members:a,typeArguments:s}}function kt(n){return p.isFunctionDeclaration(n)||p.isVariableDeclaration(n)||p.isClassDeclaration(n)||p.isInterfaceDeclaration(n)||p.isTypeAliasDeclaration(n)||p.isEnumDeclaration(n)||p.isMethodDeclaration(n)||p.isPropertyDeclaration(n)||p.isPropertySignature(n)||p.isMethodSignature(n)}class gu{program;constructor(n){this.program=n}collectAt(n,u){let i=this.program.getProgram(),t=this.program.getChecker();if(u<0)return null;let m=i.getSourceFile(n);if(!m)return null;if(u>=m.getEnd())return null;let g=c(m,u);if(!g)return null;if(!p.isIdentifier(g))return null;try{let O=t.getTypeAtLocation(g);return $n(t,O)}catch{return null}}collectFile(n){let u=new Map,i=this.program.getProgram(),t=this.program.getChecker(),m=i.getSourceFile(n);if(!m)return u;function g(O){if(kt(O)&&O.name&&p.isIdentifier(O.name)){let r=O.name;try{let w=t.getTypeAtLocation(r),a=r.getStart(m);u.set(a,$n(t,w))}catch{}}p.forEachChild(O,g)}return g(m),u}}import mn from"typescript";var It=1000,Ht=1;function Kt(n){let u=n.declarations?.[0],i=u?.getSourceFile(),t=u?mn.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:i?.fileName??"",position:t?.getStart(i,!1)??u?.getStart(i,!1)??0}}function Zn(n,u=0){let i=n.declarations?.[0],t=i?.getSourceFile(),m=i?mn.getNameOfDeclaration(i):void 0,g=t?.fileName??"",O=m?.getStart(t,!1)??i?.getStart(t,!1)??0,r={name:n.getName(),filePath:g,position:O},w=n;if(w.parent)r.parent=Kt(w.parent);if(u<Ht){let a=n.flags,s=!!(a&mn.SymbolFlags.Enum),f=!!(a&(mn.SymbolFlags.NamespaceModule|mn.SymbolFlags.ValueModule)),M=!!(a&(mn.SymbolFlags.Class|mn.SymbolFlags.Interface));if(s&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((H)=>{k.push(Zn(H,u+1))}),r.members=k}else if(M&&n.members&&n.members.size>0){let k=[];n.members.forEach((H)=>{k.push(Zn(H,u+1))}),r.members=k}if(f&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((H)=>{k.push(Zn(H,u+1))}),r.exports=k}}return r}class ru{#n;#u;#i=new Map;constructor(n,u=It){this.#n=n,this.#u=new Mn(u)}get(n,u){if(this.#n.isDisposed)return null;let i=`${n}:${u}`,t=this.#u.get(i);if(t!==void 0)return t;let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;let O=c(g,u);if(!O||!mn.isIdentifier(O))return null;let w=this.#n.getChecker().getSymbolAtLocation(O);if(!w)return null;let a=Zn(w);this.#u.set(i,a);let s=this.#i.get(n);if(!s)s=new Set,this.#i.set(n,s);return s.add(i),a}invalidate(n){let u=this.#i.get(n);if(u){for(let i of u)this.#u.delete(i);this.#i.delete(n)}}clear(){this.#u.clear(),this.#i.clear()}}import Vt from"typescript";class wu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),t=i.getSourceFile(n);if(!t)return[];let m=c(t,u);if(!m||!Vt.isIdentifier(m))return[];let O=this.#n.getLanguageService().findReferences(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O)for(let a of w.references){let s=i.getSourceFile(a.fileName);if(!s)continue;let{line:f,character:M}=s.getLineAndCharacterOfPosition(a.textSpan.start);r.push({filePath:a.fileName,position:a.textSpan.start,line:f+1,column:M,isDefinition:a.isDefinition??!1,isWrite:a.isWriteAccess??!1})}return r}}import G from"typescript";function zt(n,u){let i=c(n,u);if(!i)return;if(bu(i))return i;let t=i.parent;for(let m=0;m<5&&t;m++){if(bu(t))return t;t=t.parent}return i}function bu(n){return G.isClassDeclaration(n)||G.isClassExpression(n)||G.isFunctionDeclaration(n)||G.isFunctionExpression(n)||G.isArrowFunction(n)||G.isVariableDeclaration(n)||G.isObjectLiteralExpression(n)}function Ru(n){if(G.isClassDeclaration(n)||G.isClassExpression(n))return"class";if(G.isFunctionDeclaration(n)||G.isFunctionExpression(n)||G.isArrowFunction(n))return"function";if(G.isObjectLiteralExpression(n))return"object";if(G.isVariableDeclaration(n)&&n.initializer)return Ru(n.initializer);return"class"}function Bt(n,u){if(G.isClassDeclaration(n)||G.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(G.isClassExpression(n))return n.name?.getText(u)??"";if(G.isVariableDeclaration(n)&&G.isIdentifier(n.name))return n.name.getText(u);if(G.isFunctionExpression(n))return n.name?.getText(u)??"";if(G.isArrowFunction(n)&&n.parent&&G.isVariableDeclaration(n.parent)){if(G.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(G.isObjectLiteralExpression(n)&&n.parent&&G.isVariableDeclaration(n.parent)){if(G.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Ut(n){if(!G.isClassDeclaration(n)&&!G.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((i)=>i.token===G.SyntaxKind.ImplementsKeyword)}class Ou{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),t=i.getSourceFile(n);if(!t)return[];let m=c(t,u);if(!m||!G.isIdentifier(m))return[];let O=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O){if(w.kind===G.ScriptElementKind.interfaceElement||w.kind===G.ScriptElementKind.typeElement)continue;let a=i.getSourceFile(w.fileName);if(!a)continue;let s=zt(a,w.textSpan.start);if(!s)continue;let f=Ru(s),M=Bt(s,a),k=Ut(s);r.push({filePath:w.fileName,symbolName:M,position:w.textSpan.start,kind:f,isExplicit:k})}return r}}function yu(n){return F.canHaveModifiers(n)&&F.getModifiers(n)?.some((u)=>u.kind===F.SyntaxKind.ExportKeyword)===!0}function Lt(n){if(F.isFunctionDeclaration(n))return"function";if(F.isClassDeclaration(n))return"class";if(F.isInterfaceDeclaration(n))return"interface";if(F.isTypeAliasDeclaration(n))return"type";if(F.isEnumDeclaration(n))return"enum";if(F.isVariableDeclaration(n))return"const";if(F.isVariableStatement(n))return"const";return"unknown"}function Fu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Gn{#n;#u;#i;#m;#t;#g=!1;constructor(n,u,i,t,m){this.#n=n,this.#u=u,this.#i=i,this.#m=t,this.#t=m}static create(n,u={}){let i=Yn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(Qt(i))return i;let t=i,m=u.typeCollector??new gu(t),g=u.symbolGraph??new ru(t),O=u.referenceResolver??new wu(t),r=u.implementationFinder??new Ou(t);return new Gn(t,m,g,O,r)}get isDisposed(){return this.#g}collectTypeAt(n,u){return this.#r(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#r(),this.#u.collectFile(n)}findReferences(n,u){return this.#r(),this.#m.findAt(n,u)}findImplementations(n,u){return this.#r(),this.#t.findAt(n,u)}getSymbolNode(n,u){return this.#r(),this.#i.get(n,u)}getModuleInterface(n){this.#r();let u=this.#u.collectFile(n),i=[],m=this.#n.getProgram().getSourceFile(n);if(!m)return{filePath:n,exports:i};function g(O){if(F.isVariableStatement(O)&&yu(O)){for(let r of O.declarationList.declarations)if(F.isIdentifier(r.name)){let w=r.name.getStart(m),a=u.get(w)??null;i.push({name:r.name.text,kind:"const",resolvedType:a})}return}if((F.isFunctionDeclaration(O)||F.isClassDeclaration(O)||F.isInterfaceDeclaration(O)||F.isTypeAliasDeclaration(O)||F.isEnumDeclaration(O))&&yu(O)&&O.name){let r=O.name,w=r.getStart(m),a=u.get(w)??null;i.push({name:r.text,kind:Lt(O),resolvedType:a});return}F.forEachChild(O,g)}return g(m),{filePath:n,exports:i}}notifyFileChanged(n,u){if(this.#g)return;this.#n.notifyFileChanged(n,u),this.#i.invalidate(n)}notifyFileDeleted(n){if(this.#g)return;this.#n.removeFile(n),this.#i.invalidate(n)}lineColumnToPosition(n,u,i){this.#r();let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;try{return F.getPositionOfLineAndCharacter(t,u-1,i)}catch{return null}}findNamePosition(n,u,i){this.#r();let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;let m=t.getFullText(),g=u;while(g<m.length){let O=m.indexOf(i,g);if(O<0)return null;let r=O>0?m.charCodeAt(O-1):32,w=O+i.length<m.length?m.charCodeAt(O+i.length):32;if(!Fu(r)&&!Fu(w))return O;g=O+1}return null}dispose(){if(this.#g)return;this.#g=!0,this.#n.dispose(),this.#i.clear()}#r(){if(this.#g)throw Error("SemanticLayer is disposed")}}var Zt=30000,pu=60000,Gt=10;function Xt(n,u){return(i)=>{if(u.handleWatcherEvent?.(i),n.semanticLayer)if(i.eventType==="delete")n.semanticLayer.notifyFileDeleted(i.filePath);else n.readFileFn(i.filePath).then((t)=>{n.semanticLayer?.notifyFileChanged(i.filePath,t)}).catch(()=>{})}}async function Tt(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(i)=>{try{let t=Dn.resolve(n.projectRoot,i.filePath),m=await n.readFileFn(t);n.semanticLayer?.notifyFileChanged(t,m)}catch{}}))}async function Eu(n,u){let i=n.coordinatorFactory?n.coordinatorFactory():new en({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=i;for(let t of n.onIndexedCallbacks)i.onIndexed(t);if(i.onIndexed(()=>{n.graphCache=null,n.graphCacheKey=null}),u.isWatchMode){let t=n.watcherFactory?n.watcherFactory():new Pn({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await t.start(Xt(n,i)).then((m)=>{if(Wn(m))throw m.data}),n.watcher=t,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Zt)}await i.fullIndex(),await Tt(n)}function Ct(n,u){let i=["SIGTERM","SIGINT","beforeExit"];for(let t of i){let m=()=>{u().catch((g)=>n.logger.error("[Gildash] close error during signal",t,g))};if(t==="beforeExit")process.on("beforeExit",m);else process.on(t,m);n.signalHandlers.push([t,m])}}async function vu(n){let{projectRoot:u,extensions:i=[".ts",".mts",".cts"],ignorePatterns:t=["**/node_modules/**"],parseCacheCapacity:m=500,logger:g=console,existsSyncFn:O=Yt,dbConnectionFactory:r,watcherFactory:w,coordinatorFactory:a,repositoryFactory:s,acquireWatcherRoleFn:f=Gu,releaseWatcherRoleFn:M=Xu,updateHeartbeatFn:k=Tu,discoverProjectsFn:H=zn,parseSourceFn:K=Nn,extractSymbolsFn:B=Qn,extractRelationsFn:A=Ln,symbolSearchFn:N=uu,relationSearchFn:S=iu,patternSearchFn:_=tu,loadTsconfigPathsFn:$=Jn,readFileFn:I=async(Q)=>Bun.file(Q).text(),unlinkFn:z=async(Q)=>{await Bun.file(Q).unlink()},watchMode:L,semantic:V,semanticLayerFactory:X}=n;if(!Dn.isAbsolute(u))return Xn(J("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`));if(!O(u))return Xn(J("validation",`Gildash: projectRoot does not exist: "${u}"`));let D=r?r():new pn({projectRoot:u}),Y=D.open();if(Wn(Y))return Y;try{let Q=await H(u),E=Q[0]?.project??Dn.basename(u),h=s?s():(()=>{let P=D;return{fileRepo:new En(P),symbolRepo:new vn(P),relationRepo:new qn(P),parseCache:new nu(m)}})(),o=L??!0,An;if(o)An=await Promise.resolve(f(D,process.pid,{}));else An="owner";let Z={projectRoot:u,extensions:i,ignorePatterns:t,logger:g,defaultProject:E,role:An,db:D,symbolRepo:h.symbolRepo,relationRepo:h.relationRepo,fileRepo:h.fileRepo,parseCache:h.parseCache,releaseWatcherRoleFn:M,parseSourceFn:K,extractSymbolsFn:B,extractRelationsFn:A,symbolSearchFn:N,relationSearchFn:S,patternSearchFn:_,readFileFn:I,unlinkFn:z,existsSyncFn:O,acquireWatcherRoleFn:f,updateHeartbeatFn:k,watcherFactory:w,coordinatorFactory:a,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:Q,onIndexedCallbacks:new Set,graphCache:null,graphCacheKey:null,semanticLayer:null};if(Bn(u),Z.tsconfigPaths=await $(u),V){let P=Dn.join(u,"tsconfig.json"),Sn=X?X(P):Gn.create(P);if(Wn(Sn))return D.close(),Sn;Z.semanticLayer=Sn}if(An==="owner")await Eu(Z,{isWatchMode:o});else{let P=0,Sn=async()=>{try{let bn=await Promise.resolve(Z.acquireWatcherRoleFn(Z.db,process.pid,{}));if(P=0,bn==="owner"){clearInterval(Z.timer),Z.timer=null;try{await Eu(Z,{isWatchMode:!0})}catch(Rn){if(Z.logger.error("[Gildash] owner promotion failed, reverting to reader",Rn),Z.watcher){let kn=await Z.watcher.close();if(Wn(kn))Z.logger.error("[Gildash] watcher close error during promotion rollback",kn.data);Z.watcher=null}if(Z.coordinator)await Z.coordinator.shutdown().catch((kn)=>Z.logger.error("[Gildash] coordinator shutdown error during promotion rollback",kn)),Z.coordinator=null;if(Z.timer===null)Z.timer=setInterval(Sn,pu)}}}catch(bn){if(P++,Z.logger.error("[Gildash] healthcheck error",bn),P>=Gt)Z.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(Z.timer),Z.timer=null,Tn(Z).catch((Rn)=>Z.logger.error("[Gildash] close error during healthcheck shutdown",Rn))}};Z.timer=setInterval(Sn,pu)}if(o)Ct(Z,()=>Tn(Z));return Z}catch(Q){return D.close(),Xn(J("store","Gildash: initialization failed",Q))}}async function Tn(n,u){if(n.closed)return;n.closed=!0;let i=[];for(let[t,m]of n.signalHandlers)if(t==="beforeExit")process.off("beforeExit",m);else process.off(t,m);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}if(n.watcher){let t=await n.watcher.close();if(Wn(t))i.push(t.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(t){i.push(t instanceof Error?t:Error(String(t)))}try{n.db.close()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}if(u?.cleanup)for(let t of["","-wal","-shm"])try{await n.unlinkFn(Dn.join(n.projectRoot,nn,In+t))}catch{}if(i.length>0)return Xn(J("close","Gildash: one or more errors occurred during close()",i))}import{err as qu,isErr as ju}from"@zipbul/result";function Pu(n,u,i,t){if(n.closed)return qu(J("closed","Gildash: instance is closed"));let m=n.parseSourceFn(u,i,t);if(ju(m))return m;return n.parseCache.set(u,m),m}async function du(n,u,i){if(n.closed)return qu(J("closed","Gildash: instance is closed"));let t=new Map;return await Promise.all(u.map(async(m)=>{try{let g=await n.readFileFn(m),O=n.parseSourceFn(m,g,i);if(!ju(O))t.set(m,O)}catch{}})),t}function hu(n,u){if(n.closed)return;return n.parseCache.get(u)}import{err as ou}from"@zipbul/result";function xu(n,u){if(n.closed)return ou(J("closed","Gildash: instance is closed"));return n.extractSymbolsFn(u)}function lu(n,u){if(n.closed)return ou(J("closed","Gildash: instance is closed"));return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import{err as b}from"@zipbul/result";import cu from"path";function eu(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(i){return b(J("store","Gildash: getStats failed",i))}}function Su(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(i){return b(J("search","Gildash: searchSymbols failed",i))}}function ni(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(i){return b(J("search","Gildash: searchRelations failed",i))}}function ui(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(i){return b(J("search","Gildash: searchAllSymbols failed",i))}}function ii(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(i){return b(J("search","Gildash: searchAllRelations failed",i))}}function ti(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(i){return b(J("store","Gildash: listIndexedFiles failed",i))}}function mi(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(t){return b(J("search","Gildash: getInternalRelations failed",t))}}function gi(n,u,i,t){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let m=t??n.defaultProject,g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:m,query:{text:u,exact:!0,filePath:i,limit:1}});if(g.length===0)return b(J("search",`Gildash: symbol '${u}' not found in '${i}'`));let O=g[0],r=O.detail,w={...O,members:Array.isArray(r.members)?r.members:void 0,jsDoc:typeof r.jsDoc==="string"?r.jsDoc:void 0,parameters:typeof r.parameters==="string"?r.parameters:void 0,returnType:typeof r.returnType==="string"?r.returnType:void 0,heritage:Array.isArray(r.heritage)?r.heritage:void 0,decorators:Array.isArray(r.decorators)?r.decorators:void 0,typeParameters:typeof r.typeParameters==="string"?r.typeParameters:void 0};if(n.semanticLayer)try{let a=cu.isAbsolute(i)?i:cu.resolve(n.projectRoot,i),s=n.semanticLayer.lineColumnToPosition(a,O.span.start.line,O.span.start.column);if(s!==null){let f=n.semanticLayer.findNamePosition(a,s,O.name)??s,M=n.semanticLayer.collectTypeAt(a,f);if(M)w.resolvedType=M}}catch{}return w}catch(m){return b(J("search","Gildash: getFullSymbol failed",m))}}function ri(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let t=i??n.defaultProject,m=n.fileRepo.getFile(t,u);if(!m)return b(J("search",`Gildash: file '${u}' is not in the index`));let g=n.symbolRepo.getFileSymbols(t,u),O=n.relationRepo.getOutgoing(t,u);return{filePath:m.filePath,lineCount:m.lineCount??0,size:m.size,symbolCount:g.length,exportedSymbolCount:g.filter((r)=>r.isExported).length,relationCount:O.length}}catch(t){return b(J("store","Gildash: getFileStats failed",t))}}function wi(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.fileRepo.getFile(i??n.defaultProject,u)}catch(t){return b(J("store","Gildash: getFileInfo failed",t))}}function Oi(n,u,i){return Su(n,{filePath:u,project:i??void 0,limit:1e4})}function Si(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i??n.defaultProject,query:{filePath:u,isExported:!0}}).map((g)=>({name:g.name,kind:g.kind,parameters:g.detail.parameters??void 0,returnType:g.detail.returnType??void 0,jsDoc:g.detail.jsDoc??void 0}));return{filePath:u,exports:m}}catch(t){return b(J("search","Gildash: getModuleInterface failed",t))}}import{err as v}from"@zipbul/result";class Cn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((i)=>[...this.options.relationRepo.getByType(i,"imports"),...this.options.relationRepo.getByType(i,"type-references"),...this.options.relationRepo.getByType(i,"re-exports")]);for(let i of u){let{srcFilePath:t,dstFilePath:m}=i;if(!this.adjacencyList.has(t))this.adjacencyList.set(t,new Set);if(this.adjacencyList.get(t).add(m),!this.adjacencyList.has(m))this.adjacencyList.set(m,new Set);if(!this.reverseAdjacencyList.has(m))this.reverseAdjacencyList.set(m,new Set);this.reverseAdjacencyList.get(m).add(t)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,i=[n];while(i.length>0){let t=i.shift();for(let m of this.reverseAdjacencyList.get(t)??[])if(!u.has(m))u.add(m),i.push(m)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let t=[{node:i,entered:!1}];while(t.length>0){let m=t.pop();if(m.entered){u.delete(m.node);continue}if(u.has(m.node))return!0;if(n.has(m.node))continue;n.add(m.node),u.add(m.node),t.push({node:m.node,entered:!0});for(let g of this.adjacencyList.get(m.node)??[]){if(u.has(g))return!0;if(!n.has(g))t.push({node:g,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let i of n)for(let t of this.getTransitiveDependents(i))u.add(t);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,i]of this.adjacencyList)n.set(u,Array.from(i));return n}getTransitiveDependencies(n){let u=new Set,i=[n];while(i.length>0){let t=i.shift();for(let m of this.adjacencyList.get(t)??[])if(!u.has(m))u.add(m),i.push(m)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let i=new Map;for(let[t,m]of this.adjacencyList)i.set(t,Array.from(m));return qt(i,u)}}var Ft=(n,u)=>n.localeCompare(u);function pt(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let i=u;for(let t=1;t<u.length;t++){let m=u.slice(t).concat(u.slice(0,t));if(m.join("::")<i.join("::"))i=m}return[...i]}function au(n,u,i){let t=pt(i);if(t.length===0)return!1;let m=t.join("->");if(n.has(m))return!1;return n.add(m),u.push(t),!0}function Et(n){let u=0,i=[],t=new Set,m=new Map,g=new Map,O=[],r=(w)=>{m.set(w,u),g.set(w,u),u+=1,i.push(w),t.add(w);for(let a of n.get(w)??[])if(!m.has(a))r(a),g.set(w,Math.min(g.get(w)??0,g.get(a)??0));else if(t.has(a))g.set(w,Math.min(g.get(w)??0,m.get(a)??0));if(g.get(w)===m.get(w)){let a=[],s="";do s=i.pop()??"",t.delete(s),a.push(s);while(s!==w&&i.length>0);O.push(a)}};for(let w of n.keys())if(!m.has(w))r(w);return{components:O}}function vt(n,u,i){let t=[],m=new Set,g=[...n].sort(Ft),O=(r,w,a)=>{w.delete(r);let s=a.get(r);if(!s)return;for(let f of s)if(w.has(f))O(f,w,a);s.clear()};for(let r=0;r<g.length&&t.length<i;r++){let w=g[r]??"",a=new Set(g.slice(r)),s=new Set,f=new Map,M=[],k=(K)=>(u.get(K)??[]).filter((B)=>a.has(B)),H=(K)=>{if(t.length>=i)return!0;let B=!1;M.push(K),s.add(K);for(let A of k(K)){if(t.length>=i)break;if(A===w)au(m,t,M.concat(w)),B=!0;else if(!s.has(A)){if(H(A))B=!0}}if(B)O(K,s,f);else for(let A of k(K)){let N=f.get(A)??new Set;N.add(K),f.set(A,N)}return M.pop(),B};H(w)}return t}function qt(n,u){let{components:i}=Et(n),t=[],m=new Set;for(let g of i){if(t.length>=u)break;if(g.length===0)continue;if(g.length===1){let w=g[0]??"";if((n.get(w)??[]).includes(w))au(m,t,[w,w]);continue}let O=u-t.length,r=vt(g,n,O);for(let w of r){if(t.length>=u)break;au(m,t,w)}}return t}function ai(n){n.graphCache=null,n.graphCacheKey=null}function fn(n,u){let i=u??"__cross__";if(n.graphCache&&n.graphCacheKey===i)return n.graphCache;let t=new Cn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((m)=>m.project)});return t.build(),n.graphCache=t,n.graphCacheKey=i,t}function si(n,u,i,t=1e4){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,type:"imports",project:i??n.defaultProject,limit:t}}).map((m)=>m.dstFilePath)}catch(m){return v(J("search","Gildash: getDependencies failed",m))}}function fi(n,u,i,t=1e4){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{dstFilePath:u,type:"imports",project:i??n.defaultProject,limit:t}}).map((m)=>m.srcFilePath)}catch(m){return v(J("search","Gildash: getDependents failed",m))}}async function Ai(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,i).getAffectedByChange(u)}catch(t){return v(J("search","Gildash: getAffected failed",t))}}async function _i(n,u){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).hasCycle()}catch(i){return v(J("search","Gildash: hasCycle failed",i))}}async function Ji(n,u){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).getAdjacencyList()}catch(i){return v(J("search","Gildash: getImportGraph failed",i))}}async function Ni(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,i).getTransitiveDependencies(u)}catch(t){return v(J("search","Gildash: getTransitiveDependencies failed",t))}}async function Mi(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).getCyclePaths(i)}catch(t){return v(J("search","Gildash: getCyclePaths failed",t))}}async function $i(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{let t=fn(n,i);return{filePath:u,fanIn:t.getDependents(u).length,fanOut:t.getDependencies(u).length}}catch(t){return v(J("search","Gildash: getFanMetrics failed",t))}}import{err as q}from"@zipbul/result";import Wi from"path";function su(n,u,i,t){let m=t??n.defaultProject,g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:m,query:{text:u,exact:!0,filePath:i,limit:1}});if(g.length===0)return null;let O=g[0],r=Wi.isAbsolute(i)?i:Wi.resolve(n.projectRoot,i),w=n.semanticLayer.lineColumnToPosition(r,O.span.start.line,O.span.start.column);if(w===null)return null;let a=n.semanticLayer.findNamePosition(r,w,O.name)??w;return{sym:O,position:a,absPath:r}}function Di(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.collectTypeAt(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getResolvedType failed",m))}}function ki(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.findReferences(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getSemanticReferences failed",m))}}function Ii(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.findImplementations(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getImplementations failed",m))}}function Hi(n,u){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{return n.semanticLayer.getModuleInterface(u)}catch(i){return q(J("search","Gildash: getSemanticModuleInterface failed",i))}}import{err as e}from"@zipbul/result";function Ki(n,u){let i=new Map(n.map((r)=>[`${r.name}::${r.filePath}`,r])),t=new Map(u.map((r)=>[`${r.name}::${r.filePath}`,r])),m=[],g=[],O=[];for(let[r,w]of t){let a=i.get(r);if(!a)m.push(w);else if(a.fingerprint!==w.fingerprint)O.push({before:a,after:w})}for(let[r,w]of i)if(!t.has(r))g.push(w);return{added:m,removed:g,modified:O}}function Vi(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let i=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),i()}}async function zi(n){if(n.closed)return e(J("closed","Gildash: instance is closed"));if(!n.coordinator)return e(J("closed","Gildash: reindex() is not available for readers"));try{let u=await n.coordinator.fullIndex();return ai(n),u}catch(u){return e(J("index","Gildash: reindex failed",u))}}function Bi(n,u,i,t){if(n.closed)return e(J("closed","Gildash: instance is closed"));let m=t??n.defaultProject,g=new Set,O=[],r=u,w=i;for(;;){let a=`${w}::${r}`;if(g.has(a))return e(J("search","Gildash: resolveSymbol detected circular re-export chain"));g.add(a);let s=n.relationSearchFn({relationRepo:n.relationRepo,project:m,query:{type:"re-exports",srcFilePath:w,limit:500}}),f,M;for(let k of s){let H;if(k.metaJson)try{let B=JSON.parse(k.metaJson);if(Array.isArray(B.specifiers))H=B.specifiers}catch{}if(!H)continue;let K=H.find((B)=>B.exported===r);if(!K)continue;f=k.dstFilePath,M=K.local;break}if(!f||!M)return{originalName:r,originalFilePath:w,reExportChain:O};O.push({filePath:w,exportedAs:r}),w=f,r=M}}async function Ui(n,u,i){if(n.closed)return e(J("closed","Gildash: instance is closed"));try{let t=i?.project??n.defaultProject,m=i?.filePaths?i.filePaths:n.fileRepo.getAllFiles(t).map((g)=>g.filePath);return await n.patternSearchFn({pattern:u,filePaths:m})}catch(t){return e(J("search","Gildash: findPattern failed",t))}}async function Qi(n,u,i,t){if(n.closed)return e(J("closed","Gildash: instance is closed"));try{let m=t??n.defaultProject,g=new Set,O=(r,w,a)=>{let s=`${r}::${w}`;if(g.has(s))return{symbolName:r,filePath:w,kind:a,children:[]};g.add(s);let k=n.relationSearchFn({relationRepo:n.relationRepo,project:m,query:{srcFilePath:w,srcSymbolName:r,limit:1000}}).filter((H)=>H.type==="extends"||H.type==="implements").filter((H)=>H.dstSymbolName!=null).map((H)=>O(H.dstSymbolName,H.dstFilePath,H.type));return{symbolName:r,filePath:w,kind:a,children:k}};return O(u,i)}catch(m){return e(J("search","Gildash: getHeritageChain failed",m))}}class fu{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await vu(n);if(ht(u))return u;return new fu(u)}async close(n){return Tn(this._ctx,n)}parseSource(n,u,i){return Pu(this._ctx,n,u,i)}async batchParse(n,u){return du(this._ctx,n,u)}getParsedAst(n){return hu(this._ctx,n)}extractSymbols(n){return xu(this._ctx,n)}extractRelations(n){return lu(this._ctx,n)}getStats(n){return eu(this._ctx,n)}searchSymbols(n){return Su(this._ctx,n)}searchRelations(n){return ni(this._ctx,n)}searchAllSymbols(n){return ui(this._ctx,n)}searchAllRelations(n){return ii(this._ctx,n)}listIndexedFiles(n){return ti(this._ctx,n)}getInternalRelations(n,u){return mi(this._ctx,n,u)}getFullSymbol(n,u,i){return gi(this._ctx,n,u,i)}getFileStats(n,u){return ri(this._ctx,n,u)}getFileInfo(n,u){return wi(this._ctx,n,u)}getSymbolsByFile(n,u){return Oi(this._ctx,n,u)}getModuleInterface(n,u){return Si(this._ctx,n,u)}getDependencies(n,u,i=1e4){return si(this._ctx,n,u,i)}getDependents(n,u,i=1e4){return fi(this._ctx,n,u,i)}async getAffected(n,u){return Ai(this._ctx,n,u)}async hasCycle(n){return _i(this._ctx,n)}async getImportGraph(n){return Ji(this._ctx,n)}async getTransitiveDependencies(n,u){return Ni(this._ctx,n,u)}async getCyclePaths(n,u){return Mi(this._ctx,n,u)}async getFanMetrics(n,u){return $i(this._ctx,n,u)}getResolvedType(n,u,i){return Di(this._ctx,n,u,i)}getSemanticReferences(n,u,i){return ki(this._ctx,n,u,i)}getImplementations(n,u,i){return Ii(this._ctx,n,u,i)}getSemanticModuleInterface(n){return Hi(this._ctx,n)}diffSymbols(n,u){return Ki(n,u)}onIndexed(n){return Vi(this._ctx,n)}async reindex(){return zi(this._ctx)}resolveSymbol(n,u,i){return Bi(this._ctx,n,u,i)}async findPattern(n,u){return Ui(this._ctx,n,u)}async getHeritageChain(n,u,i){return Qi(this._ctx,n,u,i)}}export{uu as symbolSearch,iu as relationSearch,tu as patternSearch,J as gildashError,fu as Gildash,Cn as DependencyGraph};
6
8
 
7
- //# debugId=17EE0521DDE8D3DB64756E2164756E21
9
+ //# debugId=019D7FA17E588F3E64756E2164756E21
8
10
  //# sourceMappingURL=index.js.map