scip-query 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -2
- package/README.md +158 -62
- 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 +587 -305
- package/dist/{config-types-BrHl3Bge.d.ts → config-types-SVkUIufk.d.ts} +10 -2
- package/dist/{db-_Bdx0E1W.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-BEZ1Rt0S.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-C7cg4ZHR.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 +11 -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 +21 -18
- package/skills/scip-calibrate/SKILL.md +9 -3
- 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 +24 -13
- package/dist/chunk-27HMTUJE.js +0 -3
- package/dist/chunk-27XEGMCT.js +0 -7
- package/dist/chunk-3AMWF6V5.js +0 -3
- 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-U3VMUDXJ.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-XC2PJOVM.js +0 -3
- package/dist/chunk-XDESMVOL.js +0 -4
- package/dist/chunk-XZBLZHXL.js +0 -16
- package/dist/chunk-ZMGBWSFZ.js +0 -2
package/dist/reindex-worker.js
CHANGED
|
@@ -1,14 +1,258 @@
|
|
|
1
|
-
import{a as $,b as A,c as N,d as B}from"./chunk-X7CHWTZ2.js";import{a as v,b as E,c as ge}from"./chunk-TFWDJDGO.js";import{execFileSync as An}from"child_process";import{createHash as Nn}from"crypto";import{closeSync as Bn,copyFileSync as ae,existsSync as j,mkdirSync as D,mkdtempSync as _n,openSync as Wn,readdirSync as Un,readFileSync as O,renameSync as R,rmSync as x,statSync as Jn,writeFileSync as Xe}from"fs";import{basename as M,dirname as g,extname as qn,join as f}from"path";import{platform as zn}from"os";import{execFileSync as ct}from"child_process";import{existsSync as ut,readdirSync as me}from"fs";import{extname as he,join as ye}from"path";var pt=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),lt=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Pe(e){let t=[],n=dt(e),r=ht(e);for(let i of lt){if(gt(e,i.files)){t.push(i.language);continue}if(ft(n,i.globs)){t.push(i.language);continue}Pt(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&fe(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&fe(t,"c"),t}function dt(e){try{return me(e)}catch{return[]}}function gt(e,t){return t?.length?t.some(n=>ut(ye(e,n))):!1}function ft(e,t){return t?.length?e.some(n=>t.some(r=>mt(n,r))):!1}function mt(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function ht(e){let t=yt(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let s;try{s=me(i,{withFileTypes:!0})}catch{continue}for(let a of s){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let o=ye(i,a.name);if(a.isDirectory()){pt.has(a.name)||r.push(o);continue}let c=he(a.name).toLowerCase();c&&n.add(c)}}return n}function yt(e){try{let t=ct("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
|
|
2
|
-
`)){if(!r)continue;let i=he(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Pt(e,t){return t?.length?t.some(n=>e.has(n)):!1}function fe(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as xe,readdirSync as xt}from"fs";import{isAbsolute as St,join as _,resolve as bt}from"path";var jt={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",St(r)?r:bt(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Se(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Se(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=_(e,"vendor","bin","scip-php"),r=_(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",xe(r)?r:xe(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function W(e){return jt[e]}function Se(e,t){let n;try{n=xt(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return _(e,i);return null}import{readFileSync as Rt,writeFileSync as vt}from"fs";import{create as U}from"@bufbuild/protobuf";import{deserializeSCIP as kt,serializeSCIP as It,DocumentSchema as wt,IndexSchema as Ct,SymbolInformationSchema as Mt}from"@c4312/scip";function Dt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Lt(e),n=Ot(e.flatMap(i=>i.documents??[])),r=be(e.flatMap(i=>i.externalSymbols??[]));return U(Ct,{metadata:t,documents:n,externalSymbols:r})}function J(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>kt(Rt(i))),r=Dt(n);return vt(t,Buffer.from(It(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Lt(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Ot(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,U(wt,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Ft([...r.occurrences,...n.occurrences]),symbols:be([...r.symbols,...n.symbols]),text:Et(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ft(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function be(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,U(Mt,{symbol:r.symbol,documentation:$t([...r.documentation,...n.documentation]),relationships:Tt([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Tt(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Et(e,t){return e?t?e.length>=t.length?e:t:e:t}function $t(e){return[...new Set(e)]}import{createHash as Bt}from"crypto";import{existsSync as q,readFileSync as _t,readdirSync as Wt}from"fs";import{dirname as z,join as k,relative as Ut,resolve as G,sep as je}from"path";import{isAbsolute as At,relative as Nt}from"path";function S(e,t){let n=Nt(e,t);return n===""||!n.startsWith("..")&&!At(n)}function Re(e,t){let n=t.includes("."),r={};for(let s of t)r[s]=[];let i=[];for(let s of e){let a=we(s.path,t);a?r[a].push(s):n?r["."].push(s):i.push(s)}return{files:r,shared:i}}function ve(e,t){let n=new Map;for(let i of e){let s=t[i]?.packageName;s&&n.set(s,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let s=t[i],a=r.get(i);if(!s||s.parseFailed){for(let o of e)o!==i&&a.add(o);continue}for(let o of s.dependencyNames){let c=n.get(o);c&&c!==i&&a.add(c)}for(let o of[...s.pathsTargets,...s.referencesPaths]){let c=we(o,e);c&&c!==i&&a.add(c)}}return Jt(e,r)}function ke(e,t,n){let r={};for(let i of e){let s=new Map;for(let a of t.files[i]??[])s.set(a.path,a);for(let a of n[i]??[])for(let o of t.files[a]??[])s.set(o.path,o);for(let a of t.shared)s.set(a.path,a);r[i]={files:[...s.values()].sort((a,o)=>a.path.localeCompare(o.path))}}return r}function X(e){if(e===".")return"root";let t=Bt("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ie(e,t){let n=G(e),r={};for(let i of t)r[i]=qt(n,i);return r}function we(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function Jt(e,t){let n={};for(let r of e){let i=new Set,s=[...t.get(r)??[]];for(;s.length>0;){let a=s.pop();if(!(a===r||i.has(a))){i.add(a);for(let o of t.get(a)??[])o!==r&&!i.has(o)&&s.push(o)}}n[r]=[...i].sort((a,o)=>a.localeCompare(o))}return n}function qt(e,t){let n=t==="."?e:k(e,t),r=zt(n),i=Gt(n),s=i?Xt(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:s.pathsTargets,referencesPaths:s.referencesPaths,parseFailed:r.failed||s.failed}}function zt(e){let t=k(e,"package.json");if(!q(t))return{name:void 0,dependencyNames:[],failed:!1};let n=H(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let s of["dependencies","devDependencies","peerDependencies"]){let a=n.value[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(let o of Object.keys(a))i.add(o)}return{name:r,dependencyNames:[...i],failed:!1}}function Gt(e){let t=k(e,"tsconfig.json");if(q(t))return t;let n;try{n=Wt(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?k(e,n[0]):void 0}function Xt(e,t){let n=H(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Ht(n.value,e,t),i=Ce(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Ht(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=z(t),s=new Set;for(let a of r){if(!a||typeof a!="object")continue;let o=a.path;if(typeof o!="string"||o.trim()==="")continue;let c=Me(o,i,n);c&&s.add(c)}return[...s]}function Ce(e,t,n,r){let i=Kt(t);if(i)return{pathsTargets:Qt(i,z(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let s=Yt(t.extends,e,n);if(!s)return{pathsTargets:[],failed:!1};let a=H(s);return a.ok?Ce(s,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Kt(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Qt(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let s of i){if(typeof s!="string")continue;let a=Me(s,t,n);a&&r.add(a)}return[...r]}function Yt(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=G(z(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(je).includes("node_modules")&&S(n,i)&&q(i))return i}function Me(e,t,n){let r=e.replace(/\/?\*+$/,""),i=G(t,r===""?".":r);if(!S(n,i))return;let a=Ut(n,i).split(je).join("/");return a===""?".":a}function Zt(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let s=e[n];if(r){if(t+=s,s==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}s==='"'&&(r=!1),n+=1;continue}if(s==='"'){r=!0,t+=s,n+=1;continue}if(s==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
|
|
3
|
-
|
|
4
|
-
`)[0]}`,l=e.label===e.language?p:`${e.label}: ${p}`;return n(`Skipping ${e.label}: ${p}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-s,command:i,skipped:{language:e.language,reason:l}}}finally{kn(r)}if(!I(e.scipPath)){let o=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?o:`${e.label}: ${o}`;return n(`Skipping ${e.label}: ${o}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-s,command:i,skipped:{language:e.language,reason:c}}}let a;try{a=bn(e.scipPath).size}catch{a=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-s,command:i,outputBytes:a}}function wn(e,t,n){return new Promise((r,i)=>{Sn(e,[...t],n,s=>{s?i(s):r()})})}async function Cn(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,s=Math.max(1,Math.min(e.length,t)),a=Array.from({length:s},async()=>{for(;i<e.length;){let o=i++;r[o]=await n(e[o])}});return await Promise.all(a),r}import{execFileSync as ee}from"child_process";import{existsSync as V,readFileSync as Mn}from"fs";import{createRequire as Dn}from"module";import{platform as Ln}from"os";import{dirname as Ne,join as w}from"path";var On=Dn(import.meta.url);function te(e){return[e.indexerBinary,...e.binaryAliases??[]]}function ne(e){let t=te(e);return t.length===1?t[0]:t.join(" or ")}function C(e){for(let t of te(e))if(v(t))return t;return Tn(e)}function Be(e){return C(e)!==null||Fn(e)}function Fn(e){return _e(e)!==null}function Tn(e){let t=_e(e);if(!t)return null;let r=JSON.parse(Mn(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return w(Ne(t),r);for(let i of te(e)){let s=r[i];if(s)return w(Ne(t),s)}return null}function _e(e){if(!e.bundledNpmPackage)return null;try{return On.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function We(e,t){for(let n of e.projectLocalBinaries??[]){let r=w(t,n);if(V(r))return r}return null}function Ue(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||qe(n,t))return t;let r=En(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Je(e,t){let n=e.installMethods,r=ne(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(v(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{ee(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let s=C(e);if(s){let a=s===e.indexerBinary?"":` (using ${s})`;return t(`Successfully installed ${r} via ${i.label}${a}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(s){let a=s instanceof Error?s.message:String(s);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function En(e,t){for(let n of $n(t))if(qe(e,{...t,DOTNET_ROOT:n}))return n;return null}function $n(e){let t=[],n=e.DOTNET_ROOT;if(n&&V(n)&&t.push(n),Ln()==="darwin"&&v("brew"))try{let r=ee("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=w(r,"libexec");V(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function qe(e,t){try{return ee(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}async function He(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,s=Gn(e),a=Date.now();D(g(s.outputScip),{recursive:!0}),D(g(s.outputDb),{recursive:!0});let o=e.languages??Pe(t);if(o.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${o.join(", ")}`);let c=vr(t,o,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),p=await hr(f(g(s.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),l=null;try{let u=Xn({opts:e,paths:s,languages:o,fingerprint:c,start:a,onStatus:r});if(u)return u;await ur(i,r);let P=Kn(s);return l=P.runDir,await Qn({opts:e,languages:o,projectRoot:t,paths:s,tempPaths:P,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}catch(u){throw et(s.metaPath,le({trigger:e.trigger,result:"failed",start:a,error:u instanceof Error?u.message:String(u)})),u}finally{l&&x(l,{recursive:!0,force:!0}),p()}}function Gn(e){let t=e.outputScip??f(e.projectRoot,"index.scip"),n=e.outputDb??f(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:f(g(n),"meta.json")}}function Xn(e){if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||!kr(e.paths.metaPath,e.fingerprint))return null;A($(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=le({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return et(e.paths.metaPath,n),e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[],lastRefresh:n,shards:Hn(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Hn(e,t,n,r){let i=ce(t,n,r);return n.map(s=>({id:s,language:s,reused:!0,fingerprint:b(i[s]),outputBytes:L(ue(e.outputDb,s)),durationMs:0}))}function Kn(e){let t=_n(f(g(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:f(t,M(e.outputScip)),tempOutputDb:f(t,M(e.outputDb)),tempMetaPath:f(t,M(e.metaPath))}}async function Qn(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,shards:s,typescriptProjectShardContext:a}=await Yn(e,t);i.length>0&&e.onStatus(`Reused ${i.length} cached language shard(s): ${i.join(", ")}`);let o=ir(e,t,n,r,i,a),c=o.durationMs;return e.onStatus(`Done in ${(c/1e3).toFixed(1)}s`),{languages:n.map(p=>p.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:c,reused:!1,skipped:r,lastRefresh:o,shards:s}}async function Yn(e,t){let n=nr({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[h,de]of n)de.reused&&(r.push({language:h,scipPath:de.scipPath}),i.add(h));for(let h of i)e.onStatus(`Reusing cached ${h} SCIP shard (language inputs unchanged).`);let s=Zn(e,n),{preparedRuns:a,skippedLanguages:o,languageOutputScipPaths:c}=pr({languages:e.languages.filter(h=>!i.has(h)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:s?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),p=s?a.filter(h=>h.language!=="typescript"||s.missedProjectIds.has(h.id)):a,l=await Ae(p,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),u=[];if(s){er(e.paths.outputDb,l);let h=c.typescript??e.tempPaths.tempOutputScip;u=tr({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:h,reusedProjects:s.reusedProjects})}let P=[...l,...u],{indexedOutputs:T}=dr(P,o),m=[...r,...T];gr(m,o,e.languages,e.opts.allowPartial,e.onStatus);let ot=rr(n,l,s?{outputDb:e.paths.outputDb,classification:s.classification}:void 0);return{indexedOutputs:m,skippedLanguages:o,reusedLanguages:[...i],shards:ot,typescriptProjectShardContext:s?{projects:s.allProjects,fingerprints:s.fingerprints}:void 0}}function Zn(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=K(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ie(e.projectRoot,r),s=Re(n.fingerprint.files,r),a=ve(r,i),o=ke(r,s,a),c=pe(e.paths.metaPath),l=Vn(c,o,m=>j(F(e.paths.outputDb,m))),u=[...l.entries()].filter(([,m])=>m.reused).map(([m])=>m),P=new Set(u),T=new Set(r.filter(m=>!P.has(m)).map(m=>`typescript:${m}`));return{allProjects:r,fingerprints:o,classification:l,reusedProjects:u,missedProjectIds:T}}function Vn(e,t,n){let r=new Map;for(let i of Object.keys(t)){let s=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s});continue}let a=e.typescriptProjectShards?.[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:s});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s});continue}if(y(a)!==y(s)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:s});continue}r.set(i,{reused:!0,fingerprint:s})}return r}function er(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=F(e,r);D(g(i),{recursive:!0}),ae(n.scipPath,i)}}function tr(e){return e.reusedProjects.map((t,n)=>{let r=F(e.outputDb,t),i=oe(e.tempOutputScip,"typescript-project-cached",n);return ae(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:L(i)??void 0}})}function nr(e){let t=pe(e.paths.metaPath),n=ce(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let s=ue(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:s});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:s});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:s});continue}let o=t.languageFingerprints[i];if(!o){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:s});continue}if(!j(s)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:s});continue}if(y(o)!==y(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:s});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:s})}return r}function rr(e,t,n){let r=[];for(let[i,s]of e)s.reused&&r.push({id:i,language:i,reused:!0,fingerprint:b(s.fingerprint),outputBytes:L(s.scipPath),durationMs:0});for(let i of t){let s=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,o=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:o?.reason??s?.reason??i.skipped?.reason,fingerprint:o?b(o.fingerprint):s?b(s.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,s]of n.classification)s.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:b(s.fingerprint),outputBytes:L(F(n.outputDb,i)),durationMs:0});return r}function b(e){return Nn("sha256").update(y(e)).digest("hex").slice(0,16)}function L(e){try{return Jn(e).size}catch{return null}}function ir(e,t,n,r,i,s){cr(e.paths.outputDb,n),fr(n,e.tempPaths.tempOutputScip,e.onStatus),mr(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),A($(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let a=sr({mode:e.opts.typescriptProjectMode,skippedLanguages:r,reusedLanguages:i,context:s,metaPath:e.paths.metaPath});ar(e.paths.outputDb,a.pruneProjects);let o=le({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(c=>c.language),skipped:[...r]});return Ve(e.tempPaths.tempMetaPath,{version:3,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:ce(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),typescriptProjectShards:a.field,requestedLanguages:e.languages,indexedLanguages:n.map(c=>c.language),skipped:[...r],lastRefresh:o}),Rr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath}),o}function sr(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=pe(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function ar(e,t){let n=Ze(e);if(t===null){x(n,{recursive:!0,force:!0});return}let r;try{r=Un(n)}catch{return}for(let i of or(r,t))x(f(n,i),{force:!0})}function or(e,t){let n=new Set(t.map(r=>`${X(r)}.scip`));return e.filter(r=>!n.has(r))}function cr(e,t){for(let n of t){let r=ue(e,n.language);D(g(r),{recursive:!0}),n.scipPath!==r&&ae(n.scipPath,r)}}async function ur(e,t){if(!E()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import{a as ae,b as oe}from"./chunk-JRFCWCOD.js";import{a as vt}from"./chunk-P5XHIJHI.js";import{E as J,G as Et,K as Tt,L as re,M as Ft,N as ie,O as Dt,P as jt,Q as _t,R as se,S as je,U as ce,V as kt,X as Ot,a as O,b as B,d as bt,e as Pt,f as xt,g as te,m as U,u as It,w as Rt,x as wt,y as De}from"./chunk-XAEU4ROB.js";import{b as yt,c as St,f as j,g as ne,h as Te,i as Fe}from"./chunk-FFIYGYQR.js";import{a as C,b as E}from"./chunk-3M2UCPFS.js";import{e as T,f as G}from"./chunk-JHK2DMUQ.js";import{a as ee,b as Ee,c as ht}from"./chunk-TFWDJDGO.js";import{execFileSync as bo}from"child_process";import{createHash as Po}from"crypto";import{closeSync as xo,copyFileSync as Ie,existsSync as D,mkdirSync as xe,mkdtempSync as Io,openSync as vo,readdirSync as Ro,readFileSync as ve,renameSync as Sr,rmSync as k,statSync as wo,writeFileSync as Eo}from"fs";import{basename as Pe,dirname as S,extname as To,join as I}from"path";import{platform as Fo}from"os";import{existsSync as Mt,readdirSync as $r}from"fs";import{isAbsolute as Gr,join as _e,resolve as Br}from"path";var Ur={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",Gr(r)?r:Br(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",At(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",At(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=_e(e,"vendor","bin","scip-php"),r=_e(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Mt(r)?r:Mt(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function ke(e){return Ur[e]}function At(e,t){let n;try{n=$r(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return _e(e,i);return null}import{execFileSync as Me}from"child_process";import{existsSync as Oe,readFileSync as Jr}from"fs";import{createRequire as Hr}from"module";import{platform as zr}from"os";import{dirname as Ct,join as de}from"path";var Wr=Hr(import.meta.url);function Ae(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Ce(e){let t=Ae(e);return t.length===1?t[0]:t.join(" or ")}function le(e){for(let t of Ae(e))if(ee(t))return t;return Vr(e)}function Nt(e){return le(e)!==null||qr(e)}function qr(e){return Lt(e)!==null}function Vr(e){let t=Lt(e);if(!t)return null;let r=JSON.parse(Jr(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return de(Ct(t),r);for(let i of Ae(e)){let a=r[i];if(a)return de(Ct(t),a)}return null}function Lt(e){if(!e.bundledNpmPackage)return null;try{return Wr.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function $t(e,t){for(let n of e.projectLocalBinaries??[]){let r=de(t,n);if(Oe(r))return r}return null}function Gt(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Ut(n,t))return t;let r=Xr(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Bt(e,t){let n=e.installMethods,r=Ce(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(ee(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Me(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let a=le(e);if(a){let o=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${r} via ${i.label}${o}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let o=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${o}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Xr(e,t){for(let n of Yr(t))if(Ut(e,{...t,DOTNET_ROOT:n}))return n;return null}function Yr(e){let t=[],n=e.DOTNET_ROOT;if(n&&Oe(n)&&t.push(n),zr()==="darwin"&&ee("brew"))try{let r=Me("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=de(r,"libexec");Oe(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Ut(e,t){try{return Me(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import{readFileSync as Ls}from"fs";import{dirname as Gs,join as Bs}from"path";var Jt=xt({kind:"file-dependency-graph",invalidation:te("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:ri}),Qr=yt("file-dep-graph",{clearGroups:["whole-project"]});function N(e,t,n={}){let r=n.scipEdges??"all-references";return Qr.get(e,`${r}:${t??""}`,()=>{let i=new Set(j(e,{includeIgnored:!1})),a=bt(e),o=ei(t,r),s=0,c=0,d=null,l=!1,p=0,u=0;return T("file-dep-graph.product",()=>{if(a){let m=Jt.read(e,o,a);if(m){l=!0;let x=ni(m);return s=m.sourceFileCount,c=m.sourceEdgeCount,p=m.scipEdgeCount,u=x.size,d=m.sourceImportFingerprint,x}}let f=T("file-dep-graph.source-imports",()=>{let m=Kr(e,i,t);return s=m.files.length,c=m.edges.length,d=m.fingerprint,m},()=>({scope:t??null,files:s,edges:c})),g=new Map,y=(m,x)=>si(e,g,i,m,x);T("file-dep-graph.scip-edges",()=>{for(let m of oi(e,t,r))p+=1,y(m.from_file,m.to_file)},()=>({scope:t??null,edges:p}));for(let m of f.edges)y(m.fromFile,m.toFile);return u=g.size,a&&Jt.write(e,o,a,{sourceImportFingerprint:f.fingerprint,sourceFileCount:f.files.length,sourceEdgeCount:f.edges.length,scipEdgeCount:p,graph:ti(g)}),g},()=>({scope:t??null,available:a!==null,hit:l,files:s,sourceEdges:c,scipEdges:p,graphFiles:u,sourceImportFingerprint:d}))})}function Kr(e,t,n){let r=[],i=[];for(let a of t)if(!(n&&!a.includes(n))){r.push(a);for(let o of It(e,a))o.sourcePath&&i.push({fromFile:a,toFile:o.sourcePath})}return{files:r,edges:i,fingerprint:Zr(r,i)}}function Zr(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return B(JSON.stringify({files:e,edges:n}))}function ei(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function ti(e){return[...e].map(([t,n])=>[t,[...n]])}function ni(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function ri(e){let t=JSON.parse(e);return ii(t)?t:null}function ii(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(ai)}function ai(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function oi(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],a=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
|
|
2
|
+
d1.relative_path AS from_file,
|
|
3
|
+
d2.relative_path AS to_file
|
|
4
|
+
FROM mentions m
|
|
5
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
6
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
7
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
8
|
+
JOIN (
|
|
9
|
+
SELECT m2.symbol_id, c2.document_id
|
|
10
|
+
FROM mentions m2
|
|
11
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
12
|
+
WHERE m2.role = 1
|
|
13
|
+
GROUP BY m2.symbol_id
|
|
14
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
15
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
16
|
+
WHERE d1.id != d2.id
|
|
17
|
+
${a}
|
|
18
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
19
|
+
${r}`,...i)}function si(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let a=t.get(r);a||(a=new Set,t.set(r,a)),a.add(i)}function ue(e){let t=pe(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(p=>[p.path,p])),i=e.snapshot.files.filter(p=>{let u=ne(p.path,["typescript"]);return u==="config"||u==="ambient"}).map(p=>p.path),a=pe([...t,...i]),o=a.find(p=>!r.has(p)),s=new Set(e.snapshot.files.map(p=>p.path)).size!==e.snapshot.files.length,c=!o&&a.some(p=>Ht(r.get(p))),d=B(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:pe(e.snapshot.typescriptProjects),membership:t})),l=new Map;return{identityFor(p,u){if(!n.has(p))return L("target-outside-project");if(s)return L("duplicate-input-path");if(o)return L("missing-input-fingerprint");if(c)return L("unreadable-input");let f=[],g,y;if(e.graph===null)f.push("dependency-graph-unavailable"),y="whole-project",g=a;else{let h=di(p,e.graph,l);if(h.find(b=>!r.has(b)))return L("missing-input-fingerprint");if(g=pe([...h,...i]),g.some(b=>Ht(r.get(b))))return L("unreadable-input");y="dependency-closure"}let m=g.map(h=>li(r.get(h)));return{version:1,key:B(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:u,projectIdentity:d,inputs:m})),mode:y,inputFiles:g,reasons:f}}}}function ci(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let a=r[i];if(!(a===void 0||n.has(a))){n.add(a);for(let o of[...t.get(a)??[]].sort())n.has(o)||r.push(o)}}return[...n].sort()}function di(e,t,n){let r=n.get(e);if(r)return r;let i=ci(e,t);return n.set(e,i),i}function li(e){return{path:e.path,size:e.size,hash:e.hash}}function Ht(e){return e.size<0||e.hash==="unreadable"}function L(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function pe(e){return[...new Set(e)].sort()}var zs=St("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function zt(e){return j(e,{includeIgnored:!1}).filter(J).sort()}var pi="typescript-reference-fragment-v2",ui=Pt({kind:"typescript-reference-fragments",invalidation:te("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:gi});function Wt(e,t,n,r=e){let i=zt(e),a=ue({projectFiles:i,snapshot:t,graph:N(e),engineIdentity:Et()}),o=[...n].map(([s,c])=>({relativePath:s,contentHash:a.identityFor(s,pi).key,value:[...c]}));if(o.some(s=>s.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return ui.writeBatch(r,o.map(s=>({...s,contentHash:s.contentHash}))),o.length}function gi(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(fi)?null:t}catch{return null}}function fi(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}import{createHash as mi}from"crypto";import{appendFileSync as hi,existsSync as yi,mkdirSync as Si,readFileSync as nc}from"fs";import{dirname as Xt,join as qt}from"path";var bi="<global-symbols>";function Pi(e){let t=[];for(let n of e.all(`
|
|
20
|
+
SELECT relative_path, language, position_encoding, text
|
|
21
|
+
FROM documents
|
|
22
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
23
|
+
SELECT d.relative_path,
|
|
24
|
+
c.chunk_index,
|
|
25
|
+
c.start_line,
|
|
26
|
+
c.end_line,
|
|
27
|
+
hex(c.occurrences) AS occurrences_hex
|
|
28
|
+
FROM chunks c
|
|
29
|
+
JOIN documents d ON d.id = c.document_id
|
|
30
|
+
`))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
|
|
31
|
+
SELECT d.relative_path,
|
|
32
|
+
r.start_line,
|
|
33
|
+
r.start_char,
|
|
34
|
+
r.end_line,
|
|
35
|
+
r.end_char,
|
|
36
|
+
g.symbol,
|
|
37
|
+
g.display_name,
|
|
38
|
+
g.kind,
|
|
39
|
+
g.documentation,
|
|
40
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
41
|
+
g.enclosing_symbol,
|
|
42
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
43
|
+
FROM defn_enclosing_ranges r
|
|
44
|
+
JOIN documents d ON d.id = r.document_id
|
|
45
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
46
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:Ne(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
47
|
+
SELECT d.relative_path,
|
|
48
|
+
c.chunk_index,
|
|
49
|
+
m.role,
|
|
50
|
+
g.symbol,
|
|
51
|
+
g.display_name,
|
|
52
|
+
g.kind,
|
|
53
|
+
g.documentation,
|
|
54
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
55
|
+
g.enclosing_symbol,
|
|
56
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
57
|
+
FROM mentions m
|
|
58
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
59
|
+
JOIN documents d ON d.id = c.document_id
|
|
60
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
61
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:Ne(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
62
|
+
SELECT g.symbol,
|
|
63
|
+
g.display_name,
|
|
64
|
+
g.kind,
|
|
65
|
+
g.documentation,
|
|
66
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
67
|
+
g.enclosing_symbol,
|
|
68
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
69
|
+
FROM global_symbols g
|
|
70
|
+
WHERE NOT EXISTS (
|
|
71
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
72
|
+
) AND NOT EXISTS (
|
|
73
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
74
|
+
)
|
|
75
|
+
`))t.push({relativePath:bi,kind:"global-symbol",values:Ne(n)});return xi(t)}function xi(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),a=t.get(r.relativePath)??[];a.push(i),t.set(r.relativePath,a)}let n=new Map;for(let[r,i]of[...t].sort(([a],[o])=>a.localeCompare(o))){let a=mi("sha256");for(let o of i.sort())a.update(String(Buffer.byteLength(o))),a.update(":"),a.update(o),a.update(`
|
|
76
|
+
`);n.set(r,a.digest("hex"))}return n}function Ii(e,t){let n=[],r=[],i=[],a=[],o=new Set([...e.keys(),...t.keys()]);for(let s of[...o].sort()){let c=e.get(s),d=t.get(s);c===void 0?n.push(s):d===void 0?i.push(s):c!==d?r.push(s):a.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:a}}function Le(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),a=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),o=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-a.length;return{passed:a.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:a,extraFiles:o}}function $e(e,t=Ri){let n=t.now();if(!t.databaseExists(e.previousDbPath))return ge(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return ge(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let a=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),o=re(e.previousSnapshot,e.currentSnapshot),s=new Set(a),c=o.changes.length>0&&!Ft(o).fullProject&&o.changes.every(u=>s.has(u.path)),d=ie(o,c?t.dependencyGraph(r):new Map,a),l=Ii(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:o,plan:d,comparison:l,evaluation:Le(d,l,a.length)}}catch(a){return ge(e.refreshResult,"oracle-error",n,t.now(),a instanceof Error?a.message:String(a))}finally{Vt(r),Vt(i)}}function Yt(e,t,n,r=Date.now()){return ge(e,t,r,r,n)}function vi(e){let t=Xt(e);return{latestPath:qt(t,"affected-shadow-latest.json"),historyPath:qt(t,"affected-shadow.jsonl")}}function Qt(e,t,n=wi){let r=vi(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function Ne(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Ri={now:()=>Date.now(),databaseExists:e=>yi(e),openDatabase:(e,t,n)=>new O({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>j(e),dependencyGraph:e=>N(e),factDigests:e=>Pi(e)},wi={appendHistory:(e,t)=>{Si(Xt(e),{recursive:!0}),hi(e,`${JSON.stringify(t)}
|
|
77
|
+
`)},writeLatest:(e,t)=>E(e,t,{spacing:2,trailingNewline:!0})};function ge(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function Vt(e){try{e?.close()}catch{}}import{readFileSync as en,writeFileSync as tn}from"fs";import{create as Be}from"@bufbuild/protobuf";import{deserializeSCIP as nn,serializeSCIP as rn,DocumentSchema as Oi,IndexSchema as Mi,SymbolInformationSchema as Ai}from"@c4312/scip";import{readFileSync as Ei,writeFileSync as Ti}from"fs";import{create as Kt}from"@bufbuild/protobuf";import{deserializeSCIP as Fi,DocumentSchema as Di,IndexSchema as ji,serializeSCIP as _i,SymbolRole as ki}from"@c4312/scip";function Zt(e){let t;try{t=Fi(Ei(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Ge(t);return n.removedDefinitionOccurrences>0&&Ti(e,Buffer.from(_i(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Ge(e){let t=new Set;for(let a of e.documents)for(let o of a.symbols)o.symbol&&t.add(o.symbol);for(let a of e.externalSymbols)a.symbol&&t.add(a.symbol);let n=0,r=0,i=[];for(let a of e.documents){let o=a.occurrences.filter(s=>(s.symbolRoles&ki.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(o.length===a.occurrences.length){i.push(a);continue}r+=1,i.push(Kt(Di,{language:a.language,relativePath:a.relativePath,occurrences:o,symbols:a.symbols,text:a.text,positionEncoding:a.positionEncoding}))}return{index:n===0?e:Kt(ji,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function an(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ci(e),n=Ni(e.flatMap(i=>i.documents??[])),r=cn(e.flatMap(i=>i.externalSymbols??[]));return Be(Mi,{metadata:t,documents:n,externalSymbols:r})}function on(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>nn(en(i))),r=an(n);return tn(t,Buffer.from(rn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function sn(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>nn(en(i))),r=Ge(an(n));return tn(t,Buffer.from(rn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Ci(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Ni(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Be(Oi,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Li([...r.occurrences,...n.occurrences]),symbols:cn([...r.symbols,...n.symbols]),text:Gi(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Li(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function cn(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Be(Ai,{symbol:r.symbol,documentation:Bi([...r.documentation,...n.documentation]),relationships:$i([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function $i(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Gi(e,t){return e?t?e.length>=t.length?e:t:e:t}function Bi(e){return[...new Set(e)]}import{createHash as Ui}from"crypto";import{copyFileSync as Ji,existsSync as dn,rmSync as ln}from"fs";import{resolve as Hi}from"path";import gn from"better-sqlite3";var zi={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Wi={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function fn(e){let t=Date.now(),n=qi(e.affectedFiles);if(Vi(e.previousDbPath,e.miniDbPath,e.candidateDbPath),ln(e.candidateDbPath,{force:!0}),!dn(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!dn(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");pn(e.previousDbPath,"previous SQLite generation",!1),pn(e.miniDbPath,"incremental SQLite mini database"),Ji(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new gn(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Ue(r,"main","candidate SQLite generation"),Ue(r,"incremental","incremental SQLite mini database"),Xi(r,n),Yi(r,n.length);let i=Je(r,"main",!0),a=_(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Qi(r),Ki(r),Zi(r),e.onStage?.("after-delete"),ea(r),e.onStage?.("after-symbol-reconciliation"),ta(r),e.onStage?.("after-insert"),na(r),ra(r,n.length,a),e.onStage?.("before-commit")}).immediate(),mn(r,"main","candidate SQLite generation");let c=[...ia(r)].filter(([d,l])=>i.get(d)!==l).map(([d])=>d).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{ln(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function qi(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Vi(e,t,n){let r=[e,t,n].map(i=>Hi(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function pn(e,t,n=!0){let r=new gn(e,{readonly:!0,fileMustExist:!0});try{Ue(r,"main",t),n&&mn(r,"main",t)}finally{r.close()}}function Ue(e,t,n){for(let[r,i]of Object.entries(zi)){let o=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:d,pk:l})=>({name:s,type:c.toUpperCase(),notnull:d,pk:l}));if(JSON.stringify(o)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Wi)){let a=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),o=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(a?.tbl_name!==i.table||JSON.stringify(o)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}un(e,t,"documents",["relative_path"],n),un(e,t,"global_symbols",["symbol"],n)}function un(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(d=>d.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function mn(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Xi(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let a of i)n.run(a)})(t)}function Yi(e,t){let n=_(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=_(e,`SELECT COUNT(*) AS value
|
|
78
|
+
FROM main.documents d
|
|
79
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
80
|
+
FROM temp.incremental_affected_paths p
|
|
81
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
82
|
+
WHERE d.id IS NULL
|
|
83
|
+
LIMIT 1`).pluck().get(),a=e.prepare(`SELECT d.relative_path
|
|
84
|
+
FROM incremental.documents d
|
|
85
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
86
|
+
WHERE p.relative_path IS NULL
|
|
87
|
+
LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||a!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Qi(e){e.exec(`
|
|
88
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
89
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
90
|
+
SELECT g.symbol
|
|
91
|
+
FROM main.defn_enclosing_ranges r
|
|
92
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
93
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
94
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
|
|
95
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
96
|
+
SELECT g.symbol
|
|
97
|
+
FROM main.mentions m
|
|
98
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
99
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
100
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
101
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
102
|
+
WHERE m.role = 1;
|
|
103
|
+
|
|
104
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
105
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
106
|
+
SELECT g.symbol
|
|
107
|
+
FROM incremental.defn_enclosing_ranges r
|
|
108
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
109
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
110
|
+
SELECT g.symbol
|
|
111
|
+
FROM incremental.mentions m
|
|
112
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
113
|
+
WHERE m.role = 1;
|
|
114
|
+
`)}function Ki(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
115
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
116
|
+
UNION
|
|
117
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
118
|
+
), unaffected_definitions AS (
|
|
119
|
+
SELECT g.symbol
|
|
120
|
+
FROM main.defn_enclosing_ranges r
|
|
121
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
122
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
123
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
124
|
+
WHERE p.relative_path IS NULL
|
|
125
|
+
UNION
|
|
126
|
+
SELECT g.symbol
|
|
127
|
+
FROM main.mentions m
|
|
128
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
129
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
130
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
131
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
132
|
+
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
133
|
+
)
|
|
134
|
+
SELECT u.symbol
|
|
135
|
+
FROM unaffected_definitions u
|
|
136
|
+
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
137
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Zi(e){e.exec(`
|
|
138
|
+
DELETE FROM main.mentions
|
|
139
|
+
WHERE chunk_id IN (
|
|
140
|
+
SELECT c.id
|
|
141
|
+
FROM main.chunks c
|
|
142
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
143
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
144
|
+
);
|
|
145
|
+
DELETE FROM main.chunks
|
|
146
|
+
WHERE document_id IN (
|
|
147
|
+
SELECT d.id
|
|
148
|
+
FROM main.documents d
|
|
149
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
150
|
+
);
|
|
151
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
152
|
+
WHERE document_id IN (
|
|
153
|
+
SELECT d.id
|
|
154
|
+
FROM main.documents d
|
|
155
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
156
|
+
);
|
|
157
|
+
DELETE FROM main.documents
|
|
158
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
159
|
+
`)}function ea(e){e.exec(`
|
|
160
|
+
UPDATE main.global_symbols
|
|
161
|
+
SET display_name = NULL,
|
|
162
|
+
kind = NULL,
|
|
163
|
+
documentation = NULL,
|
|
164
|
+
signature = NULL,
|
|
165
|
+
enclosing_symbol = NULL,
|
|
166
|
+
relationships = NULL
|
|
167
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
168
|
+
|
|
169
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
170
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
171
|
+
)
|
|
172
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
173
|
+
FROM incremental.global_symbols;
|
|
174
|
+
|
|
175
|
+
UPDATE main.global_symbols
|
|
176
|
+
SET display_name = (
|
|
177
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
178
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
179
|
+
),
|
|
180
|
+
kind = (
|
|
181
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
182
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
183
|
+
),
|
|
184
|
+
documentation = (
|
|
185
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
186
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
187
|
+
),
|
|
188
|
+
signature = (
|
|
189
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
190
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
191
|
+
),
|
|
192
|
+
enclosing_symbol = (
|
|
193
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
194
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
195
|
+
),
|
|
196
|
+
relationships = (
|
|
197
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
198
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
199
|
+
)
|
|
200
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
201
|
+
`)}function ta(e){let t=_(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=_(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=_(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
|
|
202
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
203
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
204
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
205
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
206
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
207
|
+
FROM incremental.mentions m
|
|
208
|
+
JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
209
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
210
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
211
|
+
)
|
|
212
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
213
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
214
|
+
FROM incremental.defn_enclosing_ranges r
|
|
215
|
+
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
216
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function na(e){e.exec(`
|
|
217
|
+
DELETE FROM main.global_symbols
|
|
218
|
+
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
219
|
+
AND NOT EXISTS (
|
|
220
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
221
|
+
);
|
|
222
|
+
`)}function ra(e,t,n){let r=_(e,"SELECT COUNT(*) AS value FROM main.documents"),i=_(e,`SELECT COUNT(*) AS value
|
|
223
|
+
FROM main.documents d
|
|
224
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let a=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),o=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(a!==void 0||o!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ia(e){let t=Je(e,"main",!0),n=Je(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function Je(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
|
|
225
|
+
FROM ${t}.documents d
|
|
226
|
+
${r}
|
|
227
|
+
ORDER BY d.relative_path`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
|
|
228
|
+
FROM ${t}.chunks c
|
|
229
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
230
|
+
${r}
|
|
231
|
+
ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),o=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
|
|
232
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
233
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
234
|
+
g.enclosing_symbol,
|
|
235
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
236
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
237
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
238
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
239
|
+
${r}
|
|
240
|
+
ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),s=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
|
|
241
|
+
FROM ${t}.mentions m
|
|
242
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
243
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
244
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
245
|
+
${r}
|
|
246
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,p]of Object.entries({documents:i,chunks:a,definitions:o,mentions:s}))for(let u of p){let f=JSON.stringify([l,u]),g=c.get(u.relative_path)??[];g.push(f),c.set(u.relative_path,g)}let d=new Map;for(let[l,p]of[...c].sort(([u],[f])=>u.localeCompare(f))){let u=Ui("sha256");for(let f of p.sort())u.update(f).update(`
|
|
247
|
+
`);d.set(l,u.digest("hex"))}return d}function _(e,t){return e.prepare(t).get().value}import{createHash as aa}from"crypto";import{existsSync as He,readFileSync as oa,readdirSync as sa}from"fs";import{dirname as ze,join as fe,relative as ca,resolve as We,sep as hn}from"path";function yn(e,t){let n=t.includes("."),r={};for(let a of t)r[a]=[];let i=[];for(let a of e){let o=xn(a.path,t);o?r[o].push(a):n?r["."].push(a):i.push(a)}return{files:r,shared:i}}function Sn(e,t){let n=new Map;for(let i of e){let a=t[i]?.packageName;a&&n.set(a,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let a=t[i],o=r.get(i);if(!a||a.parseFailed){for(let s of e)s!==i&&o.add(s);continue}for(let s of a.dependencyNames){let c=n.get(s);c&&c!==i&&o.add(c)}for(let s of[...a.pathsTargets,...a.referencesPaths]){let c=xn(s,e);c&&c!==i&&o.add(c)}}return da(e,r)}function bn(e,t,n){let r={};for(let i of e){let a=new Map;for(let o of t.files[i]??[])a.set(o.path,o);for(let o of n[i]??[])for(let s of t.files[o]??[])a.set(s.path,s);for(let o of t.shared)a.set(o.path,o);r[i]={files:[...a.values()].sort((o,s)=>o.path.localeCompare(s.path))}}return r}function qe(e){if(e===".")return"root";let t=aa("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Pn(e,t){let n=We(e),r={};for(let i of t)r[i]=la(n,i);return r}function xn(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function da(e,t){let n={};for(let r of e){let i=new Set,a=[...t.get(r)??[]];for(;a.length>0;){let o=a.pop();if(!(o===r||i.has(o))){i.add(o);for(let s of t.get(o)??[])s!==r&&!i.has(s)&&a.push(s)}}n[r]=[...i].sort((o,s)=>o.localeCompare(s))}return n}function la(e,t){let n=t==="."?e:fe(e,t),r=pa(n),i=ua(n),a=i?ga(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:a.pathsTargets,referencesPaths:a.referencesPaths,parseFailed:r.failed||a.failed}}function pa(e){let t=fe(e,"package.json");if(!He(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ve(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let o=n.value[a];if(o&&typeof o=="object"&&!Array.isArray(o))for(let s of Object.keys(o))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function ua(e){let t=fe(e,"tsconfig.json");if(He(t))return t;let n;try{n=sa(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?fe(e,n[0]):void 0}function ga(e,t){let n=Ve(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=fa(n.value,e,t),i=In(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function fa(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=ze(t),a=new Set;for(let o of r){if(!o||typeof o!="object")continue;let s=o.path;if(typeof s!="string"||s.trim()==="")continue;let c=vn(s,i,n);c&&a.add(c)}return[...a]}function In(e,t,n,r){let i=ma(t);if(i)return{pathsTargets:ha(i,ze(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let a=ya(t.extends,e,n);if(!a)return{pathsTargets:[],failed:!1};let o=Ve(a);return o.ok?In(a,o.value,n,r+1):{pathsTargets:[],failed:!0}}function ma(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ha(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let a of i){if(typeof a!="string")continue;let o=vn(a,t,n);o&&r.add(o)}return[...r]}function ya(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=We(ze(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(hn).includes("node_modules")&&U(n,i)&&He(i))return i}function vn(e,t,n){let r=e.replace(/\/?\*+$/,""),i=We(t,r===""?".":r);if(!U(n,i))return;let o=ca(n,i).split(hn).join("/");return o===""?".":o}function Sa(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let a=e[n];if(r){if(t+=a,a==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}a==='"'&&(r=!1),n+=1;continue}if(a==='"'){r=!0,t+=a,n+=1;continue}if(a==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
|
|
248
|
+
`;)n+=1;continue}if(a==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=a,n+=1}return t}function Ve(e){try{let t=oa(e,"utf-8"),n=JSON.parse(Sa(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as Fa}from"crypto";import{existsSync as H,mkdirSync as Da,readFileSync as W,readdirSync as Ze,renameSync as ja,rmSync as Hn,writeFileSync as _a}from"fs";import{join as w}from"path";import{createHash as ba}from"crypto";import{existsSync as Ye,mkdirSync as Pa,readFileSync as me,readdirSync as _c,renameSync as xa,rmSync as kc,writeFileSync as Ia}from"fs";import{join as $}from"path";import{create as wn,fromBinary as En,toBinary as va}from"@bufbuild/protobuf";import{deserializeSCIP as he,DocumentSchema as Qe,IndexSchema as Tn,serializeSCIP as Fn}from"@c4312/scip";var Dn=1,Ra="typescript-scip-fragments";function jn(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let a of e){let o=M(a.relativePath);if(t.has(o))throw new Error(`duplicate TypeScript fragment replacement: ${o}`);if(t.add(o),a.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${o}`);let s=En(Qe,a.bytes);if(s.relativePath!==o)throw new Error(`TypeScript fragment path mismatch: expected ${o}, got ${s.relativePath}`);n.push(s)}let r=Fn(wn(Tn,{documents:n,externalSymbols:[]})),i=he(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function ye(e){let t=$(e,Ra);return{rootDir:t,blobDir:$(t,"blobs"),generationDir:$(t,"generations")}}function wa(e){let t=he(e.indexBytes);Un(t.metadata,Jn(e)),Bn(t.externalSymbols);let n=new Set,r=[];for(let a of t.documents){let o=M(a.relativePath);if(n.has(o))throw new Error(`duplicate TypeScript SCIP document path: ${o}`);n.add(o);let s=va(Qe,a),c=e.documentIdentities.get(o)??(e.allowUntrackedDocuments?A(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:o,contentHash:A(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${o}`);r.push(Nn(e.cacheDir,{relativePath:o,bytes:s,occurrences:a.occurrences.length,symbols:a.symbols.length,referenceFragments:[]},c))}let i=Ln(e,r);return $n(e.cacheDir,i),i}function _n(e){let t=ye(e.cacheDir);if(!Ye(Ke(t,e.generationIdentity)))return wa(e);let n=On({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function kn(e){let t=On({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(a=>[a.relativePath,a])),r=new Set;for(let a of e.fragments){let o=M(a.relativePath);if(r.has(o))throw new Error(`duplicate TypeScript fragment replacement: ${o}`);if(r.add(o),!n.has(o))throw new Error(`TypeScript fragment replacement has no prior document: ${o}`);let s=e.documentIdentities.get(o);if(!s)throw new Error(`missing TypeScript document identity: ${o}`);a.bytes===null?n.delete(o):n.set(o,Nn(e.cacheDir,a,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Ln(e,[...n.values()]);return $n(e.cacheDir,i),i}function On(e){let t=ye(e.cacheDir),n=Ke(t,e.generationIdentity),r;try{r=Gn(me(n,"utf8"))}catch(a){throw new Error(`TypeScript fragment generation is unavailable: ${a instanceof Error?a.message:String(a)}`,{cause:a})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let a of r.documents){let o=$(t.blobDir,`${a.blobHash}.scipdoc`),s=me(o);if(s.byteLength!==a.byteLength||A(s)!==a.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${a.relativePath}`);i.set(a.relativePath,s)}return{manifest:r,fragments:i}}function Mn(e){let t=Cn(e);return Xe(t.baseIndex,t.completeDocuments,"assembled")}function An(e){let t=Cn(e);return Ea(t.deletedAffectedPaths),{completeIndexBytes:Xe(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Xe(t.baseIndex,t.affectedDocuments,"affected")}}function Cn(e){let t=he(e.baseIndexBytes);Un(t.metadata,Jn(e)),Bn(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=M(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],a=[],o=[];for(let s of t.documents){let c=M(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let d=n.get(c);if(!d){i.push(s);continue}if(n.delete(c),d.bytes===null){o.push(c);continue}let l=En(Qe,d.bytes);if(l.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${l.relativePath}`);i.push(l),a.push(l)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:a,deletedAffectedPaths:o}}function Xe(e,t,n){let r=Fn(wn(Tn,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=he(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Ea(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Nn(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=M(t.relativePath),i=Buffer.from(t.bytes),a=A(i),o=ye(e);Pa(o.blobDir,{recursive:!0});let s=$(o.blobDir,`${a}.scipdoc`);if(Ye(s)){let c=me(s);if(c.byteLength!==i.byteLength||A(c)!==a)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Ia(c,i),xa(c,s)}return{relativePath:r,blobHash:a,byteLength:i.byteLength,documentIdentity:n}}function Ln(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Dn,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function $n(e,t){let n=ye(e),r=Ke(n,t.generationIdentity);if(Ye(r)){let i=Gn(me(r,"utf8"));if(Rn(i)!==Rn(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}E(r,t,{spacing:2,trailingNewline:!0})}function Rn(e){return A(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Gn(e){let t=JSON.parse(e);if(t.version!==Dn||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(M(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Ke(e,t){return $(e.generationDir,Ta(t))}function Ta(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${A(e)}.json`}function Bn(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Un(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Jn(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function M(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function A(e){return ba("sha256").update(e).digest("hex")}var Wn=1,qn=64*1024*1024,ka="typescript-scip-overlays";function Vn(e){let t=Qn(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(a=>[a.relativePath,a])),r=new Set;for(let a of e.fragments){let o=nt(a.relativePath);if(r.has(o))throw new Error(`duplicate TypeScript overlay: ${o}`);r.add(o),n.set(o,Oa(e.cacheDir,a))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Wn,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((a,o)=>a.relativePath.localeCompare(o.relativePath))};return Ma(e.cacheDir,i),i}function Xn(e){let t=Qn(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=W(w(q(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||z(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Mn({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Yn(e,t){let n=q(e),r=w(n,"generations");if(!H(r))return;let i=new Set(t.map(tt)),a=new Set;for(let s of Ze(r).filter(c=>i.has(c))){let c=et(W(w(r,s),"utf8"));for(let d of c.overlays)d.blobHash&&a.add(`${d.blobHash}.scipdoc`)}for(let s of Ze(r))i.has(s)||Hn(w(r,s),{force:!0});let o=w(n,"blobs");if(H(o))for(let s of Ze(o))a.has(s)||Hn(w(o,s),{force:!0})}function Qn(e,t){let n=w(q(e),"generations",tt(t));if(!H(n))return null;let r=et(W(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Oa(e,t){let n=nt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=z(r),a=w(q(e),"blobs");Da(a,{recursive:!0});let o=w(a,`${i}.scipdoc`);if(H(o)){let s=W(o);if(s.byteLength!==r.byteLength||z(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${o}.${process.pid}.${Date.now()}.tmp`;_a(s,r),ja(s,o)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Ma(e,t){let n=w(q(e),"generations",tt(t.generationIdentity));if(H(n)){let r=et(W(n,"utf8"));if(zn(r)!==zn(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}E(n,t,{spacing:2,trailingNewline:!0})}function et(e){let t=JSON.parse(e);if(t.version!==Wn||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(nt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function q(e){return w(e,ka)}function tt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${z(e)}.json`}function zn(e){return z(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function nt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function z(e){return Fa("sha256").update(e).digest("hex")}import{existsSync as Aa,readFileSync as Ca,readdirSync as Na,statSync as La}from"fs";import P from"path";var $a=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function V(e,t=[]){let n=P.resolve(e),r=t.flatMap(c=>Ba(n,c));if(r.length>0)return Kn(n,Zn(r));let i=Ga(n),a=Zn(i),o=Ja(n,a)?[n,...a]:a,s=o.length>0?o:[n];return Kn(n,s)}function Kn(e,t){return[...new Set(t.map(n=>za(e,n)))].sort((n,r)=>n.localeCompare(r))}function Ga(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Na(r,{withFileTypes:!0})}catch{continue}for(let a of i){let o=P.join(r,a.name);if(a.isDirectory()){!$a.has(a.name)&&!a.name.startsWith(".")&&n.push(o);continue}a.isFile()&&Ua(o)&&t.push(P.dirname(o))}}return t}function Ba(e,t){let n=t.trim();if(!n)return[];let r=P.resolve(e,n);if(!U(e,r))return[];try{let i=La(r);if(i.isDirectory())return[r];if(i.isFile()&&er(P.basename(r)))return[P.dirname(r)]}catch{return[]}return[]}function Ua(e){if(!er(P.basename(e)))return!1;let t=tr(e);return t?P.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function er(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Zn(e){let t=[...new Set(e.map(n=>P.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Wa(n,r)))}function Ja(e,t){if(t.length===0||t.some(r=>P.resolve(r)===e))return!1;let n=P.join(e,"tsconfig.json");return Aa(n)&&Ha(n)}function Ha(e){let n=tr(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!P.extname(r))):!1}function tr(e){try{let t=JSON.parse(Ca(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function za(e,t){let n=P.relative(e,t);return n?n.split(P.sep).join("/"):"."}function Wa(e,t){let n=P.relative(e,t);return!!n&&!n.startsWith("..")&&!P.isAbsolute(n)}import{createHash as io}from"crypto";import{existsSync as it,readFileSync as cr,statSync as ao,writeFileSync as at}from"fs";import{join as oo}from"path";import{randomUUID as qa}from"crypto";import{existsSync as Va,mkdirSync as nr,readFileSync as Xa,rmSync as rr}from"fs";import{resolve as rt}from"path";var Ya=12e4,Qa=5,Se=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=rt(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??no(),this.runtime=n.runtime??ro}request(t){let n=wt(this.cacheDir),r=kt(this.cacheDir),i=De(n.statePath);if(!ir(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let a=this.runtime.randomId(),o=rt(r.requestDir,`${a}.json`),s=rt(r.responseDir,`${a}.json`),c=this.runtime.now()+this.timeoutMs;nr(r.requestDir,{recursive:!0}),nr(r.responseDir,{recursive:!0}),E(o,{protocolVersion:ce,id:a,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Va(s))return Ka(Xa(s,"utf8"),a,this.baseGeneration,t.producerIdentity,t.affectedFiles);let d=De(n.statePath);if(!ir(d,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Qa)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{rr(o,{force:!0}),rr(s,{force:!0})}}};function ir(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Rt,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===ce&&n.isProcessAlive(e.pid)&&(r||i)}function Ka(e,t,n,r,i){let a=JSON.parse(e);if(a.protocolVersion!==ce||a.id!==t||a.ok===!0&&a.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0)throw new Error(typeof a.error=="string"?a.error:"TypeScript index service request failed.");let o=Za(a.response,r),s=[...new Set(i)].sort(),c=o.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return o}function Za(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(a=>{if(!a||typeof a.relativePath!="string"||a.bytesBase64!==null&&typeof a.bytesBase64!="string"||typeof a.occurrences!="number"||!Number.isInteger(a.occurrences)||a.occurrences<0||typeof a.symbols!="number"||!Number.isInteger(a.symbols)||a.symbols<0||!Array.isArray(a.referenceFragments)||!a.referenceFragments.every(eo)||r.has(a.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(a.relativePath);let o=a.bytesBase64===null?null:to(a.bytesBase64);return{relativePath:a.relativePath,bytes:o,occurrences:a.occurrences,symbols:a.symbols,referenceFragments:a.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function eo(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function to(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function no(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Ya}var ro={now:Date.now,randomId:qa,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:C};function so(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=re(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(d=>d.kind!=="modified"||d.inputKind!=="source"||!J(d.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=ie(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=co([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let a=ar(e.currentSnapshot,e.projectFiles,e.producerIdentity),o=ar(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(a!==o)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=sr(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=sr(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:a,previousFragmentGeneration:or(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:or(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function co(e,t){let n=null;for(let r of e){let i=t.filter(a=>a==="."||r===a||r.startsWith(`${a}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function dr(e){let t=Date.now();try{if(!it(e.previousDbPath)||!it(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=je();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let a=new O({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),o,s;try{o=j(a,{includeIgnored:!1}).filter(J).sort(),s=N(a)}finally{a.close()}let c=performance.now()-n,d=so({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?V(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:o,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:it(oo(e.projectRoot,"tsconfig.json"))});if(!d.eligible)throw new Error(d.reason);let l=Ot(e.previousDbPath);if(!l)throw new Error("published TypeScript base generation unavailable");n=performance.now();let u=new Se({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:l}).request({kind:"emit-documents",tsconfigPath:d.tsconfigPath,projectArgument:d.projectArgument,projectIdentity:d.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:d.plan.changedFiles,affectedFiles:d.plan.affectedFiles}),f=performance.now()-n,g=ao(e.previousShardPath).size>=qn;n=performance.now();let y=g?null:cr(e.previousShardPath),m=g?{completeIndexBytes:null,affectedIndexBytes:jn(u.fragments)}:An({packageVersion:r.packageVersion,baseIndexBytes:y,fragments:u.fragments}),x=performance.now()-n;n=performance.now(),g?Vn({cacheDir:e.cacheDir,previousGenerationIdentity:d.previousFragmentGeneration,nextGenerationIdentity:d.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:u.fragments}):(_n({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:y,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,generationIdentity:d.previousFragmentGeneration,documentIdentities:d.previousDocumentIdentities,allowUntrackedDocuments:!0}),kn({cacheDir:e.cacheDir,previousGenerationIdentity:d.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,generationIdentity:d.nextFragmentGeneration,fragments:u.fragments,documentIdentities:d.nextDocumentIdentities}));let h=performance.now()-n;n=performance.now(),m.completeIndexBytes&&at(e.candidateShardPath,m.completeIndexBytes),at(e.candidateAffectedScipPath,m.affectedIndexBytes);let v=performance.now()-n,b={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:u.cold,changedFiles:d.plan.changedFiles,affectedFiles:d.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:d.previousFragmentGeneration,nextFragmentGeneration:d.nextFragmentGeneration,manifest:d.manifest,plan:d.plan,projectFileCount:o.length,referenceFragmentsByFile:new Map(u.fragments.map(Z=>[Z.relativePath,Z.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:u.durationMs,assemblyMs:x,fragmentStoreMs:h,writeMs:v}};return e.onStatus(`Incremental TypeScript index emitted ${b.affectedFiles.length} affected document(s) in ${(b.durationMs/1e3).toFixed(3)}s (${b.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${x.toFixed(0)}ms, fragments ${h.toFixed(0)}ms, write ${v.toFixed(0)}ms).`),b}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function lr(e){let t=je();if(!t.available)throw new Error(t.reason);let n=Xn({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:cr(e.baseShardPath),packageVersion:t.packageVersion});at(e.candidateShardPath,n)}function ar(e,t,n){let r=e.files.filter(i=>ne(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,a)=>i.path.localeCompare(a.path));return ot(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function or(e,t){return ot(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function sr(e,t,n,r,i){let a=new Set(e.files.map(c=>c.path)),o=ue({projectFiles:t.filter(c=>a.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let d=o.identityFor(c,"typescript-scip-document-v1");if(d.key){s.set(c,d.key);continue}if(a.has(c))return null;s.set(c,ot(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function ot(e){return io("sha256").update(e).digest("hex")}import{execFile as lo}from"child_process";import{existsSync as be,renameSync as ct,rmSync as dt,statSync as po}from"fs";import{cpus as uo}from"os";import{join as pr}from"path";function go(e,t,n){if(!e.defaultOutputPath)return;let r=pr(t,e.defaultOutputPath);n!==r&&be(r)&&ct(r,n)}function fo(e,t,n){if(!e.defaultOutputPath)return null;let r=pr(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return dt(i,{force:!0}),be(r)?(ct(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function mo(e){e&&(dt(e.defaultOutputPath,{force:!0}),e.backupPath&&be(e.backupPath)&&ct(e.backupPath,e.defaultOutputPath))}function ho(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,uo().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function ur(e,t,n,r){let i=e.filter(d=>d.config.defaultOutputPath),a=e.filter(d=>!d.config.defaultOutputPath),o=[],s=ho(a.length,r),c=await So(a,s,d=>st(d,t,n));if(s>1){let d=new Map;for(let l of c.filter(p=>p.skipped)){let p=a.find(u=>u.id===l.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),d.set(p.id,await st(p,t,n)))}o.push(...c.map(l=>d.get(l.id)??l))}else o.push(...c);for(let d of i)o.push(await st(d,t,n));return o.sort((d,l)=>e.findIndex(p=>p.id===d.id)-e.findIndex(p=>p.id===l.id))}async function st(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),dt(e.scipPath,{force:!0});let r=fo(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),a=Date.now();try{await yo(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),go(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),d=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
249
|
+
`)[0]}`,l=e.label===e.language?d:`${e.label}: ${d}`;return n(`Skipping ${e.label}: ${d}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-a,command:i,skipped:{language:e.language,reason:l}}}finally{mo(r)}if(!be(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-a,command:i,skipped:{language:e.language,reason:c}}}let o;try{o=po(e.scipPath).size}catch{o=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-a,command:i,outputBytes:o}}function yo(e,t,n){return new Promise((r,i)=>{lo(e,[...t],n,a=>{a?i(a):r()})})}async function So(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,a=Math.max(1,Math.min(e.length,t)),o=Array.from({length:a},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(o),r}async function br(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,a=Do(e),o=Date.now();xe(S(a.outputScip),{recursive:!0}),xe(S(a.outputDb),{recursive:!0});let s=e.languages??Dt(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=T("reindex.fingerprint",()=>cs(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),d=await G("reindex.lock",()=>ts(I(S(a.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length}),l=null;try{let p=null,u=T("reindex.reuse-check",()=>(p=jo({opts:e,paths:a,languages:s,fingerprint:c,start:o,onStatus:r}),p),()=>({languages:s.length,reused:p!==null}));if(u)return u;await G("reindex.scip-cli-ready",()=>qo(i,r));let f=ko(a);l=f.runDir;let g;return await G("reindex.fresh",async()=>(g=await Oo({opts:e,languages:s,projectRoot:t,paths:a,tempPaths:f,fingerprint:c,start:o,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),g),()=>({languages:s.length,reused:g?.reused,skipped:g?.skipped.length}))}catch(p){throw jr(a.metaPath,we({trigger:e.trigger,result:"failed",start:o,error:p instanceof Error?p.message:String(p)})),p}finally{l&&k(l,{recursive:!0,force:!0}),d()}}function Do(e){let t=e.outputScip??I(e.projectRoot,"index.scip"),n=e.outputDb??I(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:I(S(n),"meta.json")}}function jo(e){let t=se(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!D(e.paths.outputScip)||!D(e.paths.outputDb)||!ds(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;oe(ae(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=we({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return jr(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:_o(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function _o(e,t,n,r){let i=Er(t,n,r);return n.map(a=>({id:a,language:a,reused:!0,fingerprint:X(i[a]),outputBytes:Y(ut(e.outputDb,a)),durationMs:0}))}function ko(e){let t=Io(I(S(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:I(t,Pe(e.outputScip)),tempOutputDb:I(t,Pe(e.outputDb)),tempMetaPath:I(t,Pe(e.metaPath))}}async function Oo(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await G("reindex.language-indexers",async()=>(n=await Ao(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:a,reusedLanguages:o,languageFingerprints:s,shards:c,typescriptProjectShardContext:d,incrementalTypeScript:l}=r;if(o.length>0&&e.onStatus(`Reused ${o.length} cached language shard(s): ${o.join(", ")}`),Mo({run:e,indexedOutputs:i,skippedLanguages:a,reusedLanguages:o})){let f=T("reindex.publish",()=>Ho(e,i,a,o,s,d),{mode:"metadata-only",languages:i.length,reused:o.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(y=>y.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:a,lastRefresh:f,shards:c}}let p=T("reindex.publish",()=>Jo(e,t,i,a,o,s,d,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:o.length,skipped:a.length}),u=p.durationMs;return e.onStatus(`Done in ${(u/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:u,reused:!1,skipped:a,lastRefresh:p,shards:c}}function Mo(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!D(e.run.paths.outputScip)||!D(e.run.paths.outputDb))return!1;let t=se(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Ao(e,t){let n=Go({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[R,mt]of n)mt.reused&&(r.push({language:R,scipPath:mt.scipPath}),i.add(R));for(let R of i)e.onStatus(`Reusing cached ${R} SCIP shard (language inputs unchanged).`);let a=n.get("typescript"),o=se(e.paths.outputDb,e.paths.metaPath),s=K(e.paths.metaPath),c=o.state==="legacy"||o.state==="current",d=s?.scipCompanion!=="deferred"&&(o.state!=="current"||o.generation.publication?.scipCompanion!=="deferred"),l=a&&!a.reused&&c?dr({projectRoot:e.projectRoot,cacheDir:S(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:Q(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Q(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:d,previousSnapshot:pt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(l?["typescript"]:[]),u=l?void 0:Co(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:y}=Vo({languages:e.languages.filter(R=>!i.has(R)&&!p.has(R)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:u?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),m=u?f.filter(R=>R.language!=="typescript"||u.missedProjectIds.has(R.id)):f,x=await ur(m,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),h=[];if(u){Lo(e.paths.outputDb,x);let R=y.typescript??e.tempPaths.tempOutputScip;h=$o({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:R,reusedProjects:u.reusedProjects})}let v=[...x,...h],{indexedOutputs:b}=Yo(v,g),Z=l?[{language:"typescript",scipPath:l.scipPath}]:[],ft=[...r,...Z,...b];Qo(ft,g,e.languages,e.opts.allowPartial,e.onStatus);let Nr=l?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:l.scipPath,outputScipPath:l.scipPath,durationMs:l.durationMs,command:"watch-service:typescript-index",outputBytes:Y(l.scipPath)??void 0}]:[],Lr=Bo(n,[...x,...Nr],u?{outputDb:e.paths.outputDb,classification:u.classification}:void 0);return{indexedOutputs:ft,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Uo(n,e.languages),shards:Lr,typescriptProjectShardContext:u?{projects:u.allProjects,fingerprints:u.fingerprints}:void 0,incrementalTypeScript:l??void 0}}function Co(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=V(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Pn(e.projectRoot,r),a=yn(n.fingerprint.files,r),o=Sn(r,i),s=bn(r,a,o),c=K(e.paths.metaPath),l=No(c,s,g=>D(Re(e.paths.outputDb,g))),p=[...l.entries()].filter(([,g])=>g.reused).map(([g])=>g),u=new Set(p),f=new Set(r.filter(g=>!u.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:p,missedProjectIds:f}}function No(e,t,n){let r=new Map;for(let i of Object.keys(t)){let a=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a});continue}let o=e.typescriptProjectShards?.[i];if(!o){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:a});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a});continue}if(F(o)!==F(a)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:a});continue}r.set(i,{reused:!0,fingerprint:a})}return r}function Lo(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=Re(e,r);xe(S(i),{recursive:!0}),Ie(n.scipPath,i)}}function $o(e){return e.reusedProjects.map((t,n)=>{let r=Re(e.outputDb,t),i=Q(e.tempOutputScip,"typescript-project-cached",n);return Ie(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Y(i)??void 0}})}function Go(e){let t=K(e.paths.metaPath),n=Er(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let a=ut(e.paths.outputDb,i),o=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o,scipPath:a});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:o,scipPath:a});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:o,scipPath:a});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:o,scipPath:a});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:o,scipPath:a});continue}if(!D(a)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o,scipPath:a});continue}if(F(s)!==F(o)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:o,scipPath:a});continue}r.set(i,{reused:!0,fingerprint:o,scipPath:a})}return r}function Bo(e,t,n){let r=[];for(let[i,a]of e)a.reused&&r.push({id:i,language:i,reused:!0,fingerprint:X(a.fingerprint),outputBytes:Y(a.scipPath),durationMs:0});for(let i of t){let a=e.get(i.language),o=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=o?n.classification.get(o):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??a?.reason??i.skipped?.reason,fingerprint:s?X(s.fingerprint):a?X(a.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,a]of n.classification)a.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:X(a.fingerprint),outputBytes:Y(Re(n.outputDb,i)),durationMs:0});return r}function X(e){return Po("sha256").update(F(e)).digest("hex").slice(0,16)}function Y(e){try{return wo(e).size}catch{return null}}function Uo(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Jo(e,t,n,r,i,a,o,s){let c=!s||s.completeScipUpdated,d=!1;c&&(gr(e.paths.outputDb,n),d=fr(n,e.tempPaths.tempOutputScip,e.onStatus));let l=Ko({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:d,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return d;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),lr({cacheDir:S(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(v=>v.language==="typescript"?{language:v.language,scipPath:s.candidateScipPath}:v);return gr(e.paths.outputDb,h),d=fr(h,e.tempPaths.tempOutputScip,e.onStatus),d}});if(oe(ae(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),l.mode==="incremental"&&s){let h=null,v=null;try{h=new O({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),v=new O({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let b=Wt(h,e.fingerprint,s.referenceFragmentsByFile,v);e.onStatus(`Cached exact TypeScript reference fragments for ${b} affected document(s).`)}catch(b){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${b instanceof Error?b.message:String(b)}.`)}finally{h?.close(),v?.close()}}let p=pt(e.paths.metaPath),u=l.mode==="incremental"&&s?es(s,l.changedDocumentPaths):$e({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=we({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(h=>h.language),skipped:[...r]}),g=l.mode==="incremental"&&l.scipCompanion==="deferred",y={...a};g&&delete y.typescript;let{metadata:m,pruneProjects:x}=xr({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:y,typescriptProjectShardContext:o,lastRefresh:f});return m.scipCompanion=g?"deferred":"current",Ir(e.paths.outputDb,x),gt(e.tempPaths.tempMetaPath,m),jt({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}),Yn(S(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Pr(e.paths.outputDb,u,e.onStatus),f}function Ho(e,t,n,r,i,a){let o=pt(e.paths.metaPath),s=null;try{Ie(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Yt("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}oe(ae(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=$e({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:o,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=we({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:d,pruneProjects:l}=xr({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:a,lastRefresh:c});return Ir(e.paths.outputDb,l),gt(e.paths.metaPath,d),_t(e.paths.outputDb,e.paths.metaPath),Pr(e.paths.outputDb,s,e.onStatus),c}function pt(e){return Tt(K(e)?.fingerprint)}function Pr(e,t,n){try{Qt(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function xr(e){let t=zo({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function zo(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=K(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Ir(e,t){let n=Dr(e);if(t===null){k(n,{recursive:!0,force:!0});return}let r;try{r=Ro(n)}catch{return}for(let i of Wo(r,t))k(I(n,i),{force:!0})}function Wo(e,t){let n=new Set(t.map(r=>`${qe(r)}.scip`));return e.filter(r=>!n.has(r))}function gr(e,t){for(let n of t){let r=ut(e,n.language);xe(S(r),{recursive:!0}),n.scipPath!==r&&Ie(n.scipPath,r)}}async function qo(e,t){if(!Ee()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
250
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(Fo()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!ht(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
251
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Vo(e){let t=[],n=[],r=e.languages.map((a,o)=>({language:a,scipPath:e.languages.length>1?Q(e.tempOutputScip,a,o):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:a,scipPath:o})=>[a,o]));for(let{language:a,scipPath:o}of r){let s=Xo({...e,language:a,scipPath:o});for(let c of s)"skipped"in c?vr(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Xo(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[lt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??V(e.projectRoot,e.typescriptProjects);return t.length===0?[lt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>lt({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Q(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function lt(e){let t=ke(e.language),n=Ce(t),r=$t(t,e.projectRoot);if(!r&&!Nt(t)){if(e.skipAutoInstall){let s=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Bt(t,e.onStatus)){let s=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}}let i=r??le(t);if(!i){let s=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}let{binary:a,args:o}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:a,args:o,env:Gt(t,e.env,i)}}}function Yo(e,t){let n=new Map;for(let i of e)if(i.skipped)vr(t,i.skipped);else{let a=`${i.language}\0${i.outputScipPath}`,o=n.get(a)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};o.scipPaths.push(i.scipPath),n.set(a,o)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)on(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let a=i.scipPaths[0];a!==i.outputScipPath&&Sr(a,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function vr(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function Qo(e,t,n,r,i){if(e.length===0){let a=t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
7
252
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
8
|
-
`+
|
|
9
|
-
`+t.map(
|
|
10
|
-
`))}function fr(e,t,n){e.length>1
|
|
11
|
-
`),()=>{try{
|
|
12
|
-
`)
|
|
13
|
-
`)}).then(()=>{process.exit(0)}).catch(e=>{console.error(`reindex-worker error: ${e}`),process.exit(1)});function Lr(e){switch(e){case"manual-cli":case"setup":case"watch-source":case"watch-git-head":case"watch-git-index":case"watch-git-state":return e;default:return"unknown"}}function Or(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};let n=t,r=n.projectMode==="single"||n.projectMode==="workspace"?n.projectMode:void 0,i=Array.isArray(n.projects)?n.projects.filter(s=>typeof s=="string"&&s.trim()!==""):void 0;return{projectMode:r,projects:i&&i.length>0?i:void 0}}catch{return{}}}function Fr(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}
|
|
253
|
+
`+a)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(a=>a.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
|
|
254
|
+
`+t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
255
|
+
`))}function fr(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=sn(e.map(a=>a.scipPath),t);return wr(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Sr(e[0].scipPath,t);return!1}function Ko(e){let t;if(Zo(e)){let i=I(e.run.tempPaths.runDir,"typescript-affected.db");try{Rr(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let a=performance.now();mr(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-a).toFixed(0)}ms.`);let o=fn({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${o.affectedDocumentCount} SQLite document(s) in ${(o.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:o.changedDocumentPaths,patchDurationMs:o.durationMs,converterDurationMs:performance.now()-a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(a){t=a instanceof Error?a.message:String(a),k(i,{force:!0}),k(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return mr(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Zo(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!D(e.run.paths.outputDb)||!D(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function es(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),a={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(o=>!i.has(o)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:a,evaluation:Le(e.plan,a,e.projectFileCount)}}function mr(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!D(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Rr(e,r);let a=Ee();if(!a)throw new Error("scip CLI is not available");bo(a,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(a){let o=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:a})}}function Rr(e,t){let n=Zt(e);wr(n,t)}function wr(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Q(e,t,n){let r=To(e)||".scip",i=Pe(e,r);return I(S(e),`${i}.${n+1}.${t}${r}`)}async function ts(e,t){for(let n=0;n<2;n++){let r=ns(e,t);if(r)return r;let i=rs(e);if(i&&is(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await os(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${S(e)}; refusing to steal an active lock.`);k(e,{force:!0});continue}if(i&&!C(i.pid)){k(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${S(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${S(e)}.`)}function ns(e,t){let n;try{n=vo(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return Eo(n,JSON.stringify(r)+`
|
|
256
|
+
`),()=>{try{xo(n)}finally{k(e,{force:!0})}}}function rs(e){try{let t=JSON.parse(ve(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:S(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function is(e,t){return e?.kind==="manual-cli"&&as(t?.trigger)}function as(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function os(e){return hr(e,"SIGTERM"),await yr(e,2e3)?!0:(hr(e,"SIGKILL"),yr(e,1e3))}function hr(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function yr(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!C(e))return!0;await ss(50)}return!C(e)}function ss(e){return new Promise(t=>setTimeout(t,e))}function cs(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:Fr(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Te(n.typescriptProjects),clojureConfigPath:Tr(n.clojureConfigPath),files:Fe(e)}}function Er(e,t,n){return Object.fromEntries(t.map(r=>{let i=ke(r).markerFiles,a=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Te(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},o=r==="clojure"?Tr(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Fr(n),...a,clojureConfigPath:o,files:Fe(e,{language:r,markerFiles:i})}]}))}function Tr(e){return e?.trim()||void 0}function Fr(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function ut(e,t){return I(S(e),"language-indexes",`${t}.scip`)}function Dr(e){return I(S(e),"language-indexes","typescript-projects")}function Re(e,t){return I(Dr(e),`${qe(t)}.scip`)}function K(e){try{return JSON.parse(ve(e,"utf-8"))}catch{return null}}function ds(e,t){try{let n=JSON.parse(ve(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&F(n.fingerprint)===F(t)&&F([...n.indexedLanguages??[]].sort())===F(t.languages)}catch{return!1}}function gt(e,t){E(e,t,{spacing:2,trailingNewline:!0})}function jr(e,t){try{let n=JSON.parse(ve(e,"utf-8"));if(n.version!==2&&n.version!==3)return;gt(e,{...n,lastRefresh:t})}catch{}}function we(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function F(e){return JSON.stringify(e)}var Mr=process.env.SCIP_REINDEX_PROJECT_ROOT,Ar=process.env.SCIP_REINDEX_OUTPUT_SCIP,Cr=process.env.SCIP_REINDEX_OUTPUT_DB,_r=process.env.SCIP_REINDEX_LANGUAGES,ls=vt(process.env.SCIP_REINDEX_INDEXER_CONCURRENCY),ps=process.env.SCIP_REINDEX_PNPM_WORKSPACES==="1",kr=hs(process.env.SCIP_REINDEX_TYPESCRIPT_CONFIG),us=process.env.SCIP_REINDEX_CLOJURE_CONFIG_PATH||void 0,gs=ms(process.env.SCIP_REINDEX_TRIGGER_KIND),fs=process.env.SCIP_REINDEX_TRIGGER_DETAIL;(!Mr||!Ar||!Cr)&&(console.error("reindex-worker: missing required env vars"),process.exit(1));var Or=_r?_r.split(",").filter(Boolean):void 0;br({projectRoot:Mr,outputScip:Ar,outputDb:Cr,languages:Or?.length?Or:void 0,pnpmWorkspaces:ps,typescriptProjectMode:kr.projectMode,typescriptProjects:kr.projects,clojureConfigPath:us,indexerConcurrency:ls,trigger:{kind:gs,detail:fs||void 0},onStatus:e=>process.stderr.write(`[reindex] ${e}
|
|
257
|
+
`)}).then(()=>{process.exit(0)}).catch(e=>{console.error(`reindex-worker error: ${e}`),process.exit(1)});function ms(e){switch(e){case"manual-cli":case"setup":case"watch-source":case"watch-git-head":case"watch-git-index":case"watch-git-state":return e;default:return"unknown"}}function hs(e){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};let n=t,r=n.projectMode==="single"||n.projectMode==="workspace"?n.projectMode:void 0,i=Array.isArray(n.projects)?n.projects.filter(a=>typeof a=="string"&&a.trim()!==""):void 0;return{projectMode:r,projects:i&&i.length>0?i:void 0}}catch{return{}}}
|
|
14
258
|
//# sourceMappingURL=reindex-worker.js.map
|