scip-query 0.20.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +81 -0
- package/README.md +255 -884
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-XXGZGNZ6.js +2 -0
- package/dist/call-graph-VGY3R4L3.js +2 -0
- package/dist/call-graph-evidence-lZa2dwQA.d.ts +11 -0
- package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
- package/dist/chunk-26CT72HM.js +2 -0
- package/dist/chunk-27OUNZW5.js +3 -0
- package/dist/chunk-2LJLEM5B.js +2 -0
- package/dist/chunk-3KXFB2FM.js +2 -0
- package/dist/chunk-3T5U2EQ2.js +2 -0
- package/dist/chunk-3TNRNKAT.js +2 -0
- package/dist/{chunk-PXY7F6Y4.js → chunk-3XQLJG7V.js} +5 -5
- package/dist/chunk-3XZELASU.js +2 -0
- package/dist/chunk-3YETOKNO.js +4 -0
- package/dist/chunk-47WX6UC4.js +2 -0
- package/dist/{chunk-7SQQWSY3.js → chunk-4HQYNZ3P.js} +2 -2
- package/dist/chunk-4IASLUOP.js +3 -0
- package/dist/{chunk-KMKTIO2G.js → chunk-4KIPF45P.js} +2 -2
- package/dist/chunk-4SZJF4GK.js +2 -0
- package/dist/chunk-4TOU7HHQ.js +2 -0
- package/dist/chunk-4ZCLDH6T.js +11 -0
- package/dist/{chunk-DQGFVPUV.js → chunk-527HV7JY.js} +3 -3
- package/dist/{chunk-ZTETIQ35.js → chunk-5BJPJUXF.js} +2 -2
- package/dist/chunk-5J3A6RBZ.js +16 -0
- package/dist/chunk-5KIJMEPC.js +2 -0
- package/dist/{chunk-JDOEX4E6.js → chunk-5QM7QT5B.js} +2 -2
- package/dist/chunk-5Z2H76VD.js +11 -0
- package/dist/chunk-63TFRBMB.js +2 -0
- package/dist/chunk-67FK5KGV.js +3 -0
- package/dist/chunk-6DO3VBLV.js +2 -0
- package/dist/chunk-6LS3IG2I.js +13 -0
- package/dist/chunk-6QN4FYQW.js +2 -0
- package/dist/chunk-6X4KO5A7.js +11 -0
- package/dist/chunk-743MEVFJ.js +8 -0
- package/dist/chunk-7G2WIVIX.js +2 -0
- package/dist/chunk-7KCZELVM.js +2 -0
- package/dist/chunk-7MUHSZGN.js +3 -0
- package/dist/chunk-7YZGSLW6.js +3 -0
- package/dist/chunk-7Z4GMCHM.js +117 -0
- package/dist/{chunk-32LVLCLN.js → chunk-AAOEROT3.js} +3 -3
- package/dist/chunk-AFRS7WJU.js +26 -0
- package/dist/chunk-ANCHW2R4.js +57 -0
- package/dist/{chunk-SXP2MBJH.js → chunk-AQF35NGT.js} +2 -2
- package/dist/chunk-ARGPDW2Y.js +6 -0
- package/dist/chunk-B3AREUQK.js +16 -0
- package/dist/chunk-BCTCADNB.js +2 -0
- package/dist/chunk-BM4OTGSY.js +3 -0
- package/dist/chunk-BMKTDJI6.js +16 -0
- package/dist/chunk-BOJ5SVE2.js +2 -0
- package/dist/{chunk-WXZLAAWK.js → chunk-BVR44XXB.js} +2 -2
- package/dist/{chunk-RUJURYSV.js → chunk-BYXWXLKM.js} +2 -2
- package/dist/chunk-BZCRHP46.js +3 -0
- package/dist/chunk-BZYSGZRK.js +2 -0
- package/dist/chunk-C52Q3JEQ.js +2 -0
- package/dist/chunk-C7WSQA6A.js +21 -0
- package/dist/{chunk-BDCC2NPY.js → chunk-CNT4ND5O.js} +2 -2
- package/dist/chunk-CQVDALWQ.js +2 -0
- package/dist/chunk-CTO3TRX7.js +2 -0
- package/dist/chunk-CXT3GZSQ.js +2 -0
- package/dist/{chunk-JVYA47YU.js → chunk-DGM2RJ3I.js} +2 -2
- package/dist/{chunk-7PIO7NKH.js → chunk-DK6MB565.js} +2 -2
- package/dist/chunk-DNPETNXT.js +2 -0
- package/dist/chunk-DRENNWRG.js +2 -0
- package/dist/chunk-DUDUIT5P.js +2 -0
- package/dist/chunk-DXEJ4FLZ.js +21 -0
- package/dist/chunk-DXYMTQZ4.js +2 -0
- package/dist/chunk-DZA7MQMU.js +6 -0
- package/dist/{chunk-ZHXX42OH.js → chunk-DZNWXJN2.js} +4 -4
- package/dist/{chunk-CJST5ETY.js → chunk-E6N6YTVM.js} +2 -2
- package/dist/chunk-E7CJ6O72.js +2 -0
- package/dist/chunk-EJHNTAEE.js +2 -0
- package/dist/chunk-EPLE5O5O.js +2 -0
- package/dist/chunk-F4FNK44D.js +2 -0
- package/dist/chunk-FCGMQETU.js +2 -0
- package/dist/chunk-FIO44MVK.js +3 -0
- package/dist/chunk-FLSVYEPL.js +2 -0
- package/dist/chunk-FOP7HD6H.js +3 -0
- package/dist/chunk-FSPENGSU.js +4 -0
- package/dist/chunk-FUUDUAKM.js +2 -0
- package/dist/chunk-FYCH2EYQ.js +2 -0
- package/dist/{chunk-5E4WNAVD.js → chunk-G47MFF47.js} +2 -2
- package/dist/chunk-G6VV7ROY.js +2 -0
- package/dist/chunk-GBZCVYWA.js +2 -0
- package/dist/chunk-GSHTVE56.js +3 -0
- package/dist/chunk-GTZFKDP3.js +2 -0
- package/dist/{chunk-2HPVVXM5.js → chunk-H2RBDP5S.js} +2 -2
- package/dist/chunk-H5EXS3HM.js +2 -0
- package/dist/chunk-HR5JYLVV.js +4 -0
- package/dist/chunk-HW7FASEL.js +2 -0
- package/dist/chunk-HYU4W353.js +10 -0
- package/dist/{chunk-FKSELJQF.js → chunk-I2LY3KN7.js} +2 -2
- package/dist/chunk-IGBQVEHE.js +2 -0
- package/dist/{chunk-3G66UZBH.js → chunk-IH3K5J6K.js} +2 -2
- package/dist/chunk-IHGK3SZ7.js +29 -0
- package/dist/chunk-IM23CSG5.js +2 -0
- package/dist/chunk-IQMGNIGY.js +2 -0
- package/dist/chunk-ITF3CWS5.js +2 -0
- package/dist/chunk-IZKJQQCQ.js +3 -0
- package/dist/chunk-J4HUBIVF.js +5 -0
- package/dist/{chunk-AZJQQKDD.js → chunk-JGMD6JGB.js} +2 -2
- package/dist/chunk-JLZWYDCZ.js +4 -0
- package/dist/chunk-JO6FK3Q5.js +2 -0
- package/dist/chunk-JSHDCVUM.js +81 -0
- package/dist/chunk-K2DZCH2K.js +2 -0
- package/dist/chunk-K63CAPS2.js +23 -0
- package/dist/chunk-KBIC6JHJ.js +2 -0
- package/dist/chunk-KFFQURUZ.js +2 -0
- package/dist/chunk-KFOYCQAJ.js +9 -0
- package/dist/chunk-KGKCJFWZ.js +6 -0
- package/dist/chunk-KK7GPALL.js +28 -0
- package/dist/chunk-L7WRUNKJ.js +2 -0
- package/dist/{chunk-W4ETQAXM.js → chunk-LFWB7TOJ.js} +2 -2
- package/dist/chunk-LGVTIZPV.js +61 -0
- package/dist/chunk-LIWIV26I.js +29 -0
- package/dist/chunk-LJMWILX6.js +3 -0
- package/dist/{chunk-BPAPWKP6.js → chunk-LXMW6ZAX.js} +8 -8
- package/dist/chunk-MFBVUQJZ.js +2 -0
- package/dist/{chunk-O64IZ6UX.js → chunk-MLTKGHD2.js} +2 -2
- package/dist/chunk-MLTSTKXD.js +5 -0
- package/dist/chunk-MR4ZKWO6.js +57 -0
- package/dist/{chunk-EN3O7VJA.js → chunk-MRXBLYRE.js} +2 -2
- package/dist/chunk-MXNGIEPU.js +3 -0
- package/dist/chunk-N4EFQIRX.js +20 -0
- package/dist/chunk-ND3BWIVN.js +7 -0
- package/dist/chunk-NODZYYGC.js +2 -0
- package/dist/chunk-NP4JFCLE.js +133 -0
- package/dist/chunk-NQXWWE6S.js +8 -0
- package/dist/chunk-NSDPPUDY.js +7 -0
- package/dist/chunk-NT4NVEHU.js +18 -0
- package/dist/chunk-O2VY47Y5.js +325 -0
- package/dist/chunk-O3EX5STE.js +5 -0
- package/dist/chunk-O4PZFAXA.js +3 -0
- package/dist/chunk-OA2BO4DR.js +2 -0
- package/dist/chunk-OFZVFIDF.js +3 -0
- package/dist/{chunk-PQCI4SQX.js → chunk-OG5UK2K7.js} +2 -2
- package/dist/chunk-OMVNRPST.js +2 -0
- package/dist/{chunk-7BAVHKMJ.js → chunk-OU6SDWAM.js} +9 -9
- package/dist/{chunk-LY4WC4AD.js → chunk-OY7PCALC.js} +2 -2
- package/dist/{chunk-A73XVBCR.js → chunk-P3UFF22M.js} +2 -2
- package/dist/chunk-PAZSBPJR.js +3 -0
- package/dist/chunk-PJBYDCBQ.js +38 -0
- package/dist/chunk-PRLU3I7G.js +79 -0
- package/dist/chunk-PU6XDQ2X.js +16 -0
- package/dist/{chunk-3CLX5EOX.js → chunk-PWEQ6CZZ.js} +2 -2
- package/dist/{chunk-XSRF6Q77.js → chunk-PX6QNUYF.js} +2 -2
- package/dist/chunk-Q4MRRB3C.js +3 -0
- package/dist/chunk-QGVUPYBC.js +35 -0
- package/dist/chunk-QH5Q6M5C.js +2 -0
- package/dist/chunk-QLWZUFDT.js +2 -0
- package/dist/chunk-QN2AI3D2.js +3 -0
- package/dist/{chunk-JAYYFEQY.js → chunk-QZCACNV5.js} +2 -2
- package/dist/chunk-RNKRYK6B.js +4 -0
- package/dist/chunk-RSUH7G5T.js +29 -0
- package/dist/chunk-RZWBTKXO.js +5 -0
- package/dist/chunk-SBFDPHKH.js +4 -0
- package/dist/{chunk-HX4GQPZP.js → chunk-SGSPCEFC.js} +3 -3
- package/dist/chunk-SIGVQT43.js +2 -0
- package/dist/chunk-SRIZDEWX.js +4 -0
- package/dist/chunk-SV2LEFVM.js +2 -0
- package/dist/chunk-T2PBOVDI.js +3 -0
- package/dist/chunk-TP2X2C2Y.js +3 -0
- package/dist/chunk-U2MNECDU.js +2 -0
- package/dist/chunk-U7DOYZDH.js +2 -0
- package/dist/chunk-UAQQR55F.js +2 -0
- package/dist/chunk-UBETC3Q2.js +2 -0
- package/dist/chunk-UEQORB2A.js +2 -0
- package/dist/chunk-UM56ZET4.js +38 -0
- package/dist/chunk-UXNXOMXJ.js +2 -0
- package/dist/{chunk-6SHPK5ZE.js → chunk-V6XENWOF.js} +2 -2
- package/dist/chunk-VJAD5WX5.js +2 -0
- package/dist/chunk-VRJG7N3I.js +453 -0
- package/dist/chunk-W7HN6V4E.js +7 -0
- package/dist/chunk-WCIKJ2E3.js +3 -0
- package/dist/chunk-WEXQYJY3.js +5 -0
- package/dist/chunk-WOPZX5GM.js +2 -0
- package/dist/chunk-WRQXLNYE.js +9 -0
- package/dist/{chunk-XKWKXZKW.js → chunk-WV6R37XV.js} +2 -2
- package/dist/{chunk-N5W4YZMK.js → chunk-WZ7V4BQV.js} +2 -2
- package/dist/chunk-WZRNEVYC.js +2 -0
- package/dist/chunk-X5MWO4DM.js +7 -0
- package/dist/chunk-XDAUYDFT.js +2 -0
- package/dist/{chunk-L7AW2QB5.js → chunk-XDOEHEET.js} +2 -2
- package/dist/chunk-XDQX6LDT.js +4 -0
- package/dist/chunk-XFRHBAIT.js +2 -0
- package/dist/chunk-XIPGCT3D.js +5 -0
- package/dist/chunk-XKM5D2XS.js +16 -0
- package/dist/chunk-XNF5T4T2.js +4 -0
- package/dist/chunk-Y2S4YNLH.js +3 -0
- package/dist/chunk-YA72ZUKO.js +2 -0
- package/dist/chunk-YBWE6J32.js +43 -0
- package/dist/chunk-YCXQQ3YB.js +2 -0
- package/dist/chunk-YDTK77JP.js +43 -0
- package/dist/chunk-YF25RQER.js +4 -0
- package/dist/chunk-YKHL4J3G.js +2 -0
- package/dist/chunk-YLNCTPOI.js +4 -0
- package/dist/chunk-YR7VRWNX.js +2 -0
- package/dist/chunk-YT4IQBET.js +3 -0
- package/dist/chunk-YUKYB54I.js +1 -0
- package/dist/chunk-Z2KGMIL4.js +2 -0
- package/dist/chunk-Z2QB75BS.js +3 -0
- package/dist/chunk-Z67JOKRE.js +554 -0
- package/dist/chunk-ZGDHC5AT.js +2 -0
- package/dist/chunk-ZMS4YCY7.js +2 -0
- package/dist/chunk-ZNW5A5VX.js +3 -0
- package/dist/{chunk-TFRAYKN6.js → chunk-ZP2WUVZ5.js} +2 -2
- package/dist/chunk-ZQUNCTEZ.js +2 -0
- package/dist/cli-main.js +8 -0
- package/dist/cli.js +1 -3
- package/dist/code-AXLJBZ6T.js +2 -0
- package/dist/code-B17qEMbt.d.ts +121 -0
- package/dist/code-result-json-CTZHAQXJ.js +2 -0
- package/dist/command-descriptors-6INSCKLW.js +342 -0
- package/dist/{config-types-jVM3D7MA.d.ts → config-types-B9B60MiR.d.ts} +199 -23
- package/dist/dataflow-AFXY423Q.js +2 -0
- package/dist/{db-B5PM5yNk.d.ts → db-BwIVAYNB.d.ts} +1 -1
- package/dist/dependence-slice-2G4X6VSJ.js +2 -0
- package/dist/deps-LMCAV5DO.js +2 -0
- package/dist/direct-navigation-2ONV22Y2.js +3 -0
- package/dist/entry-map-ZOC3VXO5.js +2 -0
- package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
- package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
- package/dist/file-kind-BKCVMNUf.d.ts +10 -0
- package/dist/files-WJQJLHMH.js +2 -0
- package/dist/graph-evidence-Bjyky2V4.d.ts +126 -0
- package/dist/graph-exploration-contract-CqDsnPQL.d.ts +7 -0
- package/dist/{health-Do5TKSJI.d.ts → health-CPp2Jf1Z.d.ts} +33 -34
- package/dist/hierarchy-ASNIHAX4.js +2 -0
- package/dist/imports-JICEKDKK.js +2 -0
- package/dist/index.d.ts +4 -31
- package/dist/index.js +1 -1
- package/dist/members-C5H2K3MS.js +2 -0
- package/dist/methods-KZOZHSD4.js +2 -0
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
- package/dist/output-continuation-command-NX3RH3TP.js +3 -0
- package/dist/output-pagination-3OFL2MJV.js +19 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-A2SXUH2H.js +3 -0
- package/dist/queries/affected.d.ts +22 -4
- package/dist/queries/affected.js +1 -1
- package/dist/queries/anchors.d.ts +123 -0
- package/dist/queries/anchors.js +2 -0
- package/dist/queries/architecture.d.ts +3 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +26 -7
- 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 +17 -3
- 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 +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +5 -26
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +145 -0
- package/dist/queries/context.js +2 -0
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +8 -3
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +34 -7
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +40 -14
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +3 -3
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +4 -38
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/dependence-slice.d.ts +47 -0
- package/dist/queries/dependence-slice.js +2 -0
- package/dist/queries/dependency-depth.d.ts +49 -0
- package/dist/queries/dependency-depth.js +2 -0
- package/dist/queries/deps.d.ts +4 -2
- package/dist/queries/deps.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 -4
- 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 +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +121 -0
- package/dist/queries/entry-map.js +2 -0
- package/dist/queries/evidence.d.ts +70 -0
- package/dist/queries/evidence.js +2 -0
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +18 -5
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +4 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +5 -3
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +11 -5
- 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 +4 -4
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +56 -136
- 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 +3 -3
- 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 +5 -9
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +27 -64
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -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 +2 -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/reference-neighborhood.d.ts +4 -0
- package/dist/queries/reference-neighborhood.js +2 -0
- package/dist/queries/reference-reachability.d.ts +48 -0
- package/dist/queries/reference-reachability.js +2 -0
- 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 +3 -36
- package/dist/queries/slice.js +1 -1
- package/dist/queries/source-inspection.d.ts +209 -0
- package/dist/queries/source-inspection.js +2 -0
- package/dist/queries/source-search.d.ts +13 -0
- package/dist/queries/source-search.js +2 -0
- 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 +13 -4
- 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-map.d.ts +449 -0
- package/dist/queries/system-map.js +2 -0
- package/dist/queries/system.d.ts +5 -3
- 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 +47 -3
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +3 -3
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +3 -3
- 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/value-flow.d.ts +43 -0
- package/dist/queries/value-flow.js +2 -0
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -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/query-service-fastpath.js +6 -0
- package/dist/query-service-server.js +5 -0
- package/dist/refs-ZOORVRQC.js +2 -0
- package/dist/refs-pagination-SRCUOYRD.js +2 -0
- package/dist/reindex-worker.js +85 -86
- package/dist/reindex.d.ts +64 -42
- package/dist/reindex.js +93 -77
- package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
- package/dist/runtime.d.ts +287 -8
- package/dist/runtime.js +4 -3
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-BnEwZRLJ.d.ts → scip-cli-H-n59izO.d.ts} +33 -2
- package/dist/slice-NOTBWA7S.js +2 -0
- package/dist/source-search-types-Dwz8KeuW.d.ts +79 -0
- package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
- package/dist/stats-OOJ74B32.js +2 -0
- package/dist/surface-BTBCLKNA.js +2 -0
- package/dist/symbol-resolution-SVSMX4RN.js +2 -0
- package/dist/system-2EIUFP6B.js +2 -0
- package/dist/trace-BB2GHQPG.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/value-flow-OA7AHSUG.js +2 -0
- package/dist/watch-server.js +3 -2
- package/docs/AGENT_GUIDE.md +133 -476
- package/docs/AI_FAILURE_MODES.md +30 -301
- package/docs/API.md +1 -1
- package/docs/API_EVOLUTION.md +6 -0
- package/docs/CLI_JSON_OUTPUT.md +207 -29
- package/docs/COMMAND_REFERENCE.md +255 -154
- package/docs/CONFIGURATION_WRITE_SAFETY.md +14 -13
- package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +84 -0
- package/docs/DETECTOR_GUIDE.md +46 -138
- package/docs/DURABILITY.md +7 -1
- package/docs/INDEX_GENERATIONS.md +6 -0
- package/docs/LOCK_PROTOCOL.md +8 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +13 -3
- package/docs/SECURITY_MODEL.md +39 -42
- package/docs/accuracy-audit-checklist.md +4 -0
- package/docs/accuracy-hardening-goal.md +9 -2
- package/docs/analyzer-inventory.md +59 -264
- package/docs/analyzer-validation-protocol.md +62 -170
- package/docs/architecture-coherence-vision.md +18 -12
- package/docs/locality-analyzer-design.md +1 -1
- package/docs/schemas/cli-json-envelope.schema.json +212 -27
- package/docs/schemas/cli-json-export-receipt.schema.json +25 -0
- package/docs/schemas/cli-output-page.schema.json +1 -1
- package/docs/schemas/observation-receipt.schema.json +164 -0
- package/docs/schemas/project-config.schema.json +37 -45
- package/docs/schemas/suppression-record.schema.json +1 -34
- package/package.json +69 -11
- package/skills/concrete-plan/SKILL.md +8 -0
- package/skills/concrete-plan/agents/openai.yaml +4 -0
- package/skills/scip-explore/SKILL.md +49 -61
- package/skills/scip-explore/agents/openai.yaml +3 -3
- package/skills/scip-explore/references/delegated-exploration.md +51 -0
- package/skills/scip-explore/references/external-evidence.md +72 -0
- package/skills/scip-explore/references/information-model.md +51 -0
- package/skills/scip-explore/scripts/capture-evidence.mjs +666 -0
- package/skills/scip-integrity-audit/SKILL.md +185 -0
- package/skills/scip-integrity-audit/agents/openai.yaml +4 -0
- package/skills/scip-plan/SKILL.md +67 -49
- package/skills/scip-plan/agents/openai.yaml +3 -3
- package/skills/scip-query/SKILL.md +98 -77
- package/skills/scip-query/agents/openai.yaml +3 -3
- package/skills/scip-setup/SKILL.md +10 -102
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/dist/chunk-26QA6FAI.js +0 -8
- package/dist/chunk-2KAZEZ6M.js +0 -2
- package/dist/chunk-3ORVDL3H.js +0 -2
- package/dist/chunk-46XGSFNI.js +0 -2
- package/dist/chunk-4MAK2HOY.js +0 -6
- package/dist/chunk-4TURLRL5.js +0 -16
- package/dist/chunk-4UQVNCQE.js +0 -2
- package/dist/chunk-55Q3WLZX.js +0 -2
- package/dist/chunk-5I5G2QOX.js +0 -3
- package/dist/chunk-6LDJQXAH.js +0 -2
- package/dist/chunk-6O5TICIZ.js +0 -3
- package/dist/chunk-7O5IKBTZ.js +0 -16
- package/dist/chunk-7S5E7KWT.js +0 -2
- package/dist/chunk-7WPLAODU.js +0 -5
- package/dist/chunk-AFHORGLH.js +0 -42
- package/dist/chunk-AIE7TFJW.js +0 -9
- package/dist/chunk-AQOFWNQJ.js +0 -1
- package/dist/chunk-B2PX5I6M.js +0 -2
- package/dist/chunk-B75HZHUP.js +0 -2
- package/dist/chunk-B7PBSLZN.js +0 -2
- package/dist/chunk-BBW6JFHN.js +0 -2
- package/dist/chunk-BNXCIFVY.js +0 -2
- package/dist/chunk-BS2NMXQZ.js +0 -4
- package/dist/chunk-C3KV2II6.js +0 -2
- package/dist/chunk-C43RDDP4.js +0 -20
- package/dist/chunk-DAFAHMNB.js +0 -42
- package/dist/chunk-DQLPXMH6.js +0 -8
- package/dist/chunk-EKZTZXHZ.js +0 -117
- package/dist/chunk-EW2NTSFA.js +0 -18
- package/dist/chunk-F3Z4OUDS.js +0 -8
- package/dist/chunk-FJH2NW7J.js +0 -66
- package/dist/chunk-FTFP6O3L.js +0 -11
- package/dist/chunk-FYLK2DEJ.js +0 -2
- package/dist/chunk-GH74ASD6.js +0 -11
- package/dist/chunk-GMXWZP2B.js +0 -2
- package/dist/chunk-GOUBFH5O.js +0 -3
- package/dist/chunk-HLF2TX6R.js +0 -2
- package/dist/chunk-HX7M4BDI.js +0 -30
- package/dist/chunk-HZ72SESS.js +0 -128
- package/dist/chunk-IB2N4FIY.js +0 -10
- package/dist/chunk-IZYYAFN5.js +0 -2
- package/dist/chunk-JFGGXWQF.js +0 -947
- package/dist/chunk-JN4NMBEX.js +0 -8
- package/dist/chunk-JW56N3KI.js +0 -4
- package/dist/chunk-JZ2OXNWB.js +0 -2
- package/dist/chunk-KFZNKUNT.js +0 -2
- package/dist/chunk-L5GJNV2T.js +0 -8
- package/dist/chunk-L7JDSCDF.js +0 -4
- package/dist/chunk-LU47HG23.js +0 -14
- package/dist/chunk-LVY7NPF7.js +0 -2
- package/dist/chunk-MKCDWWGV.js +0 -4
- package/dist/chunk-MNE7YG56.js +0 -2
- package/dist/chunk-MRXBEXSY.js +0 -26
- package/dist/chunk-MV7OWDUX.js +0 -2
- package/dist/chunk-NGEXCJJW.js +0 -11
- package/dist/chunk-NIW6JDC5.js +0 -29
- package/dist/chunk-PBUQFCNB.js +0 -16
- package/dist/chunk-POAVPHH7.js +0 -2
- package/dist/chunk-QZ4JVECJ.js +0 -2
- package/dist/chunk-RDO52JGY.js +0 -2
- package/dist/chunk-RJT3TUUZ.js +0 -2
- package/dist/chunk-RVLDN63O.js +0 -4
- package/dist/chunk-RXOXSKY3.js +0 -2
- package/dist/chunk-S7OYBOCK.js +0 -2
- package/dist/chunk-SMNXQT5Z.js +0 -3
- package/dist/chunk-SRAFT254.js +0 -2
- package/dist/chunk-T7YQSHPQ.js +0 -3
- package/dist/chunk-UJCOIXDY.js +0 -2
- package/dist/chunk-UJPRPGCO.js +0 -13
- package/dist/chunk-WCCFZ7V7.js +0 -113
- package/dist/chunk-WUPW3UN3.js +0 -3
- package/dist/chunk-X54AGLVX.js +0 -2
- package/dist/chunk-Y2MVPNKY.js +0 -5
- package/dist/chunk-YKUU5AIC.js +0 -3
- package/dist/chunk-YLCJLTPL.js +0 -2
- package/dist/chunk-YTQVETEO.js +0 -2
- package/dist/chunk-Z4N3MZYA.js +0 -38
- package/dist/chunk-ZJOOT3BG.js +0 -2
- package/dist/chunk-ZK26BAQL.js +0 -2
- package/dist/command-descriptors-DSS46KXI.js +0 -642
- package/dist/diff-gate-types-B0QYpDv1.d.ts +0 -11
- package/dist/direct-navigation-6YHV6IB5.js +0 -3
- package/dist/queries/diff-gate.d.ts +0 -253
- package/dist/queries/diff-gate.js +0 -2
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +0 -154
- package/docs/analyzer-validation-ledger.md +0 -516
- package/docs/schemas/outcome-event-record.schema.json +0 -95
- package/skills/_shared/SKILL.md +0 -101
- package/skills/_shared/agents/openai.yaml +0 -4
- package/skills/_shared/references/agent-contract-catalog.md +0 -105
- package/skills/_shared/references/command-catalog.md +0 -118
- package/skills/_shared/references/detector-precision-and-diffgate.md +0 -59
- package/skills/_shared/references/evidence-and-dead-code.md +0 -25
- package/skills/scip-audit/SKILL.md +0 -77
- package/skills/scip-audit/agents/openai.yaml +0 -4
- package/skills/scip-audit/references/claims.md +0 -98
- package/skills/scip-audit/references/cleanup.md +0 -100
- package/skills/scip-audit/references/directory.md +0 -222
- package/skills/scip-audit/references/frontend.md +0 -130
- package/skills/scip-audit/references/integrity.md +0 -154
- package/skills/scip-audit/references/maintainability.md +0 -162
- package/skills/scip-audit/references/twin-drift.md +0 -104
- package/skills/scip-diagnose/SKILL.md +0 -52
- package/skills/scip-diagnose/agents/openai.yaml +0 -4
- package/skills/scip-diagnose/references/debug.md +0 -117
- package/skills/scip-diagnose/references/probe-reachability.md +0 -77
- package/skills/scip-diagnose/references/root-cause.md +0 -145
- package/skills/scip-diagnose/references/triage.md +0 -119
- package/skills/scip-explore/references/diagrams.md +0 -40
- package/skills/scip-explore/references/language-playbook.md +0 -49
- package/skills/scip-improve/SKILL.md +0 -56
- package/skills/scip-improve/agents/openai.yaml +0 -4
- package/skills/scip-improve/references/cleanup-batches.md +0 -53
- package/skills/scip-improve/references/directory-moves.md +0 -53
- package/skills/scip-improve/references/doc-reconcile.md +0 -30
- package/skills/scip-improve/references/frontend-extraction.md +0 -39
- package/skills/scip-improve/references/maintainability-mechanism.md +0 -43
- package/skills/scip-improve/references/twin-drift.md +0 -35
- package/skills/scip-plan/references/api-impact.md +0 -19
- package/skills/scip-plan/references/conductor.md +0 -41
- package/skills/scip-plan/references/high-assurance.md +0 -43
- package/skills/scip-plan/references/hyper-optimization.md +0 -50
- package/skills/scip-plan/references/tla-model.md +0 -88
- package/skills/scip-setup/references/bootstrap-workflow.md +0 -119
- package/skills/scip-setup/references/language-verification.md +0 -61
- package/skills/scip-setup/references/lifecycle-commands.md +0 -119
- package/skills/scip-setup/references/per-repo-triage.md +0 -24
- package/skills/scip-verify/SKILL.md +0 -229
- package/skills/scip-verify/agents/openai.yaml +0 -4
- package/skills/scip-verify/references/calibrate-detectors.md +0 -170
package/dist/reindex.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
VALUES (?, ?, NULL, ?)`),c=i.transaction(
|
|
3
|
-
`).filter(r=>r&&t.has(
|
|
1
|
+
import{a as Y}from"./chunk-WV6R37XV.js";import{a as Ki,b as Xi,c as wt,d as Fn,h as Cn,i as Et,j as no,k as ro,m as An,n as io}from"./chunk-6X4KO5A7.js";import{a as pi,b as U,c as mt,d as gn,e as fi,f as gi,g as me,h as Fe,i as mi,j as St,k as mn,l as J,m as hi,o as yi,p as Ye,q as bt,r as Rt,t as hn,u as he,v as Ke,w as Yi}from"./chunk-LGVTIZPV.js";import{e as Qi,f as Zi,g as eo,i as to}from"./chunk-ANCHW2R4.js";import"./chunk-U2MNECDU.js";import{a as _e,b as Xe,c as Oe,d as vn,e as Pn,f as Bi,g as qi,h as wn,k as En,l as Ui,m as kn,n as Tn,o as Wi,p as Hi,q as zi,r as Dn,t as je,z as Ji}from"./chunk-XDQX6LDT.js";import"./chunk-B3AREUQK.js";import"./chunk-KK7GPALL.js";import"./chunk-7MUHSZGN.js";import{a as ui,b as ze,c as K,d as se,e as w,f as yt,i as De,j as H,k as In,l as Vi}from"./chunk-FOP7HD6H.js";import"./chunk-HW7FASEL.js";import"./chunk-YUKYB54I.js";import{b as Mi,c as Pt,d as Ni,e as Gi,f as $i}from"./chunk-YBWE6J32.js";import"./chunk-7Z4GMCHM.js";import"./chunk-6LS3IG2I.js";import{K as ji,L as Li,a as vt}from"./chunk-C7WSQA6A.js";import{g as Ci,h as ne,j as xn,k as Ai,r as _i,t as S,u as Se,v as Oi}from"./chunk-JSHDCVUM.js";import{$ as Ri,A as fn,Aa as Di,B as di,Ba as Fi,C as G,Ca as Rn,D as ae,E as V,H as A,I as D,J as L,M as li,N as gt,R as ht,S as ce,T as Je,U as Si,V as bi,Y as xt,aa as ye,b as ln,ba as Ce,ca as Ae,e as pn,ea as It,f as ai,fa as xi,g as ke,h as si,ha as Ii,i as We,ia as vi,j as lt,ja as Pi,k as pt,ka as wi,l as He,m as j,ma as yn,na as Sn,pa as Ei,ua as ki,w as Te,x as te,y as ft,ya as Ti,z as ci,za as bn}from"./chunk-WEXQYJY3.js";import{createHash as $f}from"crypto";import{existsSync as q,mkdirSync as rn,mkdtempSync as Vf,readdirSync as fc,renameSync as gc,rmSync as qe,statSync as Bf}from"fs";import{basename as nn,dirname as v,extname as qf,join as _,resolve as nc}from"path";import{platform as Uf}from"os";import{execFileSync as jc}from"child_process";import{constants as Lc,copyFileSync as oo,statSync as Mc}from"fs";import{platform as Nc}from"os";var Gc=Object.freeze({size:e=>Mc(e).size,clone:Vc,copy:(e,t)=>oo(e,t)}),$c=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function be(e,t,n=Gc){let r=n.size(e);try{return n.clone(e,t),{method:"reflink",bytes:r}}catch(i){if(!qc(i))throw i}return n.copy(e,t),{method:"copy",bytes:r}}function Vc(e,t){if(Nc()!=="darwin"){oo(e,t,Lc.COPYFILE_FICLONE_FORCE);return}try{jc("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw Bc(n)}}function Bc(e){let t=e?.stderr,n=Buffer.isBuffer(t)?t.toString("utf8"):t??"";return/operation not supported|not supported/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"ENOTSUP"}):/cross-device link/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"EXDEV"}):e}function qc(e){let t=e?.code;return t!==void 0&&$c.has(t)}function ao(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function Re(e,t){t.method==="reflink"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function kt(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import Uc from"better-sqlite3";import{execFileSync as Wc}from"child_process";import{existsSync as Hc,readdirSync as zc}from"fs";import{extname as Tt,join as Jc}from"path";function de(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>so({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function so(e){let t=new Set((e.extensions??ji).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Hc(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Yi(e.projectRoot),r=Yc(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Uc(e.dbPath);try{let o=Xc(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
2
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let l=0;for(let p of u){if(o.has(p))continue;let f=ki(e.projectRoot,p,{inputKind:"auxiliary source file"}),g=a.run(Qc(p),p,f);l+=Number(g.changes)}return l})(r),d={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${d.existing} already present).`),d}finally{i.close()}}function Yc(e,t){let n=Kc(e,t);if(n)return n;let r=[],i=o=>{let a=o?Jc(e,o):e,s;try{s=zc(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Li.has(c.name))continue;let d=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(d);continue}t.has(Tt(c.name).toLowerCase())&&r.push(d)}};return i(""),r.sort()}function Kc(e,t){try{return Wc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
3
|
+
`).filter(r=>r&&t.has(Tt(r).toLowerCase())).sort()}catch{return null}}function Xc(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function Qc(e){return Tt(e).toLowerCase()===".vue"?"vue":Tt(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Zc,join as ed}from"path";function co(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new Y({projectRoot:t,dbPath:n,indexPath:e.indexPath??ed(Zc(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let d=e.reuseExisting||e.affectedFiles?to(i):null;e.reuseExisting&&d?.extractorVersion===Qi?(o=d,a=!0):(o=Zi(i,{...d?{previousGraph:d}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:S}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||eo(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(d=>`${d.id} ${d.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}import{createHash as nd}from"crypto";import{existsSync as rd}from"fs";import{dirname as id,join as lo}from"path";function _n(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Qe(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=_n(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),uo(r,i,a)):a.size>0?uo(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:td(r,t,i),reasons:[]}}function uo(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function td(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let d=r.get(c)??new Set;d.add(a),r.set(c,d)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var od="<global-symbols>";function ad(e){let t=[];for(let n of e.all(`
|
|
4
4
|
SELECT relative_path, language, position_encoding, text
|
|
5
5
|
FROM documents
|
|
6
6
|
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
@@ -27,7 +27,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
27
27
|
FROM defn_enclosing_ranges r
|
|
28
28
|
JOIN documents d ON d.id = r.document_id
|
|
29
29
|
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
-
`))t.push({relativePath:n.relative_path,kind:"definition",values:
|
|
30
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:On(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
31
|
SELECT d.relative_path,
|
|
32
32
|
c.chunk_index,
|
|
33
33
|
m.role,
|
|
@@ -42,7 +42,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
42
42
|
JOIN chunks c ON c.id = m.chunk_id
|
|
43
43
|
JOIN documents d ON d.id = c.document_id
|
|
44
44
|
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
-
`))t.push({relativePath:n.relative_path,kind:"mention",values:
|
|
45
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:On(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
46
|
SELECT g.symbol,
|
|
47
47
|
g.display_name,
|
|
48
48
|
g.kind,
|
|
@@ -56,69 +56,84 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
56
56
|
) AND NOT EXISTS (
|
|
57
57
|
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
58
|
)
|
|
59
|
-
`))t.push({relativePath:
|
|
60
|
-
`);n.set(r,o.digest("hex"))}return n}function Ps(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function Kt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.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:o,extraFiles:a}}function Xt(e,t=Fs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,d)=>{let l=r();return Zr(e.refreshResult,u,n?l:i(),Math.max(0,l-o),d)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),d=Ue(e.previousSnapshot,e.currentSnapshot),l=new Set(u),p=d.changes.length>0&&!Jt(d).fullProject&&d.changes.every(y=>l.has(y.path)),m=nt(d,p?t.dependencyGraph(s):new Map,u),g=Ps(t.factDigests(s),t.factDigests(c)),f=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?f:i()).toISOString(),durationMs:Math.max(0,f-o),manifest:d,plan:m,comparison:g,evaluation:Kt(m,g,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{Kr(s),Kr(c)}}function Xr(e,t,n,r=Date.now()){return Zr(e,t,r,0,n)}function ws(e){let t=Rs(e);return{latestPath:Yr(t,"affected-shadow-latest.json"),historyPath:Yr(t,"affected-shadow.jsonl")}}function Qr(e,t,n=As){let r=ws(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ks=8*1024*1024,Es=Vr;function Ts(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function Ds(e,t,n=ks){Br(e,Ts(t),{maxSegmentBytes:n,previousSuffix:Es})}function Yt(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 Fs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:x,databaseExists:e=>bs(e),openDatabase:(e,t,n)=>new oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Xe(e),dependencyGraph:e=>Ze(e),factDigests:e=>Is(e)},As={appendHistory:Ds,writeLatest:(e,t)=>X(e,t,{spacing:2,trailingNewline:!0})};function Zr(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function Kr(e){try{e?.close()}catch{}}import{execFileSync as _s}from"child_process";import{existsSync as Ls,readdirSync as ti}from"fs";import{extname as ni,join as ri}from"path";var ii=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Os=[{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 Qt(e){let t=[],n=Cs(e),r=Gs(e);for(let i of Os){if(js(e,i.files)){t.push(i.language);continue}if(Ms(n,i.globs)){t.push(i.language);continue}Vs(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&ei(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&ei(t,"c"),t}function Cs(e){try{return ti(e)}catch{return[]}}function js(e,t){return t?.length?t.some(n=>Ls(ri(e,n))):!1}function Ms(e,t){return t?.length?e.some(n=>t.some(r=>Ns(n,r))):!1}function Ns(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 Gs(e){let t=$s(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ti(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=ri(i,a.name);if(a.isDirectory()){ii.has(a.name)||r.push(s);continue}let c=ni(a.name).toLowerCase();c&&n.add(c)}}return n}function $s(e){try{let t=_s("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}),n=new Set;for(let r of t.split(`
|
|
61
|
-
`)){if(!r||r.split("/").some(o=>ii.has(o)))continue;let i=ni(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Vs(e,t){return t?.length?t.some(n=>e.has(n)):!1}function ei(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as Bs}from"fs";import{isAbsolute as oi,join as qs,resolve as Us}from"path";var rt="@sourcegraph/scip-typescript@0.4.0",ai="scip-python-plus@0.7.5",si="github.com/sourcegraph/scip-go@v0.2.7",ci="scip-dotnet@0.2.14",Ws="scip_dart@1.6.2",di={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",identity:rt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",rt]}],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",identity:rt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",rt]}],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:le.language,indexerBinary:le.indexerBinary,checkCommand:`${le.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:le.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[],installUrl:le.installUrl},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",identity:ai,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",ai]}],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",oi(r)?r:Us(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",identity:si,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",si]}],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",ui(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",identity:ci,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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",ui(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",identity:ci,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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",identity:Ws,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],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:({indexerBinary:e})=>oi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function it(e){return di[e]}function ui(e,t){let n;try{n=Bs(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return qs(e,i);return null}import{writeFileSync as en}from"fs";import{create as Te}from"@bufbuild/protobuf";import{deserializeSCIP as tn,serializeSCIP as nn,DocumentSchema as Qs,IndexSchema as gi,MetadataSchema as Zs,SymbolInformationSchema as ec}from"@c4312/scip";import{writeFileSync as Hs}from"fs";import{create as li}from"@bufbuild/protobuf";import{deserializeSCIP as zs,DocumentSchema as Js,IndexSchema as Ys,serializeSCIP as Ks,SymbolRole as Xs}from"@c4312/scip";function pi(e){let t;try{t=zs(w(e,{inputKind:"SCIP sanitization input",maxBytes:_}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Zt(t);return n.removedDefinitionOccurrences>0&&Hs(e,Buffer.from(Ks(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Zt(e){let t=new Set;for(let o of e.documents){dr(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Xs.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(li(Js,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:li(Ys,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function rn(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=nc(e),n=rc(e.flatMap(i=>i.documents??[])),r=hi(e.flatMap(i=>i.externalSymbols??[]));return Te(gi,{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=>tn(w(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=rn(n);return en(t,Buffer.from(nn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function fi(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>tn(w(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=Zt(rn(n));return en(t,Buffer.from(nn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function tc(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Te(gi,{metadata:Te(Zs,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function mi(e,t,n){let r=tn(w(e,{inputKind:"SCIP normalization input",maxBytes:_})),i=tc(r,t,n);en(e,Buffer.from(nn(i)))}function nc(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 rc(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,Te(Qs,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ic([...r.occurrences,...n.occurrences]),symbols:hi([...r.symbols,...n.symbols]),text:ac(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ic(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 hi(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,Te(ec,{symbol:r.symbol,documentation:sc([...r.documentation,...n.documentation]),relationships:oc([...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 oc(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 ac(e,t){return e?t?e.length>=t.length?e:t:e:t}function sc(e){return[...new Set(e)]}import{createHash as cc}from"crypto";import{copyFileSync as uc,existsSync as yi,rmSync as Si}from"fs";import{resolve as dc}from"path";import xi from"better-sqlite3";var lc={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}]},pc={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_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ii(e){let t=x(),n=gc(e.affectedFiles);if(fc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Si(e.candidateDbPath,{force:!0}),!yi(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!yi(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");bi(e.previousDbPath,"previous SQLite generation",!1),bi(e.miniDbPath,"incremental SQLite mini database"),uc(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new xi(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),an(r,"main","candidate SQLite generation"),an(r,"incremental","incremental SQLite mini database"),mc(r,n),hc(r,n.length);let i=sn(r,"main",!0),o=Z(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{yc(r),Sc(r),bc(r),e.onStage?.("after-delete"),Rc(r),e.onStage?.("after-symbol-reconciliation"),xc(r),e.onStage?.("after-insert"),Ic(r),vc(r,n.length,o),e.onStage?.("before-commit")}).immediate(),vi(r,"main","candidate SQLite generation");let c=[...Pc(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:x()-t}}catch(i){try{r?.close()}finally{Si(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function gc(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 fc(e,t,n){let r=[e,t,n].map(i=>dc(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function bi(e,t,n=!0){let r=new xi(e,{readonly:!0,fileMustExist:!0});try{an(r,"main",t),n&&vi(r,"main",t)}finally{r.close()}}function an(e,t,n){for(let[r,i]of Object.entries(lc)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(pc)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Ri(e,t,"documents",["relative_path"],n),Ri(e,t,"global_symbols",["symbol"],n)}function Ri(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(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function vi(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 mc(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 o of i)n.run(o)})(t)}function hc(e,t){let n=Z(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Z(e,`SELECT COUNT(*) AS value
|
|
59
|
+
`))t.push({relativePath:od,kind:"global-symbol",values:On(n)});return sd(t)}function sd(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[a])=>o.localeCompare(a))){let o=nd("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
60
|
+
`);n.set(r,o.digest("hex"))}return n}function cd(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].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):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function jn(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.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:o,extraFiles:a}}function Ln(e,t=gd){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(d,u)=>{let l=r();return mo(e.refreshResult,d,n?l:i(),Math.max(0,l-o),u)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let d=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),u=He(e.previousSnapshot,e.currentSnapshot),l=new Set(d),p=u.changes.length>0&&!_n(u).fullProject&&u.changes.every(b=>l.has(b.path)),f=Qe(u,p?t.dependencyGraph(s):new Map,d),g=cd(t.factDigests(s),t.factDigests(c)),y=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?y:i()).toISOString(),durationMs:Math.max(0,y-o),manifest:u,plan:f,comparison:g,evaluation:jn(f,g,d.length)}}catch(d){return a("oracle-error",d instanceof Error?d.message:String(d))}finally{po(s),po(c)}}function fo(e,t,n,r=Date.now()){return mo(e,t,r,0,n)}function dd(e){let t=id(e);return{latestPath:lo(t,"affected-shadow-latest.json"),historyPath:lo(t,"affected-shadow.jsonl")}}function go(e,t,n=md){let r=dd(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ud=8*1024*1024,ld=no;function pd(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function fd(e,t,n=ud){ro(e,pd(t),{maxSegmentBytes:n,previousSuffix:ld})}function On(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 gd={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:w,databaseExists:e=>rd(e),openDatabase:(e,t,n)=>new Y({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>vt(e),dependencyGraph:e=>Mi(e),factDigests:e=>ad(e)},md={appendHistory:fd,writeLatest:(e,t)=>De(e,t,{spacing:2,trailingNewline:!0})};function mo(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function po(e){try{e?.close()}catch{}}import{execFileSync as hd}from"child_process";import{existsSync as yd,readdirSync as ho}from"fs";import{extname as yo,join as So}from"path";var bo=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Sd=[{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 Nn(e){let t=[],n=bd(e),r=vd(e);for(let i of Sd){if(Rd(e,i.files)){t.push(i.language);continue}if(xd(n,i.globs)){t.push(i.language);continue}wd(r,i.extensions)&&t.push(i.language)}if(t.includes("typescript")&&Mn(t,"javascript"),t.includes("cpp")&&t.includes("c")){let i=r.has(".c"),o=[".cc",".cpp",".cxx"].some(a=>r.has(a));i&&!o?Mn(t,"cpp"):i||Mn(t,"c")}return t}function bd(e){try{return ho(e)}catch{return[]}}function Rd(e,t){return t?.length?t.some(n=>yd(So(e,n))):!1}function xd(e,t){return t?.length?e.some(n=>t.some(r=>Id(n,r))):!1}function Id(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 vd(e){let t=Pd(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ho(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=So(i,a.name);if(a.isDirectory()){bo.has(a.name)||r.push(s);continue}let c=yo(a.name).toLowerCase();c&&n.add(c)}}return n}function Pd(e){try{let t=Si(e,26214400,()=>hd("git",["-C",e,"ls-files","-co","-v","-z","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:52428800,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})),n=new Set;for(let r of bi(t)){if(r.split("/").some(o=>bo.has(o)))continue;let i=yo(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function wd(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Mn(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as Ed}from"fs";import{isAbsolute as Ro,join as kd,resolve as Td}from"path";var Dt="@sourcegraph/scip-typescript@0.4.0",xo="scip-python-plus@0.7.5",Io="github.com/sourcegraph/scip-go@v0.2.7",vo="scip-dotnet@0.2.14",Dd="scip_dart@1.6.2",wo={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...j.typescript],installMethods:[{label:"npm",identity:Dt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Dt]}],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","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...j.javascript],installMethods:[{label:"npm",identity:Dt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Dt]}],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:[...j.java],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:[...j.scala],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:[...j.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:_e.language,indexerBinary:_e.indexerBinary,checkCommand:`${_e.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:_e.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...j.rust],installMethods:[],installUrl:_e.installUrl},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:[...j.python],installMethods:[{label:"npm",identity:xo,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",xo]}],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",Ro(r)?r:Td(e,r)),{binary:n,args:i}},markerFiles:[...j.clojure],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:[...j.ruby],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:[...j.go],installMethods:[{label:"go install",identity:Io,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Io]}],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:[...j.cpp],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:[...j.c],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",Po(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...j.csharp],installMethods:[{label:"dotnet",identity:vo,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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",Po(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...j.vb],installMethods:[{label:"dotnet",identity:vo,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],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:[...j.dart],installMethods:[{label:"dart pub",identity:Dd,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],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:({indexerBinary:e})=>Ro(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...j.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Eo(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function Ft(e){return wo[e]}function Po(e,t){let n;try{n=Ed(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return kd(e,i);return null}import{writeFileSync as $n}from"fs";import{create as Ze}from"@bufbuild/protobuf";import{deserializeSCIP as Vn,serializeSCIP as Bn,DocumentSchema as Ld,IndexSchema as Do,MetadataSchema as Md,SymbolInformationSchema as Nd}from"@c4312/scip";import{writeFileSync as Fd}from"fs";import{create as ko}from"@bufbuild/protobuf";import{deserializeSCIP as Cd,DocumentSchema as Ad,IndexSchema as _d,serializeSCIP as Od,SymbolRole as jd}from"@c4312/scip";function To(e){let t;try{t=Cd(A(e,{inputKind:"SCIP sanitization input",maxBytes:V}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Gn(t);return n.removedDefinitionOccurrences>0&&Fd(e,Od(n.index)),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Gn(e){let t=new Set;for(let o of e.documents){ai(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&jd.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ko(Ad,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ko(_d,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function qn(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=$d(e),n=Vd(e.flatMap(i=>i.documents??[])),r=Ao(e.flatMap(i=>i.externalSymbols??[]));return Ze(Do,{metadata:t,documents:n,externalSymbols:r})}function Un(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Vn(A(i,{inputKind:"SCIP merge input",maxBytes:V}))),r=qn(n);return $n(t,Bn(r)),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Fo(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=S("reindex.publish.scip-output.deserialize",()=>e.map(o=>Vn(A(o,{inputKind:"SCIP merge input",maxBytes:V})))),r=S("reindex.publish.scip-output.merge",()=>qn(n)),i=S("reindex.publish.scip-output.sanitize",()=>Gn(r));return S("reindex.publish.scip-output.serialize",()=>$n(t,Bn(i.index))),{documentCount:i.index.documents.length,externalSymbolCount:i.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:i.removedDefinitionOccurrences,touchedDocuments:i.touchedDocuments}}function Gd(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Ze(Do,{metadata:Ze(Md,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function Co(e,t,n){let r=Vn(A(e,{inputKind:"SCIP normalization input",maxBytes:V})),i=Gd(r,t,n);$n(e,Bn(i))}function $d(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 Vd(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,Ze(Ld,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Bd([...r.occurrences,...n.occurrences]),symbols:Ao([...r.symbols,...n.symbols]),text:Ud(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Bd(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 Ao(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,Ze(Nd,{symbol:r.symbol,documentation:Wd([...r.documentation,...n.documentation]),relationships:qd([...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 qd(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 Ud(e,t){return e?t?e.length>=t.length?e:t:e:t}function Wd(e){return[...new Set(e)]}import{createHash as Hd}from"crypto";import{existsSync as Hn,rmSync as _o,statSync as zd}from"fs";import{resolve as Jd}from"path";import Lo from"better-sqlite3";var Yd={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}]},Kd={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_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Mo(e){let t=w(),n=Oo(e.affectedFiles),r=Oo(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Qd(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Hn(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Hn(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");S("reindex.publish.sqlite-patch.validate-inputs",()=>{Wn(e.previousDbPath,"previous SQLite generation",!1),Wn(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?S("reindex.publish.sqlite-patch.reuse-candidate",()=>Wn(e.candidateDbPath,"incremental SQLite candidate",!1)):S("reindex.publish.sqlite-patch.clone",()=>{_o(e.candidateDbPath,{force:!0});let s=be(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&Re(e.writeTelemetry,s)});let a=null;try{a=S("reindex.publish.sqlite-patch.open",()=>{let f=new Lo(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),zn(f,"main","candidate SQLite generation"),zn(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=S("reindex.publish.sqlite-patch.prepare",()=>(tu(a,n,r),{...nu(a,n.length,r.length),previousFactDigests:Jn(a,"main",!0)})),d=ue(a,"SELECT COUNT(*) AS value FROM main.documents"),u=a.transaction(()=>{S("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>ru(a)),S("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>iu(a)),S("reindex.publish.sqlite-patch.transaction.delete",()=>ou(a)),e.onStage?.("after-delete"),S("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>au(a)),e.onStage?.("after-symbol-reconciliation"),S("reindex.publish.sqlite-patch.transaction.insert",()=>su(a)),e.onStage?.("after-insert"),S("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>cu(a,e.trustedPriorGeneration===!0)),S("reindex.publish.sqlite-patch.transaction.validate",()=>du(a,o,d,s)),e.onStage?.("before-commit")});S("reindex.publish.sqlite-patch.transaction",()=>u.immediate()),e.writeTelemetry&&kt(e.writeTelemetry,2*Xd(e.candidateDbPath)),S("reindex.publish.sqlite-patch.integrity",()=>eu(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let l=S("reindex.publish.sqlite-patch.validate-facts",()=>uu(a)),p=[...new Set([...c.keys(),...l.keys()])].filter(f=>c.get(f)!==l.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:w()-t}}catch(s){try{a?.close()}finally{_o(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Xd(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Hn(r)&&(t+=zd(r).size)}return t}function Oo(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Qd(e,t,n){let r=[e,t,n].map(i=>Jd(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Wn(e,t,n=!0){let r=new Lo(e,{readonly:!0,fileMustExist:!0});try{zn(r,"main",t),n&&Zd(r,"main",t)}finally{r.close()}}function zn(e,t,n){for(let[r,i]of Object.entries(Yd)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:d,pk:u})=>({name:s,type:c.toUpperCase(),notnull:d,pk:u}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Kd)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}jo(e,t,"documents",["relative_path"],n),jo(e,t,"global_symbols",["symbol"],n)}function jo(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 Zd(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 eu(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function tu(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function nu(e,t,n){let r=ue(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=ue(e,`SELECT COUNT(*) AS value
|
|
62
61
|
FROM main.documents d
|
|
63
|
-
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
62
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
|
|
63
|
+
FROM temp.incremental_affected_paths p
|
|
64
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
65
|
+
LEFT JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = p.relative_path
|
|
66
|
+
WHERE d.id IS NULL AND deleted.relative_path IS NULL
|
|
67
|
+
LIMIT 1`).pluck().get(),a=e.prepare(`SELECT d.relative_path
|
|
68
68
|
FROM incremental.documents d
|
|
69
69
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
70
70
|
WHERE p.relative_path IS NULL
|
|
71
|
-
LIMIT 1`).pluck().get()
|
|
71
|
+
LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
|
|
72
|
+
FROM incremental.documents d
|
|
73
|
+
JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
|
|
74
|
+
LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function ru(e){e.exec(`
|
|
72
75
|
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
76
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
77
|
+
SELECT g.symbol
|
|
78
|
+
FROM temp.incremental_affected_paths p
|
|
79
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
80
|
+
CROSS JOIN main.defn_enclosing_ranges r ON r.document_id = d.id
|
|
81
|
+
CROSS JOIN main.global_symbols g ON g.id = r.symbol_id;
|
|
82
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
83
|
+
SELECT g.symbol
|
|
84
|
+
FROM temp.incremental_affected_paths p
|
|
85
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
86
|
+
CROSS JOIN main.chunks c ON c.document_id = d.id
|
|
87
|
+
CROSS JOIN main.mentions m ON m.chunk_id = c.id
|
|
88
|
+
CROSS JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
89
|
+
WHERE m.role = 1;
|
|
87
90
|
|
|
88
91
|
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
89
|
-
|
|
90
|
-
|
|
92
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
93
|
+
SELECT g.symbol
|
|
91
94
|
FROM incremental.defn_enclosing_ranges r
|
|
92
95
|
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
93
96
|
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
94
97
|
SELECT g.symbol
|
|
95
98
|
FROM incremental.mentions m
|
|
96
99
|
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
97
|
-
|
|
98
|
-
|
|
100
|
+
WHERE m.role = 1;
|
|
101
|
+
|
|
102
|
+
CREATE TEMP TABLE incremental_touched_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
103
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
104
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols;
|
|
105
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
106
|
+
SELECT g.symbol
|
|
107
|
+
FROM temp.incremental_affected_paths p
|
|
108
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
109
|
+
CROSS JOIN main.chunks c ON c.document_id = d.id
|
|
110
|
+
CROSS JOIN main.mentions m ON m.chunk_id = c.id
|
|
111
|
+
CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
|
|
112
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
113
|
+
SELECT symbol FROM incremental.global_symbols;
|
|
114
|
+
`)}function iu(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
99
115
|
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
100
116
|
UNION
|
|
101
117
|
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
102
|
-
)
|
|
103
|
-
|
|
118
|
+
)
|
|
119
|
+
SELECT c.symbol
|
|
120
|
+
FROM changed_symbols c
|
|
121
|
+
CROSS JOIN main.global_symbols g ON g.symbol = c.symbol
|
|
122
|
+
WHERE EXISTS (
|
|
123
|
+
SELECT 1
|
|
104
124
|
FROM main.defn_enclosing_ranges r
|
|
105
125
|
JOIN main.documents d ON d.id = r.document_id
|
|
106
|
-
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
107
126
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
108
|
-
WHERE p.relative_path IS NULL
|
|
109
|
-
|
|
110
|
-
SELECT
|
|
127
|
+
WHERE r.symbol_id = g.id AND p.relative_path IS NULL
|
|
128
|
+
) OR EXISTS (
|
|
129
|
+
SELECT 1
|
|
111
130
|
FROM main.mentions m
|
|
112
|
-
JOIN main.chunks
|
|
113
|
-
JOIN main.documents d ON d.id =
|
|
114
|
-
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
131
|
+
JOIN main.chunks chunk ON chunk.id = m.chunk_id
|
|
132
|
+
JOIN main.documents d ON d.id = chunk.document_id
|
|
115
133
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
116
|
-
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
134
|
+
WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
|
|
117
135
|
)
|
|
118
|
-
|
|
119
|
-
FROM unaffected_definitions u
|
|
120
|
-
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
121
|
-
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function bc(e){e.exec(`
|
|
136
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function ou(e){e.exec(`
|
|
122
137
|
DELETE FROM main.mentions
|
|
123
138
|
WHERE chunk_id IN (
|
|
124
139
|
SELECT c.id
|
|
@@ -140,7 +155,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
140
155
|
);
|
|
141
156
|
DELETE FROM main.documents
|
|
142
157
|
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
143
|
-
`)}function
|
|
158
|
+
`)}function au(e){e.exec(`
|
|
144
159
|
UPDATE main.global_symbols
|
|
145
160
|
SET display_name = NULL,
|
|
146
161
|
kind = NULL,
|
|
@@ -182,30 +197,31 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
182
197
|
WHERE source.symbol = main.global_symbols.symbol
|
|
183
198
|
)
|
|
184
199
|
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
185
|
-
`)}function
|
|
200
|
+
`)}function su(e){let t=ue(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=ue(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=ue(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)
|
|
186
201
|
SELECT id + ?, language, relative_path, position_encoding, text
|
|
187
202
|
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
188
203
|
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
189
204
|
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
205
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
206
|
+
FROM incremental.mentions m
|
|
207
|
+
CROSS JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
208
|
+
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
194
209
|
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
195
210
|
)
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
211
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
212
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
213
|
+
FROM incremental.defn_enclosing_ranges r
|
|
214
|
+
CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
215
|
+
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function cu(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
|
|
201
216
|
DELETE FROM main.global_symbols
|
|
202
|
-
WHERE
|
|
217
|
+
WHERE ${n}
|
|
218
|
+
NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
203
219
|
AND NOT EXISTS (
|
|
204
220
|
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
205
221
|
);
|
|
206
|
-
`)}function
|
|
222
|
+
`)}function du(e,t,n,r){let i=ue(e,"SELECT COUNT(*) AS value FROM main.documents"),o=ue(e,`SELECT COUNT(*) AS value
|
|
207
223
|
FROM main.documents d
|
|
208
|
-
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(
|
|
224
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function uu(e){let t=Jn(e,"main",!0),n=Jn(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 Jn(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
|
|
209
225
|
FROM ${t}.documents d
|
|
210
226
|
${r}
|
|
211
227
|
ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
|
|
@@ -227,12 +243,12 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
|
|
|
227
243
|
JOIN ${t}.documents d ON d.id = c.document_id
|
|
228
244
|
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
229
245
|
${r}
|
|
230
|
-
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[
|
|
231
|
-
`);
|
|
232
|
-
`)}function
|
|
233
|
-
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function gn(e){try{let t=v(e,{maxBytes:A,inputKind:"TypeScript project manifest"}),n=JSON.parse(Vc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as To,randomUUID as vu}from"crypto";import{existsSync as ne,lstatSync as Pu,mkdirSync as me,mkdtempSync as Do,readdirSync as wu,realpathSync as ku,renameSync as ce,rmSync as te,statSync as ht}from"fs";import{dirname as Ln,join as h,resolve as On}from"path";import{setTimeout as Eu}from"timers/promises";import{pathToFileURL as Po}from"url";import{deserializeSCIP as Fo}from"@c4312/scip";import Tu from"better-sqlite3";import{lstatSync as nu,readdirSync as ru}from"fs";import{join as iu,relative as ou,resolve as In,sep as au}from"path";import{createHash as Bc}from"crypto";import{existsSync as mn,mkdirSync as qc,readdirSync as Cg,renameSync as Uc,rmSync as jg,writeFileSync as Wc}from"fs";import{join as ge}from"path";import{create as $i,fromBinary as Vi,toBinary as Hc}from"@bufbuild/protobuf";import{deserializeSCIP as ct,DocumentSchema as hn,IndexSchema as Bi,serializeSCIP as qi}from"@c4312/scip";var ut=1,De="typescript-scip-fragments";function Ui(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=ae(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=Vi(hn,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=qi($i(Bi,{documents:n,externalSymbols:[]})),i=ct(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function dt(e){let t=ge(e,De);return{rootDir:t,blobDir:ge(t,"blobs"),generationDir:ge(t,"generations")}}function zc(e){let t=ct(e.indexBytes);no(t.metadata,ro(e)),to(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=ae(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Hc(hn,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?se(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:se(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Xi(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Qi(e,r);return Zi(e.cacheDir,i),i}function Wi(e){let t=dt(e.cacheDir);if(!mn(yn(t,e.generationIdentity)))return zc(e);let n=zi({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 Hi(e){let t=zi({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=ae(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Xi(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Qi(e,[...n.values()]);return Zi(e.cacheDir,i),i}function zi(e){let t=dt(e.cacheDir),n=yn(t,e.generationIdentity),r;try{r=eo(v(n,{maxBytes:A,inputKind:"TypeScript fragment manifest"}))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}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 o of r.documents){let a=ge(t.blobDir,`${o.blobHash}.scipdoc`),s=w(a,{maxBytes:B,inputKind:"TypeScript fragment blob"});if(s.byteLength!==o.byteLength||se(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Ji(e){let t=Ki(e);return fn(t.baseIndex,t.completeDocuments,"assembled")}function Yi(e){let t=Ki(e);return Jc(t.deletedAffectedPaths),{completeIndexBytes:fn(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:fn(t.baseIndex,t.affectedDocuments,"affected")}}function Ki(e){let t=ct(e.baseIndexBytes);no(t.metadata,ro(e)),to(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=ae(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=[],o=[],a=[];for(let s of t.documents){let c=ae(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Vi(hn,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function fn(e,t,n){let r=qi($i(Bi,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=ct(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Jc(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Xi(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=ae(t.relativePath),i=Buffer.from(t.bytes),o=se(i),a=dt(e);qc(a.blobDir,{recursive:!0});let s=ge(a.blobDir,`${o}.scipdoc`);if(mn(s)){let c=w(s,{maxBytes:B,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||se(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Wc(c,i),Uc(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Qi(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:ut,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Zi(e,t){let n=dt(e),r=yn(n,t.generationIdentity);if(mn(r)){let i=eo(v(r,{maxBytes:A,inputKind:"TypeScript fragment manifest"}));if(Gi(i)!==Gi(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}X(r,t,{spacing:2,trailingNewline:!0})}function Gi(e){return se(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function eo(e){let t=JSON.parse(e);if(t.version!==ut||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(ae(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function yn(e,t){return ge(e.generationDir,Yc(t))}function Yc(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${se(e)}.json`}function to(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function no(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 ro(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function ae(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 se(e){return Bc("sha256").update(e).digest("hex")}import{createHash as Kc}from"crypto";import{existsSync as Fe,mkdirSync as Xc,readdirSync as Sn,renameSync as Qc,rmSync as io,writeFileSync as Zc}from"fs";import{join as N}from"path";var lt=1,ao=64*1024*1024,_e="typescript-scip-overlays";function so(e){let t=lo(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(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=xn(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,eu(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:lt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return tu(e.cacheDir,i),i}function co(e){let t=lo(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(N(Le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:B,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||Ae(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 Ji({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function uo(e,t){let n=Le(e),r=N(n,"generations");if(!Fe(r))return;let i=new Set(t.map(Rn)),o=new Set;for(let s of Sn(r).filter(c=>i.has(c))){let c=bn(v(N(r,s),{maxBytes:A,inputKind:"TypeScript overlay manifest"}));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Sn(r))i.has(s)||io(N(r,s),{force:!0});let a=N(n,"blobs");if(Fe(a))for(let s of Sn(a))o.has(s)||io(N(a,s),{force:!0})}function lo(e,t){let n=N(Le(e),"generations",Rn(t));if(!Fe(n))return null;let r=bn(v(n,{maxBytes:A,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function eu(e,t){let n=xn(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Ae(r),o=N(Le(e),"blobs");Xc(o,{recursive:!0});let a=N(o,`${i}.scipdoc`);if(Fe(a)){let s=w(a,{maxBytes:B,inputKind:"TypeScript overlay blob"});if(s.byteLength!==r.byteLength||Ae(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Zc(s,r),Qc(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function tu(e,t){let n=N(Le(e),"generations",Rn(t.generationIdentity));if(Fe(n)){let r=bn(v(n,{maxBytes:A,inputKind:"TypeScript overlay manifest"}));if(oo(r)!==oo(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}X(n,t,{spacing:2,trailingNewline:!0})}function bn(e){let t=JSON.parse(e);if(t.version!==lt||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(xn(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Le(e){return N(e,_e)}function Rn(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Ae(e)}.json`}function oo(e){return Ae(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function xn(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 Ae(e){return Kc("sha256").update(e).digest("hex")}var Oe=1,vn="language-indexes",po=["index.db","index.scip","meta.json"],go=[vn,De,_e];function pt(e){let t=[];for(let n of po)su(e,n),t.push(n);for(let n of go)fo(e,n,t);return{version:Oe,files:t.sort()}}function gt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!po.includes(e)&&!go.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function $(e,t){let n=gt(t),r=In(e),i=In(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${au}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function fo(e,t,n){let r=iu(e,t),i;try{i=ru(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?fo(e,a,n):o.isFile()&&n.push(gt(a))}}function su(e,t){let n=$(e,t),r;try{r=nu(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(ou(In(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Tn}from"crypto";import{closeSync as cu,existsSync as I,mkdirSync as uu,openSync as du,readSync as lu,readdirSync as Dn,renameSync as En,rmSync as Ce,statSync as fe}from"fs";import{basename as So,dirname as V,join as S,relative as mo}from"path";var pu=Object.freeze({maxGenerations:8,maxLogicalBytes:2*1024*1024*1024});function mt(e){let t=M(e.outputDb),n=hu(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=_n({generationRoot:t,databasePath:e.tempOutputDb,indexPath:I(r)?r:void 0,metadataPath:I(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:de,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},s=j(S(t,"state.json"),a,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||kn(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),kn(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),kn(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,u={...a,stableMirrors:An(e.outputDb,e.outputScip)};j(S(t,"state.json"),u,{spacing:2,trailingNewline:!0});let d=Ro(e.outputDb,{now:e.now}),l=Ie(i.directorySync,s.directorySync);return{currentGeneration:c,...n?{previousGeneration:n}:{},retention:d,achievedDurability:l==="synced"?"directory-durable":"file-flushed",directorySync:l}}function Fn(e,t,n,r=()=>new Date){if(!I(e))return null;let i=ve(e),o=S(M(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Lt(e,i.currentGeneration))return i;let a=M(e),s=!i&&I(o)?Su(n,e,t):void 0;if(s&&!Ke(a,s))return null;let c=_n({generationRoot:a,databasePath:e,indexPath:I(t)?t:void 0,metadataPath:I(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),u={version:de,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:An(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return j(S(a,"state.json"),u,{spacing:2,trailingNewline:!0}),u}function bo(e,t,n=()=>new Date){if(!I(e)||!I(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=ve(e),i=M(e),o=_n({generationRoot:i,databasePath:e,indexPath:I(S(V(e),"index.scip"))?S(V(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?Io(e,r.currentGeneration):void 0,s={version:de,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:An(e,S(V(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return j(S(M(e),"state.json"),s,{spacing:2,trailingNewline:!0}),Ro(e,{now:n}),s}function Ro(e,t={}){let n=gu(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=ue(Rr(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:"another process owns local generation retention"};try{let a=ve(e),s=fu(e),c=xr(e,s.map(y=>y.identity),{isProcessAlive:t.isProcessAlive??Y,readProcessIdentity:t.readProcessIdentity??J}),u=new Set(c.protectedGenerations);a?.currentGeneration&&u.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&u.add(a.previousGeneration.generationIdentity);let d=s.length,l=s.reduce((y,R)=>y+R.logicalBytes,0),p=0,m=0;for(let y of s){if(d<=n.maxGenerations&&l<=n.maxLogicalBytes)break;u.has(y.identity)||(t.onBeforeRemove?.(y.identity),Ce(y.path,{recursive:!0,force:!0}),d-=1,l-=y.logicalBytes,p+=1,m+=y.logicalBytes)}let g=d>n.maxGenerations||l>n.maxLogicalBytes,f={state:g?"protected":p>0?"collected":"within-bounds",generationCount:d,logicalBytes:l,protectedGenerations:u.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:m,limits:n,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return ho(e,f),f}catch(a){let s={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:a instanceof Error?a.message:String(a)};try{ho(e,s)}catch{}return s}finally{o.release()}}function gu(e={}){let t={...pu,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function fu(e){let t=M(e);return I(t)?Dn(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=S(t,n.name),i=Ke(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):xo(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:fe(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function xo(e){let t=0;for(let n of Dn(e,{withFileTypes:!0})){let r=S(e,n.name);n.isDirectory()?t+=xo(r):n.isFile()&&(t+=fe(r).size)}return t}function ho(e,t){X(S(M(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function ee(e,t=S(V(e),"meta.json")){let n=S(M(e),"state.json");if(!I(n))return{state:"legacy",statePath:n};let r=ve(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Lt(e,r.currentGeneration),o=i!==null,a=i?mu(e,t,i,r):!1,s=r.previousGeneration?I(S(V(e),r.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:n,currentMatches:a,recoveryExists:s,generation:r,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:a,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function mu(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==Pe(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==Pe(S(V(e),"index.scip")))||!yo(e,n.database))return!1;let i=S(V(e),"index.scip");if(n.index&&!yo(i,n.index))return!1;if(!n.metadata)return!I(t);if(!I(t))return!1;let o=S(M(e),n.identity,n.metadata.file);return I(o)&&ie(k(t,"reindex metadata"))===ie(k(o,"immutable reindex metadata"))}function yo(e,t){return I(e)&&fe(e).isFile()&&fe(e).size===t.size}function hu(e){let t=Fn(e.outputDb,e.outputScip,e.metaPath);return t?Io(e.outputDb,t.currentGeneration):void 0}function An(e,t){return{databaseFileIdentity:Pe(e),...I(t)?{indexFileIdentity:Pe(t)}:{}}}function Io(e,t){let n=S(M(e),t),r=S(n,So(e)),i=S(n,"meta.json");return{generationIdentity:t,databasePath:mo(V(e),r),...I(i)?{metadataPath:mo(V(e),i)}:{}}}function yu(e){if(I(e))for(let t of Dn(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&Ce(S(e,t.name),{recursive:!0,force:!0})}function Su(e,t,n=S(V(t),"index.scip")){let r=Tn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(ft(t)),I(n)&&r.update(`\0${ft(n)}`),I(e)&&r.update(`\0${ie(k(e,"reindex metadata"))}`),r.digest("hex")}function _n(e){let t=Pn(e.databasePath),n=e.indexPath?Pn(e.indexPath):void 0,r=e.metadataPath?Pn(e.metadataPath):void 0,i=e.forcedIdentity??bu(t,n,e.metadataPath),o=S(e.generationRoot,i),a=S(o,_t);if(I(a)){let u=Ke(e.generationRoot,i);if(u&&vo(o,u.database,t)&&xu(o,u.index,n)&&Iu(o,u.metadata,e.metadataPath))return{identity:i,directorySync:K(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[ze(e.generationRoot)];yu(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;Ce(c,{recursive:!0,force:!0}),uu(c,{recursive:!0});try{s.push(wn(e.databasePath,S(c,t.file))),n&&e.indexPath&&s.push(wn(e.indexPath,S(c,n.file))),r&&e.metadataPath&&s.push(wn(e.metadataPath,S(c,r.file)));let u=j(S(c,_t),{version:br,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});u.directorySync!=="not-requested"&&s.push(u.directorySync),s.push(K(c)),En(c,o),s.push(K(e.generationRoot))}finally{Ce(c,{recursive:!0,force:!0})}return{identity:i,directorySync:Ie(...s)}}function bu(e,t,n){let r=Tn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ie(k(n,"reindex metadata"))}`),r.digest("hex")}function Pn(e){return{file:So(e),size:fe(e).size,sha256:ft(e)}}function ft(e){let t=Tn("sha256"),n=du(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=Ru(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{cu(n)}return t.digest("hex")}function Ru(e,t){let n=0;for(;n<t.length;){let r=lu(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function wn(e,t){return Je(e,t,{mode:292})}function vo(e,t,n){let r=S(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&I(r)&&fe(r).size===t.size&&ft(r)===t.sha256}function xu(e,t,n){return!t||!n?t===n:vo(e,t,n)}function Iu(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=S(e,t.file);return I(r)&&ie(k(r,"stored reindex metadata"))===ie(k(n,"candidate reindex metadata"))}function kn(e,t){Ce(`${t}.tmp-replace`,{force:!0}),En(e,`${t}.tmp-replace`),En(`${t}.tmp-replace`,t)}var jn=1,wo="SCIP_QUERY_SHARED_CACHE",Cn=JSON.stringify({cliVersion:Mr,artifactCatalogVersion:Oe,sqliteGenerationStoreVersion:de,typescriptFragmentStoreVersion:ut,typescriptOverlayStoreVersion:lt}),Ao="manifest.json",Du="shared-cache.json",Mn=[vn,De,_e];function yt(e,t){if(!e.clean||!e.treeOid)return;let n=Mo(JSON.stringify({version:jn,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Cn}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Cn,generationId:n,repositoryCacheDir:Gr(e.repositoryId)}}function _o(e,t,n){if(process.env[wo]==="0")return`${wo}=0`;if(!$r(n))return"explicit cache or database override";if(Ut(Ln(t))!==Ut(Nr(e))||t!==h(Ln(t),"index.db"))return"index database is outside the managed worktree cache"}function re(e,t=!0){let n=$n(e),r;try{r=Au(v(h(n,Ao),{inputKind:"shared-generation manifest",maxBytes:A}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=$(n,i.path),a=ht(o);if(!a.isFile()||a.size!==i.size||We(o,{inputKind:"shared-generation artifact",maxBytes:_})!==i.sha256)return null}}catch{return null}return r}function Lo(e){let t=re(e.snapshot);if(t)return ko(e.snapshot,t);if(!jo(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Eo(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=pt(e.sourceCacheDir),i=h(e.snapshot.repositoryCacheDir,"generations"),o=[ze(i)],a=Do(h(i,`.tmp-${process.pid}-`));try{let s=[];for(let g of r.files){let f=$(e.sourceCacheDir,g),y=$(a,g);o.push(Me(f,y,292)),e.onPublicationStage?.("after-artifact-flushed",g);let R=ht(y).size;s.push({path:g,size:R,sha256:We(y,{inputKind:"staged shared-generation artifact",maxBytes:_})})}let c=Fo(w(h(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:_})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let u=Vn(e.sourceProjectRoot);if(c!==u)throw new Error("shared SCIP generation root does not match its source worktree");if(Eo(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let d={version:jn,artifactCatalogVersion:Oe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((g,f)=>g.path.localeCompare(f.path))},l=j(h(a,Ao),d,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(K(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=$n(e.snapshot);try{if(ne(p)&&!re(e.snapshot)){let g=`${p}.corrupt-${process.pid}-${Date.now()}`;ce(p,g),te(g,{recursive:!0,force:!0})}ce(a,p)}catch(g){let f=re(e.snapshot);if(f)return ko(e.snapshot,f);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push(K(i)),e.onPublicationStage?.("after-generations-directory-synced");let m=Ie(...o);return{kind:"published",manifest:d,achievedDurability:m==="synced"?"directory-durable":"file-flushed",directorySync:m}}finally{te(a,{recursive:!0,force:!0})}}function ko(e,t){let n=K(h(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function Nn(e){let t=$n(e.snapshot);me(e.targetCacheDir,{recursive:!0});let n=ue(h(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=Do(h(e.targetCacheDir,".shared-hydrate-")),Nu(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=$(t,c.path),d=$(r,c.path);if(Me(u,d),ht(d).size!==c.size||We(d,{inputKind:"hydrated shared-generation artifact",maxBytes:_})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Vn(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&mi($(r,c.path),e.manifest.scipProjectRoot,a);if(!jo(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Cu(e.targetCacheDir,r),o=!0,ju(r,e.targetCacheDir,i),mt({tempOutputScip:h(r,"index.scip"),tempOutputDb:h(r,"index.db"),tempMetaPath:h(r,"meta.json"),outputScip:h(e.targetCacheDir,"index.scip"),outputDb:h(e.targetCacheDir,"index.db"),metaPath:h(e.targetCacheDir,"meta.json"),now:e.now});let s=ee(h(e.targetCacheDir,"index.db"),h(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);Gn(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Mu(e.targetCacheDir,i),a}finally{r&&te(r,{recursive:!0,force:!0}),n.release()}}async function Oo(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??x,o=i()+n,a=h(e.repositoryCacheDir,"locks"),s=h(a,`${e.generationId}.lock`),c=u=>{if(!u||typeof u!="object"||Array.isArray(u))return null;let d=u.pid;return typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pid:d}:null};for(;i()<=o;){if(re(e))return{kind:"generation-ready"};let u=He(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(u.kind==="acquired")return{kind:"owner",release:()=>u.lock.release()};let d=o-i();if(d<=0)break;await Eu(Math.min(r,d))}return re(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Gn(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Fu(i)};return Ou(e.repositoryCacheDir,o,!0),o}function Fu(e){return Mo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:On(e.projectRoot),localCacheDir:On(e.localCacheDir)}))}function Au(e){let t=JSON.parse(e);if(t.version!==jn||t.artifactCatalogVersion!==Oe||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Cn||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(gt(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function Me(e,t,n=384){return Je(e,t,{mode:n})}function _u(e,t,n){me(e,{recursive:!0}),j(h(e,Du),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Eo(e){try{let t=pt(e),n=To("sha256");for(let r of t.files){let i=$(e,r),o=ht(i).size;n.update(r).update("\0").update(String(o)).update("\0"),hr(i,{inputKind:"source-generation artifact",maxBytes:_},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Lu(e){try{let t=z(v(h(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:A}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function $n(e){return h(e.repositoryCacheDir,"generations",e.generationId)}function Ou(e,t,n){let r=Sr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!ne(h(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=h(e,"worktrees");me(i,{recursive:!0}),j(h(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),_u(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Cu(e,t){let n=h(t,".rollback"),r=new Map,i=new Map;me(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=h(e,s),u=ne(c);r.set(s,u),u&&Me(c,h(n,"stable",s))}for(let s of Mn){let c=h(e,s),u=ne(c);if(u){let d=Pu(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=h(e,Ye),a=ne(o);return a&&Co(o,h(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function ju(e,t,n){for(let r of Mn){let i=h(t,r);if(n.managedDirectories.get(r)){let a=h(n.root,"managed",r);me(Ln(a),{recursive:!0}),ce(i,a)}let o=h(e,r);ne(o)&&ce(o,i)}}function Mu(e,t){for(let i of Mn){let o=h(e,i),a=h(t.root,"managed",i);t.managedDirectories.get(i)?ne(a)&&(te(o,{recursive:!0,force:!0}),ce(a,o)):te(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=h(e,i);if(!o){te(a,{force:!0});continue}let s=`${a}.shared-restore-${vu()}`;Me(h(t.root,"stable",i),s),te(a,{force:!0}),ce(s,a)}let n=h(e,Ye);te(n,{recursive:!0,force:!0});let r=h(t.root,"sqlite-generations");t.generationStoreExisted&&ne(r)&&ce(r,n)}function Co(e,t){me(t,{recursive:!0});for(let n of wu(e,{withFileTypes:!0})){let r=h(e,n.name),i=h(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?Co(r,i):n.isFile()&&Me(r,i)}}function Nu(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function jo(e,t,n,r=!0,i=!0){try{let o=Lu(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return je("source validation rejected metadata"),!1;let a=pt(e),s=ee(h(e,"index.db"),h(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return je(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Tu(h(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=Vn(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=Fo(w($(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:_})).metadata?.projectRoot;return m!==u&&je(`source validation rejected SCIP root for ${p}: ${String(m)}`),m===u});return l||je("source validation rejected SCIP project roots"),l}catch(o){return je(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function je(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Vn(e){try{return Po(ku(e)).href}catch{return Po(On(e)).href}}function Mo(e){return To("sha256").update(e).digest("hex")}import{existsSync as Gu,readdirSync as $u,statSync as Vu}from"fs";import L from"path";var Bu=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Ne(e,t=[]){let n=L.resolve(e),r=t.flatMap(c=>Uu(n,c));if(r.length>0)return No(n,Go(r));let i=qu(n),o=Go(i),a=Hu(n,o)?[n,...o]:o,s=a.length>0?a:[n];return No(n,s)}function No(e,t){return[...new Set(t.map(n=>Ju(e,n)))].sort((n,r)=>n.localeCompare(r))}function qu(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=$u(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=L.join(r,o.name);if(o.isDirectory()){!Bu.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Wu(a)&&t.push(L.dirname(a))}}return t}function Uu(e,t){let n=t.trim();if(!n)return[];let r=L.resolve(e,n);if(!be(e,r))return[];try{let i=Vu(r);if(i.isDirectory())return[r];if(i.isFile()&&$o(L.basename(r)))return[L.dirname(r)]}catch{return[]}return[]}function Wu(e){if(!$o(L.basename(e)))return!1;let t=Vo(e);return t?L.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function $o(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Go(e){let t=[...new Set(e.map(n=>L.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Yu(n,r)))}function Hu(e,t){if(t.length===0||t.some(r=>L.resolve(r)===e))return!1;let n=L.join(e,"tsconfig.json");return Gu(n)&&zu(n)}function zu(e){let n=Vo(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!L.extname(r))):!1}function Vo(e){try{let t=JSON.parse(k(e,"TypeScript project config"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ju(e,t){let n=L.relative(e,t);return n?n.split(L.sep).join("/"):"."}function Yu(e,t){let n=L.relative(e,t);return!!n&&!n.startsWith("..")&&!L.isAbsolute(n)}import{createHash as fd}from"crypto";import{existsSync as qn,statSync as md,writeFileSync as Un}from"fs";import{join as hd}from"path";import{createRequire as Ku}from"module";import{dirname as Xu,isAbsolute as Bf,relative as qf,resolve as Uf,sep as Wf}from"path";var Bo=Ku(import.meta.url),Qu=1,qo="0.4.0";function Bn(){let e=Zu();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Zu(){try{let e=Bo.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(k(e,"scip-typescript package manifest"));if(t.version!==qo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${qo}`};let n=Xu(e),r=Bo.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(k(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:ed(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function ed(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Qu}`}import{createHash as td}from"crypto";import{dirname as nd,join as Uo}from"path";var St=3;var rd="typescript-index";function Wo(e){let t=Uo(e,rd),n=Fr(t);return{...n,requestDir:n.legacyRequestDir}}function Ho(e){try{let t=gr(z(k(Uo(nd(e),"meta.json"),"reindex metadata")));return t?td("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as id}from"crypto";import{existsSync as od}from"fs";var ad=12e4,sd=5,bt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=Lr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??pd(),this.runtime=n.runtime??gd,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=_r(this.cacheDir),r=Wo(this.cacheDir),i=Vt(n.statePath);if(!zo(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??x)()+this.timeoutMs,c=Gt("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),d=Ar(r,{mailboxVersion:Nt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:St,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??x)()<=s;){if(od(d.responsePath))return cd(v(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Vt(n.statePath);if(!zo(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(sd)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function zo(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===St&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&xe(e.processIdentity,r))}function cd(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==St||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)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 s=ud(a.response,i),c=[...new Set(o)].sort(),u=s.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(u)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return s}function ud(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(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(dd)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:ld(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function dd(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 ld(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function pd(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:ad}var gd={now:Date.now,monotonicNow:x,randomId:id,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Y,readProcessIdentity:J};function yd(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=Ue(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!Bt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=nt(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=Sd([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Jo(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Jo(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Ko(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Ko(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Yo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Yo(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 Sd(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Xo(e){let t=x();try{if(!qn(e.previousDbPath)||!qn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Bn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new oe({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Xe(o,{includeIgnored:!1}).filter(Bt).sort(),s=Ze(o)}finally{o.close()}let c=performance.now()-n,u=yd({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Ne(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:qn(hd(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Ho(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new bt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=md(e.previousShardPath).size>=ao;n=performance.now();let f=g?null:w(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),y=g?{completeIndexBytes:null,affectedIndexBytes:Ui(p.fragments)}:Yi({packageVersion:r.packageVersion,baseIndexBytes:f,fragments:p.fragments}),R=performance.now()-n;n=performance.now(),g?so({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(Wi({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:f,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Hi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:p.fragments,documentIdentities:u.nextDocumentIdentities}));let F=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Un(e.candidateShardPath,y.completeIndexBytes),Un(e.candidateAffectedScipPath,y.affectedIndexBytes);let E=performance.now()-n,P={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:x()-t,cold:p.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(p.fragments.map(T=>[T.relativePath,T.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:p.durationMs,assemblyMs:R,fragmentStoreMs:F,writeMs:E}};return e.onStatus(`Incremental TypeScript index emitted ${P.affectedFiles.length} affected document(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${R.toFixed(0)}ms, fragments ${F.toFixed(0)}ms, write ${E.toFixed(0)}ms).`),P}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 Qo(e){let t=Bn();if(!t.available)throw new Error(t.reason);let n=co({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:w(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),packageVersion:t.packageVersion});Un(e.candidateShardPath,n)}function Jo(e,t,n){let r=e.files.filter(i=>lr(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Wn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Yo(e,t){return Wn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Ko(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Or({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,Wn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function Wn(e){return fd("sha256").update(e).digest("hex")}import{existsSync as Rt,renameSync as Jn,rmSync as Yn,statSync as bd}from"fs";import{cpus as Rd}from"os";import{join as ta}from"path";var Hn=Symbol("no-error");async function Zo(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),a=0,s=Hn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let d=a++;try{r[d]=await n(e[d])}catch(l){s===Hn&&(s=l),c=!1}}});if(await Promise.all(u),s!==Hn)throw s;return r}function xd(e,t,n){if(!e.defaultOutputPath)return;let r=ta(t,e.defaultOutputPath);n!==r&&Rt(r)&&Jn(r,n)}function Id(e,t,n){if(!e.defaultOutputPath)return null;let r=ta(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Yn(i,{force:!0}),Rt(r)?(Jn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function vd(e){e&&(Yn(e.defaultOutputPath,{force:!0}),e.backupPath&&Rt(e.backupPath)&&Jn(e.backupPath,e.defaultOutputPath))}function Pd(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,Rd().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function na(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Pd(o.length,r),c=await Zo(o,s,u=>zn(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(l=>l.result.skipped&&l.retryable)){let l=o.find(p=>p.id===d.result.id);l&&(n(`Retrying ${l.label} indexer serially after parallel failure...`),u.set(l.id,(await zn(l,t,n)).result))}a.push(...c.map(({result:d})=>u.get(d.id)??d))}else a.push(...c.map(({result:u})=>u));for(let u of i)a.push((await zn(u,t,n)).result);return a.sort((u,d)=>e.findIndex(l=>l.id===u.id)-e.findIndex(l=>l.id===d.id))}async function zn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Yn(e.scipPath,{force:!0});let r=Id(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=x();try{e.trustedProjectTool&&Dr(t,e.trustedProjectTool);let s=Er(e.binary,e.args),c=await Hr({command:s.binary,args:s.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:wd(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let u=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${u?`:
|
|
234
|
-
${
|
|
235
|
-
|
|
246
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[u,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let f=JSON.stringify([u,p]),g=c.get(p.relative_path)??[];g.push(f),c.set(p.relative_path,g)}let d=new Map;for(let[u,l]of[...c].sort(([p],[f])=>p.localeCompare(f))){let p=Hd("sha256");for(let f of l.sort())p.update(f).update(`
|
|
247
|
+
`);d.set(u,p.digest("hex"))}return d}function ue(e,t){return e.prepare(t).get().value}import lu from"better-sqlite3";var Ct="idx_mentions_definitions",pu=["symbol_id","chunk_id"];function Yn(e,t={}){let n=new lu(e),r=[],i=[],o=[];try{return n.transaction(()=>{fu(n,r),At(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&No(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):At(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=At(n,"idx_chunks_doc_id"),s=No(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");a?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):a&&o.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:o,analyzed:t.analyze!==!1}}catch(a){if(a.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw a}finally{n.close()}}function fu(e,t){let n=Go(e,Ct);if(n){let r=n.columns.join("\0")===pu.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${Ct} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${Ct}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(Ct)}function No(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:At(e,n.name)??[]}))}function At(e,t){return Go(e,t)?.columns??null}function Go(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(i=>i.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{writeFileSync as gu}from"fs";function X(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Vo(e){let t=e.readFingerprint(),n=qo(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Uo(e.cachePath,e.readFingerprint(),r),r}async function Bo(e){let t=e.readFingerprint(),n=qo(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Uo(e.cachePath,e.readFingerprint(),r),r}function qo(e,t){try{let n=JSON.parse(D(e,{maxBytes:G,inputKind:"post-index augmentation cache"}));return $o(n.fingerprint)===$o(t)?{result:n.result}:null}catch{return null}}function Uo(e,t,n){gu(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
248
|
+
`)}function $o(e){return JSON.stringify(e)}import mu from"better-sqlite3";var hu=25,yu=new Set(["typescript","javascript"]);function _t(e,t,n){let r=null;try{r=new mu(e,{readonly:!0,fileMustExist:!0});let i=new Set(r.prepare("SELECT relative_path FROM documents").pluck().all().map(ln)),o=Su(t,n),a=new Set([...o.values()].flatMap(u=>[...u])),s=[...a].filter(u=>!i.has(u)).sort();if(s.length===0)return{state:"complete",expectedDocumentCount:a.size,actualDocumentCount:i.size};let c=new Set(s),d=n.filter(u=>[...o.get(u)??[]].some(l=>c.has(l)));return{state:"incomplete",expectedDocumentCount:a.size,actualDocumentCount:i.size,missingDocumentCount:s.length,missingPaths:s.slice(0,hu),affectedLanguages:d}}catch(i){return{state:"unavailable",reason:i instanceof Error?i.message:String(i)}}finally{r?.close()}}function Su(e,t){let n=new Map,r=t.filter(i=>yu.has(i));for(let i of r)n.set(i,new Set);for(let i of e.files){let o=ln(i.path);for(let a of r)ke(o,[a])==="source"&&n.get(a).add(o)}return n}import{createHash as bu}from"crypto";import{existsSync as Kn,readdirSync as Ru}from"fs";import{dirname as Xn,join as Ot,relative as xu,resolve as Qn,sep as Wo}from"path";function Ho(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Ko(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function zo(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],a=r.get(i);if(!o||o.parseFailed){for(let s of e)s!==i&&a.add(s);continue}for(let s of o.dependencyNames){let c=n.get(s);c&&c!==i&&a.add(c)}for(let s of[...o.pathsTargets,...o.referencesPaths]){let c=Ko(s,e);c&&c!==i&&a.add(c)}}return Iu(e,r)}function Jo(e,t,n){let r={};for(let i of e){let o=new Map;for(let a of t.files[i]??[])o.set(a.path,a);for(let a of n[i]??[])for(let s of t.files[a]??[])o.set(s.path,s);for(let a of t.shared)o.set(a.path,a);r[i]={files:[...o.values()].sort((a,s)=>a.path.localeCompare(s.path))}}return r}function Zn(e){if(e===".")return"root";let t=bu("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Yo(e,t){let n=Qn(e),r={};for(let i of t)r[i]=vu(n,i);return r}function Ko(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 Iu(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let a=o.pop();if(!(a===r||i.has(a))){i.add(a);for(let s of t.get(a)??[])s!==r&&!i.has(s)&&o.push(s)}}n[r]=[...i].sort((a,s)=>a.localeCompare(s))}return n}function vu(e,t){let n=t==="."?e:Ot(e,t),r=Pu(n),i=wu(n),o=i?Eu(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function Pu(e){let t=Ot(e,"package.json");if(!Kn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=er(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 o of["dependencies","devDependencies","peerDependencies"]){let a=n.value[o];if(a&&typeof a=="object"&&!Array.isArray(a))for(let s of Object.keys(a))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function wu(e){let t=Ot(e,"tsconfig.json");if(Kn(t))return t;let n;try{n=Ru(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Ot(e,n[0]):void 0}function Eu(e,t){let n=er(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ku(n.value,e,t),i=Xo(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ku(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Xn(t),o=new Set;for(let a of r){if(!a||typeof a!="object")continue;let s=a.path;if(typeof s!="string"||s.trim()==="")continue;let c=Qo(s,i,n);c&&o.add(c)}return[...o]}function Xo(e,t,n,r){let i=Tu(t);if(i)return{pathsTargets:Du(i,Xn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Fu(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=er(o);return a.ok?Xo(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Tu(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 Du(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let a=Qo(o,t,n);a&&r.add(a)}return[...r]}function Fu(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=Qn(Xn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Wo).includes("node_modules")&&pn(n,i)&&Kn(i))return i}function Qo(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Qn(t,r===""?".":r);if(!pn(n,i))return;let a=xu(n,i).split(Wo).join("/");return a===""?".":a}function Cu(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
|
|
249
|
+
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function er(e){try{let t=D(e,{maxBytes:G,inputKind:"TypeScript project manifest"}),n=JSON.parse(Cu(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as _a,randomUUID as hl}from"crypto";import{existsSync as pe,lstatSync as Rr,mkdirSync as Me,mkdtempSync as Oa,readdirSync as ja,realpathSync as La,renameSync as Ie,rmSync as le,statSync as Ut}from"fs";import{dirname as xr,join as m,resolve as Ir}from"path";import{setTimeout as yl}from"timers/promises";import{pathToFileURL as Ta}from"url";import{deserializeSCIP as Ma}from"@c4312/scip";import Sl from"better-sqlite3";import{lstatSync as zu,readdirSync as Ju}from"fs";import{join as Yu,relative as Ku,resolve as sr,sep as Xu}from"path";import{existsSync as ea,readdirSync as ta,rmSync as na}from"fs";import{join as Le}from"path";import{create as ia,fromBinary as oa,toBinary as dh}from"@bufbuild/protobuf";import{deserializeSCIP as tr,DocumentSchema as aa,IndexSchema as sa,serializeSCIP as ca}from"@c4312/scip";import{existsSync as Au,mkdirSync as _u,renameSync as Ou,writeFileSync as ju}from"fs";import{join as Lu}from"path";function Zo(e){_u(e.blobDir,{recursive:!0});let t=Lu(e.blobDir,`${e.blobHash}.scipdoc`);if(Au(t)){let r=A(t,{maxBytes:ae,inputKind:e.inputKind});if(r.byteLength!==e.bytes.byteLength||ne(r)!==e.blobHash)throw new Error(`existing ${e.inputKind} is corrupt: ${e.relativePath}`);return}let n=`${t}.${process.pid}.${Date.now()}.tmp`;ju(n,e.bytes),Ou(n,t)}var nr=1,et="typescript-scip-fragments";function da(e){let t=new Set,n=[];for(let o of e){let a=jt(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=oa(aa,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=ca(ia(sa,{documents:n,externalSymbols:[]})),i=tr(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Mu(e){let t=Le(e,et);return{rootDir:t,blobDir:Le(t,"blobs"),generationDir:Le(t,"generations")}}function ua(e){let t=Nu(e);return Gu(t.baseIndex,t.completeDocuments,"assembled")}function Nu(e){let t=tr(e.baseIndexBytes);qu(t.metadata,Uu(e)),Bu(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=jt(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=[],o=[],a=[];for(let s of t.documents){let c=jt(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){a.push(c);continue}let u=ra(c,d.bytes);i.push(u),o.push(u)}for(let s of[...n.keys()].sort()){let c=n.get(s);if(c.bytes===null)continue;if(r.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);r.add(s);let d=ra(s,c.bytes);i.push(d),o.push(d)}return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function ra(e,t){let n=oa(aa,t);if(n.relativePath!==e)throw new Error(`TypeScript fragment path mismatch: expected ${e}, got ${n.relativePath}`);return n}function Gu(e,t,n){let r=ca(ia(sa,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=tr(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function la(e,t){let n=Mu(e);if(!ea(n.generationDir))return;let r=new Set(t.map(a=>Vu(a))),i=ta(n.generationDir).filter(a=>a.endsWith(".json")),o=new Set;for(let a of i.filter(s=>r.has(s))){let s=$u(D(Le(n.generationDir,a),{maxBytes:G,inputKind:"TypeScript fragment manifest"}));for(let c of s.documents)o.add(`${c.blobHash}.scipdoc`)}for(let a of i)r.has(a)||na(Le(n.generationDir,a),{force:!0});if(ea(n.blobDir))for(let a of ta(n.blobDir))o.has(a)||na(Le(n.blobDir,a),{force:!0})}function $u(e){let t=JSON.parse(e);if(t.version!==nr||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(jt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Vu(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${ne(e)}.json`}function Bu(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function qu(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 Uu(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function jt(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}import{existsSync as Lt,readdirSync as rr,rmSync as pa}from"fs";import{join as Q}from"path";var Mt=1,tt="typescript-scip-overlays",fa="typescript-project-v3:";function ma(e){let t=Sa(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t?.producerIdentity!==void 0&&t.producerIdentity!==e.producerIdentity)throw new Error("TypeScript overlay producer identity changed");let n=e.allowLegacyProjectIdentityMigration===!0&&t!==null&&!t.projectIdentity.startsWith(fa)&&e.projectIdentity.startsWith(fa);if(t&&t.projectIdentity!==e.projectIdentity&&!e.allowProjectIdentityChange&&!n)throw new Error("TypeScript overlay project identity changed");let r=new Map((t?.overlays??[]).map(a=>[a.relativePath,a])),i=new Set;for(let a of e.fragments){let s=ar(a.relativePath);if(i.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);i.add(s),r.set(s,Wu(e.cacheDir,a))}if(i.size===0)throw new Error("TypeScript overlay generation requires affected documents");let o={version:Mt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...r.values()].sort((a,s)=>a.relativePath.localeCompare(s.relativePath))};return Hu(e.cacheDir,o),o}function ha(e){let t=Sa(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=A(Q(nt(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:ae,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||ne(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 ua({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ya(e,t){let n=nt(e),r=Q(n,"generations");if(!Lt(r))return;let i=new Set(t.map(or)),o=new Set;for(let s of rr(r).filter(c=>i.has(c))){let c=ir(D(Q(r,s),{maxBytes:G,inputKind:"TypeScript overlay manifest"}));for(let d of c.overlays)d.blobHash&&o.add(`${d.blobHash}.scipdoc`)}for(let s of rr(r))i.has(s)||pa(Q(r,s),{force:!0});let a=Q(n,"blobs");if(Lt(a))for(let s of rr(a))o.has(s)||pa(Q(a,s),{force:!0})}function Sa(e,t){let n=Q(nt(e),"generations",or(t));if(!Lt(n))return null;let r=ir(D(n,{maxBytes:G,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Wu(e,t){let n=ar(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ne(r);return Zo({blobDir:Q(nt(e),"blobs"),blobHash:i,bytes:r,relativePath:n,inputKind:"TypeScript overlay blob"}),{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Hu(e,t){let n=Q(nt(e),"generations",or(t.generationIdentity));if(Lt(n)){let r=ir(D(n,{maxBytes:G,inputKind:"TypeScript overlay manifest"}));if(ga(r)!==ga(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}De(n,t,{spacing:2,trailingNewline:!0})}function ir(e){let t=JSON.parse(e);if(t.version!==Mt||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(ar(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function nt(e){return Q(e,tt)}function or(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ne(e)}.json`}function ga(e){return ne(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function ar(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}var rt=1,cr="language-indexes",ba=["index.db","index.scip","meta.json"],Ra=[cr,et,tt];function Nt(e){let t=[];for(let n of ba)Qu(e,n),t.push(n);for(let n of Ra)xa(e,n,t);return{version:rt,files:t.sort()}}function Gt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!ba.includes(e)&&!Ra.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function Z(e,t){let n=Gt(t),r=sr(e),i=sr(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Xu}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function xa(e,t,n){let r=Yu(e,t),i;try{i=Ju(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?xa(e,a,n):o.isFile()&&n.push(Gt(a))}}function Qu(e,t){let n=Z(e,t),r;try{r=zu(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(Ku(sr(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as gr}from"crypto";import{closeSync as Zu,existsSync as k,mkdirSync as el,openSync as tl,readSync as nl,readdirSync as mr,renameSync as pr,rmSync as it,statSync as xe}from"fs";import{basename as hr,dirname as ee,join as P,relative as Ia}from"path";var rl=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function Vt(e){let t=J(e.outputDb),n=sl(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=cl(e,n),o=br({generationRoot:t,databasePath:e.tempOutputDb,indexPath:k(r)?r:void 0,verifiedIndexArtifact:i,metadataPath:k(e.tempMetaPath)?e.tempMetaPath:void 0}),a=(e.now??(()=>new Date))().toISOString(),s={version:Fe,currentGeneration:o.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:a},c=H(P(t,"state.json"),s,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||lr(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),lr(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),lr(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let d=o.identity,u={...s,stableMirrors:Sr(e.outputDb,e.outputScip)};H(P(t,"state.json"),u,{spacing:2,trailingNewline:!0});let l=Pa(e.outputDb,{now:e.now}),p=Je(o.directorySync,c.directorySync);return{currentGeneration:d,...n?{previousGeneration:n}:{},retention:l,achievedDurability:p==="synced"?"directory-durable":"file-flushed",directorySync:p}}function yr(e,t,n,r=()=>new Date){if(!k(e))return null;let i=Ye(e),o=P(J(e),"state.json");if(i?.artifactSet==="immutable-v1"&&bt(e,i.currentGeneration))return i;let a=J(e),s=!i&&k(o)?ul(n,e,t):void 0;if(s&&!Rt(a,s))return null;let c=br({generationRoot:a,databasePath:e,indexPath:k(t)?t:void 0,metadataPath:k(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),d={version:Fe,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Sr(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return H(P(a,"state.json"),d,{spacing:2,trailingNewline:!0}),d}function Bt(e,t,n=()=>new Date){if(!k(e)||!k(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=Ye(e),i=J(e),o=br({generationRoot:i,databasePath:e,indexPath:k(P(ee(e),"index.scip"))?P(ee(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?Ea(e,r.currentGeneration):void 0,s={version:Fe,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Sr(e,P(ee(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return H(P(J(e),"state.json"),s,{spacing:2,trailingNewline:!0}),Pa(e,{now:n}),s}function Pa(e,t={}){let n=il(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=me(hi(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:"another process owns local generation retention"};try{let a=Ye(e),s=ol(e),c=yi(e,s.map(b=>b.identity),{isProcessAlive:t.isProcessAlive??se,readProcessIdentity:t.readProcessIdentity??K}),d=new Set(c.protectedGenerations);a?.currentGeneration&&d.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&d.add(a.previousGeneration.generationIdentity);let u=s.length,l=s.reduce((b,C)=>b+C.logicalBytes,0),p=0,f=0;for(let b of s){if(u<=n.maxGenerations&&l<=n.maxLogicalBytes)break;d.has(b.identity)||(t.onBeforeRemove?.(b.identity),it(b.path,{recursive:!0,force:!0}),u-=1,l-=b.logicalBytes,p+=1,f+=b.logicalBytes)}let g=u>n.maxGenerations||l>n.maxLogicalBytes,y={state:g?"protected":p>0?"collected":"within-bounds",generationCount:u,logicalBytes:l,protectedGenerations:d.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:f,limits:n,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return va(e,y),y}catch(a){let s={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:a instanceof Error?a.message:String(a)};try{va(e,s)}catch{}return s}finally{o.release()}}function il(e={}){let t={...rl,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function ol(e){let t=J(e);return k(t)?mr(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=P(t,n.name),i=Rt(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):wa(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:xe(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function wa(e){let t=0;for(let n of mr(e,{withFileTypes:!0})){let r=P(e,n.name);n.isDirectory()?t+=wa(r):n.isFile()&&(t+=xe(r).size)}return t}function va(e,t){De(P(J(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function z(e,t=P(ee(e),"meta.json")){let n=P(J(e),"state.json");if(!k(n))return{state:"legacy",statePath:n};let r=Ye(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=bt(e,r.currentGeneration),o=i!==null,a=i?al(e,t,i,r):!1,s=r.previousGeneration?k(P(ee(e),r.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:n,currentMatches:a,recoveryExists:s,generation:r,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:a,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function al(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==Ke(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==Ke(P(ee(e),"index.scip")))||!fr(e,n.database))return!1;let i=P(ee(e),"index.scip");if(n.index&&!fr(i,n.index))return!1;if(!n.metadata)return!k(t);if(!k(t))return!1;let o=P(J(e),n.identity,n.metadata.file);return k(o)&&he(L(t,"reindex metadata"))===he(L(o,"immutable reindex metadata"))}function fr(e,t){return k(e)&&xe(e).isFile()&&xe(e).size===t.size}function sl(e){let t=yr(e.outputDb,e.outputScip,e.metaPath);return t?Ea(e.outputDb,t.currentGeneration):void 0}function cl(e,t){if(!e.preserveOutputScip)return;if(!t)throw new Error("deferred SCIP publication requires an accepted immutable generation");let n=z(e.outputDb,e.metaPath);if(n.state!=="current"||n.generation.currentGeneration!==t.generationIdentity){let i=n.state==="current"?"generation identity changed":"reason"in n?n.reason:`generation state is ${n.state}`;throw new Error(`deferred SCIP publication requires a verified accepted companion: ${i}`)}let r=bt(e.outputDb,t.generationIdentity);if(!r?.index||!fr(e.outputScip,r.index))throw new Error("deferred SCIP publication requires the verified accepted index artifact");return r.index}function Sr(e,t){return{databaseFileIdentity:Ke(e),...k(t)?{indexFileIdentity:Ke(t)}:{}}}function Ea(e,t){let n=P(J(e),t),r=P(n,hr(e)),i=P(n,"meta.json");return{generationIdentity:t,databasePath:Ia(ee(e),r),...k(i)?{metadataPath:Ia(ee(e),i)}:{}}}function dl(e){if(k(e))for(let t of mr(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&it(P(e,t.name),{recursive:!0,force:!0})}function ul(e,t,n=P(ee(t),"index.scip")){let r=gr("sha256").update("sqlite-generation-artifacts-v1\0");return r.update($t(t)),k(n)&&r.update(`\0${$t(n)}`),k(e)&&r.update(`\0${he(L(e,"reindex metadata"))}`),r.digest("hex")}function br(e){let t=dr(e.databasePath),n=e.indexPath?e.verifiedIndexArtifact?pl(e.indexPath,e.verifiedIndexArtifact):dr(e.indexPath):void 0,r=e.metadataPath?dr(e.metadataPath):void 0,i=e.forcedIdentity??ll(t,n,e.metadataPath),o=P(e.generationRoot,i),a=P(o,mn);if(k(a)){let d=Rt(e.generationRoot,i);if(d&&ka(o,d.database,t)&&gl(o,d.index,n)&&ml(o,d.metadata,e.metadataPath))return{identity:i,directorySync:ce(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[ht(e.generationRoot)];dl(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;it(c,{recursive:!0,force:!0}),el(c,{recursive:!0});try{s.push(ur(e.databasePath,P(c,t.file))),n&&e.indexPath&&s.push(ur(e.indexPath,P(c,n.file))),r&&e.metadataPath&&s.push(ur(e.metadataPath,P(c,r.file)));let d=H(P(c,mn),{version:mi,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&s.push(d.directorySync),s.push(ce(c)),pr(c,o),s.push(ce(e.generationRoot))}finally{it(c,{recursive:!0,force:!0})}return{identity:i,directorySync:Je(...s)}}function ll(e,t,n){let r=gr("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${he(L(n,"reindex metadata"))}`),r.digest("hex")}function dr(e){return{file:hr(e),size:xe(e).size,sha256:$t(e)}}function pl(e,t){if(t.file!==hr(e)||xe(e).size!==t.size)throw new Error(`verified SQLite generation artifact changed before publication: ${e}`);return t}function $t(e){let t=gr("sha256"),n=tl(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=fl(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{Zu(n)}return t.digest("hex")}function fl(e,t){let n=0;for(;n<t.length;){let r=nl(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function ur(e,t){return yt(e,t,{mode:292})}function ka(e,t,n){let r=P(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&k(r)&&xe(r).size===t.size&&$t(r)===t.sha256}function gl(e,t,n){return!t||!n?t===n:ka(e,t,n)}function ml(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=P(e,t.file);return k(r)&&he(L(r,"stored reindex metadata"))===he(L(n,"candidate reindex metadata"))}function lr(e,t){it(`${t}.tmp-replace`,{force:!0}),pr(e,`${t}.tmp-replace`),pr(`${t}.tmp-replace`,t)}var vr=1,Da="SCIP_QUERY_SHARED_CACHE",bl=2,qt=JSON.stringify({cliVersion:xi,artifactCatalogVersion:rt,postIndexAugmentationSchemaVersion:bl,sqliteGenerationStoreVersion:Fe,typescriptFragmentStoreVersion:nr,typescriptOverlayStoreVersion:Mt}),Pr="manifest.json",Rl="shared-cache.json";var wr=[cr,et,tt];function Wt(e,t){if(!e.clean||!e.treeOid)return;let n=Ya(JSON.stringify({version:vr,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:lt(t),producerIdentity:qt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:qt,generationId:n,repositoryCacheDir:Pi(e.repositoryId)}}function Na(e,t,n){if(process.env[Da]==="0")return`${Da}=0`;if(!wi(n))return"explicit cache or database override";if(Sn(xr(t))!==Sn(vi(e))||t!==m(xr(t),"index.db"))return"index database is outside the managed worktree cache"}function re(e,t=!0){let n=kr(e),r;try{r=Ua(D(m(n,Pr),{inputKind:"shared-generation manifest",maxBytes:G}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||!pt(r.fingerprint,e.fingerprint)||!vl(n))return null;if(!t)return r;try{for(let i of r.artifacts){let o=Z(n,i.path),a=Ut(o);if(!a.isFile()||a.size!==i.size||gt(o,{inputKind:"shared-generation artifact",maxBytes:V})!==i.sha256)return null}}catch{return null}return r}function Ga(e,t,n,r){if(!e.treeOid)return null;let i=Rn(t,n),o=m(Ii(),"repositories",e.repositoryId),a;try{let d=Rr(o);if(!d.isDirectory()||d.isSymbolicLink())return null;a=La(o)}catch{return null}let s=m(a,"generations"),c=[];try{for(let d of ja(s)){if(!/^[a-f0-9]{64}$/.test(d))continue;let u=m(s,d),l;try{l=Rr(u)}catch{continue}if(!(!l.isDirectory()||l.isSymbolicLink()))try{let p=Ua(D(m(u,Pr),{inputKind:"shared-generation baseline manifest",maxBytes:G}));p.generationId===d&&p.repositoryId===e.repositoryId&&p.producerIdentity===qt&&Pl(p.fingerprint,i)&&c.push(p)}catch{continue}}}catch{return null}c.sort((d,u)=>{let l=d.treeOid===e.treeOid?0:1,p=u.treeOid===e.treeOid?0:1;if(l!==p)return l-p;if(r){let g=Aa(d.fingerprint,r)-Aa(u.fingerprint,r);if(g!==0)return g}return Date.parse(u.createdAt)-Date.parse(d.createdAt)||d.generationId.localeCompare(u.generationId)});for(let d of c){let u={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:d.treeOid,fingerprint:d.fingerprint,producerIdentity:d.producerIdentity,generationId:d.generationId,repositoryCacheDir:a},l=re(u);if(l)return{snapshot:u,manifest:l}}return null}function $a(e){let t=me(m(e.snapshot.repositoryCacheDir,"locks",`${e.snapshot.generationId}.publish.lock`));if(!t)throw new Error(`shared generation publication is already in progress for ${e.snapshot.generationId}`);try{return xl(e)}finally{t.release()}}function xl(e){let t=re(e.snapshot);if(t)return Fa(e.snapshot,t);if(!Ja(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Ca(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Nt(e.sourceCacheDir),i=m(e.snapshot.repositoryCacheDir,"generations"),o=[ht(i)],a=Oa(m(i,`.tmp-${process.pid}-`));try{let s=[];for(let g of r.files){let y=Z(e.sourceCacheDir,g),b=Z(a,g);o.push(at(y,b,292)),e.onPublicationStage?.("after-artifact-flushed",g);let C=Ut(b).size;s.push({path:g,size:C,sha256:gt(b,{inputKind:"staged shared-generation artifact",maxBytes:V})})}let c=Ma(A(m(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:V})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let d=Tr(e.sourceProjectRoot);if(c!==d)throw new Error("shared SCIP generation root does not match its source worktree");if(Ca(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:vr,artifactCatalogVersion:rt,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((g,y)=>g.path.localeCompare(y.path))},l=H(m(a,Pr),u,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(ce(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=kr(e.snapshot);try{if(pe(p)&&!re(e.snapshot)){let g=`${p}.corrupt-${process.pid}-${Date.now()}`;Ie(p,g),le(g,{recursive:!0,force:!0})}Ie(a,p)}catch(g){let y=re(e.snapshot);if(y)return Fa(e.snapshot,y);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push(ce(i)),e.onPublicationStage?.("after-generations-directory-synced");let f=Je(...o);return{kind:"published",manifest:u,achievedDurability:f==="synced"?"directory-durable":"file-flushed",directorySync:f}}finally{le(a,{recursive:!0,force:!0})}}function Fa(e,t){let n=ce(m(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function Ht(e){let t=kr(e.snapshot);Me(e.targetCacheDir,{recursive:!0});let n=me(m(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:e.lockWaitMs??3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=Oa(m(e.targetCacheDir,".shared-hydrate-")),Tl(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let d=Z(t,c.path),u=Z(r,c.path);if(at(d,u),Ut(u).size!==c.size||gt(u,{inputKind:"hydrated shared-generation artifact",maxBytes:V})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Tr(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Co(Z(r,c.path),e.manifest.scipProjectRoot,a);if(!Ja(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=wl(e.targetCacheDir,r),o=!0,El(r,e.targetCacheDir,i),Vt({tempOutputScip:m(r,"index.scip"),tempOutputDb:m(r,"index.db"),tempMetaPath:m(r,"meta.json"),outputScip:m(e.targetCacheDir,"index.scip"),outputDb:m(e.targetCacheDir,"index.db"),metaPath:m(e.targetCacheDir,"meta.json"),now:e.now});let s=z(m(e.targetCacheDir,"index.db"),m(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);e.persistLease!==!1&&Er(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&kl(e.targetCacheDir,i),a}finally{r&&le(r,{recursive:!0,force:!0}),n.release()}}async function Va(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??w,o=i()+n,a=m(e.repositoryCacheDir,"locks"),s=m(a,`${e.generationId}.lock`),c=d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;let u=d.pid;return typeof u=="number"&&Number.isSafeInteger(u)&&u>0?{pid:u}:null};for(;i()<=o;){if(re(e))return{kind:"generation-ready"};let d=mt(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(d.kind==="acquired")return{kind:"owner",release:()=>d.lock.release()};let u=o-i();if(u<=0)break;await yl(Math.min(r,u))}return re(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Er(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:qa(i)};return Ha(e.repositoryCacheDir,o,!0),o}function Ba(e,t,n=void 0){let r={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,lastAction:"overlay",lastReason:`private cache forked from shared baseline ${e.generationId}`,lastSeenAt:(n??(()=>new Date))().toISOString()},i={...r,ownershipChecksum:qa(r)};return Ha(e.repositoryCacheDir,i,!0),i}function qa(e){return Ya(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Ir(e.projectRoot),localCacheDir:Ir(e.localCacheDir)}))}function Ua(e){let t=JSON.parse(e);if(t.version!==vr||t.artifactCatalogVersion!==rt||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==qt||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Gt(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function at(e,t,n=384){return yt(e,t,{mode:n})}function Il(e,t,n){Me(e,{recursive:!0}),H(m(e,Rl),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Ca(e){try{let t=Nt(e),n=_a("sha256");for(let r of t.files){let i=Z(e,r),o=Ut(i).size;n.update(r).update("\0").update(String(o)).update("\0"),li(i,{inputKind:"source-generation artifact",maxBytes:V},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Wa(e){try{let t=te(D(m(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:G}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function vl(e){return Wa(e)?.scipCompanion!=="deferred"}function Pl(e,t){let n=Rn(e.languages,e);return JSON.stringify(n)===JSON.stringify(t)}function Aa(e,t){let n=new Map(e.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),r=new Map(t.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),i=0;for(let[o,a]of n)r.get(o)!==a&&(i+=1);for(let o of r.keys())n.has(o)||(i+=1);return i}function kr(e){return m(e.repositoryCacheDir,"generations",e.generationId)}function Ha(e,t,n){let r=gi(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!pe(m(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=m(e,"worktrees");Me(i,{recursive:!0}),H(m(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Il(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function wl(e,t){let n=m(t,".rollback"),r=new Map,i=new Map;Me(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=m(e,s),d=pe(c);r.set(s,d),d&&at(c,m(n,"stable",s))}for(let s of wr){let c=m(e,s),d=pe(c);if(d){let u=Rr(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,d)}let o=m(e,St),a=pe(o);return a&&za(o,m(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function El(e,t,n){for(let r of wr){let i=m(t,r);if(n.managedDirectories.get(r)){let a=m(n.root,"managed",r);Me(xr(a),{recursive:!0}),Ie(i,a)}let o=m(e,r);pe(o)&&Ie(o,i)}}function kl(e,t){for(let i of wr){let o=m(e,i),a=m(t.root,"managed",i);t.managedDirectories.get(i)?pe(a)&&(le(o,{recursive:!0,force:!0}),Ie(a,o)):le(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=m(e,i);if(!o){le(a,{force:!0});continue}let s=`${a}.shared-restore-${hl()}`;at(m(t.root,"stable",i),s),le(a,{force:!0}),Ie(s,a)}let n=m(e,St);le(n,{recursive:!0,force:!0});let r=m(t.root,"sqlite-generations");t.generationStoreExisted&&pe(r)&&Ie(r,n)}function za(e,t){Me(t,{recursive:!0});for(let n of ja(e,{withFileTypes:!0})){let r=m(e,n.name),i=m(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?za(r,i):n.isFile()&&at(r,i)}}function Tl(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||!pt(e.fingerprint,t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Ja(e,t,n,r=!0,i=!0){try{let o=Wa(e);if(!o||o.scipCompanion==="deferred"||!pt(We(o.fingerprint),n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return ot("source validation rejected metadata"),!1;let a=Nt(e),s=z(m(e,"index.db"),m(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return ot(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Sl(m(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let d=Tr(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let f=Ma(A(Z(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:V})).metadata?.projectRoot;return f!==d&&ot(`source validation rejected SCIP root for ${p}: ${String(f)}`),f===d});return l||ot("source validation rejected SCIP project roots"),l}catch(o){return ot(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function ot(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Tr(e){try{return Ta(La(e)).href}catch{return Ta(Ir(e)).href}}function Ya(e){return _a("sha256").update(e).digest("hex")}import{createHash as Nr}from"crypto";import{existsSync as Mr,writeFileSync as ls}from"fs";import{join as Zl}from"path";import{createRequire as Dl}from"module";import{dirname as _r,isAbsolute as Fl,relative as Qa,resolve as ge,sep as Fr}from"path";var fe=Dl(import.meta.url),Cl=1,Ka="0.4.0";function Al(){try{let e=Za();if(!e.available)return e;let{packageRoot:t}=e,n=fe.resolve("typescript",{paths:[t]}),r=fe(n),{FileIndexer:i}=fe(ge(t,"dist/src/FileIndexer.js")),{Input:o}=fe(ge(t,"dist/src/Input.js")),{Packages:a}=fe(ge(t,"dist/src/Packages.js")),s=fe(ge(t,"dist/src/scip.js"));if(!i||!o||!a||!s.scip?.Document||!s.scip.Index)return{available:!1,reason:"scip-typescript document runtime has an unsupported module shape"};let c={packageVersion:e.packageVersion,typescript:r,Document:s.scip.Document,Index:s.scip.Index,FileIndexer:i,Input:o,Packages:a};return{available:!0,runtime:c,producerIdentity:jr(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Or(){let e=Za();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Za(){try{let e=fe.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(L(e,"scip-typescript package manifest"));if(t.version!==Ka)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Ka}`};let n=_r(e),r=fe.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(L(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:ts(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function es(e){let t=e.runtime===void 0?Al():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:jr(e.runtime)};return t.available?{available:!0,emitter:new Cr(e,t.runtime)}:t}var Cr=class{producerIdentity;workspaceRoot;tsconfigPath;projectRoot;maxFileByteSize;runtime;host;config=null;includedFiles=new Set;program=null;checker=null;symbolTable=new Map;constructorTable=new Map;packages;fragments=new Map;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=ge(t.workspaceRoot),this.tsconfigPath=ge(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??Ol(this.workspaceRoot,_r(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=jr(n);let r=Dr(n.typescript,this.tsconfigPath);this.config=r,this.host=new Ar(n.typescript,r.options,this.workspaceRoot),this.packages=new n.Packages(this.projectRoot)}initialize(){let t=performance.now();this.initializeProgram();let n=[];for(let r of this.program.getSourceFiles())this.includedFiles.has($e(r.fileName))&&n.push(this.emitSourceFile(r));return this.result(n,t)}advance(t){if(!this.program||!this.checker||!this.config)return this.initializeAndAdvance(t);let n=performance.now(),r=Ge(t.modifiedFiles),i=Ge(t.removedFiles??[]),o=Ge(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=Dr(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map($e));let s=this.program,c=new Map;for(let d of[...r,...i]){let u=Ne(this.workspaceRoot,d),l=s.getSourceFile(u);l&&(c.set(d,l),this.stats.symbolEntriesPruned+=Xa(this.symbolTable,l),this.stats.symbolEntriesPruned+=Xa(this.constructorTable,l)),this.host.invalidate(u)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[d,u]of c)this.program.getSourceFile(Ne(this.workspaceRoot,d))===u?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(zt(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=Ge(t.modifiedFiles),i=Ge(t.removedFiles??[]),o=Ge(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??Dr(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map($e)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Ne(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Ne(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Ne(this.workspaceRoot,n);if(!this.includedFiles.has($e(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Ne(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=zt(Qa(this.workspaceRoot,t.fileName)),r=new this.runtime.Document({relative_path:n,occurrences:[]});if(new this.runtime.FileIndexer(this.checker,{cwd:this.workspaceRoot,projectRoot:this.projectRoot,projectDisplayName:this.projectRoot,maxFileByteSizeNumber:this.maxFileByteSize},new this.runtime.Input(t.fileName,t.getText()),r,this.symbolTable,this.constructorTable,this.packages,t).index(),this.stats.documentsEmitted+=1,r.occurrences.length===0)return this.fragments.delete(n),this.stats.documentsRemoved+=1,{relativePath:n,bytes:null,occurrences:0,symbols:r.symbols.length,referenceFragments:[]};let o=r.serializeBinary();return this.fragments.set(n,o),{relativePath:n,bytes:o,occurrences:r.occurrences.length,symbols:r.symbols.length,referenceFragments:_l(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function _l(e,t){let n=new Map;for(let r of t.occurrences){if(!r.symbol||(r.symbol_roles&1)!==0||r.range.length<3)continue;let i=r.range[0],o=r.range[1];if(!Number.isInteger(i)||!Number.isInteger(o))continue;let a={targetSymbol:r.symbol,location:{file:e,line:i,column:o}};n.set(`${r.symbol}\0${i}\0${o}`,a)}return[...n.values()].sort((r,i)=>r.targetSymbol.localeCompare(i.targetSymbol)||r.location.line-i.location.line||r.location.column-i.location.column)}var Ar=class{compilerHost;sourceFiles=new Map;constructor(t,n,r){let i=t.createCompilerHost(n),o=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(a,s,c,d)=>{let u=$e(a);if(this.sourceFiles.has(u))return this.sourceFiles.get(u);let l=o(a,s,c,d);return this.sourceFiles.set(u,l),l}}}invalidate(t){this.sourceFiles.delete($e(t))}};function Dr(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(e.formatDiagnostics([n.error],e.createCompilerHost({})));let r=e.parseJsonConfigFileContent(n.config,e.sys,_r(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function jr(e){return ts(e.packageVersion,e.typescript.version)}function ts(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Cl}`}function Ol(e,t){return zt(Qa(e,t))||"."}function Ne(e,t){if(Fl(t))throw new Error(`expected a project-relative path: ${t}`);let n=ge(e,t),r=e.endsWith(Fr)?e:`${e}${Fr}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function Ge(e){return[...new Set(e.map(zt))].sort()}function zt(e){return e.split(Fr).join("/").replace(/^\.\//,"")}function $e(e){return ge(e)}function Xa(e,t){let n=0;for(let r of e.keys())if(jl(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function jl(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as Ll}from"crypto";import{dirname as Ml,join as ns}from"path";var Ve=5;var Nl="typescript-index";function rs(e){let t=ns(e,Nl),n=Ui(t);return{...n,requestDir:n.legacyRequestDir}}function is(e){try{let t=ci(te(L(ns(Ml(e),"meta.json"),"reindex metadata")));return t?Ll("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Bl}from"crypto";import{existsSync as ql,rmSync as Ul}from"fs";import{randomUUID as Gl}from"crypto";import{getHeapStatistics as $l}from"v8";import{resolve as Vl}from"path";var Jt=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;maxActiveSessions;softMemoryLimitBytes;memoryUsage;active=new Map;requests=0;sessionsCreated=0;sessionsReplaced=0;sessionsEvicted=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(t){if(this.projectRoot=Vl(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??es,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??w,t.maxActiveSessions!==void 0&&(!Number.isInteger(t.maxActiveSessions)||t.maxActiveSessions<1))throw new Error("TypeScript index maxActiveSessions must be a positive integer.");if(this.maxActiveSessions=t.maxActiveSessions??8,t.softMemoryLimitMb!==void 0&&(!Number.isInteger(t.softMemoryLimitMb)||t.softMemoryLimitMb<1))throw new Error("TypeScript index softMemoryLimitMb must be a positive integer.");this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:$l().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:Ve,state:this.unavailable?"unavailable":this.lastError?"error":this.active.size>0?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,sessionsEvicted:this.sessionsEvicted,activeSessions:this.active.size,maxActiveSessions:this.maxActiveSessions,heapUsedBytes:i.heapUsedBytes,heapLimitBytes:i.heapLimitBytes,...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:o,initializations:r("initializations"),programUpdates:r("programUpdates"),documentsEmitted:r("documentsEmitted"),documentsRemoved:r("documentsRemoved"),...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...t?{mailbox:t}:{}}}close(){this.active.clear()}emitterFor(t){let n=`${t.tsconfigPath}\0${t.projectArgument}`,r=this.active.get(n);if(r?.projectIdentity===t.projectIdentity)return this.active.delete(n),this.active.set(n,r),r;if(r)this.active.delete(n);else if(this.active.size>=this.maxActiveSessions){let a=this.active.keys().next().value;a!==void 0&&(this.active.delete(a),this.sessionsEvicted+=1)}let i=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:t.tsconfigPath,projectRoot:t.projectArgument});if(!i.available)throw this.unavailable=!0,new Error(i.reason);r&&(this.sessionsReplaced+=1);let o={projectIdentity:t.projectIdentity,emitter:i.emitter};return this.active.set(n,o),this.sessionsCreated+=1,o}};var Ty=`typescript-index-${process.pid}-${Gl()}`,os=K(process.pid),Dy={pid:process.pid,...os?{processIdentity:os}:{}};var Wl=12e4,Hl=5,st=class extends Error{name="TypeScriptIndexMemoryPressureError"},Yt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Ri(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Xl(),this.runtime=n.runtime??Ql,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=zi(this.cacheDir),r=rs(this.cacheDir),i=Dn(n.statePath);if(!as(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??w)()+this.timeoutMs,c=kn("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),d=Tn(c),u=Wi(r,{mailboxVersion:En,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ve,id:d,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??w)()<=s;){if(ql(u.responsePath))try{return zl(D(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{Ul(u.responsePath,{force:!0})}let l=Dn(n.statePath);if(!as(l,this.projectRoot,this.runtime))return this.requestLocally(t);this.runtime.sleep(Hl)}return this.requestLocally(t)}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?Lr(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new Jt({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),Lr(ss(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function as(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Ve&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Hi&&(!e.processIdentity||r!=null&&ze(e.processIdentity,r))}function zl(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ve||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0){let s=typeof a.error=="string"?a.error:"TypeScript index service request failed.";throw Jl(s)?new st(s):new Error(s)}return Lr(ss(a.response,i),i,o)}function Jl(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function Lr(e,t,n){if(e.producerIdentity!==t)throw new Error("TypeScript index service wrote an invalid response.");let r=[...new Set(n)].sort(),i=e.fragments.map(o=>o.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function ss(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(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Yl)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Kl(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Yl(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 Kl(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Xl(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Wl}var Ql={now:Date.now,monotonicNow:w,randomId:Bl,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:se,readProcessIdentity:K};var ep=128,tp=256;function np(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=Ce(t);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 r=He(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(h=>h.inputKind==="source"&&je(h.path)),o=ps(r,n),a={...r,changes:o},s=i.filter(h=>h.kind==="added").map(h=>h.path),c=i.filter(h=>h.kind==="deleted").map(h=>h.path),d=i.filter(h=>h.kind==="modified"),u=Xt(e.currentSnapshot,e.producerIdentity,n),l=Xt(e.previousSnapshot,e.producerIdentity,n),p=fs(r,o,u,l),f=!p&&ms(r);if(i.length===0&&!p)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let g=e.currentSnapshot.files.filter(h=>ke(h.path,e.currentSnapshot.languages)==="source"&&je(h.path)).map(h=>h.path).sort(),y=new Set(g),b=p?e.projectFiles.filter(h=>!y.has(h)).sort():[...c].sort(),C=p?a:{...r,changes:i},F=p?{eligible:!0,plan:{...Qe(a,e.graph,[...new Set([...g,...b])]),mode:"full-project"}}:ip(d,s,b,e.graph,e.projectFiles);if(!F.eligible)return F;let M=F.plan,N=new Set(b),x=op(M,t,e.graph,N);if(!x)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let R=x.length===1?x[0]:void 0;return{eligible:!0,manifest:C,plan:M,projectIdentity:u,previousFragmentGeneration:us(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:us(e.currentSnapshot,e.producerIdentity),projects:x,deletedFiles:b,replaceProject:p,dependencyGraphUnchanged:f,...R?{tsconfigPath:R.tsconfigPath,projectArgument:R.projectArgument}:{}}}function ps(e,t){return e.changes.filter(n=>n.inputKind==="source"&&je(n.path)||n.inputKind==="config"&&(!Ae(n.path)||t.has(n.path))&&rp(n)||n.inputKind==="ambient")}function rp(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function fs(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>tp||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function ip(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...cs(n,r,i)])].sort(),reasons:[]}};let o=Qe({version:1,changes:e.filter(gs),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...cs(n,r,i)])].sort(),reasons:[]}}}function gs(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function ms(e){let t=e.changes.filter(n=>n.inputKind==="source"&&je(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!gs(n))}function op(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=ap(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[d])=>c.localeCompare(d))){let c=new Set(s),d=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(f=>ds(f,p,n)))),u=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(f=>ds(f,p,n)))),l=s.filter(p=>!r.has(p));if(d.length===0&&u.length===0&&l.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:d,removedFiles:u,affectedFiles:[...l].sort()})}return o}function cs(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let d of c){let u=i.get(d)??new Set;u.add(s),i.set(d,u)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let d of i.get(c)??[])o.has(d)||(o.add(d),a.push(d))}return[...o].sort()}function ap(e,t){let n=t.filter(o=>o==="."||e===o||e.startsWith(`${o}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((o,a)=>Kt(a)-Kt(o)||o.localeCompare(a)),i=r[0];return r[1]&&Kt(r[1])===Kt(i)?null:i}function Kt(e){return e==="."?0:e.split("/").filter(Boolean).length}function ds(e,t,n){let r=new Set,i=[e];for(let o=0;o<i.length;o+=1){let a=i[o];if(!(!a||r.has(a))){r.add(a);for(let s of n.get(a)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function hs(e){let t=w();try{if(!Mr(e.previousDbPath)||!Mr(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Or();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Y({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=cp(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?ye(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=Ce(s),d,u,l;try{d=vt(o,{includeIgnored:!1}).filter(je).sort();let E=a?He(a,e.currentSnapshot):null,T=E&&a&&fs(E,ps(E,c),Xt(e.currentSnapshot,r.producerIdentity,c),Xt(a,r.producerIdentity,c)),W=E!==null&&!T&&ms(E);T?(l=Ni(o,"none")??void 0,u=new Map):W?u=new Map:(l=Pt(o),u=l.graph)}finally{o.close()}let p=performance.now()-n,f=np({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:d,graph:u,producerIdentity:r.producerIdentity,rootTsconfigExists:Mr(Zl(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let g=is(e.previousDbPath);if(!g)throw new Error("published TypeScript base generation unavailable");n=performance.now();let y=new Yt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:g},{requireService:!0}),b=f.projects.flatMap(E=>{let T=sp(E.affectedFiles,ep);return(T.length>0?T:[[]]).map((un,Ee)=>({project:E,affectedFiles:un,removedFiles:Ee===0?E.removedFiles:[],firstForProject:Ee===0}))}),C=[],F=new Map,M=[],N=!1,x=0,R=0,h=0,O=f.previousFragmentGeneration;for(let[E,T]of b.entries()){let W=y.request({kind:"emit-documents",tsconfigPath:T.project.tsconfigPath,projectArgument:T.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:T.firstForProject?T.project.modifiedFiles:[],removedFiles:T.firstForProject?T.project.removedFiles:[],affectedFiles:T.affectedFiles});N||=W.cold,M.push(W.durationMs);let un=T.removedFiles.map(ut=>({relativePath:ut,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),Ee=[...W.fragments,...un];if(!f.replaceProject)for(let ut of Ee)F.set(ut.relativePath,ut.referenceFragments);let Cc=performance.now(),Ac=da(W.fragments);x+=performance.now()-Cc;let ii=E===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${E}.scip`,_c=performance.now();ls(ii,Ac),h+=performance.now()-_c;let Oc=performance.now(),oi=E===b.length-1?f.nextFragmentGeneration:dp({previousGenerationIdentity:O,targetGenerationIdentity:f.nextFragmentGeneration,fragments:Ee});ma({cacheDir:e.cacheDir,previousGenerationIdentity:O,nextGenerationIdentity:oi,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:E===0?e.baseShardCurrent:!1,fragments:Ee,allowProjectIdentityChange:f.replaceProject&&E===0,allowLegacyProjectIdentityMigration:!0}),R+=performance.now()-Oc,O=oi,C.push({scipPath:ii,affectedFiles:[...T.affectedFiles,...T.removedFiles].sort(),deletedFiles:[...T.removedFiles].sort()})}let $=performance.now()-n,I={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:C,completeScipUpdated:!1,durationMs:w()-t,cold:N,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:d.length,dependencyGraphSnapshot:l,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:F,timings:{runtimeMs:i,graphMs:p,requestMs:$,serviceMs:M.reduce((E,T)=>E+T,0),assemblyMs:x,fragmentStoreMs:R,writeMs:h}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${I.affectedFiles.length-I.deletedFiles.length} document(s), removed ${I.deletedFiles.length}, and produced ${C.length} bounded batch(es) across ${f.projects.length} project(s) in ${(I.durationMs/1e3).toFixed(3)}s (${I.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${p.toFixed(0)}ms, request ${$.toFixed(0)}ms, assembly ${x.toFixed(0)}ms, fragments ${R.toFixed(0)}ms, write ${h.toFixed(0)}ms).`),I}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof st)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function sp(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function cp(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=It(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function dp(e){let t=Nr("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(Nr("sha256").update(n.bytes).digest()));return t.digest("hex")}function Gr(e){let t=Or();if(!t.available)throw new Error(t.reason);let n=ha({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:A(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:V}),packageVersion:t.packageVersion});ls(e.candidateShardPath,n)}function Xt(e,t,n){let r=e.files.filter(i=>{let o=ke(i.path,e.languages);return o==="ambient"||o==="config"&&(!Ae(i.path)||n.has(i.path))}).map(i=>{let a=ke(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${ys(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function us(e,t){return ys(JSON.stringify({version:1,producerIdentity:t,snapshot:lt(e)}))}function ys(e){return Nr("sha256").update(e).digest("hex")}import{closeSync as up,existsSync as Qt,fstatSync as lp,lstatSync as pp,openSync as fp,renameSync as Br,rmSync as Zt,statSync as gp,writeSync as mp}from"fs";import{cpus as hp}from"os";import{join as qr}from"path";var $r=Symbol("no-error");async function Ss(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),a=0,s=$r,c=!0,d=Array.from({length:o},async()=>{for(;c&&a<e.length;){let u=a++;try{r[u]=await n(e[u])}catch(l){s===$r&&(s=l),c=!1}}});if(await Promise.all(d),s!==$r)throw s;return r}var bs=8*1024;function yp(e,t){if(e.temporaryRootConfigContent===void 0)return null;let n=qr(t,"tsconfig.json"),r=Buffer.from(e.temporaryRootConfigContent,"utf8"),i;try{i=fp(n,"wx",384)}catch(o){if(o.code==="EEXIST")return null;throw o}try{mp(i,r);let o=lp(i);return{path:n,content:r,device:o.dev,inode:o.ino}}finally{up(i)}}function Sp(e){if(e)try{let t=pp(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=A(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Zt(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function bp(e,t,n){if(!e.defaultOutputPath)return;let r=qr(t,e.defaultOutputPath);n!==r&&Qt(r)&&Br(r,n)}function Rp(e,t,n){if(!e.defaultOutputPath)return null;let r=qr(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Zt(i,{force:!0}),Qt(r)?(Br(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function xp(e){e&&(Zt(e.defaultOutputPath,{force:!0}),e.backupPath&&Qt(e.backupPath)&&Br(e.backupPath,e.defaultOutputPath))}function Ip(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,hp().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function xs(e,t,n,r,i){U(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath),s=[],c=Ip(a.length,r),d=await Ss(a,c,u=>Vr(u,t,n,i));if(c>1){let u=new Map;for(let l of d.filter(p=>p.result.skipped&&p.retryable)){let p=a.find(f=>f.id===l.result.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),U(i,"Reindex cancelled by its owner."),u.set(p.id,(await Vr(p,t,n,i)).result))}s.push(...d.map(({result:l})=>u.get(l.id)??l))}else s.push(...d.map(({result:u})=>u));for(let u of o)U(i,"Reindex cancelled by its owner."),s.push((await Vr(u,t,n,i)).result);return s.sort((u,l)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===l.id))}async function Vr(e,t,n,r){U(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Zt(e.scipPath,{force:!0});let i=Rp(e.config,t,e.scipPath),o=yp(e,t),a=[e.binary,...e.args].join(" "),s=w();try{e.trustedProjectTool&&qi(t,e.trustedProjectTool);let d=Vi(e.binary,e.args),u=await wt({command:d.binary,args:d.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:vp(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(u.status!==0){let l=u.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${u.status}${l?`:
|
|
250
|
+
${l}`:""}`)}bp(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw pi(r,"Reindex cancelled by its owner.");let u=d instanceof Error?d.message:String(d),l=u.length<=bs?u:`${u.slice(0,bs)}
|
|
251
|
+
[indexer failure detail truncated]`,p=`${e.resolvedBinary} indexer failed: ${l}`,f=e.label===e.language?p:`${e.label}: ${p}`;return n(`Skipping ${e.label}: ${p}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-s,command:a,skipped:{language:e.language,reason:f}},retryable:Pp(d)}}finally{xp(i),Sp(o)}if(!Qt(e.scipPath)){let d=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,u=e.label===e.language?d:`${e.label}: ${d}`;return n(`Skipping ${e.label}: ${d}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-s,command:a,skipped:{language:e.language,reason:u}},retryable:!1}}let c;try{c=gp(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:w()-s,command:a,outputBytes:c},retryable:!1}}function vp(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Ki.indexer}function Pp(e){return e instanceof Xi?e.kind==="spawn"&&Rs(e.cause):Rs(e)}function Rs(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as vs}from"child_process";import{homedir as Is,platform as wp}from"os";import{delimiter as Ep,join as en}from"path";function Wr(e,t){let n=e.installMethods,r=Xe(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(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!In(i.prerequisite))continue;let o=kp(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{vs(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:wp()==="win32"});let a=Oe(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${i.identity} via ${i.label}${s}; resolved executable: ${a}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function kp(e){if(e.binary==="npm")return Ur("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Ur("go",["env","GOBIN"]);if(t)return t;let n=Ur("go",["env","GOPATH"]);if(n)return en(n.split(Ep)[0],"bin")}return e.binary==="dotnet"?en(process.env.DOTNET_CLI_HOME??Is(),".dotnet","tools"):e.binary==="dart"?en(process.env.PUB_CACHE??en(Is(),".pub-cache"),"bin"):e.destination}function Ur(e,t){try{return vs(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import Hs from"better-sqlite3";import{existsSync as zs}from"fs";import{dirname as Js,join as Ys,resolve as Ks}from"path";import{randomUUID as Dp}from"crypto";import{mkdtempSync as Fp,rmSync as Cp,statSync as ws}from"fs";import{tmpdir as Ap}from"os";import{join as Es}from"path";import{Worker as _p}from"worker_threads";function Tp(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Be(){return{skippedReferences:0,skippedReferenceReasons:Tp(),skippedReferenceSamples:[]}}function tn(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var Op=3e5,ks=64*1024*1024,jp={createResultDirectory:()=>Fp(Es(Ap(),"scip-query-vue-workers-")),spawn:(e,t)=>new _p(e,{workerData:t}),resultSize:e=>ws(e).size,readResult:e=>D(e,{maxBytes:ks,inputKind:"Vue worker result"}),removeResultDirectory:e=>Cp(e,{recursive:!0,force:!0})};function Ts(e){return e.length>=8&&Fs(e.length)>1}async function Ds(e,t=jp){let n=Fs(e.vueFiles.length),r=Jp(e.vueFiles),i=Kp(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??Hp(),s=e.maxResultBytes??zp();Ps("timeoutMs",a),Ps("maxResultBytes",s);let c=Dp(),d=t.createResultDirectory(),u=[],l,p,f;try{for(let y=0;y<i.length;y++){let b=y,C=i[y]??[],F=C.map(x=>x.taskId),M=Es(d,`${b}.json`),N=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:C,resultPath:M,runId:c,workerId:b,taskIds:F});u.push({workerId:b,taskIds:F,resultPath:M,handle:N,completion:Lp(N,b)})}await Mp(u,a);let g=u.sort((y,b)=>y.workerId-b.workerId).map(y=>Gp(y,c,s,t));f={occurrences:g.flatMap(y=>y.occurrences),...Be()};for(let y of g)tn(f,y)}catch(g){l=g}finally{let g=await Np(u);if(g.length===0)try{t.removeResultDirectory(d)}catch(y){g.push(y)}if(g.length>0){let y=l===void 0?g:[l,...g];p=new AggregateError(y,`Vue worker cleanup failed: ${Wp(y[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function Lp(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function Mp(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Np(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Gp(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(a){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:a})}if(!ct(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!Up(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!$p(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function $p(e){if(!ct(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Vp)||!ie(e.skippedReferences)||!ct(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!ie(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Bp)}function Vp(e){return ct(e)&&typeof e.sourceFile=="string"&&ie(e.sourceLine)&&ie(e.sourceStartChar)&&ie(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&ie(e.symbolId)}function Bp(e){return ct(e)&&typeof e.sourceFile=="string"&&ie(e.sourceLine)&&ie(e.sourceStartChar)&&ie(e.sourceEndChar)&&typeof e.token=="string"&&qp(e.reason)}function qp(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function ie(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Up(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Ps(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Wp(e){return e instanceof Error?e.message:String(e)}function Fs(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function Hp(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Op}function zp(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:ks}function Jp(e){let t=Yp(),n=[];for(let r of e){let i=Cs(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({taskId:`${n.length}:${r}:${a}`,fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Yp(){return Number.POSITIVE_INFINITY}function Kp(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Xp(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Xp(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Cs(e.fileName)-e.startOffset)}function Cs(e){try{return ws(e).size}catch{return 1}}import{createRequire as Qp}from"module";import{existsSync as Zp}from"fs";import{dirname as As,extname as ef,join as _s,relative as tf,resolve as nf}from"path";import{pathToFileURL as rf}from"url";function of(e){e.transaction(()=>{e.prepare(`
|
|
236
252
|
DELETE FROM mentions
|
|
237
253
|
WHERE chunk_id IN (
|
|
238
254
|
SELECT c.id
|
|
@@ -247,12 +263,12 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
247
263
|
FROM documents
|
|
248
264
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
249
265
|
)
|
|
250
|
-
`).run()})()}function
|
|
266
|
+
`).run()})()}function zr(e,t){return e.prepare(`
|
|
251
267
|
SELECT relative_path AS relativePath
|
|
252
268
|
FROM documents
|
|
253
269
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
254
270
|
ORDER BY relative_path
|
|
255
|
-
`).all().map(r=>
|
|
271
|
+
`).all().map(r=>nf(t,r.relativePath))}function Os(e,t){let{vueCore:n,ts:r,volarTs:i}=af(e),{parsed:o,vueOptions:a}=sf(n,r,t),s=As(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),d=cf(n,r,c),u=df(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,d,f=>f,u),p=r.createLanguageService(l);return{ts:r,language:d,languageService:p,fileNames:o.fileNames,configDir:s}}function af(e){let t=Qp(rf(_s(e,"package.json")).href);return{vueCore:Hr(t,"@vue/language-core",e),ts:Hr(t,"typescript",e),volarTs:Hr(t,"@volar/typescript",e)}}function sf(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,As(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function cf(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Zp(o))return;let a=D(o,{maxBytes:ae,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??mf(o))});return r.current=i,i}function df(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Hr(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function js(e,t,n){let r=uf(e);return i=>{if(!i.name)return null;let o=oe(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let d=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(d)return d.symbolId;let u=c.containingByLine.get(s.line);return u&&u.displayName===i.name?u.symbolId:lf(c.starts,s.line,2,i.name)}}function uf(e){let t=e.prepare(`
|
|
256
272
|
SELECT
|
|
257
273
|
d.relative_path AS relativePath,
|
|
258
274
|
der.start_line AS startLine,
|
|
@@ -263,22 +279,22 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
263
279
|
JOIN documents d ON d.id = der.document_id
|
|
264
280
|
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
265
281
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
266
|
-
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function
|
|
282
|
+
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function lf(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let d=Math.abs(c.line-t);d>n||(!a||d<a.distance)&&(a={distance:d,symbolId:c.symbolId})}return a?.symbolId??null}function Jr(e,t,n){let r=Sf(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
267
283
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
268
284
|
VALUES (?, ?, ?, ?)
|
|
269
|
-
`),a=0,s=new Map;return e.transaction(()=>{for(let
|
|
285
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let d of n){let u=oe(t,d),l=Us(r.name,r.version,u);o.run(l,"default",7,`Vue component|${u}`);let p=bf(i,r,t,d);p&&(a++,s.set(d,p))}})(),{get(d){return s.get(d)??null},syntheticSymbols:a}}function Ls(e,t,n,r,i){return e.transaction(()=>(of(e),pf(e,t,n,r),ff(e,i)))()}function pf(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
270
286
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
271
287
|
VALUES (?, ?, ?, ?, X'00')
|
|
272
288
|
`),a=e.prepare(`
|
|
273
289
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
274
290
|
VALUES (?, ?, 1)
|
|
275
|
-
`);for(let s of n){let c=r.get(s);if(!c)continue;let
|
|
291
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let d=oe(t,s),u=i.get(d);if(!u)continue;let l=o.run(u.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function Ms(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(Yr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ns(e){let t=new Set,n=[];for(let r of e){let i=Gs(r);t.has(i)||(t.add(i),n.push(r))}return n}function Gs(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function ff(e,t){let n=yf(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
276
292
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
277
293
|
VALUES (?, ?, ?, ?, X'00')
|
|
278
294
|
`),i=e.prepare(`
|
|
279
295
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
280
296
|
VALUES (?, ?, 0)
|
|
281
|
-
`),o=new Set,a=0,s=0;for(let c of t){let
|
|
297
|
+
`),o=new Set,a=0,s=0;for(let c of t){let d=Gs(c);if(o.has(d))continue;o.add(d);let u=n.get(c.sourceFile);if(!u)continue;let l=r.run(u,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*$s(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Vs(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Yr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function gf(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Bs(e,t){return oe(e,t).startsWith("node_modules/")}function oe(e,t){return tf(e,t).replaceAll("\\","/")}function mf(e){switch(ef(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function qs(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=D(t,{maxBytes:ae,inputKind:"Vue source file"}),r={text:n,lineStarts:hf(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:gf}}function hf(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function yf(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function Sf(e){try{let t=JSON.parse(D(_s(e,"package.json"),{maxBytes:G,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function bf(e,t,n,r){let i=oe(n,r),o=Us(t.name,t.version,i);return e.get(o)?.id??null}function Us(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Xs(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>vf({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function xf(e){return X(de(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),X(Xs({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function If(e){return X(de(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Pf(e)}function vf(e){let t=Ks(e.projectRoot,e.tsconfig);if(!zs(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Hs(e.dbPath);try{let r=zr(n,e.projectRoot),i=Ys(Js(e.dbPath),"augment-vue-meta.json");return Vo({cachePath:i,readFingerprint:()=>ec(n,e.projectRoot,e.tsconfig),compute:()=>wf({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}async function Pf(e){let t=Ks(e.projectRoot,e.tsconfig);if(!zs(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Hs(e.dbPath);try{let r=zr(n,e.projectRoot),i=Ys(Js(e.dbPath),"augment-vue-meta.json");return await Bo({cachePath:i,readFingerprint:()=>ec(n,e.projectRoot,e.tsconfig),compute:()=>Ef({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function wf(e){let t=Jr(e.db,e.projectRoot,e.vueFiles),n=Zs(e,t);return Qs(e,t,n)}async function Ef(e){let t=Jr(e.db,e.projectRoot,e.vueFiles),n=Ts(e.vueFiles)?await Ds({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Zs(e,t);return Qs(e,t,n)}function Qs(e,t,n){let r=Ns(n.occurrences),i=Ls(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:jf(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Of(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Zs(e,t){let n=kf({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Tf({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function ec(e,t,n){let r=e.prepare(`
|
|
282
298
|
SELECT
|
|
283
299
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
284
300
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -287,13 +303,13 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
287
303
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
288
304
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
289
305
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
290
|
-
`).get();return{version:3,tsconfig:n,files:
|
|
291
|
-
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Ll(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function ka(e,t,n){let r=he();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:W(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function nr(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function rr(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function Ol(e,t){let n=rr(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=rr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Cl(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...rr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function jl(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Ol(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Ml(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Gl(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(ja(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ja(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function Nl(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Gl(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=$l(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function $l(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=tr(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function oy(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Jl(e),a=Date.now(),s=x();Pt(b(o.outputScip),{recursive:!0}),Pt(b(o.outputDb),{recursive:!0});let c=e.languages??Qt(t);if(c.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: ${c.join(", ")}`);let u=we("reindex.fingerprint",()=>Pr(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,l;if(e.skipIfUnchanged!==!1&&!_o(t,o.outputDb)&&Ma(o.outputScip)===Ma(D(b(o.outputDb),"index.scip"))){let f=et(t);if(d=f?yt(f,u):void 0,d){let y=re(d);if(y){if(!zl(o,u))try{Nn({snapshot:d,manifest:y,targetCacheDir:b(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(R){r(`Shared generation attach failed; continuing locally: ${Se(R)}`)}}else{let R=await Oo(d);if(R.kind==="owner")l=R.release;else if(R.kind==="generation-ready"){let F=re(d);if(F)try{Nn({snapshot:d,manifest:F,targetCacheDir:b(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(E){r(`Shared generation attach failed after waiting; continuing locally: ${Se(E)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ue(D(b(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw l?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${b(o.outputDb)}.`);let m;try{m=await ke("reindex.lock",()=>xp(D(b(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(f){throw p.release(),l?.(),f}let g=null;try{Fn(o.outputDb,o.outputScip,o.metaPath);let f=Ql(b(o.outputDb));f.removed>0&&r(`Removed ${f.removed} abandoned reindex workspace(s)`);for(let O of f.errors)r(`Could not remove abandoned reindex workspace: ${O}`);let y=null,R=we("reindex.reuse-check",()=>(y=Yl({opts:e,paths:o,languages:c,fingerprint:u,start:a,monotonicStart:s,onStatus:r}),y),()=>({languages:c.length,reused:y!==null}));if(R){Na({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r});let O=zt(o.outputDb,R);return O.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${O.reason}`),qt(t,b(o.outputDb)),R}await ke("reindex.scip-cli-ready",()=>gp(i,r));let F=Xl(o);g=F.runDir;let E,P=await ke("reindex.fresh",async()=>(E=await Zl({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:F,fingerprint:u,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),E),()=>({languages:c.length,reused:E?.reused,skipped:E?.skipped.length}));Na({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r});let T=zt(o.outputDb,P);return T.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${T.reason}`),qt(t,b(o.outputDb)),P}catch(f){let y=Tt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:f instanceof Error?f.message:String(f)});os(o.metaPath,y);let R=qr(o.outputDb,y);throw R.state==="failed"&&r(`Warning: failed reindex activity telemetry was not recorded: ${R.reason}`),f}finally{g&&ye(g,{recursive:!0,force:!0}),m(),p.release(),l?.()}}function Na(e){if(e.snapshot)try{let t=et(e.projectRoot),n=t?yt(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=Lo({snapshot:e.snapshot,sourceCacheDir:b(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=et(e.projectRoot);return(i?yt(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});Gn(e.snapshot,b(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Se(t)}`)}}function zl(e,t){if(!G(e.outputScip)||!G(e.outputDb)||!is(e.metaPath,t))return!1;let n=ee(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Se(e){return e instanceof Error?e.message:String(e)}function Jl(e){let t=e.outputScip??D(e.projectRoot,"index.scip"),n=e.outputDb??D(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:D(b(n),"meta.json")}}function Yl(e){let t=ee(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!G(e.paths.outputScip)||!G(e.paths.outputDb)||!is(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;q(Q(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=x()-e.monotonicStart,r=Tt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return os(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:Kl(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Kl(e,t,n,r){let i=ns(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:$e(i[o]),outputBytes:Ve(sr(e.outputDb,o)),durationMs:0}))}function Xl(e){let t=ql(D(b(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,vt(e.outputScip)),tempOutputDb:D(t,vt(e.outputDb)),tempMetaPath:D(t,vt(e.metaPath))}}function Ql(e){let t=[],n;try{n=Wa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Se(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{ye(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Se(o)}`)}return{removed:r,errors:t}}async function Zl(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ke("reindex.language-indexers",async()=>(n=await tp(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),ep({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=we("reindex.publish",()=>dp(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let l=we("reindex.publish",()=>up(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=l.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c}}function ep(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!G(e.run.paths.outputScip)||!G(e.run.paths.outputDb))return!1;let t=ee(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 tp(e,t){let n=ap({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[C,ur]of n)ur.reused&&(r.push({language:C,scipPath:ur.scipPath}),i.add(C));for(let C of i)e.onStatus(`Reusing cached ${C} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=ee(e.paths.outputDb,e.paths.metaPath),s=qe(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Xo({projectRoot:e.projectRoot,cacheDir:b(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Be(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Be(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:ar(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,l=new Set(d?["typescript"]:[]),p=d?void 0:np(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:f}=fp({languages:e.languages.filter(C=>!i.has(C)&&!l.has(C)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:p?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),y=p?m.filter(C=>C.language!=="typescript"||p.missedProjectIds.has(C.id)):m,R=await na(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),F=[];if(p){ip(e.paths.outputDb,R);let C=f.typescript??e.tempPaths.tempOutputScip;F=op({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:C,reusedProjects:p.reusedProjects})}let E=[...R,...F],{indexedOutputs:P}=hp(E,g),T=d?[{language:"typescript",scipPath:d.scipPath}]:[],O=[...r,...T,...P];yp(O,g,e.languages,e.opts.allowPartial,e.onStatus);let as=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Ve(d.scipPath)??void 0}]:[],ss=sp(n,[...R,...as],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:O,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:cp(n,e.languages),shards:ss,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function np(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ci(e.projectRoot,r),o=_i(n.fingerprint.files,r),a=Li(r,i),s=Oi(r,o,a),c=qe(e.paths.metaPath),d=rp(c,s,g=>G(Et(e.paths.outputDb,g))),l=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),m=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:l,missedProjectIds:m}}function rp(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===Re&&Ft(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(H(a)!==H(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function ip(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=Et(e,r);Pt(b(i),{recursive:!0}),kt(n.scipPath,i)}}function op(e){return e.reusedProjects.map((t,n)=>{let r=Et(e.outputDb,t),i=Be(e.tempOutputScip,"typescript-project-cached",n);return kt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ve(i)??void 0}})}function ap(e){let t=qe(e.paths.metaPath),n=ns(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=sr(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==Re){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!Ft(t).languageShardReuse||!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!G(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(H(s)!==H(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function sp(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:$e(o.fingerprint),outputBytes:Ve(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?$e(s.fingerprint):o?$e(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:$e(o.fingerprint),outputBytes:Ve(Et(n.outputDb,i)),durationMs:0});return r}function $e(e){return Bl("sha256").update(H(e)).digest("hex").slice(0,16)}function Ve(e){try{return Ul(e).size}catch{return null}}function cp(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function up(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Ga(e.paths.outputDb,n),u=$a(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Sp({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Qo({cacheDir:b(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let P=n.map(T=>T.language==="typescript"?{language:T.language,scipPath:s.candidateScipPath}:T);return Ga(e.paths.outputDb,P),u=$a(P,e.tempPaths.tempOutputScip,e.onStatus),u}});q(Q(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let l=cn(e.tempPaths.tempOutputDb);if(l.added.length>0&&e.onStatus(`Added SQLite query indexes: ${l.added.join(", ")}`),l.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${l.removed.join(", ")}`),d.mode==="incremental"&&s){let P=null,T=null;try{P=new oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),T=new oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let O=Cr(P,e.fingerprint,s.referenceFragmentsByFile,T);e.onStatus(`Cached exact TypeScript reference fragments for ${O} affected document(s).`)}catch(O){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${O instanceof Error?O.message:String(O)}.`)}finally{P?.close(),T?.close()}}let p=ar(e.paths.metaPath),m=d.mode==="incremental"&&s?Rp(s,d.changedDocumentPaths):Xt({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"}),g=Tt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(P=>P.language),skipped:[...r]}),f=d.mode==="incremental"&&d.scipCompanion==="deferred",y={...o};f&&delete y.typescript;let{metadata:R,pruneProjects:F}=Ja({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:y,typescriptProjectShardContext:a,lastRefresh:g});R.scipCompanion=f?"deferred":"current",Ya(e.paths.outputDb,F),cr(e.tempPaths.tempMetaPath,R);let E=mt({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:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}});return E.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${E.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),uo(b(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),za(e.paths.outputDb,m,e.onStatus),g}function dp(e,t,n,r,i,o){let a=ar(e.paths.metaPath),s=null;try{kt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Xr("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}q(Q(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let c=cn(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),s??=Xt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let u=Tt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:d,pruneProjects:l}=Ja({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return Ya(e.paths.outputDb,l),cr(e.paths.metaPath,d),bo(e.paths.outputDb,e.paths.metaPath),za(e.paths.outputDb,s,e.onStatus),u}function ar(e){return pr(qe(e)?.fingerprint)}function za(e,t,n){try{Qr(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 Ja(e){let t=lp({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Re,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,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 lp(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=qe(e.metaPath),n=t?.version===Re?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Ya(e,t){let n=rs(e);if(t===null){ye(n,{recursive:!0,force:!0});return}let r;try{r=Wa(n)}catch{return}for(let i of pp(r,t))ye(D(n,i),{force:!0})}function pp(e,t){let n=new Set(t.map(r=>`${pn(r)}.scip`));return e.filter(r=>!n.has(r))}function Ga(e,t){for(let n of t){let r=sr(e,n.language);Pt(b(r),{recursive:!0}),n.scipPath!==r&&kt(n.scipPath,r)}}async function gp(e,t){if(!Wt()){if(Hl()==="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 scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
306
|
+
`).get();return{version:3,tsconfig:n,files:Ti(t),db:r}}function kf(e){let t=qs();return{projectRoot:e.projectRoot,context:Os(e.projectRoot,e.configPath),symbolLookup:js(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Tf(e){let t=[],n=Be(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Df(e,i);t.push(...o.occurrences),tn(n,o)}return{occurrences:t,...n}}function Df(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Ws(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Ws(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=oe(e.projectRoot,t.fileName),s=[...$s(n.text)],c={tokens:s.filter(d=>d.start>=t.startOffset&&d.start<t.endOffset),tokenByStart:new Map(s.map(d=>[d.start,d])),tokenTextCounts:Mf(s),processedStarts:new Set};return Ff({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Ff(e){let t=[],n=Be();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Cf(e.sourceInfo.text,r.start))continue;let i=Vs(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!Bs(e.projectRoot,u.fileName));if(!a){Kr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=oe(e.projectRoot,a.fileName),c=Af(e.sourceFile,r.text,s);if(c){Kr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let d=Ms(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(d===null){Kr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}tc(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,d),e.tokenContext.processedStarts.add(r.start),Lf(t,e,r,i,s,d)}return{occurrences:t,...n}}function Cf(e,t){let n=e.lastIndexOf(`
|
|
307
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Af(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Ws(e,t,n){let r=Be();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:oe(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Kr(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function Xr(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function _f(e,t){let n=Xr(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Xr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Of(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...Xr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function jf(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return _f(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Lf(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Nf(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(tc(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function tc(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function Mf(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Nf(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let d of c.highlightSpans){let u=Gf(r,d.textSpan.start,o,i.text);u!==null&&s.push(u)}return s}function Gf(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Yr(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Kb(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??zf(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Yf(e),a=Date.now(),s=w();rn(v(o.outputScip),{recursive:!0}),rn(v(o.outputDb),{recursive:!0});let c=e.languages??Nn(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let d=an(o.metaPath),u=S("reindex.fingerprint",()=>Fi(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},d,e.changeJournal,hn(o.outputDb)),{languages:c.length}),l=u.fingerprint,p=u.mode==="delta"?e.changeJournal?.entries.filter(R=>R.kind!=="add").length??0:0,f=Math.max(0,(d?.files.length??0)-p);n(u.mode==="delta"?`Project fingerprint revalidated ${u.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${l.files.length} input(s)`:`Project fingerprint used full scan: ${u.reason}`);let g=await Wf({opts:e,paths:o,languages:c,fingerprint:l,onStatus:n}),y=g.snapshot,b=g.releaseBuildLock,C=Ec(e.trigger),F=me(_(v(o.outputDb),"cache-lifecycle.lock"),{waitMs:C?1e3:3e4});if(!F)throw b?.(),new Et(C?`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let M;try{M=await Se("reindex.lock",()=>Pg(_(v(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(R){throw F.release(),b?.(),R}let N=null,x=ao();try{u.mode==="delta"&&hn(o.outputDb)!==e.changeJournal?.baseGeneration&&(l=bn(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),u={mode:"full",fingerprint:l,reason:"accepted-generation-changed-before-lock"},y=void 0,b?.(),b=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),yr(o.outputDb,o.outputScip,o.metaPath);let R=Zf(v(o.outputDb));R.removed>0&&n(`Removed ${R.removed} abandoned reindex workspace(s)`);for(let W of R.errors)n(`Could not remove abandoned reindex workspace: ${W}`);let h=null,O=S("reindex.reuse-check",()=>(h=Kf({opts:e,paths:o,languages:c,fingerprint:l,start:a,monotonicStart:s,onStatus:n}),h),()=>({languages:c.length,reused:h!==null}));if(O){ic({snapshot:y,paths:o,projectRoot:t,fingerprint:l,onStatus:n});let W=An(o.outputDb,O);return W.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${W.reason}`),yn(t,v(o.outputDb)),O}await Se("reindex.scip-cli-ready",()=>hg(i,n));let $=Qf(o);N=$.runDir;let I,E=await Se("reindex.fresh",async()=>(I=await eg({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:$,fingerprint:l,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:x}),I),()=>({languages:c.length,reused:I?.reused,skipped:I?.skipped.length}));ic({snapshot:y,paths:o,projectRoot:t,fingerprint:l,onStatus:n});let T=An(o.outputDb,E);return T.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${T.reason}`),yn(t,v(o.outputDb)),E}catch(R){let h=dn({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:R instanceof Error?R.message:String(R)});Fc(o.metaPath,h);let O=io(o.outputDb,h);throw O.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${O.reason}`),R}finally{N&&qe(N,{recursive:!0,force:!0}),M(),F.release(),b?.()}}async function Wf(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Na(a,n.outputDb)&&nc(n.outputScip)===nc(_(v(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=xt(a),d=c?.clean?Wt(c,i):void 0;if(c&&!c.clean&&!oc(n))return rc({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:d,releaseBuildLock:void 0};if(!d)return{snapshot:void 0,releaseBuildLock:void 0};let u=re(d);if(u){if(!Hf(n,i))try{Ht({snapshot:d,manifest:u,targetCacheDir:v(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(p){o(`Shared generation attach failed; continuing locally: ${ve(p)}`)}return{snapshot:d,releaseBuildLock:void 0}}c&&!oc(n)&&rc({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let l=await Va(d);if(l.kind==="owner")return{snapshot:d,releaseBuildLock:l.release};if(l.kind==="generation-ready"){let p=re(d);if(p)try{Ht({snapshot:d,manifest:p,targetCacheDir:v(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${ve(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:d,releaseBuildLock:void 0}}function rc(e){let t=Ga(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Ht({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:v(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),Ba(t.snapshot,v(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ve(n)}`)}}function ic(e){if(e.snapshot)try{let t=xt(e.projectRoot),n=t?Wt(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=$a({snapshot:e.snapshot,sourceCacheDir:v(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=xt(e.projectRoot);return(i?Wt(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});Er(e.snapshot,v(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ve(t)}`)}}function Hf(e,t){if(!q(e.outputScip)||!q(e.outputDb)||Dc(e.metaPath,t)===null)return!1;let n=z(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function oc(e){if(!q(e.outputScip)||!q(e.outputDb)||!we(e.metaPath))return!1;let t=z(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ve(e){return e instanceof Error?e.message:String(e)}function zf(e){let t=e?.match(/--max[-_]old[-_]space[-_]size(?:=|\s+)(\d+)/u);if(!t)return;let n=Number.parseInt(t[1],10);return Number.isInteger(n)&&n>0?n:void 0}function Jf(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}function ei(e,t,n,r,i,o,a,s=!1){try{X(co({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function Yf(e){let t=e.outputScip??_(e.projectRoot,"index.scip"),n=e.outputDb??_(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:_(v(n),"meta.json")}}function Kf(e){let t=z(e.paths.outputDb,e.paths.metaPath),n=Dc(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!q(e.paths.outputScip)||!q(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=_t(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(ti("Accepted SQLite index",r)),null;X(de(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),ei(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),z(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Bt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(Ag(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Bt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=w()-e.monotonicStart,o=dn({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Fc(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:Xf(e.paths,e.languages,e.opts,e.fingerprint)}}function Xf(e,t,n,r){let i=ni(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:dt(i[o]),outputBytes:Pe(ri(e.outputDb,o)),durationMs:0}))}function Qf(e){let t=Vf(_(v(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:_(t,nn(e.outputScip)),tempOutputDb:_(t,nn(e.outputDb)),tempMetaPath:_(t,nn(e.metaPath))}}function Zf(e){let t=[],n;try{n=fc(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ve(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{qe(_(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ve(o)}`)}return{removed:r,errors:t}}async function eg(e){let t={...process.env,NODE_OPTIONS:Jf(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await Se("reindex.language-indexers",async()=>(n=await ng(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:d,incrementalTypeScript:u}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),tg({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=S("reindex.publish",()=>pg(e,i,o,a,s,d),{mode:"metadata-only",languages:i.length,reused:a.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:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let l=await Se("reindex.publish",()=>ug(e,t,i,o,a,s,d,u),{mode:u?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=l.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c,writeTelemetry:e.writeTelemetry}}function tg(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!q(e.run.paths.outputScip)||!q(e.run.paths.outputDb))return!1;let t=z(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 ng(e,t){let n=sg({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,projectFingerprint:e.fingerprint}),r=[],i=new Set;for(let[I,E]of n)E.reused&&(r.push({language:I,scipPath:E.scipPath}),i.add(I));for(let I of i)e.onStatus(`Reusing cached ${I} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=z(e.paths.outputDb,e.paths.metaPath),s=we(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",d=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),u,l=o&&!o.reused&&c?hs({projectRoot:e.projectRoot,cacheDir:v(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Ue(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Ue(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:d,previousSnapshot:an(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:I=>{u=I}}):null,p=new Set(l?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let I=e.languages.filter(E=>!i.has(E)&&!p.has(E));if(I.length>0){let E=I.length===1&&I[0]==="typescript"&&u?`: ${u}`:"";throw new Error(`Incremental indexing is unavailable for ${I.join(", ")}${E}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let f=l||i.has("typescript")?void 0:rg(e,n),{preparedRuns:g,skippedLanguages:y,languageOutputScipPaths:b}=yg({languages:e.languages.filter(I=>!i.has(I)&&!p.has(I)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:f?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),C=f?g.filter(I=>I.language!=="typescript"||f.missedProjectIds.has(I.id)):g,F=await xs(C,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(_i())for(let I of F)Oi({type:"span",name:`reindex.language-indexer.${I.id}`,durationMs:Math.round(I.durationMs),ok:!I.skipped,language:I.language,indexerCommand:I.command,outputBytes:I.outputBytes,measurement:"indexer-run-result"});let M=[];if(f){og(e.paths.outputDb,F,e.writeTelemetry);let I=b.typescript??e.tempPaths.tempOutputScip;M=ag({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:I,reusedProjects:f.reusedProjects,writeTelemetry:e.writeTelemetry})}let N=[...F,...M],{indexedOutputs:x}=bg(N,y),R=l?[{language:"typescript",scipPath:l.scipPath}]:[],h=[...r,...R,...x];Rg(h,y,e.languages,e.opts.allowPartial,e.onStatus);let O=l?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:l.scipPath,outputScipPath:l.scipPath,durationMs:l.durationMs,command:"watch-service:typescript-index",outputBytes:Pe(l.scipPath)??void 0,producedOutputBytes:Pe(l.affectedScipPath)??void 0}]:[],$=cg(n,[...F,...O],f?{outputDb:e.paths.outputDb,classification:f.classification}:void 0,u);return{indexedOutputs:h,skippedLanguages:y,reusedLanguages:[...i],languageFingerprints:dg(n,e.languages),shards:$,typescriptProjectShardContext:f?{projects:f.allProjects,fingerprints:f.fingerprints}:void 0,incrementalTypeScript:l??void 0}}function rg(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ye(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Yo(e.projectRoot,r),o=Ho(n.fingerprint.files,r),a=zo(r,i),s=Jo(r,o,a),c=we(e.paths.metaPath),u=ig(c,s,g=>q(sn(e.paths.outputDb,g))),l=[...u.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),f=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:u,reusedProjects:l,missedProjectIds:f}}function ig(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===Te&&fn(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(B(a)!==B(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function og(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=sn(e,i);rn(v(o),{recursive:!0}),Re(n,be(r.scipPath,o))}}function ag(e){return e.reusedProjects.map((t,n)=>{let r=sn(e.outputDb,t),i=Ue(e.tempOutputScip,"typescript-project-cached",n);return Re(e.writeTelemetry,be(r,i)),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Pe(i)??void 0}})}function sg(e){let t=we(e.paths.metaPath),n=ni(e.projectFingerprint,e.languages,e),r=t&&q(e.paths.outputDb)?_t(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=ri(e.paths.outputDb,o),s=n[o];if(!t){i.set(o,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:a});continue}if(t.version!==Te){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!fn(t).languageShardReuse||!t.languageFingerprints){i.set(o,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:a});continue}let c=t.languageFingerprints[o];if(!c){i.set(o,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:a});continue}if(!q(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let d=o==="typescript"?Dg(e.projectRoot,c):c;if(B(d)!==B(s)){i.set(o,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:a});continue}if(r?.state==="unavailable"||r?.state==="incomplete"&&r.affectedLanguages.includes(o)){i.set(o,{reused:!1,reason:ti("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function cg(e,t,n,r){let i=[];for(let[o,a]of e)a.reused&&i.push({id:o,language:o,reused:!0,strategy:"reused",fingerprint:dt(a.fingerprint),outputBytes:Pe(a.scipPath),durationMs:0});for(let o of t){let a=e.get(o.language),s=n&&o.id.startsWith("typescript:")?o.id.slice(11):null,c=s?n.classification.get(s):void 0;i.push({id:o.id,language:o.language,reused:!1,strategy:o.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??a?.reason??o.skipped?.reason,fallbackReason:o.language==="typescript"?r:void 0,fingerprint:c?dt(c.fingerprint):a?dt(a.fingerprint):"unknown",outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}if(n)for(let[o,a]of n.classification)a.reused&&i.push({id:`typescript:${o}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:dt(a.fingerprint),outputBytes:Pe(sn(n.outputDb,o)),durationMs:0});return i}function dt(e){return $f("sha256").update(B(e)).digest("hex").slice(0,16)}function Pe(e){try{return Bf(e).size}catch{return null}}function dg(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function ug(e,t,n,r,i,o,a,s){U(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,d=!1;c&&(d=S("reindex.publish.scip-output",()=>{let x=mg({run:e,indexedOutputs:n,incrementalTypeScript:s});return ac(e.paths.outputDb,x,e.writeTelemetry),sc(x,e.tempPaths.tempOutputScip,e.onStatus)}));let u=await Se("reindex.publish.sqlite-output",()=>xg({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:d,materializeFullFallback:async()=>{if(U(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return d;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Gr({cacheDir:v(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let x=n.map(R=>R.language==="typescript"?{language:R.language,scipPath:s.candidateScipPath}:R);return ac(e.paths.outputDb,x,e.writeTelemetry),d=sc(x,e.tempPaths.tempOutputScip,e.onStatus),d}}));U(e.opts.signal,"Reindex cancelled by its owner."),S("reindex.publish.auxiliary-documents",()=>{X(de(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),S("reindex.publish.runtime-boundaries",()=>{let x=s?.plan.mode==="full-project",R=s?.dependencyGraphUnchanged===!0;x?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):R&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),ei(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,R,R?void 0:x?s?.changedFiles:s?.affectedFiles,_(v(e.paths.outputDb),Ci),x)});let l=S("reindex.publish.sqlite-layout",()=>Yn(e.tempPaths.tempOutputDb,{analyze:lg(s,u.mode)}));l.added.length>0&&e.onStatus(`Added SQLite query indexes: ${l.added.join(", ")}`),l.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${l.removed.join(", ")}`),S("reindex.publish.coverage",()=>Sc(e,e.tempPaths.tempOutputDb,n.map(x=>x.language)));let p,f=null;u.mode==="incremental"&&s&&S("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let h=new Y({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=xn(h),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{h.close()}return}let x=null,R=null;try{x=S("reindex.publish.reference-fragments.open-candidate",()=>new Y({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),R=S("reindex.publish.reference-fragments.open-evidence",()=>new Y({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),p=s.dependencyGraphSnapshot?S("reindex.publish.reference-fragments.dependency-graph",()=>$i(x,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let h=new Set(s.deletedFiles),O=h.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([I])=>!h.has(I))),$=S("reindex.publish.reference-fragments.seed",()=>Ji(x,e.fingerprint,O,R,p,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${$.affectedFiles} affected document(s) and carried ${$.carriedFiles} unaffected document(s) forward.`),$.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${$.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(h){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${h instanceof Error?h.message:String(h)}.`)}finally{x?.close(),R?.close()}});let g=an(e.paths.metaPath),y=S("reindex.publish.affected-shadow",()=>u.mode==="incremental"&&s?vg(s,u.changedDocumentPaths):Ln({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:g,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),b=dn({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(x=>x.language),skipped:[...r]}),C=u.mode==="incremental"&&u.scipCompanion==="deferred",{metadata:F,pruneProjects:M}=hc({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:b});F.scipCompanion=C?"deferred":"current",S("reindex.publish.metadata",()=>{yc(e),bc(e.paths.outputDb,M),cn(e.tempPaths.tempMetaPath,F)});let N=S("reindex.publish.generation-handoff",()=>Vt({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:u.mode==="incremental"&&u.scipCompanion==="deferred",publication:u.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:u.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:u.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:u.patchDurationMs,scipCompanion:u.scipCompanion,...u.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:u.converterDurationMs,scipCompanion:"current",...u.fallbackReason?{fallbackReason:u.fallbackReason}:{}}}));return N.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${N.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),u.mode==="incremental"&&s&&S("reindex.publish.dependency-graph",()=>{let x=null;try{x=new Y({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,h=!1;if(s.dependencyGraphUnchanged){let O=xn(x),$=f&&O?Ai(x,"file-dependency-graph",f,O):0;h=$>0,e.onStatus(h?`Carried ${$} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?h=Gi(x,s.dependencyGraphSnapshot,R,p):Pt(x);s.dependencyGraphUnchanged||e.onStatus(h?`Carried the dependency graph forward by replacing ${R.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(R){e.onStatus(`Dependency graph carry-forward unavailable: ${R instanceof Error?R.message:String(R)}. The next graph consumer will rebuild it.`)}finally{x?.close()}}),S("reindex.publish.cleanup",()=>{ya(v(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),la(v(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),S("reindex.publish.shadow-telemetry",()=>mc(e.paths.outputDb,y,e.onStatus)),b}function lg(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}function pg(e,t,n,r,i,o){let a=an(e.paths.metaPath),s=null;try{Re(e.writeTelemetry,be(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=fo("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}X(de(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),ei(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Yn(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),Sc(e,e.paths.outputDb,t.map(p=>p.language)),s??=Ln({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let d=dn({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:l}=hc({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:d});return yc(e),bc(e.paths.outputDb,l),cn(e.paths.metaPath,u),Bt(e.paths.outputDb,e.paths.metaPath),mc(e.paths.outputDb,s,e.onStatus),d}function an(e){return We(we(e)?.fingerprint)}function mc(e,t,n){try{go(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 hc(e){let t=fg({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Te,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,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 yc(e){U(e.opts.signal,"Reindex cancelled by its owner.");let t=Di(e.projectRoot,e.fingerprint);if(B(t)===B(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>B(n.get(o))!==B(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Sc(e,t,n){let r=_t(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${ti("Candidate SQLite index",r)} Refusing to publish it.`)}function ti(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function fg(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=we(e.metaPath),n=t?.version===Te?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function bc(e,t){let n=Tc(e);if(t===null){qe(n,{recursive:!0,force:!0});return}let r;try{r=fc(n)}catch{return}for(let i of gg(r,t))qe(_(n,i),{force:!0})}function gg(e,t){let n=new Set(t.map(r=>`${Zn(r)}.scip`));return e.filter(r=>!n.has(r))}function mg(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];let n=z(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":we(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=Ue(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Gr({cacheDir:v(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function ac(e,t,n){for(let r of t){let i=ri(e,r.language);rn(v(i),{recursive:!0}),r.scipPath!==i&&Re(n,be(r.scipPath,i))}}async function hg(e,t){if(!Fn()){if(Uf()==="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 scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
292
308
|
To install the reviewed version, run: scip-query reindex --install-missing
|
|
293
|
-
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!
|
|
294
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
309
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Cn(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
310
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function yg(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Ue(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=Sg({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Rc(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Sg(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Qr({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??ye(e.projectRoot,e.typescriptProjects);return t.length===0?[Qr({...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)=>Qr({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Ue(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Qr(e){let t=Ft(e.language),n=Xe(t),r=Pn(t,e.projectRoot),i=e.trustProjectTools&&r?Bi(t,e.projectRoot):null,o=Oe(t);if(!i&&!o&&r){let u=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(!i&&!o&&!vn(t)){if(e.skipAutoInstall){let u=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Wr(t,e.onStatus)){let u=`${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}: ${u}`),{skipped:{language:e.language,reason:u}}}}let a=i?.canonicalPath??Oe(t);if(!a){let u=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}let{binary:s,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:a,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),d=Eo({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let u=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:a,binary:s,args:c,env:wn(t,e.env,a),...d===void 0?{}:{temporaryRootConfigContent:d},...i?{trustedProjectTool:i}:{}}}}function bg(e,t){let n=new Map;for(let i of e)if(i.skipped)Rc(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Un(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&gc(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Rc(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 Rg(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
295
311
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
296
312
|
`+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.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.
|
|
297
313
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
298
|
-
`))}function $a(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=fi(e.map(o=>o.scipPath),t);return Qa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ha(e[0].scipPath,t);return!1}function Sp(e){let t;if(bp(e)){let i=D(e.run.tempPaths.runDir,"typescript-affected.db");try{Xa(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Va(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Ii({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),ye(i,{force:!0}),ye(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 Va(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function bp(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!G(e.run.paths.outputDb)||!G(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 Rp(e,t){let n=x(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:x()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Kt(e.plan,o,e.projectFileCount)}}function Va(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!G(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Xa(e,r);let o=Wt();if(!o)throw new Error("scip CLI is not available");Vl(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Xa(e,t){let n=pi(e);Qa(n,t)}function Qa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Be(e,t,n){let r=Wl(e)||".scip",i=vt(e,r);return D(b(e),`${i}.${n+1}.${t}${r}`)}async function xp(e,t){for(let n=0;n<2;n++){let r=Ip(e,t);if(r)return r;let i=vp(e);if(i&&ts(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await wp(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${Se(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${b(e)}; refusing to steal an active lock.`);let a=At(e,{parseLegacy:wt});if(!yr(e,a,{parseLegacy:wt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${b(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${b(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${b(e)}.`)}function Ip(e,t){let n=J(process.pid),r=He(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:wt});if(r.kind==="acquired"&&r.reclaimed){let i=Za(r.reclaimed,e);i&&ts(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${b(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function vp(e){return Za(At(e,{parseLegacy:wt}),e)}var wt=e=>{let t=es(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function Za(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:b(t),startedAt:e.record.startedAt,trigger:n.trigger}}return es(e.parsed,t)}function es(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=mr(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:b(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function ts(e,t){return e?.kind==="manual-cli"&&Pp(t?.trigger)}function Pp(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function wp(e){return!Y(e.pid)||(or(e),Ba(e,"SIGTERM"),await qa(e,2e3))?!0:(or(e),Ba(e,"SIGKILL"),qa(e,1e3))}function Ba(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!Y(e.pid))return;or(e)}try{process.kill(e.pid,t)}catch{}}async function qa(e,t){let n=x()+t;for(;x()<n;){if(Ua(e))return!0;await kp(50)}return Ua(e)}function or(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=J(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!xe(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Ua(e){if(!Y(e.pid))return!0;if(!e.processIdentity)return!1;let t=J(e.pid);return t!==null&&!xe(e.processIdentity,t)}function kp(e){return new Promise(t=>setTimeout(t,e))}function ns(e,t,n){return Object.fromEntries(t.map(r=>{let i=it(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ir(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Ep(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Tp(n),...o,clojureConfigPath:a,files:Qe(e,{language:r,markerFiles:i})}]}))}function Ep(e){return e?.trim()||void 0}function Tp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function sr(e,t){return D(b(e),"language-indexes",`${t}.scip`)}function rs(e){return D(b(e),"language-indexes","typescript-projects")}function Et(e,t){return D(rs(e),`${pn(t)}.scip`)}function qe(e){try{return Dt(z(k(e,"reindex metadata")))}catch{return null}}function is(e,t){try{let n=z(k(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&fr(r)&&H(r.fingerprint)===H(t)&&H([...r.indexedLanguages??[]].sort())===H(t.languages)}catch{return!1}}function cr(e,t){j(e,t,{spacing:2,trailingNewline:!0})}function os(e,t){try{let n=Dt(z(k(e,"reindex metadata")));if(!n)return;cr(e,{...n,lastRefresh:t})}catch{}}function Tt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:x()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function H(e){return JSON.stringify(e)}export{di as INDEXER_CONFIGS,zr as augmentAuxiliaryDocuments,Il as augmentVueResolvedReferences,vl as augmentVueResolvedReferencesAsync,Q as auxiliaryDocumentsAugmentationStage,Ee as describeIndexerBinary,Qt as detectLanguages,it as getIndexerConfig,Mt as getIndexerExecutionEnv,Ot as isBinaryAvailable,Ct as isIndexerInstalled,on as mergeScipFiles,rn as mergeScipIndexes,oy as reindex,pe as resolveIndexerBinary,jt as resolveProjectLocalIndexerBinary,q as runPostIndexAugmentation,Xn as tryInstallIndexer,Ht as tryInstallScipCli,_a as vueResolvedReferencesAugmentationStage};
|
|
314
|
+
`))}function sc(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Fo(e.map(o=>o.scipPath),t);return Ic(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&gc(e[0].scipPath,t);return!1}async function xg(e){let t;if(Ig(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,d]of i.entries()){let u=_(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);xc(d.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${d.affectedFiles.length-d.deletedFiles.length} emitted, ${d.deletedFiles.length} removed) to SQLite...`);let l=performance.now();await cc(d.scipPath,u,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-l,kt(e.run.writeTelemetry,Pe(u)??0);let p=Mo({previousDbPath:e.run.paths.outputDb,miniDbPath:u,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:d.affectedFiles,deletedFiles:d.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=p.durationMs;for(let f of p.changedDocumentPaths)o.add(f);qe(u,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if(U(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),qe(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await cc(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Ig(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!q(e.run.paths.outputDb)||!q(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 vg(e,t){let n=w(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:w()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:jn(e.plan,o,e.projectFileCount)}}async function cc(e,t,n,r,i=!1,o){if(U(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!q(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||xc(e,r);let a=Fn();if(!a)throw new Error("scip CLI is not available");let s=await wt({command:a,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:o});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}catch(a){U(o,"Reindex cancelled by its owner.");let s=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:a})}}function xc(e,t){let n=To(e);Ic(n,t)}function Ic(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Ue(e,t,n){let r=qf(e)||".scip",i=nn(e,r);return _(v(e),`${i}.${n+1}.${t}${r}`)}async function Pg(e,t){for(let n=0;n<2;n++){let r=wg(e,t);if(r)return r;let i=Eg(e);if(i&&wc(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await kg(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${ve(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${v(e)}; refusing to steal an active lock.`);let a=gn(e,{parseLegacy:on});if(!fi(e,a,{parseLegacy:on}))throw new Error(`Reindex lock ownership changed before preemption completed for ${v(e)}.`);continue}throw new Et(`Another scip-query reindex is already running for ${v(e)}.`)}throw new Et(`Could not acquire scip-query reindex lock for ${v(e)}.`)}function wg(e,t){let n=K(process.pid),r=mt(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:on});if(r.kind==="acquired"&&r.reclaimed){let i=vc(r.reclaimed,e);i&&wc(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${v(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Eg(e){return vc(gn(e,{parseLegacy:on}),e)}var on=e=>{let t=Pc(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function vc(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Pc(e.parsed,t)}function Pc(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=ui(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function wc(e,t){return e?.kind==="manual-cli"&&Ec(t?.trigger)}function Ec(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function kg(e){return!se(e.pid)||(Zr(e),dc(e,"SIGTERM"),await uc(e,2e3))?!0:(Zr(e),dc(e,"SIGKILL"),uc(e,1e3))}function dc(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!se(e.pid))return;Zr(e)}try{process.kill(e.pid,t)}catch{}}async function uc(e,t){let n=w()+t;for(;w()<n;){if(lc(e))return!0;await Tg(50)}return lc(e)}function Zr(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=K(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!ze(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function lc(e){if(!se(e.pid))return!0;if(!e.processIdentity)return!1;let t=K(e.pid);return t!==null&&!ze(e.processIdentity,t)}function Tg(e){return new Promise(t=>setTimeout(t,e))}function ni(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?Ei(n.typescriptProjects):[],o=r==="clojure"?Fg(n.clojureConfigPath):void 0,a=[...Ft(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Cg(n),...s,clojureConfigPath:o,files:e.files.filter(c=>si(c.path,r,a)).map(c=>kc(c,r))}]}))}function kc(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function Dg(e,t){let n=We(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ye(e,n.typescriptProjects):["."],i=Ce(r);return{...n,files:n.files.filter(o=>!Ae(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??It(e,o.path,o.hash);return kc(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function Fg(e){return e?.trim()||void 0}function Cg(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function ri(e,t){return _(v(e),"language-indexes",`${t}.scip`)}function Tc(e){return _(v(e),"language-indexes","typescript-projects")}function sn(e,t){return _(Tc(e),`${Zn(t)}.scip`)}function we(e){try{return ft(te(L(e,"reindex metadata")))}catch{return null}}function Dc(e,t){try{let n=te(L(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!di(r)||B([...r.indexedLanguages??[]].sort())!==B(t.languages)?null:B(r.fingerprint)===B(t)?"exact":B(pc(r.fingerprint))===B(pc(t))?"operational-config-compatible":null}catch{return null}}function pc(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function Ag(e,t,n,r){let i=ft(te(L(e,"reindex metadata")));i&&cn(e,{...i,fingerprint:t,...i.version===Te?{languageFingerprints:ni(t,n,r)}:{}})}function cn(e,t){H(e,t,{spacing:2,trailingNewline:!0})}function Fc(e,t){try{let n=ft(te(L(e,"reindex metadata")));if(!n)return;cn(e,{...n,lastRefresh:t})}catch{}}function dn(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:w()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function B(e){return JSON.stringify(e)}export{wo as INDEXER_CONFIGS,so as augmentAuxiliaryDocuments,xf as augmentVueResolvedReferences,If as augmentVueResolvedReferencesAsync,de as auxiliaryDocumentsAugmentationStage,Xe as describeIndexerBinary,Nn as detectLanguages,Ft as getIndexerConfig,wn as getIndexerExecutionEnv,In as isBinaryAvailable,vn as isIndexerInstalled,Un as mergeScipFiles,qn as mergeScipIndexes,Kb as reindex,Oe as resolveIndexerBinary,Pn as resolveProjectLocalIndexerBinary,X as runPostIndexAugmentation,Wr as tryInstallIndexer,Cn as tryInstallScipCli,Xs as vueResolvedReferencesAugmentationStage};
|
|
299
315
|
//# sourceMappingURL=reindex.js.map
|