scip-query 0.15.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -1
- package/README.md +148 -66
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-2EU6WVR3.js +3 -0
- package/dist/chunk-2HFXPIBT.js +2 -0
- package/dist/chunk-2LGPMYS2.js +35 -0
- package/dist/chunk-2Y7YX54K.js +16 -0
- package/dist/chunk-363TZ64I.js +2 -0
- package/dist/chunk-3I34FZ6R.js +2 -0
- package/dist/chunk-3LAKH6BV.js +2 -0
- package/dist/chunk-3M2UCPFS.js +3 -0
- package/dist/chunk-3OPIMH42.js +2 -0
- package/dist/{chunk-QZOAOLLZ.js → chunk-3YAZH3JU.js} +2 -2
- package/dist/chunk-5P26M63Y.js +2 -0
- package/dist/{chunk-72FR7KEZ.js → chunk-5TVNLPUM.js} +14 -12
- package/dist/chunk-5UKDCXVC.js +5 -0
- package/dist/{chunk-R7U2I55B.js → chunk-5XDNFOAH.js} +2 -2
- package/dist/chunk-62Y3PC27.js +4 -0
- package/dist/chunk-6DNE65QS.js +40 -0
- package/dist/{chunk-N2OTJWC2.js → chunk-6EVORGCB.js} +2 -2
- package/dist/chunk-6GZ7LM7S.js +2 -0
- package/dist/chunk-753JWTUH.js +3 -0
- package/dist/chunk-7II7NFRV.js +4 -0
- package/dist/{chunk-M7EEHYSU.js → chunk-7RAS466A.js} +2 -2
- package/dist/chunk-A46JTKTM.js +5 -0
- package/dist/{chunk-2XRXEIRK.js → chunk-AAMZRDJT.js} +2 -2
- package/dist/chunk-AMPN2VMF.js +3 -0
- package/dist/{chunk-6XA4LDHY.js → chunk-B3X6KU75.js} +2 -2
- package/dist/chunk-BFWVHD2P.js +16 -0
- package/dist/chunk-BVHP2B4D.js +61 -0
- package/dist/{chunk-BUNDZ6K2.js → chunk-BVUA3GZC.js} +2 -2
- package/dist/{chunk-EDSD3VJK.js → chunk-CKIAEVGM.js} +2 -2
- package/dist/chunk-CM4EZLW4.js +2 -0
- package/dist/chunk-CS3FXTUC.js +2 -0
- package/dist/chunk-CVBS2FD4.js +2 -0
- package/dist/chunk-D5OXYOJP.js +7 -0
- package/dist/chunk-DA34GNNO.js +29 -0
- package/dist/chunk-DKK2H4D7.js +7 -0
- package/dist/chunk-EBSSCVR4.js +5 -0
- package/dist/{chunk-OXTM2RX3.js → chunk-EVCSXWER.js} +2 -2
- package/dist/chunk-FFIYGYQR.js +67 -0
- package/dist/chunk-G4KQ7S74.js +20 -0
- package/dist/{chunk-44P4SJFN.js → chunk-GWWYLYD3.js} +2 -2
- package/dist/chunk-HGUNWXJX.js +2 -0
- package/dist/chunk-HLRWOFXC.js +9 -0
- package/dist/{chunk-YQKECTPV.js → chunk-IRIM3SUR.js} +2 -2
- package/dist/chunk-JHK2DMUQ.js +4 -0
- package/dist/chunk-JQ2PCFZW.js +3 -0
- package/dist/chunk-JRFCWCOD.js +16 -0
- package/dist/chunk-JXAJDINF.js +2 -0
- package/dist/chunk-K32ZOW3P.js +2 -0
- package/dist/{chunk-3H5OSDF7.js → chunk-KI4WPR7Q.js} +2 -2
- package/dist/{chunk-43GKP6LI.js → chunk-KP2DJY7D.js} +2 -2
- package/dist/{chunk-YTVKPJXW.js → chunk-L27UIF3E.js} +2 -2
- package/dist/chunk-LT6AHYVY.js +18 -0
- package/dist/chunk-MCNWCJYL.js +11 -0
- package/dist/{chunk-K6UI6EBZ.js → chunk-MZB3DTHW.js} +2 -2
- package/dist/chunk-NLRWGGPY.js +8 -0
- package/dist/chunk-NLVKD45E.js +13 -0
- package/dist/chunk-OO6S4ECV.js +112 -0
- package/dist/{chunk-QYOPMTZ6.js → chunk-OYGKBDAD.js} +2 -2
- package/dist/chunk-P5QZILZ4.js +2 -0
- package/dist/chunk-P5XHIJHI.js +2 -0
- package/dist/chunk-PCCMMI2M.js +3 -0
- package/dist/{chunk-2TPCIPYA.js → chunk-Q65QYKU7.js} +2 -2
- package/dist/{chunk-K7SPOJHZ.js → chunk-QB7NRST4.js} +2 -2
- package/dist/{chunk-7JZRFDCU.js → chunk-QSNG3NHQ.js} +2 -2
- package/dist/chunk-QVZSWLLZ.js +2 -0
- package/dist/chunk-RLB7FZKR.js +10 -0
- package/dist/{chunk-KYB7FPXT.js → chunk-RPMT6MTX.js} +2 -2
- package/dist/chunk-RQWNF2RM.js +2 -0
- package/dist/chunk-RYFIRFYJ.js +4 -0
- package/dist/{chunk-QARYU7R3.js → chunk-S2FZILCF.js} +2 -2
- package/dist/{chunk-HV27H2V2.js → chunk-S3IXCXW2.js} +2 -2
- package/dist/{chunk-TYCZ7S4I.js → chunk-S5MTSES5.js} +2 -2
- package/dist/chunk-S5RZQA6V.js +2 -0
- package/dist/{chunk-PEHDARNC.js → chunk-SEEJPIWG.js} +2 -2
- package/dist/chunk-SOCS3467.js +2 -0
- package/dist/chunk-U6BJVXWQ.js +2 -0
- package/dist/chunk-UO4IADXJ.js +38 -0
- package/dist/{chunk-ZEO4CXQR.js → chunk-VLSI5MYU.js} +2 -2
- package/dist/chunk-VSQRU3AP.js +2 -0
- package/dist/chunk-VYQY75NA.js +2 -0
- package/dist/{chunk-NOKUZU56.js → chunk-VZCR3VQY.js} +2 -2
- package/dist/chunk-W3ZVRLCH.js +2 -0
- package/dist/chunk-WA64GKWB.js +20 -0
- package/dist/chunk-WFRZGMWJ.js +71 -0
- package/dist/chunk-WN6XEYVX.js +2 -0
- package/dist/chunk-XAEU4ROB.js +101 -0
- package/dist/chunk-XBPAJASV.js +2 -0
- package/dist/{chunk-GY3HAWUA.js → chunk-XC6PUFNN.js} +2 -2
- package/dist/chunk-Y42DMR6F.js +6 -0
- package/dist/chunk-YCVYOV4A.js +7 -0
- package/dist/{chunk-WPZPB42I.js → chunk-YD37KSEK.js} +2 -2
- package/dist/{chunk-V5W7H7V4.js → chunk-YFEJIYWH.js} +2 -2
- package/dist/chunk-YSUD2S7T.js +3 -0
- package/dist/{chunk-KJCDEDQW.js → chunk-ZEKBAMCN.js} +2 -2
- package/dist/chunk-ZHGUZKJL.js +2 -0
- package/dist/cli.js +586 -312
- package/dist/{config-types-aCgyLrvE.d.ts → config-types-SVkUIufk.d.ts} +8 -2
- package/dist/{db-DwCdT3rv.d.ts → db-CS0TuVH6.d.ts} +1 -1
- package/dist/{git-history-Dao3_Pu9.d.ts → git-history-ChNHbfZQ.d.ts} +2 -1
- package/dist/{health-nJUidasZ.d.ts → health-Btal3mQi.d.ts} +4 -4
- package/dist/index.d.ts +7 -5
- package/dist/index.js +1 -19
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +8 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +4 -3
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +3 -3
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +5 -4
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +12 -3
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +8 -3
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +5 -4
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -3
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +4 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +3 -3
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +11 -5
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +5 -5
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +3 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +4 -4
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +4 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +4 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +4 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +4 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +4 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +256 -12
- package/dist/reindex.d.ts +29 -3
- package/dist/reindex.js +251 -22
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-server.js +2 -0
- package/dist/rust-semantic-session-worker.js +2 -0
- package/dist/rust-semantic-worker.js +2 -0
- package/dist/{scip-cli-DeAbuJ2b.d.ts → scip-cli-BKL-26TZ.d.ts} +2 -2
- package/dist/{symbol-types-DaoeXKUt.d.ts → symbol-types-BgWU6lhL.d.ts} +2 -0
- package/dist/watch-server.js +42 -0
- package/docs/AGENT_GUIDE.md +110 -34
- package/docs/AI_FAILURE_MODES.md +8 -3
- package/docs/COMMAND_REFERENCE.md +10 -6
- package/docs/REGEX_POLICY.md +3 -1
- package/docs/accuracy-audit-checklist.md +300 -0
- package/docs/accuracy-hardening-goal.md +493 -54
- package/docs/analyzer-inventory.md +31 -23
- package/docs/analyzer-validation-ledger.md +51 -21
- package/package.json +2 -1
- package/scripts/build-scip-windows.mjs +7 -7
- package/skills/_shared/SKILL.md +20 -19
- package/skills/scip-calibrate/SKILL.md +4 -2
- package/skills/scip-hyper-optimization/SKILL.md +5 -1
- package/skills/scip-query/SKILL.md +1 -1
- package/skills/scip-setup/SKILL.md +104 -4
- package/skills/scip-verify/SKILL.md +20 -14
- package/dist/chunk-27HMTUJE.js +0 -3
- package/dist/chunk-27XEGMCT.js +0 -7
- package/dist/chunk-3AMWF6V5.js +0 -3
- package/dist/chunk-4SCMYKD6.js +0 -2
- package/dist/chunk-5AAAEZ2Z.js +0 -2
- package/dist/chunk-5JRMZMLM.js +0 -2
- package/dist/chunk-5VY3RIEI.js +0 -38
- package/dist/chunk-6JUAGXR4.js +0 -4
- package/dist/chunk-6KDOYKCB.js +0 -40
- package/dist/chunk-6KMTPNZL.js +0 -3
- package/dist/chunk-7COVQPQQ.js +0 -9
- package/dist/chunk-7S5E7KWT.js +0 -2
- package/dist/chunk-7TVFPOD7.js +0 -102
- package/dist/chunk-A6KSEIRN.js +0 -61
- package/dist/chunk-AAMURYOK.js +0 -4
- package/dist/chunk-BP7S6V3M.js +0 -20
- package/dist/chunk-BRBF3E5X.js +0 -35
- package/dist/chunk-BZXE3HO4.js +0 -6
- package/dist/chunk-CXQQOXSI.js +0 -10
- package/dist/chunk-EVZSAR3S.js +0 -2
- package/dist/chunk-GMOEX7EV.js +0 -2
- package/dist/chunk-GNG622H3.js +0 -3
- package/dist/chunk-GUDKRIGW.js +0 -7
- package/dist/chunk-GULVO6NF.js +0 -43
- package/dist/chunk-HZZQKNVE.js +0 -2
- package/dist/chunk-I4R3SNMR.js +0 -2
- package/dist/chunk-IMQFJ53K.js +0 -2
- package/dist/chunk-ISLWJ4PY.js +0 -10
- package/dist/chunk-IUSSGHJO.js +0 -2
- package/dist/chunk-J5WVNZ6O.js +0 -2
- package/dist/chunk-JJUX2OAP.js +0 -2
- package/dist/chunk-JZBGTSAB.js +0 -13
- package/dist/chunk-K5N5RNGM.js +0 -2
- package/dist/chunk-KSJ544IV.js +0 -5
- package/dist/chunk-LY7NMOBW.js +0 -2
- package/dist/chunk-N23FT4EZ.js +0 -2
- package/dist/chunk-NCVFKOLB.js +0 -2
- package/dist/chunk-PESEPWZO.js +0 -2
- package/dist/chunk-PMY4UFGV.js +0 -2
- package/dist/chunk-Q7PWDXL5.js +0 -5
- package/dist/chunk-QVGFVRKD.js +0 -2
- package/dist/chunk-R5336VHZ.js +0 -2
- package/dist/chunk-RLB6SG25.js +0 -2
- package/dist/chunk-SFDVBARK.js +0 -2
- package/dist/chunk-TG7QSYCJ.js +0 -2
- package/dist/chunk-UHPWZCYQ.js +0 -3
- package/dist/chunk-URSSPS5H.js +0 -2
- package/dist/chunk-WIBFXSYB.js +0 -6
- package/dist/chunk-WMO2VZZK.js +0 -3
- package/dist/chunk-WS3Z6W3M.js +0 -65
- package/dist/chunk-X3DTIEMU.js +0 -18
- package/dist/chunk-X5C43YVI.js +0 -2
- package/dist/chunk-X7CHWTZ2.js +0 -72
- package/dist/chunk-XDESMVOL.js +0 -4
- package/dist/chunk-XZBLZHXL.js +0 -16
- package/dist/chunk-YBGC7HTY.js +0 -3
- package/dist/chunk-ZMGBWSFZ.js +0 -2
package/dist/runtime.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as ProjectConfig, a as SupportedLanguage } from './config-types-
|
|
2
|
-
import { W as WatcherStatus } from './scip-cli-
|
|
3
|
-
export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-
|
|
1
|
+
import { P as ProjectConfig, a as SupportedLanguage } from './config-types-SVkUIufk.js';
|
|
2
|
+
import { W as WatcherStatus, R as RefreshTrigger } from './scip-cli-BKL-26TZ.js';
|
|
3
|
+
export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-BKL-26TZ.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Load project config from .scipquery.json in the project root.
|
|
@@ -38,7 +38,7 @@ interface WatcherOptions {
|
|
|
38
38
|
* File watcher that triggers single-flight background reindexing.
|
|
39
39
|
*
|
|
40
40
|
* Design:
|
|
41
|
-
* - Debounce: waits
|
|
41
|
+
* - Debounce: waits for a configurable quiet period after the last file change
|
|
42
42
|
* - Single-flight: only one reindex runs at a time, never queued
|
|
43
43
|
* - Dirty flag: changes during reindex schedule ONE follow-up
|
|
44
44
|
* - Cooldown: minimum interval between reindex completions
|
|
@@ -76,6 +76,10 @@ declare class Watcher {
|
|
|
76
76
|
start(): void;
|
|
77
77
|
/** Stop watching and clean up */
|
|
78
78
|
stop(): void;
|
|
79
|
+
/** Request a refresh through the same single-flight/coalescing state machine used by file events. */
|
|
80
|
+
requestRefresh(trigger: RefreshTrigger, opts?: {
|
|
81
|
+
immediate?: boolean;
|
|
82
|
+
}): void;
|
|
79
83
|
private handleFileChange;
|
|
80
84
|
private scheduleReindex;
|
|
81
85
|
private triggerReindex;
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),t}function m(r){return
|
|
1
|
+
import{b as D,c as N,d as G}from"./chunk-Y42DMR6F.js";import{a as R}from"./chunk-YZXV3CU3.js";import"./chunk-QVZSWLLZ.js";import{readFileSync as F,writeFileSync as W,existsSync as k,mkdirSync as U}from"fs";import{isAbsolute as fe,join as u,relative as me,resolve as P}from"path";import{createHash as L}from"crypto";import{homedir as q}from"os";var f=".scipquery.json",j=250,E=0,b=10*6e4,Y={enabled:!1,debounceMs:j,cooldownMs:E,gitPollMs:2e3,idleTimeoutMs:b,autoRefresh:!0,ignore:[]},K=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var Ce=new Set(K);function y(r){let e=u(r,f);if(!k(e))return{};try{let t=F(e,"utf-8");return JSON.parse(t)}catch(t){let i=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${f} at ${e}: ${i}`,{cause:t}):new Error(`unable to read ${f} at ${e}: ${i}`,{cause:t})}}function T(r){return{...Y,...r.watch}}function H(r,e){let t=process.env.SCIP_QUERY_CACHE_DIR;if(t)return m(t);if(e?.dbPath)return m(P(r,e.dbPath));let s=process.env.XDG_CACHE_HOME||u(q(),".cache"),o=L("sha256").update(P(r)).digest("hex").slice(0,12),n=u(s,"scip-query","projects",o);return m(n)}function S(r,e){let t=H(r,e);return{cacheDir:t,dbPath:u(t,"index.db"),indexPath:u(t,"index.scip"),metaPath:u(t,"meta.json")}}function X(r,e){let t=u(r,f);return k(t)||W(t,JSON.stringify({languages:e,watch:{enabled:!0,debounceMs:j,cooldownMs:E,gitPollMs:2e3,idleTimeoutMs:b,autoRefresh:!0}},null,2)+`
|
|
2
|
+
`),t}function m(r){return U(r,{recursive:!0}),r}import{execFileSync as z,fork as J}from"child_process";import{statSync as B,watch as V}from"fs";import{join as Q,relative as Z}from"path";import ee from"ignore";var C=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=T(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=R(e.projectRoot),this.extraIgnore=ee(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=V(this.projectRoot,{recursive:!0},(t,i)=>{i&&!this.stopped&&this.handleFileChange(i)});this.fsWatchers.push(e)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=I(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}handleFileChange(e){let t=Z(this.projectRoot,Q(this.projectRoot,e));t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}scheduleReindex(e){if(this.pendingTrigger=I(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let s=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+s;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},s);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=Date.now();this.setStatus({state:"indexing",startedAt:i}),this.runReindex(t).then(s=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(s),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(s=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(s instanceof Error?s:new Error(String(s))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,i)=>{let s=Date.now(),o=y(this.projectRoot),n=Object.keys(o).length>0?o:this.config,c=S(this.projectRoot,n),a=n.indexer?.typescript,l=n.indexer?.clojure,d=J(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:c.indexPath,SCIP_REINDEX_OUTPUT_DB:c.dbPath,SCIP_REINDEX_LANGUAGES:(n.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(n.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:a?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:a?.projectMode??this.typescriptProjectMode,projects:a?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-s):i(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",i)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let i=e.head!==t.head,s=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;i&&s?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):s&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=_(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t={head:_(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:e};try{let i=B(e);t.indexMtimeMs=i.mtimeMs,t.indexSize=i.size}catch{t.indexMtimeMs=void 0,t.indexSize=void 0}return t}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function _(r,e){try{return z("git",["-C",r,...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function I(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}import{existsSync as v,mkdirSync as te,symlinkSync as re,readlinkSync as M,unlinkSync as A,readdirSync as ie}from"fs";import{join as h,dirname as w,resolve as g,relative as se,isAbsolute as ne}from"path";import{homedir as x,platform as oe}from"os";import{fileURLToPath as ae}from"url";var le=oe()==="win32",$=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function ce(r={}){let e=r.quiet?()=>{}:console.log,t=ae(import.meta.url),i=g(w(t),"..","skills"),s=[h(x(),".claude","skills"),h(x(),".codex","skills"),h(x(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let n of s){let c=w(n);if(!v(c))continue;te(n,{recursive:!0});let a=de(n);pe(n,i,a,o,e);for(let l of $){let d=h(i,l),p=h(n,l);if(!v(d)){o.skipped.push(`${a}/${l}`);continue}if(v(p)){try{let O=M(p);if(g(O)===g(d)){o.alreadyLinked.push(`${a}/${l}`),e(` ok: ${l} \u2192 ${a} (already linked)`);continue}}catch{o.skipped.push(`${a}/${l}`),e(` skip: ${l} \u2192 ${a} (exists, not a symlink)`);continue}A(p)}re(d,p,le?"junction":"dir"),o.installed.push(`${a}/${l}`),e(` done: ${l} \u2192 ${a}`)}}return o}function pe(r,e,t,i,s){let o=new Set($);for(let n of ie(r)){if(o.has(n))continue;let c=h(r,n),a;try{a=g(w(c),M(c))}catch{continue}ue(a,e)&&(A(c),i.pruned.push(`${t}/${n}`),s(` prune: ${n} \u2192 ${t} (removed stale scip-query skill link)`))}}function ue(r,e){let t=se(g(e),g(r));return t===""||!t.startsWith("..")&&!ne(t)}function de(r){return r.includes(".codex")?"Codex":r.includes(".agents")?"Agents":"Claude"}export{C as Watcher,N as getScipVersion,X as initProjectConfig,ce as installSkills,D as isScipInstalled,y as loadProjectConfig,G as printScipInstallInstructions,S as resolveIndexStoragePaths};
|
|
3
3
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-P5XHIJHI.js";import{a as b,b as v}from"./chunk-3M2UCPFS.js";import{a as w,g as k}from"./chunk-JHK2DMUQ.js";import d from"process";import{closeSync as ee,mkdirSync as y,openSync as re,readFileSync as O,readdirSync as ne,rmSync as h,writeFileSync as te}from"fs";import{dirname as se,resolve as c}from"path";import{pathToFileURL as oe}from"url";import{spawn as x}from"child_process";import{createHash as B,randomUUID as W}from"crypto";import{existsSync as L,mkdirSync as ge,readFileSync as he,realpathSync as Ee,rmSync as Ie}from"fs";import{tmpdir as _e}from"os";import{resolve as ke}from"path";var T=2;var g=class{constructor(r,n=z){this.createRequester=r;this.applyEnvironment=n}createRequester;applyEnvironment;requester=null;identityKey=null;semanticResponseCache=null;handle(r){this.applyEnvironment(r.workerEnvironment??{});let n;if(this.requester?this.identityKey!==r.identityKey?(this.semanticResponseCache=null,this.requester.shutdown(),this.requester=this.createRequester(),this.identityKey=r.identityKey,n="invalidated"):n="reused":(this.requester=this.createRequester(),this.identityKey=r.identityKey,n="created"),r.kind==="semantic"){let s=j(r.request),o=n==="reused"&&s!==null&&this.semanticResponseCache?.identityKey===r.identityKey&&this.semanticResponseCache.requestKey===s?this.semanticResponseCache.response:null;if(o)return M(!0,r.request.definitions.length),{session:n,response:o};let a=this.requester.requestSemantic(r.request,r.timeoutMs);return s!==null&&F(a)&&(this.semanticResponseCache={identityKey:r.identityKey,requestKey:s,response:a}),M(!1,r.request.definitions.length),{session:n,response:a}}return{session:n,response:this.requester.requestImportDefinitions(r.request,r.timeoutMs)}}shutdown(){this.requester?.shutdown(),this.requester=null,this.identityKey=null,this.semanticResponseCache=null}};function j(e){if(e.includeReferences===!1||e.includeCallees!==!0||e.includeSignatures===!0||(e.referenceDefinitions?.length??0)===0||(e.calleeDefinitions?.length??0)===0)return null;let{readinessDeadlineMs:r,...n}=e;return $(I(n))}function F(e){return e.available&&Array.isArray(e.callees)&&(e.incompleteReferenceSymbolIds?.length??0)===0}function M(e,r){w()&&k({type:"span",name:"rust.semantic.durable-session.response-cache",durationMs:0,ok:!0,hit:e,definitions:r})}function z(e){for(let r of Object.keys(process.env))Y(r)&&delete process.env[r];for(let[r,n]of Object.entries(e))n!==null&&(process.env[r]=n)}function K(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Y(e){return K(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var Ae={now:Date.now,randomId:W,isProcessAlive:b,spawnServer(e,r,n){if(!L(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);x(process.execPath,[e,r,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let r=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(r,0,0,e)}};function I(e){return Array.isArray(e)?`[${e.map(I).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${I(n)}`).join(",")}}`:JSON.stringify(e)}function $(e){return B("sha256").update(e).digest("hex")}import{existsSync as H,mkdtempSync as A,readFileSync as C,rmSync as D}from"fs";import{tmpdir as q}from"os";import{join as _}from"path";import{fileURLToPath as P,pathToFileURL as V}from"url";import{SHARE_ENV as J,Worker as Q}from"worker_threads";function U(e={}){let r=null,n=null,s=1,o=!1,a=()=>{n&&(D(n,{recursive:!0,force:!0}),n=null)},f=()=>{let t=r;r=null,t&&t.terminate(),a()},u=()=>{if(r)return r;let t=e.semanticWorkerPath?V(e.semanticWorkerPath):Z();if(!H(P(t)))throw new Error(`Rust semantic session worker was not found at ${P(t)}. Run npm run build before using built semantic Rust queries.`);return n=A(_(q(),"scip-query-rust-session-")),r=new Q(t,e.shareEnvironment?{env:J}:void 0),r.unref(),r},l=()=>{let t=n??A(_(q(),"scip-query-rust-session-"));return n=t,_(t,`${s++}.json`)};return{requestSemantic(t,i){if(o)throw new Error("Rust semantic session was already disposed.");let R=u(),p=l(),S=new SharedArrayBuffer(4),E=new Int32Array(S);if(R.postMessage({kind:"semantic",request:t,responsePath:p,sharedBuffer:S}),Atomics.wait(E,0,0,i)==="timed-out")throw f(),new Error(`Rust semantic session worker timed out after ${(i/1e3).toFixed(0)}s`);try{let m=G(C(p,"utf8"));if(!m.ok)throw new Error(m.error);return m.response}finally{D(p,{force:!0})}},requestImportDefinitions(t,i){if(o)throw new Error("Rust semantic session was already disposed.");let R=u(),p=l(),S=new SharedArrayBuffer(4),E=new Int32Array(S);if(R.postMessage({kind:"import-definitions",request:t,responsePath:p,sharedBuffer:S}),Atomics.wait(E,0,0,i)==="timed-out")throw f(),new Error(`Rust semantic import-definition session worker timed out after ${(i/1e3).toFixed(0)}s`);try{let m=X(C(p,"utf8"));if(!m.ok)throw new Error(m.error);return m.response}finally{D(p,{force:!0})}},shutdown(){if(o)return;if(o=!0,!r){a();return}let t=l(),i=new SharedArrayBuffer(4),R=new Int32Array(i);r.postMessage({kind:"shutdown",responsePath:t,sharedBuffer:i}),Atomics.wait(R,0,0,5e3),f()}}}function G(e){let r=JSON.parse(e);if(!r||typeof r!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=r;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof r.error=="string"?r.error:"Rust semantic session worker failed."}}function X(e){let r=JSON.parse(e);if(!r||typeof r!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=r;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof r.error=="string"?r.error:"Rust semantic session worker failed."}}function Z(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}var ie=10*6e4,ae=10,ue=1e3;function le(e,r,n={}){let s=c(e,"requests"),o=c(e,"responses");y(s,{recursive:!0}),y(o,{recursive:!0});let a=0;for(let f of ne(s).filter(u=>u.endsWith(".json")).sort()){let u=c(s,f),l=null;try{l=fe(O(u,"utf8")),n.beforeRequest?.(l.request);let t=r.handle(l.request);v(c(o,`${l.id}.json`),{ok:!0,...t})}catch(t){let i=l?.id??f.slice(0,-5);v(c(o,`${i}.json`),{ok:!1,error:t instanceof Error?t.message:String(t)})}finally{h(u,{force:!0}),a+=1}}return a}async function ce(e,r){y(c(e,"requests"),{recursive:!0}),y(c(e,"responses"),{recursive:!0});let n=c(e,"server.lock");if(!Re(n))return;let s=new g(()=>U({semanticWorkerPath:r,shareEnvironment:!0})),o=!1,a=Date.now(),f=0,u,l=()=>{o=!0};d.once("SIGINT",l),d.once("SIGTERM",l);let t=(i=!1)=>{let R=Date.now();!i&&R-f<ue||(f=R,v(c(e,"server.json"),{protocolVersion:T,pid:d.pid,heartbeatAtMs:R,...u===void 0?{}:{busyUntilMs:u}}))};try{t(!0);let i=pe();for(;!o&&Date.now()-a<i;)le(e,s,{beforeRequest(p){u=Date.now()+p.timeoutMs+5e3,t(!0)}})>0?(a=Date.now(),u=void 0,t(!0)):t(),await me(ae)}finally{s.shutdown(),h(c(e,"server.json"),{force:!0}),h(n,{force:!0})}}function Re(e){y(se(e),{recursive:!0});for(let r=0;r<2;r+=1)try{let n=re(e,"wx");return te(n,String(d.pid)),ee(n),!0}catch{let n=de(e);if(n!==null&&b(n))return!1;h(e,{force:!0})}return!1}function de(e){try{let r=Number(O(e,"utf8"));return Number.isInteger(r)&&r>0?r:null}catch{return null}}function fe(e){let r=JSON.parse(e);if(typeof r.id!="string"||!r.request||typeof r.request!="object")throw new Error("Durable Rust semantic helper received an invalid mailbox request.");return{id:r.id,request:r.request}}function pe(){let e=Number(d.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:ie}function me(e){return new Promise(r=>setTimeout(r,e))}var Se=d.argv[1]?oe(c(d.argv[1])).href:null;if(Se===import.meta.url){let e=d.argv[2],r=d.argv[3];!e||!r?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),d.exitCode=1):await ce(e,r)}export{le as processDurableRustSessionRequests};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-session-server.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{A as ue,B as de,C as b,D as S,a as A,b as q,c as ee,d as ne,e as te,f as ie,g as se,h as F,i as G,j as N,k as E,l as B,n as j,o as H,p as U,q as W,r as re,u as ae,v as oe,w as le,x as ce,y as k}from"./chunk-D5OXYOJP.js";import{a as O,f as d,g as D}from"./chunk-JHK2DMUQ.js";import _ from"process";import{existsSync as pe,readFileSync as we,writeFileSync as Pe}from"fs";import{isAbsolute as De,resolve as K}from"path";import{performance as L}from"perf_hooks";import{parentPort as ke}from"worker_threads";var be="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",Se="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",P=new Map,fe=Promise.resolve();ke?.on("message",e=>{fe=fe.then(()=>Te(e)).catch(()=>{})});async function Te(e){if(e.kind==="shutdown"){await We(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let t=await ze(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n={available:!1,reason:t instanceof Error?t.message:String(t),sourcePaths:e.request.positions.map(r=>[r.id,null])};g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}return}try{let t=await ve(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n=ye(e.request,t instanceof Error?t.message:String(t));g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}}async function ze(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Re(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let n=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{n=await Ae(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:n,positions:e.positions.length})),()=>ge(P,i,e.readinessDeadlineMs));let r=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>S(e.positions,e.concurrency??8,async o=>{let c=await i.client.definition({textDocument:{uri:A(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},t),f=Fe(e.projectRoot,c);return f&&(r+=1),[o.id,f]}),()=>({positions:e.positions.length,resolvedPositions:r,concurrency:e.concurrency??8}))}}async function ve(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,n=e.includeCallees===!0,r=e.includeSignatures===!0,a=j(e),o=H(e),c=U(e),f=W(e),l=await d("rust.semantic.worker.session",()=>Ie(e),()=>({kind:"semantic",definitions:f.length,referenceDefinitions:a.length,calleeDefinitions:o.length,signatureDefinitions:c.length,references:i,callees:n,signatures:r})),p=Ee(l.capabilities,{references:i,callees:n,signatures:r});if(p)return ye(e,p);let u=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{u=await Ce(l,e)},()=>({definitions:f.length,openedDocuments:u})),()=>ge(P,l,e.readinessDeadlineMs));let m=0,M=0,y=O(),J=y?new Map:null,T=y?me(_.env[be]):null,V=()=>i?d("rust.semantic.worker.references",()=>S(a,e.concurrency??8,async s=>{let w=y?L.now():0,h=await ue(l.client,ee(e.projectRoot,s,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),R=te(ne(e.projectRoot,h.locations)),C=y?Math.round(L.now()-w):0;return _e(J,s.relativePath,{durationMs:C,references:R.length,hasReferences:R.length>0,slow:T!==null&&C>=T}),T!==null&&C>=T&&D({type:"span",name:"rust.semantic.worker.reference-task",durationMs:C,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,references:R.length,complete:h.complete}),R.length>0&&(M+=1),m+=R.length,{symbolId:s.symbolId,references:R,complete:h.complete}}),()=>({definitions:a.length,concurrency:e.concurrency??8,definitionsWithReferences:M,references:m})):Promise.resolve(a.map(s=>({symbolId:s.symbolId,references:[],complete:!0}))),Q=0,X=0,z=O(),Y=z?new Map:null,v=z?me(_.env[Se]):null,Z=()=>n?d("rust.semantic.worker.callees",()=>S(o,e.concurrency??8,async s=>{let w=z?L.now():0,h=await de(l.client,e.projectRoot,s,t),R=z?Math.round(L.now()-w):0;return Ge(Y,s.relativePath,{durationMs:R,callees:h.length,hasCallees:h.length>0,slow:v!==null&&R>=v}),v!==null&&R>=v&&D({type:"span",name:"rust.semantic.worker.callee-task",durationMs:R,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,callees:h.length}),h.length>0&&(X+=1),Q+=h.length,{symbolId:s.symbolId,callees:h}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:X,callees:Q})):Promise.resolve([]),I,x;i&&n&&a.length>0&&o.length>0&&je()?[I,x]=await Promise.all([V(),Z()]):(I=await V(),x=await Z()),xe(J),Ne(Y);let $=0,Me=r?await d("rust.semantic.worker.signatures",()=>S(c,e.concurrency??8,async s=>{let w=await re(l.client,e.projectRoot,s,t);return w&&($+=1),{symbolId:s.symbolId,signature:w}}),()=>({definitions:c.length,concurrency:e.concurrency??8,signaturesFound:$})):[];return{available:!0,references:I.filter(s=>s.complete).map(s=>[s.symbolId,s.references]),incompleteReferenceSymbolIds:I.filter(s=>!s.complete).map(s=>s.symbolId),...n?{callees:x.map(s=>[s.symbolId,s.callees])}:{},...r?{signatures:Me.map(s=>[s.symbolId,s.signature])}:{}}}async function Ie(e){return Re(e.projectRoot,e.rustAnalyzerBinary,W(e).map(t=>t.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Re(e,t,i,n){let r=le(e,i.map(M=>({relativePath:M}))),a=oe(e,r),o=Le(t,a,r),c=P.get(o);if(c)return c;let f=ae(r),l=new ie(se(t,a),{requestTimeoutMs:n.requestTimeoutMs,configuration:f}),p=n.readinessDeadlineMs===void 0?null:{afterGeneration:l.serverStatusGeneration(),deadlineMs:n.readinessDeadlineMs},u=await E(()=>d("rust.semantic.worker.initialize",()=>l.initialize({processId:_.pid,rootUri:A(a,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:f},{timeoutMs:n.requestTimeoutMs,deadlineMs:n.readinessDeadlineMs}),()=>({linkedProjects:r.length,relativePaths:i.length})),()=>l.shutdown({deadlineMs:n.readinessDeadlineMs}).catch(()=>{})),m={key:o,client:l,capabilities:u.capabilities,openedPaths:new Set,initializationReadiness:p};return P.set(o,m),m}async function Ce(e,t){let i=W(t).filter(l=>e.openedPaths.has(l.relativePath)?!1:pe(K(t.projectRoot,l.relativePath)));if(i.length===0)return await he(e),0;let n=e.initializationReadiness,r=t.readinessDeadlineMs===void 0?null:{statusSnapshot:n?null:e.client.serverStatusSnapshot(),initializationGeneration:n?.afterGeneration,deadlineMs:t.readinessDeadlineMs},a=ce(e.client,t.projectRoot,i);for(let l of i)e.openedPaths.add(l.relativePath);let o=t.diagnosticsTimeoutMs??1e4,c=o;await d("rust.semantic.worker.diagnostics",()=>r?N(l=>(c=l,k(e.client,a,l)),o,r.deadlineMs):k(e.client,a,o),()=>({openedDocuments:a.length,timeoutMs:c}));let f=t.settleDelayMs??5e3;if(!r)await d("rust.semantic.worker.settle",()=>b(f),()=>({openedDocuments:a.length,settleDelayMs:f}));else{let l;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>b(m),()=>({openedDocuments:a.length,settleDelayMs:m})),u=r.initializationGeneration===void 0?await G(e.client,r.statusSnapshot,a.length,r.deadlineMs,f,Date.now,p):await F(e.client,r.initializationGeneration,a.length,r.deadlineMs,f,Date.now,p);r.initializationGeneration!==void 0&&(e.initializationReadiness=null),l=u?.health},()=>({phase:r.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:a.length,health:l}))}return a.length}async function Ae(e,t,i,n){let r=i.filter(u=>e.openedPaths.has(u)?!1:pe(K(t,u)));if(r.length===0)return await he(e),0;let a=e.initializationReadiness,o=n.readinessDeadlineMs===void 0?null:{statusSnapshot:a?null:e.client.serverStatusSnapshot(),initializationGeneration:a?.afterGeneration,deadlineMs:n.readinessDeadlineMs},c=[];for(let u of r){let m=A(t,u);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:we(K(t,u),"utf8")}),e.openedPaths.add(u),c.push(m)}let f=n.diagnosticsTimeoutMs??1e4,l=f;await d("rust.semantic.worker.diagnostics",()=>o?N(u=>(l=u,k(e.client,c,u)),f,o.deadlineMs):k(e.client,c,f),()=>({openedDocuments:c.length,timeoutMs:l}));let p=n.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>b(p),()=>({openedDocuments:c.length,settleDelayMs:p}));else{let u;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>b(y),()=>({openedDocuments:c.length,settleDelayMs:y})),M=o.initializationGeneration===void 0?await G(e.client,o.statusSnapshot,c.length,o.deadlineMs,p,Date.now,m):await F(e.client,o.initializationGeneration,c.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),u=M?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:c.length,health:u}))}return c.length}async function he(e){let t=e.initializationReadiness;if(!t)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await F(e.client,t.afterGeneration,0,t.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Fe(e,t){for(let i of t){let n=q(e,i.uri);if(!(!n||n===".."||n.startsWith("../")||De(n)))return n}return null}function Ee(e,t){return t.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":t.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":t.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function ye(e,t){let i=j(e),n=H(e),r=U(e);return{available:!1,reason:t,references:i.map(a=>[a.symbolId,[]]),...e.includeCallees?{callees:n.map(a=>[a.symbolId,[]])}:{},...e.includeSignatures?{signatures:r.map(a=>[a.symbolId,null])}:{}}}async function We(){let e=[...P.values()];P.clear(),await Promise.all(e.map(t=>t.client.shutdown().catch(()=>{})))}async function ge(e,t,i){e.get(t.key)===t&&e.delete(t.key),await t.client.shutdown({deadlineMs:i}).catch(()=>{})}function Le(e,t,i){return JSON.stringify({binary:e,sessionRoot:t,linkedProjects:i})}function _e(e,t,i){if(!e)return;let n=Oe(e,t);n.definitions+=1,i.hasReferences&&(n.definitionsWithReferences+=1),n.references+=i.references,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function xe(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithReferences:n.definitionsWithReferences,references:n.references,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Oe(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function Ge(e,t,i){if(!e)return;let n=Be(e,t);n.definitions+=1,i.hasCallees&&(n.definitionsWithCallees+=1),n.callees+=i.callees,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function Ne(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithCallees:n.definitionsWithCallees,callees:n.callees,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Be(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function me(e){if(e===void 0||e==="")return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}function je(){let e=_.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,t,i){Pe(e,JSON.stringify(t));let n=new Int32Array(i);Atomics.store(n,0,1),Atomics.notify(n,0)}export{ge as discardRustAnalyzerSession};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-session-worker.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{A as o,B as p,C as q,D as r,m as a,n as b,o as c,p as d,q as e,r as f,s as g,t as h,u as i,v as j,w as k,x as l,y as m,z as n}from"./chunk-D5OXYOJP.js";export{p as calleesForDefinition,k as cargoManifestsForDefinitions,h as hoverToRustSignature,g as hoverWithRetry,l as openDefinitionDocuments,o as referencesWithCompletion,n as referencesWithRetry,a as runRustAnalyzerReferenceBatch,r as runWithConcurrency,i as rustAnalyzerInitializationOptions,j as rustAnalyzerSessionRoot,c as rustRequestCalleeDefinitions,b as rustRequestReferenceDefinitions,e as rustRequestSessionDefinitions,d as rustRequestSignatureDefinitions,f as signatureForDefinition,q as sleep,m as waitForOpenedDocuments};
|
|
2
|
+
//# sourceMappingURL=rust-semantic-worker.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as SupportedLanguage } from './config-types-
|
|
1
|
+
import { a as SupportedLanguage } from './config-types-SVkUIufk.js';
|
|
2
2
|
|
|
3
3
|
type WatcherStatus = {
|
|
4
4
|
state: 'idle';
|
|
@@ -14,7 +14,7 @@ type WatcherStatus = {
|
|
|
14
14
|
until: number;
|
|
15
15
|
dirty: boolean;
|
|
16
16
|
};
|
|
17
|
-
type RefreshTriggerKind = 'manual-cli' | 'setup' | 'watch-source' | 'watch-git-head' | 'watch-git-index' | 'watch-git-state' | 'unknown';
|
|
17
|
+
type RefreshTriggerKind = 'manual-cli' | 'setup' | 'watch-source' | 'watch-startup' | 'watch-demand' | 'watch-git-head' | 'watch-git-index' | 'watch-git-state' | 'unknown';
|
|
18
18
|
interface RefreshTrigger {
|
|
19
19
|
kind: RefreshTriggerKind;
|
|
20
20
|
detail?: string;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import{A as st,B as at,C as ct,D as ee,E as te,F as lt,H as dt,I as ve,J as pt,K as ut,L as ft,O as mt,R as ht,T as gt,U as re,V as yt,W as St,X as bt,a as He,c as ye,d as Se,e as Ue,g as Ge,h as Be,i as ze,j as Ke,k as Ye,l as Ve,n as Je,o as Qe,p as be,q as xe,r as Xe,s as K,t as Ze,u as et,v as rt,x as it,z as ot}from"./chunk-XAEU4ROB.js";import{b as z,f as $,h as tt,i as nt,j as ne}from"./chunk-FFIYGYQR.js";import{b as O}from"./chunk-3M2UCPFS.js";import{a as Z,c as We,d as ge,e as E}from"./chunk-JHK2DMUQ.js";import P from"process";import{rmSync as ln}from"fs";import{resolve as dn}from"path";import{pathToFileURL as Zr}from"url";import{readFileSync as fn,writeFileSync as li,existsSync as mn,mkdirSync as hn}from"fs";import{isAbsolute as pi,join as q,relative as ui,resolve as xt}from"path";import{createHash as gn}from"crypto";import{homedir as yn}from"os";var Ie=".scipquery.json",Sn=250,bn=0,xn=10*6e4,vn={enabled:!1,debounceMs:Sn,cooldownMs:bn,gitPollMs:2e3,idleTimeoutMs:xn,autoRefresh:!0,ignore:[]},In=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var hi=new Set(In);function W(n){let e=q(n,Ie);if(!mn(e))return{};try{let t=fn(e,"utf-8");return JSON.parse(t)}catch(t){let r=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${Ie} at ${e}: ${r}`,{cause:t}):new Error(`unable to read ${Ie} at ${e}: ${r}`,{cause:t})}}function ie(n){return{...vn,...n.watch}}function Mn(n,e){let t=process.env.SCIP_QUERY_CACHE_DIR;if(t)return Me(t);if(e?.dbPath)return Me(xt(n,e.dbPath));let i=process.env.XDG_CACHE_HOME||q(yn(),".cache"),o=gn("sha256").update(xt(n)).digest("hex").slice(0,12),s=q(i,"scip-query","projects",o);return Me(s)}function H(n,e){let t=Mn(n,e);return{cacheDir:t,dbPath:q(t,"index.db"),indexPath:q(t,"index.scip"),metaPath:q(t,"meta.json")}}function Me(n){return hn(n,{recursive:!0}),n}import{existsSync as vt,readFileSync as Rn}from"fs";function Re(n,e,t){let r=new Date().toISOString();if(!vt(t.dbPath))return{state:"missing",checkedAt:r,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!vt(t.metaPath))return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(Rn(t.metaPath,"utf-8")),o=e.languages??mt(n),s=Tn(n,o,e),a=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages),l=ht(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:r,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function Tn(n,e,t){return{version:2,languages:[...e].sort(),pnpmWorkspaces:t.indexer?.typescript?.projectMode!=="workspace"&&t.indexer?.typescript?.pnpmWorkspaces===!0,typescriptProjectMode:t.indexer?.typescript?.projectMode??"single",typescriptProjects:tt(t.indexer?.typescript?.projects),clojureConfigPath:Pn(t.indexer?.clojure?.configPath),files:nt(n)}}function Pn(n){return n?.trim()||void 0}import{execFileSync as Dn,fork as Cn}from"child_process";import{statSync as Fn,watch as wn}from"fs";import{join as kn,relative as En}from"path";import Nn from"ignore";var oe=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=ie(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ne(e.projectRoot),this.extraIgnore=Nn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=wn(this.projectRoot,{recursive:!0},(t,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(e)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Mt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}handleFileChange(e){let t=En(this.projectRoot,kn(this.projectRoot,e));t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}scheduleReindex(e){if(this.pendingTrigger=Mt(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,r)=>{let i=Date.now(),o=W(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=H(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=Cn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",r)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let r=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=It(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t={head:It(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:e};try{let r=Fn(e);t.indexMtimeMs=r.mtimeMs,t.indexSize=r.size}catch{t.indexMtimeMs=void 0,t.indexSize=void 0}return t}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function It(n,e){try{return Dn("git",["-C",n,...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function Mt(n,e){return n?n.kind===e.kind?n.detail===e.detail?n:{kind:n.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${n.kind}, ${e.kind}`}:e}import{existsSync as Rt,statSync as jn}from"fs";import{join as Ln}from"path";function _n(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function An(n=_n()){let e=W(n),t=H(n,e),r=process.env.SCIP_QUERY_INDEX_DB;if(r)return{projectRoot:n,config:e,paths:t,dbPath:r,dbPathSource:"env"};if(Rt(t.dbPath))return{projectRoot:n,config:e,paths:t,dbPath:t.dbPath,dbPathSource:"configured"};let i=Ln(n,"index.db");return{projectRoot:n,config:e,paths:t,dbPath:i,dbPathSource:"root-fallback",rootFallbackWarning:On(i,t.dbPath)}}function Tt(n,e={}){let{config:t,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s}=An(n);if(!Rt(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let a={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:n,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,coverageContracts:t.coverageContracts,docs:t.docs},c=ne(n);return new He(a,c)}function On(n,e){let t="unknown time";try{t=jn(n).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${n}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as rn,readFileSync as on,readdirSync as Ur,rmSync as Gr}from"fs";import{resolve as ue}from"path";import{resolve as Qt}from"path";import{performance as h}from"perf_hooks";function se(n){return{forFile(e,t){return Pt(n,e,t)},forFiles(e,t){let r=new Map;for(let i of e)r.set(i,Pt(n,i,t));return r}}}function Pt(n,e,t){let r={file:e},i=t.facts||t.identifiers;if(t.text&&(r.text=Be(n,e)),t.lines&&(r.lines=ze(n,e)),t.ast&&(r.ast=Ke(n,e)),t.imports&&(r.imports=et(n,e)),t.reexports&&(r.reexports=Ze(n,e)),i){let o=Ye(n,e),s=o.facts;t.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),t.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}var $n={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ae(n){if(n.startsWith("local "))return{kind:"local",id:n.slice(6),raw:n};let e=n.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:n};let t=e[0],r=e[1],i=n.slice(t.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=qn(i);return{scheme:t,manager:r,packageName:o,version:s,descriptors:c,raw:n}}function U(n){let e=ae(n);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let r=e.descriptors[t];if(r?.suffix==="type")return r.name}return null}function qn(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="["){let o=n.indexOf("]",t+1);if(o===-1){e.push({name:n.slice(t+1),suffix:"type-param"});break}e.push({name:n.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(n[t]==="("&&(e.length===0||t===0||Dt(n[t-1]))){let o=n.indexOf(")",t+1);if(o!==-1&&n[o+1]!=="."){e.push({name:n.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let r;if(n[t]==="`"){let o=n.indexOf("`",t+1);if(o===-1){r=n.slice(t+1),e.push({name:r,suffix:"term"});break}r=n.slice(t+1,o),t=o+1}else{let o=t;for(;t<n.length&&!Dt(n[t]);)t++;r=n.slice(o,t)}if(t>=n.length){r&&e.push({name:r,suffix:"term"});break}let i=n[t];if(i==="("){let o=n.indexOf(")",t+1);o!==-1&&n[o+1]==="."?(e.push({name:r,suffix:"method"}),t=o+2):o!==-1?(e.push({name:r,suffix:"method"}),t=o+1):(e.push({name:r,suffix:"term"}),t++)}else{let o=$n[i];o&&e.push({name:r,suffix:o}),t+=1}}return e}function Dt(n){return n==="/"||n==="#"||n==="."||n==="("||n==="["||n===":"||n==="!"}function N(n){let e=ae(n);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function j(n){let e=ae(n);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function Ct(n){let e=j(n);return e==="method"?!0:e!=="term"?!1:n.endsWith("().")?!0:n.startsWith("rust-analyzer ")&&n.includes("#")?!1:n.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(n):!0}function Wn(n,e={}){if(U(n.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(n.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Ft(n,e,t={}){let r=new Map;for(let o of e)n.length>0&&!Wn(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of n)r.set(o.id,o);let i=[...r.values()];return t.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var Hn=z("file-definitions",{clearGroups:["definition-catalog"]}),eo=z("file-function-like-definitions",{clearGroups:["definition-catalog"]});function L(n,e,t={}){return t.includeClassMemberFallbacks?wt(n,e,void 0,{includeClassMemberFallbacks:!0}):Hn.get(n,e,()=>{let r=Un(n,e);if(r)return r;let i=wt(n,e),o=Se(n),s=se(n).forFile(e,{text:!0}).text;return o&&s&&Et.write(n,e,ye(n,e,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}var Et=Ue({kind:"file-definitions",invalidation:Ge("file-definitions"),serialize:Gn,deserialize:Bn});function Un(n,e){let t=Se(n);if(!t)return null;let r=se(n).forFile(e,{text:!0}).text;if(!r)return null;let i=Et.read(n,e,ye(n,e,r));return i?zn(i,t,e):null}function Gn(n){return JSON.stringify(n)}function Bn(n){try{let e=JSON.parse(n);return!xe(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function zn(n,e,t){if(n.projectFingerprint!==e)return null;let r=[];for(let i of n.definitions){let o=Kn(i,t);if(!o)return null;r.push(o)}return r}function Kn(n,e){return!xe(n)||typeof n.symbolId!="number"||typeof n.symbol!="string"||typeof n.documentId!="number"||typeof n.startLine!="number"||typeof n.startChar!="number"&&n.startChar!==void 0||typeof n.endLine!="number"||typeof n.endChar!="number"&&n.endChar!==void 0||n.relativePath!==e||typeof n.leaf!="string"||typeof n.parentTypeName!="string"&&n.parentTypeName!==null||typeof n.isFunctionLike!="boolean"||typeof n.isTypeLike!="boolean"||typeof n.kind!="number"&&n.kind!==null||typeof n.documentation!="string"&&n.documentation!==null||typeof n.enclosingSymbol!="string"&&n.enclosingSymbol!==null?null:{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath,leaf:n.leaf,parentTypeName:n.parentTypeName,isFunctionLike:n.isFunctionLike,isTypeLike:n.isTypeLike,kind:n.kind,documentation:n.documentation,enclosingSymbol:n.enclosingSymbol}}function wt(n,e,t,r={}){let i=Ft(Yn(n,e),Vn(n,e),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(Jn);return t&&(i=i.filter(t)),Xn(n,e,i)}function Yn(n,e){return n.all(`SELECT
|
|
2
|
+
gs.id,
|
|
3
|
+
gs.symbol,
|
|
4
|
+
der.document_id,
|
|
5
|
+
der.start_line,
|
|
6
|
+
der.start_char,
|
|
7
|
+
der.end_line,
|
|
8
|
+
der.end_char,
|
|
9
|
+
d.relative_path,
|
|
10
|
+
gs.display_name,
|
|
11
|
+
gs.kind,
|
|
12
|
+
gs.documentation,
|
|
13
|
+
gs.enclosing_symbol
|
|
14
|
+
FROM global_symbols gs
|
|
15
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
16
|
+
JOIN documents d ON der.document_id = d.id
|
|
17
|
+
WHERE d.relative_path = ?
|
|
18
|
+
${n.symbolNoiseFor("gs")}
|
|
19
|
+
ORDER BY der.start_line, der.end_line`,e)}function Vn(n,e){return n.all(`SELECT
|
|
20
|
+
gs.id,
|
|
21
|
+
gs.symbol,
|
|
22
|
+
c.document_id,
|
|
23
|
+
MIN(c.start_line) AS start_line,
|
|
24
|
+
0 AS start_char,
|
|
25
|
+
MAX(c.end_line) AS end_line,
|
|
26
|
+
0 AS end_char,
|
|
27
|
+
d.relative_path,
|
|
28
|
+
gs.display_name,
|
|
29
|
+
gs.kind,
|
|
30
|
+
gs.documentation,
|
|
31
|
+
gs.enclosing_symbol
|
|
32
|
+
FROM global_symbols gs
|
|
33
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
34
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
35
|
+
JOIN documents d ON c.document_id = d.id
|
|
36
|
+
WHERE d.relative_path = ?
|
|
37
|
+
AND m.role = 1
|
|
38
|
+
${n.symbolNoiseFor("gs")}
|
|
39
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
40
|
+
ORDER BY start_line, end_line`,e)}function Jn(n){return{symbolId:n.id,symbol:n.symbol,documentId:n.document_id,startLine:n.start_line,startChar:n.start_char??0,endLine:n.end_line,endChar:n.end_char??0,relativePath:n.relative_path,leaf:N(n.symbol),parentTypeName:U(n.symbol),isFunctionLike:Ct(n.symbol),isTypeLike:j(n.symbol)==="type",kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosing_symbol??null}}function Nt(n,e={}){return Qn(n,e.scope)}function Qn(n,e){return $(n,{scope:e,includeIgnored:!1}).flatMap(t=>L(n,t)).filter(t=>!n.isIgnored(t.relativePath))}function Xn(n,e,t){let r=se(n).forFile(e,{text:!0}).text,i=Ve(n,e);return i?ir(t,i,r):r?Zn(t,r):t}function Zn(n,e){let t=e.split(/\r?\n/),r=er(n,t),i=tr(n,r),o=nr(i,t);return rr(n,o)}function er(n,e){let t=n.some(i=>ce(i.symbol))?pr(e):null,r=new Map;for(let i of n)r.set(i.symbolId,dr(e,t,i));return r}function tr(n,e){return n.filter(t=>ce(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,r)=>t.startLine-r.startLine||t.definition.startLine-r.definition.startLine||t.definition.symbol.localeCompare(r.definition.symbol))}function nr(n,e){let t=new Map;for(let r=0;r<n.length;r+=1){let i=n[r],o=n[r+1],s=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:ur(e,i.definition,i.startLine,s)})}return t}function rr(n,e){return n.map(t=>{let r=e.get(t.symbolId);return r?{...t,startLine:r.startLine,endLine:r.endLine}:t})}function ir(n,e,t=null){let r=new Map;for(let i of e){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return n.map(i=>{if(!lr(i)||!i.leaf)return kt(i,t);let o=r.get(i.leaf);if(!o||o.length===0)return kt(i,t);let s=t?or(i,o,t):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],p=Math.abs(d.startLine-i.startLine);p<c&&(a=d,c=p)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function or(n,e,t){let r=sr(n.symbol);if(!r)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${K(r)}\\b`);for(let s of e){let a=ar(i,s.startLine);if(a&&o.test(a))return s}return null}function sr(n){return n.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function ar(n,e){for(let t=e;t>=0;t-=1){let r=n[t]?.trim()??"";if(r){if(/^impl\b/.test(r))return cr(n,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function cr(n,e,t){let r=[];for(let i=e;i<=t;i+=1){let o=n[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function lr(n){return ce(n.symbol)?!0:j(n.symbol)==="term"&&U(n.symbol)===null}function kt(n,e){if(!e||!n.leaf||j(n.symbol)!=="term"||U(n.symbol)!==null)return n;let t=K(n.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...n,startLine:o,endLine:o}:n}function dr(n,e,t){if(!ce(t.symbol))return t.startLine;let r=Math.max(0,Math.min(t.startLine,n.length-1));if(!e)return r;let i=e.get(t.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-t.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function pr(n){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<n.length;a+=1){let c=n[a]??"";for(let d of c.matchAll(e))d[1]&&s(d[1],a);for(let d of c.matchAll(t))d[1]&&s(d[1],a);let l=c.match(r);l?.[1]&&s(l[1],a);for(let d of c.matchAll(i))d[1]&&s(d[1],a)}return o}function ur(n,e,t,r){let i=Math.max(t,Math.min(n.length-1,r)),o=Math.max(t,Math.min(i,e.endLine)),s=0,a=0,c=!1;for(let l=t;l<=i;l+=1){let d=fr(n[l]??"");for(let p of d)p==="{"?(s+=1,c=!0):p==="}"?s=Math.max(0,s-1):p==="("?a+=1:p===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function fr(n){let e="",t=null,r=!1;for(let i=0;i<n.length;i+=1){let o=n[i],s=n[i+1];if(!t&&o==="/"&&s==="/"){e+=" ".repeat(n.length-i);break}if(t){if(r){r=!1,e+=" ";continue}if(o==="\\"){r=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function ce(n){return n.includes("().")}function T(n,e,t){if(n.has(e))return n.get(e);let r=t();return n.set(e,r),r}import jt from"path";function mr(n,e){return n.getReferences().map(t=>{let r=t.getNode();return le(r,e)})}function hr(n){let e=n;return typeof e.findReferences=="function"?e.findReferences():[]}function Lt(n,e,t,r){let i=[];for(let o of hr(n))for(let s of mr(o,r))s.file===e.relativePath&&s.line>=e.startLine&&s.line<=e.endLine||i.push(s);for(let o of t)i.push(o);return G(i)}function _t(n,e,t,r){let i=[],o=t?.getStart();for(let s of n.getReferences()){let a=s.getNode();B(r,a.getSourceFile().getFilePath())===e&&(o!==void 0&&a.getStart()===o||i.push({location:le(a,r),node:a}))}return i}function le(n,e){let t=n.getSourceFile(),r=t.getLineAndColumnAtPos(n.getStart());return{file:B(e,t.getFilePath())??t.getBaseName(),line:r.line-1,column:r.column-1}}function At(n,e,t){let r=n.getSourceFile(),i=Pe(r,n),o=n.getText(),s=new RegExp(`\\b${K(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
41
|
+
`),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let d=a[l]??"";s.lastIndex=0;let p;for(;(p=s.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return G(c.filter(l=>B(t,jt.join(t,l.file))===e))}function Te(n){for(let e=n;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Pe(n,e){return n.getLineAndColumnAtPos(e.getStart()).line-1}function G(n){let e=new Set,t=[];for(let r of n){let i=`${r.file}:${r.line}:${r.column}`;e.has(i)||(e.add(i),t.push(r))}return t}function B(n,e){let t=jt.relative(n||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Ot(n,e,t,r){let i=gr(e,r);return i.size===0?new Map:yr(n,t,i)}function gr(n,e){let t=new Map;for(let r of L(n,e)){let i=N(r.symbol)??r.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(r)}return t}function yr(n,e,t){let r=new Map,i=new Map;return e.forEachDescendant(o=>{for(let s of Sr(n,o)){let a=t.get(s);if(!a)continue;let c=Pe(e,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),r.set(l.symbolId,o))}}}),r}function Sr(n,e){let t=[],r=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();r(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();r(i)}return n.Node.isIdentifier(e)&&r(e.getText()),t}var br=z("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function $t(n,e,t,r){let i=Fe(n,e),o=De(i.get(r)??[],t);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||N(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return De(s,t)}function Ce(n,e,t,r){return De(Fe(n,e).get(r)??[],t)}function qt(n,e){let t=new Map;for(let[r,i]of Fe(n,e)){let o=i[0];o&&t.set(r,o)}return t}function Fe(n,e){return br.get(n,e,()=>{let t=new Map;for(let r of L(n,e)){let i=r.leaf||N(r.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...r,leaf:i})}for(let r of t.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function De(n,e){let t=null,r=Number.POSITIVE_INFINITY;for(let i of n){let o=Math.abs(i.startLine-e);(o<r||o===r&&t&&i.startLine<t.startLine)&&(t=i,r=o)}return t}import we from"path";function Wt(n,e){let t=new Map,r=null,i=null,o=()=>(i??=$(n,{extensions:ee}),i),s=()=>(r??=E("typescript.source-file-index",()=>xr(n.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),r),a=c=>te(c)?T(t,c,()=>{let l=Y(we.resolve(n.config.projectRoot,c));for(let{project:d,sourceFiles:p}of s()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(Y(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function xr(n,e,t){let r=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Y(o.getFilePath()),o]))}));for(let i of t){let o=Y(we.resolve(n,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(Y(a.getFilePath()),a);break}}}return r}function Y(n){return we.resolve(n)}function ke(n,e){for(let t of n)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Ht(n){let e=`${n.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as V,readFileSync as vr}from"fs";import v from"path";var Ee=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ne(n,e){let r=e?v.dirname(v.join(n,e)):n,i=v.resolve(n);for(;r.startsWith(i);){for(let s of Ee){let a=v.join(r,s);if(V(a))return a}let o=v.dirname(r);if(o===r)break;r=o}for(let o of Ee){let s=v.join(n,o);if(V(s))return s}return null}function Ut(n){let e=n.config.projectRoot,t=new Set(Ir(e,n.config.semantic?.typescript?.tsconfigs)),r=$(n,{includeIgnored:!1,extensions:ee});for(let i of r){let o=Ne(e,i);o&&t.add(v.resolve(o))}if(t.size===0){let i=Ne(e);i&&t.add(v.resolve(i))}return[...t].filter(i=>!Gt(e,i)).sort((i,o)=>i.localeCompare(o))}function Ir(n,e=[]){let t=new Set;for(let r of e){let i=v.isAbsolute(r)?r:v.join(n,r);V(i)&&t.add(v.resolve(i))}for(let r of Mr(n))for(let i of Ee){let o=v.join(r,i);V(o)&&t.add(v.resolve(o))}if(t.size===0){let r=Ne(n);r&&t.add(v.resolve(r))}return[...t].filter(r=>!Gt(n,r)).sort((r,i)=>r.localeCompare(i))}function Mr(n){let e=v.join(n,"package.json");if(!V(e))return[];let t;try{t=JSON.parse(vr(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Qe(n,i))}function Gt(n,e){let t=v.relative(n,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Rr=32;function Jt(n,e,t,r={}){return E("typescript.provider.construct",()=>new Le(n,e,t),()=>({tsconfigs:t.length,reusedProjects:r.reusedProjects===!0}))}var Le=class{constructor(e,t,r){this.db=e;this.tsMorph=t;this.projects=r;this.workspacePackages=Je(e.config.projectRoot),this.sourceFiles=Wt(e,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return T(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let r=Pr();return E("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,r),()=>({file:e,...r}))})}referencesFor(e){return T(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let r=new Map,i=Z(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?r.set(d.symbolId,p):o.push(d)}if(o.length===0)return r;let s=o,a=t.exact?[]:o.filter(d=>!zt(d));if(a.length>=Rr){let d=this.referencesForDefinitionsBySymbolScan(a);for(let p of a){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}if(s=o.filter(p=>zt(p)),s.length===0)return r}let c=new Map;for(let d of s){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=Kt();E("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let m of p){i&&(u.cacheMisses+=1);let S=y.get(m.symbolId)??null;i&&(S?u.nodeHits+=1:u.nodeMisses+=1);try{let f=this.referencesForDefinitionNode(m,S,i?u:void 0);this.referencesCache.set(m.symbolId,f),r.set(m.symbolId,f)}catch{u.preciseSearchFailures+=1,l.push(m)}}},()=>({relativePath:d,definitions:p.length,...Yt(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}}return r}referenceFragmentsForFiles(e){let t=Nt(this.db).filter(o=>te(o.relativePath)),r=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,r);return pt(t,i,r)}referencesForDefinitionsBySymbolScan(e,t){let r=Z(),i=Kt(),o=new Map,s=new Set(e.map(c=>c.symbolId)),a=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return E("typescript.references-map.inverted-scan",()=>{let c=r?h.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let f of e){let g=l.get(f.symbolId)??[];if(g.length>0){let M=o.get(f.symbolId)??[];M.push(...g),o.set(f.symbolId,M)}r&&(i.packageReferenceCount+=g.length)}r&&(i.packageRefsMs+=h.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(f=>f.leaf).filter(Boolean)),m=r?h.now():0;for(let f of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(f))continue;let g=this.sourceFiles.sourceFile(f);g&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,f,s,a,u,y,d,p,o,r?i:void 0))}r&&(i.scanMs+=h.now()-m);let S=r?h.now():0;this.addHierarchyMemberReferences(e,o,r?i:void 0),r&&(i.hierarchyMs+=h.now()-S);for(let[f,g]of o){let M=G(g);o.set(f,M),r&&(i.referenceCount+=M.length)}},()=>({definitions:e.length,...Yt(i)})),o}addReferencesFromSourceFileScan(e,t,r,i,o,s,a,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,y=Fr(e),m=S=>{if(this.tsMorph.ts.isIdentifier(S)){if(d&&(d.identifiers+=1),!s.has(S.text)&&!y.has(S.text)){this.tsMorph.ts.forEachChild(S,m);return}let f=this.compilerReferenceSymbol(p,S,d);if(f){let g;a.has(f)?g=a.get(f)??null:(g=this.referenceDefinitionFromCompilerSymbol(f),a.set(f,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let M=T(c,f,()=>this.compilerSymbolKeys(f)),D=null,I=null,w=g&&r.has(g.symbolId)?i.get(g.symbolId):void 0;if(w&&(D=je(u,S),!Bt(w,t,D))){let F=u.getLineAndCharacterOfPosition(S.getStart(u));I={file:t,line:F.line,column:F.character};let R=l.get(w.symbolId)??[];R.push(I),l.set(w.symbolId,R),d&&(d.requestedHits+=1)}for(let F of M)for(let R of o.get(F)?.values()??[]){if(D??=je(u,S),Bt(R,t,D))continue;if(!I){let b=u.getLineAndCharacterOfPosition(S.getStart(u));I={file:t,line:b.line,column:b.character}}let x=l.get(R.symbolId)??[];x.push(I),l.set(R.symbolId,x),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(S,m)};m(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let r of e){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(r.symbolId,r),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let d of l){let p=d.getProperty(r.name);p&&s(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return s(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,r){let i=new Map;for(let o of e){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),d=l.getSymbolAtLocation(a.name);if(!d)continue;let p=a.getSourceFile(),u=p.getLineAndCharacterOfPosition(a.name.getStart(p)),y={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},m=t.get(o.symbolId)??[];for(let f of this.hierarchyMemberSymbols(l,c,d))if(f!==d)for(let g of this.compilerSymbolLocations(f))m.push(g),r&&(r.hierarchyReferences+=1);t.set(o.symbolId,m);let S=this.hierarchyRootMemberSymbols(l,c,d);for(let f of S){let g=i.get(f)??new Map;g.set(o.symbolId,y),i.set(f,g)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=t.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));t.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(e,t,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let d=!1;for(let p of l){let u=p.getProperty(r.name);u&&(d=!0,s(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return s(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let r=t.getSourceFile();return`${r.fileName}\0${t.getStart(r)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let r of e.declarations??[]){let i=r.getSourceFile(),o=B(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));t.push({file:o,line:a.line,column:a.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let r=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)r.add(e.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(e,t){let r=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(e.getTypeAtLocation(s));return[...r]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,r){r&&(r.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return T(this.calleesCache,e.symbolId,()=>T(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,r=new Map;for(let i of e){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,r){let i=r?h.now():0,o=this.packageImportReferencesForDefinition(e);if(r&&(r.packageRefsMs+=h.now()-i,r.packageReferenceCount+=o.length),!t)return o;let s=r?h.now():0,a=Lt(t,e,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=h.now()-s,r.referenceCount+=a.length),a}signatureFor(e){return T(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let r=t.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Vt(c)}),o=r.getReturnType().getText(t);return`(${i.join(",")})=>${Vt(o)}`})}importUsageForSourceFile(e,t,r){let i=[],o=new Map;for(let s of t.getImportDeclarations()){r.declarations+=1;let a=be(this.db,e,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of _e(s)){r.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let p={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||Dr(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:le(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?Tr(e,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(e,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(e,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(e,t,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of _t(s,e,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(e,t,r,o)}valueImportUsageFromLocations(e,t,r,i){let o=i.some(c=>!Te(c.node)),s=i.some(c=>Te(c.node)),a=r.isTypeOnly;return{importer:e,sourcePath:t,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,r=new Set;for(let o of e){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=ke(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return t;let i=this.packageExportsForNames(r);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,s]of t)t.set(o,G(s));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,r);for(let[r,i]of e)e.set(r,G(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,r,o)}addPackageImportReferencesForDeclaration(e,t,r,i){let o=ke(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=t.get(o);if(s)for(let a of _e(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=At(a.identifier,r,this.db.config.projectRoot);l.length>0&&Nr(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let r of this.workspacePackages){if(!e.has(r.name))continue;let i=new Map;for(let o of Ht(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&t.set(r.name,i)}return t}collectPackageExports(e,t,r,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?be(this.db,t,a):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(e,c,r,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,y=this.indexedDefinitionByLeaf(c,p);if(!y)continue;let m=r.get(u);m||(m=new Set,r.set(u,m)),m.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return T(this.indexedDefinitionLeafCache,e,()=>qt(this.db,e)).get(t)??null}nodeForDefinition(e){return T(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return T(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Ot(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,r=!1){let i=e.name,o=t?h.now():0,s=e.declarations??[];t&&(t.declarationsMs+=h.now()-o,t.declarationChecks+=s.length);for(let a of s){let c=t?h.now():0,l=a.getSourceFile(),d=B(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(t&&(t.declarationLocationMs+=h.now()-c),!d||this.db.isIgnored(d))continue;let u=t?h.now():0,y=this.compilerDeclarationName(a),m=r?Ce(this.db,d,p,i)??(y&&y!==i?Ce(this.db,d,p,y):null):$t(this.db,d,p,i);if(t&&(t.indexedLookupMs+=h.now()-u),m)return{symbolId:m.symbolId,symbol:m.symbol,file:m.relativePath,line:m.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let r=Z(),i=0,o=0,s=0,a=0,c=0,l=0,d=0,p=0,u=r?kr():void 0;return E("typescript.callee-map.file",()=>{let y=r?h.now():0,m=this.sourceFiles.sourceFile(e);if(r&&(c=Math.round(h.now()-y)),!m)return new Map;let S=r?h.now():0,f=L(this.db,e).sort((x,b)=>x.startLine-b.startLine||b.endLine-x.endLine);if(r&&(l=Math.round(h.now()-S)),i=f.length,f.length===0)return new Map;let g=new Map,M=r?h.now():0,D=this.compilerCheckerForSourceFile(m),I=m.compilerNode;r&&(d=Math.round(h.now()-M));let w=new Map,F=x=>{if(this.tsMorph.ts.isCallExpression(x)||this.tsMorph.ts.isNewExpression(x)){r&&(o+=1);let b=this.semanticCalleeForCallNode(D,I,f,x,w,t,u);b&&(r&&(s+=1),Cr(g,b.callerId,b.target))}this.tsMorph.ts.forEachChild(x,F)},R=r?h.now():0;F(I),r&&(p=Math.round(h.now()-R));for(let[x,b]of g)g.set(x,jr(b));return a=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?Er(u):{}}))}semanticCalleeForCallNode(e,t,r,i,o,s,a){let c=a?h.now():0,l=wr(r,je(t,i));if(a&&(a.callerLookupMs+=h.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,a),u=null;if(p)if(a&&(a.targetSymbolHits+=1),o.has(p))a&&(a.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let y=a?h.now():0;u=this.definitionFromCompilerSymbol(p,a),a&&(a.targetLookupMs+=h.now()-y),o.set(p,u)}else a&&(a.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,r){let i=r?h.now():0,o=e.getSymbolAtLocation(t);if(r&&(r.expressionSymbolMs+=h.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?h.now():0,a=e.getTypeAtLocation(t).getSymbol();return r&&(r.typeSymbolMs+=h.now()-s),a}compilerCheckerForSourceFile(e){let t=e.getProject(),r=this.compilerCheckerCache.get(t);return r||(r=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,r)),r}};function _e(n){let e=[],t=n.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});let r=n.getNamespaceImport();r&&e.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});for(let i of n.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(n.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Tr(n,e,t){return{importer:n,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Pr(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Dr(n){for(let e=n;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Cr(n,e,t){let r=n.get(e);r||(r=[],n.set(e,r)),r.push(t)}function Fr(n){let e=new Set;for(let t of n.getImportDeclarations())for(let r of _e(t))r.localName&&e.add(r.localName);return e}function wr(n,e){let t=null;for(let r of n)e<r.startLine||e>r.endLine||(!t||r.startLine>=t.startLine)&&(t=r);return t}function je(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line}function Bt(n,e,t){return e===n.relativePath&&t>=n.startLine&&t<=n.endLine}function zt(n){return n.symbol.includes("#")?j(n.symbol)==="type"&&n.relativePath.endsWith(".d.ts"):!1}function kr(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Er(n){return{...n,callerLookupMs:Math.round(n.callerLookupMs),expressionSymbolMs:Math.round(n.expressionSymbolMs),typeSymbolMs:Math.round(n.typeSymbolMs),targetLookupMs:Math.round(n.targetLookupMs),declarationsMs:Math.round(n.declarationsMs),declarationLocationMs:Math.round(n.declarationLocationMs),indexedLookupMs:Math.round(n.indexedLookupMs)}}function Kt(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Yt(n){return{...n,scanMs:Math.round(n.scanMs),packageRefsMs:Math.round(n.packageRefsMs),semanticRefsMs:Math.round(n.semanticRefsMs),hierarchyMs:Math.round(n.hierarchyMs)}}function Nr(n,e,t){for(let r of e){let i=n.get(r)??[];i.push(...t),n.set(r,i)}}function jr(n){let e=new Set,t=[];for(let r of n){let i=`${r.symbol}|${r.file}|${r.line}`;e.has(i)||(e.add(i),t.push(r))}return t}function Vt(n){return n.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var de=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??lt,this.discoverTsconfigs=t.discoverTsconfigs??Ut,this.createProjects=t.createProjects??dt,this.createProvider=t.createProvider??((r,i,o)=>Jt(r,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let r=Lr(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?r.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,r):(r.mode==="refresh"&&(_r(this.projects,e.config.projectRoot,r),this.stats.sessionsRefreshed+=1),r):r}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=ve("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=ve("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Lr(n){let e=new Set;n.projectIdentityChanged&&e.add("project-identity-changed");for(let o of n.uncertainty)e.add(o);for(let o of n.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=Ae(n.changes,"added"),r=Ae(n.changes,"modified"),i=Ae(n.changes,"deleted");return{mode:t.length+r.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:r,deletedFiles:i,reasons:[]}}function Ae(n,e){return n.filter(t=>t.kind===e).map(t=>t.path).sort()}function _r(n,e,t){for(let r of n){for(let i of t.deletedFiles)r.project.getSourceFile(Qt(e,i))?.forget();for(let i of t.modifiedFiles){let o=r.project.getSourceFile(Qt(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&r.project.addSourceFilesFromTsConfig(r.tsconfigPath)}}import{createHash as Ar}from"crypto";import{readFileSync as Or}from"fs";import{dirname as $r,join as pe}from"path";var J=2,qr="typescript-semantic";function Zt(n){let e=pe(n,qr);return{rootDir:e,requestDir:pe(e,"requests"),responseDir:pe(e,"responses")}}function en(n){try{let e=JSON.parse(Or(pe($r(n),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:Ar("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function tn(n){let e=JSON.parse(n);if(e.protocolVersion!==J||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Wr(e.profileEnvironment)||!e.request||!Hr(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Wr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string"||e===null)}function Hr(n){if(!n||typeof n!="object"||!("kind"in n))return!1;let e=n;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Xe(e.files)!==null;case"references":return Xt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Xt(e.definitions);case"signature":return nn(e.definition);default:return!1}}function Xt(n){return Array.isArray(n)&&n.every(nn)}function nn(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}var fe=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new de(t)),this.generationIdentity=e.generationIdentity??en,this.readSnapshot=e.readSnapshot??Kr,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let r=this.host.semanticProvider();switch(this.available=r.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return r.availability();case"import-usage":return r.importUsage(t.file);case"references":return[...Br(r,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!r.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...r.referenceFragmentsForFiles(t.files)];case"callees":return[...zr(r,t.definitions)];case"signature":return r.signatureFor(t.definition);default:return Vr(t)}}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}status(){let e=this.host?.snapshotStats();return{protocolVersion:J,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),r=this.generationIdentity(t.config.dbPath);if(!r||r!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Yr(this.snapshot,i)),this.db=t,o.close()}this.generation=r,this.snapshot=i,this.available=null}};function Oe(n){rn(n.requestDir,{recursive:!0}),rn(n.responseDir,{recursive:!0})}function sn(n,e,t={}){Oe(n);let r=0;for(let i of Ur(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=ue(n.requestDir,i),s=i.slice(0,-5),a=null;try{let c=tn(on(o,"utf8"));if(s=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");a=We(),ge(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);O(ue(n.responseDir,`${s}.json`),{ok:!0,protocolVersion:J,id:s,generation:c.generation,response:l})}catch(c){O(ue(n.responseDir,`${s}.json`),{ok:!1,protocolVersion:J,id:s,error:c instanceof Error?c.message:String(c)})}finally{a&&ge(a),t.afterRequest?.(),Gr(o,{force:!0}),r+=1}}return r}function Br(n,e,t){return n.referencesForDefinitions?.(e,t)??new Map(e.map(r=>[r.symbolId,n.referencesFor(r)]))}function zr(n,e){return n.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,n.calleesFor(t)]))}function Kr(n){try{let e=JSON.parse(on(ue(n,"..","meta.json"),"utf8"));return ut(e.fingerprint)}catch{return null}}function Yr(n,e){return e?ft(n,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function Vr(n){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(n)}`)}import{mkdirSync as an,readFileSync as Jr,readdirSync as Qr,rmSync as Xr}from"fs";import{resolve as me}from"path";var he=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=me(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??gt,this.now=e.now??Date.now}handle(e,t){let r=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),s=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),a=this.now()-r;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=a,this.lastError=null,this.unavailable=!1,{producerIdentity:s.producerIdentity,cold:s.stats.initializations>o.initializations,durationMs:a,fragments:s.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:re,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let r=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!r.available)throw this.unavailable=!0,new Error(r.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:r.emitter},this.sessionsCreated+=1,this.active}};function $e(n){an(n.requestDir,{recursive:!0}),an(n.responseDir,{recursive:!0})}function cn(n,e,t={}){$e(n);let r=0;for(let i of Qr(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=me(n.requestDir,i),s=i.slice(0,-5);try{let a=St(Jr(o,"utf8"));if(s=a.id,a.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(a.deadlineAtMs);let c=e.handle(a.baseGeneration,a.request);O(me(n.responseDir,`${s}.json`),{ok:!0,protocolVersion:re,id:s,baseGeneration:a.baseGeneration,response:c})}catch(a){O(me(n.responseDir,`${s}.json`),{ok:!1,protocolVersion:re,id:s,error:a instanceof Error?a.message:String(a)})}finally{t.afterRequest?.(),Xr(o,{force:!0}),r+=1}}return r}var ei=1e3,ti=250,ni=10;function ri(n){return n==="fresh"?null:{kind:"watch-startup",detail:`index ${n} when watch service started`}}async function ii(n,e,t={}){let r=dn(n),i=W(r);i.watch={...i.watch,...t};let o=ie(i);if(!o.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=H(r,i),a=it(s.cacheDir),c=at(a.lockPath,r);if(!c.acquired)return;let l=Date.now(),d=l,p={state:"idle"},u,y,m=!1,S=!1,f=0,g=0,M=0,D,I,w=Zt(s.cacheDir),F=yt(s.cacheDir);Oe(w),$e(F);let R=new fe({openDb:()=>Tt(r)}),x=new he({projectRoot:r,currentGeneration:()=>bt(s.dbPath)}),b=(k=!1)=>{if(!S)return;let A=Date.now();!k&&A-g<ei||(g=A,ot(a.statePath,{version:1,protocolVersion:rt,pid:P.pid,projectRoot:r,cliVersion:e,startedAt:new Date(l).toISOString(),heartbeatAt:new Date(A).toISOString(),lastActivityAt:new Date(d).toISOString(),...o.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(d+o.idleTimeoutMs).toISOString()},watcher:p,...u?{lastRefresh:u}:{},...y?{lastError:y}:{},typescriptSemantic:{...R.status(),...D===void 0?{}:{busyUntil:new Date(D).toISOString()}},typescriptIndex:{...x.status(),...I===void 0?{}:{busyUntil:new Date(I).toISOString()}}}))},_=()=>{d=Date.now()},Q=new oe({projectRoot:r,config:{...i,watch:o},languages:i.languages,onStatus(k){p=k,k.state!=="idle"&&_(),b(!0)},onReindexComplete(){_(),u=Re(r,i,s).lastRefresh,y=void 0,b(!0)},onError(k){_(),y={at:new Date().toISOString(),message:k.message},b(!0)}}),X=()=>{m=!0};P.once("SIGINT",X),P.once("SIGTERM",X);try{Q.start();let k=Re(r,i,s);u=k.lastRefresh;let A=ri(k.state);for(A&&Q.requestRefresh(A,{immediate:!0}),_(),S=!0,b(!0);!m;){let pn=cn(F,x,{beforeRequest(C){I=C+5e3,b(!0)},afterRequest(){I=void 0,b(!0)}}),un=sn(w,R,{beforeRequest(C){D=C+5e3,b(!0)},afterRequest(){D=void 0,b(!0)}}),qe=Date.now();if(qe-M>=ti){M=qe;let C=st(a.activityPath);C&&C.atMs>d&&(d=C.atMs),C?.refreshRequestedAtMs!==void 0&&C.refreshRequestedAtMs>f&&(f=C.refreshRequestedAtMs,_(),Q.requestRefresh({kind:"watch-demand",detail:C.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((un>0||pn>0)&&(_(),b(!0)),b(),ct({watcher:p,lastActivityAtMs:d,nowMs:Date.now(),idleTimeoutMs:o.idleTimeoutMs}))break;await oi(ni)}}finally{P.off("SIGINT",X),P.off("SIGTERM",X),R.closeTypeScriptService(),x.close(),Q.stop(),ln(a.statePath,{force:!0}),ln(a.activityPath,{force:!0}),c.release()}}function oi(n){return new Promise(e=>setTimeout(e,n))}var si=P.argv[1]?Zr(dn(P.argv[1])).href:null;if(si===import.meta.url){let n=P.argv[2],e=P.argv[3],t=ai(P.argv[4]);if(!n||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await ii(n,e,t)}catch(r){console.error(`watch-service: ${r instanceof Error?r.message:String(r)}`),P.exitCode=1}}function ai(n){if(!n)return{};try{let e=JSON.parse(n);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ii as runWatchServiceServer,ri as startupRefreshTrigger};
|
|
42
|
+
//# sourceMappingURL=watch-server.js.map
|