scip-query 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (586) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +255 -884
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-CI3O6PQG.js +2 -0
  5. package/dist/call-graph-6QTUTXH7.js +2 -0
  6. package/dist/call-graph-evidence-lZa2dwQA.d.ts +11 -0
  7. package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
  8. package/dist/chunk-26CT72HM.js +2 -0
  9. package/dist/{chunk-7PIO7NKH.js → chunk-2COFMIVK.js} +2 -2
  10. package/dist/chunk-2H4IAJHO.js +2 -0
  11. package/dist/chunk-2I3RSUWX.js +16 -0
  12. package/dist/chunk-2RP27XLR.js +2 -0
  13. package/dist/chunk-2ZBMOQGG.js +3 -0
  14. package/dist/{chunk-HX4GQPZP.js → chunk-32A42O5B.js} +3 -3
  15. package/dist/chunk-35ELD3RM.js +2 -0
  16. package/dist/chunk-35IW3P4H.js +2 -0
  17. package/dist/{chunk-DQGFVPUV.js → chunk-3653GTR7.js} +3 -3
  18. package/dist/chunk-3EX7DNBC.js +2 -0
  19. package/dist/chunk-3FQ3KMCD.js +2 -0
  20. package/dist/{chunk-5E4WNAVD.js → chunk-3PII3JI5.js} +2 -2
  21. package/dist/chunk-3TNRNKAT.js +2 -0
  22. package/dist/chunk-3VLJ2DCA.js +2 -0
  23. package/dist/{chunk-XSRF6Q77.js → chunk-46JLFIGA.js} +2 -2
  24. package/dist/chunk-4DCKBY6T.js +5 -0
  25. package/dist/chunk-4EXFZP6H.js +2 -0
  26. package/dist/chunk-4IIMPWMR.js +29 -0
  27. package/dist/chunk-4ILHWBYF.js +2 -0
  28. package/dist/chunk-4N6QSEMZ.js +10 -0
  29. package/dist/chunk-4OE2JO6I.js +2 -0
  30. package/dist/{chunk-7BAVHKMJ.js → chunk-4S4DF62J.js} +9 -9
  31. package/dist/chunk-4UUCUASK.js +554 -0
  32. package/dist/chunk-5236NQV3.js +2 -0
  33. package/dist/chunk-54EOGFBR.js +2 -0
  34. package/dist/{chunk-LY4WC4AD.js → chunk-5H7IWVXJ.js} +2 -2
  35. package/dist/chunk-5IZTXSOL.js +117 -0
  36. package/dist/{chunk-AZJQQKDD.js → chunk-5SE323LF.js} +2 -2
  37. package/dist/chunk-5ZJH6DDE.js +2 -0
  38. package/dist/chunk-63MBA7EG.js +3 -0
  39. package/dist/chunk-6BJ7SOY7.js +2 -0
  40. package/dist/chunk-6GJAP4OE.js +2 -0
  41. package/dist/chunk-6IEVHGWG.js +26 -0
  42. package/dist/chunk-6SWA6B24.js +7 -0
  43. package/dist/chunk-6T7H2AFY.js +3 -0
  44. package/dist/chunk-73Z33VFI.js +4 -0
  45. package/dist/chunk-7COHFNJK.js +38 -0
  46. package/dist/chunk-7HU2IJ2T.js +3 -0
  47. package/dist/chunk-7IOAZRVL.js +60 -0
  48. package/dist/chunk-7KCZELVM.js +2 -0
  49. package/dist/chunk-7PPYXENX.js +2 -0
  50. package/dist/chunk-7TWP3MCP.js +2 -0
  51. package/dist/chunk-AA7K3XLM.js +21 -0
  52. package/dist/chunk-AJVMVE7X.js +7 -0
  53. package/dist/chunk-ANWGXPPN.js +4 -0
  54. package/dist/chunk-APLKXICZ.js +3 -0
  55. package/dist/{chunk-JDOEX4E6.js → chunk-AQDWTCDC.js} +2 -2
  56. package/dist/chunk-AUP6YI5M.js +2 -0
  57. package/dist/chunk-B7ECWJAZ.js +2 -0
  58. package/dist/{chunk-ZHXX42OH.js → chunk-BATIVRU2.js} +4 -4
  59. package/dist/chunk-BBEDPVPB.js +4 -0
  60. package/dist/chunk-BBWPOMGU.js +2 -0
  61. package/dist/chunk-BD6CV7PN.js +2 -0
  62. package/dist/{chunk-XKWKXZKW.js → chunk-BHE44MHT.js} +2 -2
  63. package/dist/chunk-BOJ5SVE2.js +2 -0
  64. package/dist/chunk-BZYSGZRK.js +2 -0
  65. package/dist/chunk-CA5RE6H7.js +2 -0
  66. package/dist/chunk-CKDOY6JA.js +2 -0
  67. package/dist/chunk-CN2WGM7D.js +2 -0
  68. package/dist/chunk-COTMS5KM.js +3 -0
  69. package/dist/chunk-CSDDOUA4.js +3 -0
  70. package/dist/chunk-CT5SI2I4.js +2 -0
  71. package/dist/chunk-D5EKVZPI.js +2 -0
  72. package/dist/{chunk-FKSELJQF.js → chunk-D5W4UZY5.js} +2 -2
  73. package/dist/{chunk-RUJURYSV.js → chunk-DEUGHURX.js} +2 -2
  74. package/dist/chunk-DHKBIOXF.js +7 -0
  75. package/dist/chunk-DMQ7ZKJG.js +81 -0
  76. package/dist/chunk-DMUGTKMD.js +2 -0
  77. package/dist/chunk-DOPCR5BY.js +2 -0
  78. package/dist/chunk-DRENNWRG.js +2 -0
  79. package/dist/chunk-E4EJBGDZ.js +2 -0
  80. package/dist/chunk-E7BJXRNV.js +2 -0
  81. package/dist/chunk-EA4SH4U5.js +5 -0
  82. package/dist/{chunk-L7AW2QB5.js → chunk-EKZRF57O.js} +2 -2
  83. package/dist/chunk-ELNRLMC5.js +29 -0
  84. package/dist/chunk-F4FNK44D.js +2 -0
  85. package/dist/chunk-F7WQ337U.js +308 -0
  86. package/dist/chunk-FEQIQ26E.js +2 -0
  87. package/dist/chunk-FGB567HK.js +23 -0
  88. package/dist/chunk-FHV7NMFU.js +29 -0
  89. package/dist/chunk-FN6EJM6Q.js +2 -0
  90. package/dist/chunk-FTSQNONX.js +2 -0
  91. package/dist/chunk-FUG6RPYY.js +6 -0
  92. package/dist/chunk-G2F6T5BV.js +2 -0
  93. package/dist/chunk-G6OGPXJW.js +9 -0
  94. package/dist/chunk-GFLTPNWV.js +3 -0
  95. package/dist/chunk-GTDP2SKQ.js +2 -0
  96. package/dist/chunk-H46QMB7E.js +2 -0
  97. package/dist/chunk-H5EXS3HM.js +2 -0
  98. package/dist/chunk-HEOMG7IM.js +8 -0
  99. package/dist/chunk-HG5YI7PV.js +2 -0
  100. package/dist/{chunk-7SQQWSY3.js → chunk-HGKEAP7F.js} +2 -2
  101. package/dist/chunk-HUZNZ3H2.js +2 -0
  102. package/dist/chunk-HWLCBKFE.js +2 -0
  103. package/dist/chunk-I3U2FN2T.js +13 -0
  104. package/dist/{chunk-JAYYFEQY.js → chunk-I7PFL5P3.js} +2 -2
  105. package/dist/{chunk-2HPVVXM5.js → chunk-ICHBVITH.js} +2 -2
  106. package/dist/chunk-ICUQONOG.js +38 -0
  107. package/dist/chunk-IDPLC3FI.js +5 -0
  108. package/dist/{chunk-A73XVBCR.js → chunk-IGKKTHJR.js} +2 -2
  109. package/dist/chunk-IOKWFRFQ.js +4 -0
  110. package/dist/chunk-IPAL6DP2.js +3 -0
  111. package/dist/chunk-IUJ3ZFEE.js +7 -0
  112. package/dist/chunk-IXJ26KJJ.js +16 -0
  113. package/dist/chunk-IYV2YBHM.js +2 -0
  114. package/dist/chunk-JVZNWJBH.js +2 -0
  115. package/dist/chunk-K5MZYZV7.js +3 -0
  116. package/dist/{chunk-3G66UZBH.js → chunk-KFK7GF5C.js} +2 -2
  117. package/dist/chunk-KTRGJLY7.js +18 -0
  118. package/dist/chunk-KW6B5OL4.js +2 -0
  119. package/dist/chunk-KWARB5FZ.js +2 -0
  120. package/dist/chunk-LHTT5C3Z.js +2 -0
  121. package/dist/chunk-LPGDO2XA.js +3 -0
  122. package/dist/chunk-LXLD46LH.js +21 -0
  123. package/dist/chunk-MEI3PTUK.js +2 -0
  124. package/dist/chunk-MJNV7OCG.js +5 -0
  125. package/dist/chunk-MO226P4Q.js +4 -0
  126. package/dist/{chunk-3CLX5EOX.js → chunk-MOBF2GH6.js} +2 -2
  127. package/dist/chunk-MXNGIEPU.js +3 -0
  128. package/dist/chunk-MYUKI5VN.js +4 -0
  129. package/dist/{chunk-TFRAYKN6.js → chunk-N5C65OFK.js} +2 -2
  130. package/dist/{chunk-PXY7F6Y4.js → chunk-O2RM7E7L.js} +5 -5
  131. package/dist/chunk-OFUBXBYX.js +3 -0
  132. package/dist/chunk-OFY4HTMI.js +2 -0
  133. package/dist/chunk-OIRWZIYL.js +38 -0
  134. package/dist/chunk-OIVZ7PW6.js +438 -0
  135. package/dist/chunk-ORBKAUCH.js +4 -0
  136. package/dist/chunk-OUB4J26T.js +2 -0
  137. package/dist/chunk-OVPS2ILI.js +20 -0
  138. package/dist/chunk-PHSPBQM6.js +5 -0
  139. package/dist/{chunk-JVYA47YU.js → chunk-PIZY2GX6.js} +2 -2
  140. package/dist/chunk-PNISDVYC.js +3 -0
  141. package/dist/chunk-PQOL42AW.js +2 -0
  142. package/dist/chunk-PUVZNFVY.js +11 -0
  143. package/dist/chunk-PZEI2TVL.js +4 -0
  144. package/dist/{chunk-ZK26BAQL.js → chunk-Q2J2VZZT.js} +2 -2
  145. package/dist/chunk-Q7HB7BFJ.js +2 -0
  146. package/dist/{chunk-ZTETIQ35.js → chunk-QBANU5BQ.js} +2 -2
  147. package/dist/chunk-QD7IFBCR.js +10 -0
  148. package/dist/chunk-QDCCHMVZ.js +2 -0
  149. package/dist/chunk-QLQBZOJH.js +3 -0
  150. package/dist/{chunk-PQCI4SQX.js → chunk-QXR5QPSF.js} +2 -2
  151. package/dist/chunk-R2MOKIVO.js +2 -0
  152. package/dist/{chunk-EN3O7VJA.js → chunk-RFWAUHVW.js} +2 -2
  153. package/dist/chunk-RGCJ4646.js +16 -0
  154. package/dist/{chunk-BPAPWKP6.js → chunk-S3RTPPLQ.js} +8 -8
  155. package/dist/chunk-S73HBCGI.js +11 -0
  156. package/dist/chunk-SDPA5DKN.js +210 -0
  157. package/dist/chunk-SEUJVWT2.js +3 -0
  158. package/dist/chunk-SF7X6QNW.js +2 -0
  159. package/dist/chunk-SKUMCCC5.js +2 -0
  160. package/dist/chunk-SSSJO4RG.js +2 -0
  161. package/dist/chunk-SWFAFA4G.js +49 -0
  162. package/dist/chunk-SYUNTKO2.js +2 -0
  163. package/dist/chunk-T6FRID7Y.js +3 -0
  164. package/dist/chunk-TGWNNMPF.js +3 -0
  165. package/dist/chunk-TM5XEDDR.js +4 -0
  166. package/dist/chunk-TNOHGHZQ.js +2 -0
  167. package/dist/chunk-U2GPTA5U.js +3 -0
  168. package/dist/{chunk-SXP2MBJH.js → chunk-U7DR7MJD.js} +2 -2
  169. package/dist/chunk-U7LRSQG6.js +3 -0
  170. package/dist/chunk-UL4VJUMD.js +2 -0
  171. package/dist/chunk-UNORWZIJ.js +16 -0
  172. package/dist/chunk-UQ7XPRWU.js +2 -0
  173. package/dist/{chunk-6SHPK5ZE.js → chunk-URMZLV2N.js} +2 -2
  174. package/dist/chunk-URTX2BEA.js +6 -0
  175. package/dist/chunk-UZFCZ7SJ.js +2 -0
  176. package/dist/{chunk-KMKTIO2G.js → chunk-V7LQZTTZ.js} +2 -2
  177. package/dist/chunk-VETXXOYU.js +3 -0
  178. package/dist/chunk-VGRUM7JI.js +3 -0
  179. package/dist/{chunk-WXZLAAWK.js → chunk-VNKYRJKN.js} +2 -2
  180. package/dist/chunk-VWLIOEEF.js +11 -0
  181. package/dist/chunk-WB6LGCFB.js +6 -0
  182. package/dist/{chunk-W4ETQAXM.js → chunk-WK4FD4PG.js} +2 -2
  183. package/dist/{chunk-O64IZ6UX.js → chunk-WKPZCQLI.js} +2 -2
  184. package/dist/chunk-WSG3DK5H.js +2 -0
  185. package/dist/chunk-WULAPQUD.js +38 -0
  186. package/dist/chunk-WZQFY5S7.js +4 -0
  187. package/dist/chunk-X434XZAI.js +2 -0
  188. package/dist/chunk-X7PJJYKX.js +29 -0
  189. package/dist/chunk-XDAUYDFT.js +2 -0
  190. package/dist/chunk-XITQLISP.js +2 -0
  191. package/dist/chunk-XRXCANFQ.js +4 -0
  192. package/dist/chunk-XVDMJMES.js +3 -0
  193. package/dist/chunk-XXJ7WL3F.js +35 -0
  194. package/dist/chunk-Y4XQ7LES.js +9 -0
  195. package/dist/chunk-YIEFEPG6.js +16 -0
  196. package/dist/chunk-YRVERHJR.js +49 -0
  197. package/dist/{chunk-CJST5ETY.js → chunk-YUFWLWIC.js} +2 -2
  198. package/dist/chunk-YUKYB54I.js +1 -0
  199. package/dist/chunk-Z3GCK3PD.js +3 -0
  200. package/dist/chunk-ZBNL3QCY.js +4 -0
  201. package/dist/chunk-ZD3Z54IW.js +2 -0
  202. package/dist/chunk-ZDVDSDFG.js +4 -0
  203. package/dist/{chunk-32LVLCLN.js → chunk-ZHSARYVS.js} +3 -3
  204. package/dist/{chunk-BDCC2NPY.js → chunk-ZW44MCJM.js} +2 -2
  205. package/dist/{chunk-N5W4YZMK.js → chunk-ZYREOING.js} +2 -2
  206. package/dist/cli-main.js +8 -0
  207. package/dist/cli.js +1 -3
  208. package/dist/code-CczEvHui.d.ts +121 -0
  209. package/dist/code-EQL6ZBLH.js +2 -0
  210. package/dist/code-result-json-6E4J6LGZ.js +2 -0
  211. package/dist/command-descriptors-QH3G2OVD.js +346 -0
  212. package/dist/{config-types-jVM3D7MA.d.ts → config-types-Cm-VSEBb.d.ts} +189 -23
  213. package/dist/dataflow-2BLMUZBP.js +2 -0
  214. package/dist/{db-B5PM5yNk.d.ts → db-LKJXAlNS.d.ts} +1 -1
  215. package/dist/dependence-slice-MGAJDZXB.js +2 -0
  216. package/dist/deps-GQMUYVKW.js +2 -0
  217. package/dist/direct-navigation-6RUJKLAV.js +3 -0
  218. package/dist/entry-map-V2NQP5JU.js +2 -0
  219. package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
  220. package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
  221. package/dist/file-kind-BKCVMNUf.d.ts +10 -0
  222. package/dist/files-VM53I4IU.js +2 -0
  223. package/dist/graph-evidence-CbUPCSKV.d.ts +126 -0
  224. package/dist/graph-exploration-contract-CqDsnPQL.d.ts +7 -0
  225. package/dist/{health-Do5TKSJI.d.ts → health-Wl5G_LRt.d.ts} +33 -34
  226. package/dist/hierarchy-D553WRSZ.js +2 -0
  227. package/dist/imports-DOZAJWLW.js +2 -0
  228. package/dist/index.d.ts +4 -31
  229. package/dist/index.js +1 -1
  230. package/dist/members-HE67475K.js +2 -0
  231. package/dist/methods-K5JK4PPH.js +2 -0
  232. package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
  233. package/dist/output-continuation-command-LKBUTNRL.js +3 -0
  234. package/dist/output-pagination-VAWOGX4R.js +19 -0
  235. package/dist/postinstall.js +1 -1
  236. package/dist/project-reindex-4ARU6QCM.js +3 -0
  237. package/dist/queries/affected.d.ts +22 -4
  238. package/dist/queries/affected.js +1 -1
  239. package/dist/queries/anchors.d.ts +123 -0
  240. package/dist/queries/anchors.js +2 -0
  241. package/dist/queries/architecture.d.ts +3 -2
  242. package/dist/queries/architecture.js +1 -1
  243. package/dist/queries/bottlenecks.d.ts +26 -7
  244. package/dist/queries/bottlenecks.js +1 -1
  245. package/dist/queries/by-kind.d.ts +2 -2
  246. package/dist/queries/by-kind.js +1 -1
  247. package/dist/queries/call-graph.d.ts +17 -3
  248. package/dist/queries/call-graph.js +1 -1
  249. package/dist/queries/change-surface.d.ts +2 -2
  250. package/dist/queries/change-surface.js +1 -1
  251. package/dist/queries/cleanup-plan.d.ts +2 -2
  252. package/dist/queries/cleanup-plan.js +1 -1
  253. package/dist/queries/co-change.d.ts +2 -2
  254. package/dist/queries/co-change.js +1 -1
  255. package/dist/queries/code.d.ts +5 -26
  256. package/dist/queries/code.js +1 -1
  257. package/dist/queries/complexity-hotspots.d.ts +2 -2
  258. package/dist/queries/complexity-hotspots.js +1 -1
  259. package/dist/queries/complexity.d.ts +2 -2
  260. package/dist/queries/complexity.js +1 -1
  261. package/dist/queries/context.d.ts +145 -0
  262. package/dist/queries/context.js +2 -0
  263. package/dist/queries/convergence.d.ts +2 -2
  264. package/dist/queries/convergence.js +1 -1
  265. package/dist/queries/coupling.d.ts +8 -3
  266. package/dist/queries/coupling.js +1 -1
  267. package/dist/queries/cycles.d.ts +34 -7
  268. package/dist/queries/cycles.js +1 -1
  269. package/dist/queries/dataflow.d.ts +40 -14
  270. package/dist/queries/dataflow.js +1 -1
  271. package/dist/queries/dead.d.ts +2 -2
  272. package/dist/queries/dead.js +1 -1
  273. package/dist/queries/decorative-checkers.d.ts +3 -3
  274. package/dist/queries/decorative-checkers.js +1 -1
  275. package/dist/queries/deep-chains.d.ts +4 -38
  276. package/dist/queries/deep-chains.js +1 -1
  277. package/dist/queries/dependence-slice.d.ts +47 -0
  278. package/dist/queries/dependence-slice.js +2 -0
  279. package/dist/queries/dependency-depth.d.ts +49 -0
  280. package/dist/queries/dependency-depth.js +2 -0
  281. package/dist/queries/deps.d.ts +4 -2
  282. package/dist/queries/deps.js +1 -1
  283. package/dist/queries/diff-impact.d.ts +3 -3
  284. package/dist/queries/diff-impact.js +1 -1
  285. package/dist/queries/doc-drift.d.ts +4 -4
  286. package/dist/queries/doc-drift.js +1 -1
  287. package/dist/queries/drift.d.ts +2 -2
  288. package/dist/queries/drift.js +1 -1
  289. package/dist/queries/duplicate-bodies.d.ts +2 -2
  290. package/dist/queries/duplicate-bodies.js +1 -1
  291. package/dist/queries/entry-map.d.ts +121 -0
  292. package/dist/queries/entry-map.js +2 -0
  293. package/dist/queries/evidence.d.ts +70 -0
  294. package/dist/queries/evidence.js +2 -0
  295. package/dist/queries/extract-candidates.d.ts +2 -2
  296. package/dist/queries/extract-candidates.js +1 -1
  297. package/dist/queries/fan.d.ts +18 -5
  298. package/dist/queries/fan.js +1 -1
  299. package/dist/queries/files.d.ts +2 -2
  300. package/dist/queries/files.js +1 -1
  301. package/dist/queries/health.d.ts +4 -3
  302. package/dist/queries/health.js +1 -1
  303. package/dist/queries/hierarchy.d.ts +5 -3
  304. package/dist/queries/hierarchy.js +1 -1
  305. package/dist/queries/hotspots.d.ts +11 -5
  306. package/dist/queries/hotspots.js +1 -1
  307. package/dist/queries/imports.d.ts +2 -2
  308. package/dist/queries/imports.js +1 -1
  309. package/dist/queries/incomplete-migration.d.ts +4 -4
  310. package/dist/queries/incomplete-migration.js +1 -1
  311. package/dist/queries/index.d.ts +56 -136
  312. package/dist/queries/index.js +1 -1
  313. package/dist/queries/isolated.d.ts +2 -2
  314. package/dist/queries/isolated.js +1 -1
  315. package/dist/queries/locality-candidates.d.ts +2 -2
  316. package/dist/queries/locality-candidates.js +1 -1
  317. package/dist/queries/members.d.ts +2 -2
  318. package/dist/queries/members.js +1 -1
  319. package/dist/queries/methods.d.ts +2 -2
  320. package/dist/queries/methods.js +1 -1
  321. package/dist/queries/not-implemented.d.ts +3 -3
  322. package/dist/queries/not-implemented.js +1 -1
  323. package/dist/queries/outline.d.ts +2 -2
  324. package/dist/queries/outline.js +1 -1
  325. package/dist/queries/passthrough-candidates.d.ts +5 -9
  326. package/dist/queries/passthrough-candidates.js +1 -1
  327. package/dist/queries/plan-context.d.ts +27 -64
  328. package/dist/queries/plan-context.js +1 -1
  329. package/dist/queries/react-component-duplicates.d.ts +2 -2
  330. package/dist/queries/react-component-duplicates.js +1 -1
  331. package/dist/queries/react-hook-candidates.d.ts +2 -2
  332. package/dist/queries/react-hook-candidates.js +1 -1
  333. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  334. package/dist/queries/react-large-component-pressure.js +1 -1
  335. package/dist/queries/recent-duplicates.d.ts +2 -2
  336. package/dist/queries/recent-duplicates.js +1 -1
  337. package/dist/queries/redundant-reexports.d.ts +2 -2
  338. package/dist/queries/redundant-reexports.js +1 -1
  339. package/dist/queries/reference-neighborhood.d.ts +4 -0
  340. package/dist/queries/reference-neighborhood.js +2 -0
  341. package/dist/queries/reference-reachability.d.ts +48 -0
  342. package/dist/queries/reference-reachability.js +2 -0
  343. package/dist/queries/refs.d.ts +2 -2
  344. package/dist/queries/refs.js +1 -1
  345. package/dist/queries/self-audit.d.ts +2 -2
  346. package/dist/queries/self-audit.js +1 -1
  347. package/dist/queries/similar-chains.d.ts +2 -2
  348. package/dist/queries/similar-chains.js +1 -1
  349. package/dist/queries/similar-files.d.ts +2 -2
  350. package/dist/queries/similar-files.js +1 -1
  351. package/dist/queries/similar-signatures.d.ts +2 -2
  352. package/dist/queries/similar-signatures.js +1 -1
  353. package/dist/queries/similar.d.ts +2 -2
  354. package/dist/queries/similar.js +1 -1
  355. package/dist/queries/slice.d.ts +3 -36
  356. package/dist/queries/slice.js +1 -1
  357. package/dist/queries/source-inspection.d.ts +209 -0
  358. package/dist/queries/source-inspection.js +2 -0
  359. package/dist/queries/source-search.d.ts +13 -0
  360. package/dist/queries/source-search.js +2 -0
  361. package/dist/queries/stale-abstractions.d.ts +2 -2
  362. package/dist/queries/stale-abstractions.js +1 -1
  363. package/dist/queries/stats.d.ts +2 -2
  364. package/dist/queries/surface.d.ts +13 -4
  365. package/dist/queries/surface.js +1 -1
  366. package/dist/queries/symbols.d.ts +2 -2
  367. package/dist/queries/symbols.js +1 -1
  368. package/dist/queries/system-map.d.ts +449 -0
  369. package/dist/queries/system-map.js +2 -0
  370. package/dist/queries/system.d.ts +5 -3
  371. package/dist/queries/system.js +1 -1
  372. package/dist/queries/test-quality.d.ts +2 -2
  373. package/dist/queries/test-quality.js +1 -1
  374. package/dist/queries/trace.d.ts +47 -3
  375. package/dist/queries/trace.js +1 -1
  376. package/dist/queries/twin-ab.d.ts +3 -3
  377. package/dist/queries/twin-ab.js +1 -1
  378. package/dist/queries/twin-drift.d.ts +3 -3
  379. package/dist/queries/twin-drift.js +1 -1
  380. package/dist/queries/unused-imports.d.ts +2 -2
  381. package/dist/queries/unused-imports.js +1 -1
  382. package/dist/queries/unused-params.d.ts +2 -2
  383. package/dist/queries/unused-params.js +1 -1
  384. package/dist/queries/value-flow.d.ts +43 -0
  385. package/dist/queries/value-flow.js +2 -0
  386. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  387. package/dist/queries/vue-component-duplicates.js +1 -1
  388. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  389. package/dist/queries/vue-composable-candidates.js +1 -1
  390. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  391. package/dist/queries/vue-large-view-pressure.js +1 -1
  392. package/dist/queries/wrapper-candidates.d.ts +2 -2
  393. package/dist/queries/wrapper-candidates.js +1 -1
  394. package/dist/query-service-fastpath.js +6 -0
  395. package/dist/query-service-server.js +5 -0
  396. package/dist/refs-NBHKL4UQ.js +2 -0
  397. package/dist/refs-pagination-BBVTIHMH.js +2 -0
  398. package/dist/reindex-worker.js +27 -45
  399. package/dist/reindex.d.ts +62 -42
  400. package/dist/reindex.js +32 -33
  401. package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
  402. package/dist/runtime.d.ts +286 -7
  403. package/dist/runtime.js +4 -3
  404. package/dist/rust-semantic-session-server.js +1 -1
  405. package/dist/rust-semantic-session-worker.js +1 -1
  406. package/dist/rust-semantic-worker.js +1 -1
  407. package/dist/{scip-cli-BnEwZRLJ.d.ts → scip-cli-CppzF5MK.d.ts} +33 -2
  408. package/dist/slice-U6S6LBSB.js +2 -0
  409. package/dist/source-search-types-Dwz8KeuW.d.ts +79 -0
  410. package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
  411. package/dist/stats-OOJ74B32.js +2 -0
  412. package/dist/surface-C7SS5CDQ.js +2 -0
  413. package/dist/symbol-resolution-3FVEKDTJ.js +2 -0
  414. package/dist/system-6K2NOO5C.js +2 -0
  415. package/dist/trace-II5K2TMH.js +2 -0
  416. package/dist/typescript-mailbox-worker.js +1 -1
  417. package/dist/value-flow-MKFUUE5B.js +2 -0
  418. package/dist/watch-server.js +3 -2
  419. package/docs/AGENT_GUIDE.md +133 -476
  420. package/docs/AI_FAILURE_MODES.md +30 -301
  421. package/docs/API.md +1 -1
  422. package/docs/API_EVOLUTION.md +6 -0
  423. package/docs/CLI_JSON_OUTPUT.md +207 -29
  424. package/docs/COMMAND_REFERENCE.md +255 -154
  425. package/docs/CONFIGURATION_WRITE_SAFETY.md +14 -13
  426. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +84 -0
  427. package/docs/DETECTOR_GUIDE.md +46 -138
  428. package/docs/DURABILITY.md +7 -1
  429. package/docs/INDEX_GENERATIONS.md +6 -0
  430. package/docs/LOCK_PROTOCOL.md +8 -0
  431. package/docs/REINDEX_METADATA_COMPATIBILITY.md +13 -3
  432. package/docs/SECURITY_MODEL.md +39 -42
  433. package/docs/accuracy-audit-checklist.md +4 -0
  434. package/docs/accuracy-hardening-goal.md +9 -2
  435. package/docs/analyzer-inventory.md +59 -264
  436. package/docs/analyzer-validation-protocol.md +62 -170
  437. package/docs/architecture-coherence-vision.md +18 -12
  438. package/docs/locality-analyzer-design.md +1 -1
  439. package/docs/schemas/cli-json-envelope.schema.json +212 -27
  440. package/docs/schemas/cli-json-export-receipt.schema.json +25 -0
  441. package/docs/schemas/cli-output-page.schema.json +1 -1
  442. package/docs/schemas/observation-receipt.schema.json +164 -0
  443. package/docs/schemas/project-config.schema.json +27 -45
  444. package/docs/schemas/suppression-record.schema.json +1 -34
  445. package/package.json +65 -8
  446. package/skills/concrete-plan/SKILL.md +8 -0
  447. package/skills/concrete-plan/agents/openai.yaml +4 -0
  448. package/skills/scip-explore/SKILL.md +3 -85
  449. package/skills/scip-explore/agents/openai.yaml +3 -3
  450. package/skills/scip-integrity-audit/SKILL.md +185 -0
  451. package/skills/scip-integrity-audit/agents/openai.yaml +4 -0
  452. package/skills/scip-plan/SKILL.md +67 -49
  453. package/skills/scip-plan/agents/openai.yaml +3 -3
  454. package/skills/scip-query/SKILL.md +77 -77
  455. package/skills/scip-query/agents/openai.yaml +3 -3
  456. package/skills/scip-setup/SKILL.md +10 -102
  457. package/skills/scip-setup/agents/openai.yaml +3 -3
  458. package/dist/chunk-26QA6FAI.js +0 -8
  459. package/dist/chunk-2KAZEZ6M.js +0 -2
  460. package/dist/chunk-3ORVDL3H.js +0 -2
  461. package/dist/chunk-46XGSFNI.js +0 -2
  462. package/dist/chunk-4MAK2HOY.js +0 -6
  463. package/dist/chunk-4TURLRL5.js +0 -16
  464. package/dist/chunk-4UQVNCQE.js +0 -2
  465. package/dist/chunk-55Q3WLZX.js +0 -2
  466. package/dist/chunk-5I5G2QOX.js +0 -3
  467. package/dist/chunk-6LDJQXAH.js +0 -2
  468. package/dist/chunk-6O5TICIZ.js +0 -3
  469. package/dist/chunk-7O5IKBTZ.js +0 -16
  470. package/dist/chunk-7S5E7KWT.js +0 -2
  471. package/dist/chunk-7WPLAODU.js +0 -5
  472. package/dist/chunk-AFHORGLH.js +0 -42
  473. package/dist/chunk-AIE7TFJW.js +0 -9
  474. package/dist/chunk-AQOFWNQJ.js +0 -1
  475. package/dist/chunk-B2PX5I6M.js +0 -2
  476. package/dist/chunk-B75HZHUP.js +0 -2
  477. package/dist/chunk-B7PBSLZN.js +0 -2
  478. package/dist/chunk-BBW6JFHN.js +0 -2
  479. package/dist/chunk-BNXCIFVY.js +0 -2
  480. package/dist/chunk-BS2NMXQZ.js +0 -4
  481. package/dist/chunk-C3KV2II6.js +0 -2
  482. package/dist/chunk-C43RDDP4.js +0 -20
  483. package/dist/chunk-DAFAHMNB.js +0 -42
  484. package/dist/chunk-DQLPXMH6.js +0 -8
  485. package/dist/chunk-EKZTZXHZ.js +0 -117
  486. package/dist/chunk-EW2NTSFA.js +0 -18
  487. package/dist/chunk-F3Z4OUDS.js +0 -8
  488. package/dist/chunk-FJH2NW7J.js +0 -66
  489. package/dist/chunk-FTFP6O3L.js +0 -11
  490. package/dist/chunk-FYLK2DEJ.js +0 -2
  491. package/dist/chunk-GH74ASD6.js +0 -11
  492. package/dist/chunk-GMXWZP2B.js +0 -2
  493. package/dist/chunk-GOUBFH5O.js +0 -3
  494. package/dist/chunk-HLF2TX6R.js +0 -2
  495. package/dist/chunk-HX7M4BDI.js +0 -30
  496. package/dist/chunk-HZ72SESS.js +0 -128
  497. package/dist/chunk-IB2N4FIY.js +0 -10
  498. package/dist/chunk-IZYYAFN5.js +0 -2
  499. package/dist/chunk-JFGGXWQF.js +0 -947
  500. package/dist/chunk-JN4NMBEX.js +0 -8
  501. package/dist/chunk-JW56N3KI.js +0 -4
  502. package/dist/chunk-JZ2OXNWB.js +0 -2
  503. package/dist/chunk-KFZNKUNT.js +0 -2
  504. package/dist/chunk-L5GJNV2T.js +0 -8
  505. package/dist/chunk-L7JDSCDF.js +0 -4
  506. package/dist/chunk-LU47HG23.js +0 -14
  507. package/dist/chunk-LVY7NPF7.js +0 -2
  508. package/dist/chunk-MKCDWWGV.js +0 -4
  509. package/dist/chunk-MNE7YG56.js +0 -2
  510. package/dist/chunk-MRXBEXSY.js +0 -26
  511. package/dist/chunk-MV7OWDUX.js +0 -2
  512. package/dist/chunk-NGEXCJJW.js +0 -11
  513. package/dist/chunk-NIW6JDC5.js +0 -29
  514. package/dist/chunk-PBUQFCNB.js +0 -16
  515. package/dist/chunk-POAVPHH7.js +0 -2
  516. package/dist/chunk-QZ4JVECJ.js +0 -2
  517. package/dist/chunk-RDO52JGY.js +0 -2
  518. package/dist/chunk-RJT3TUUZ.js +0 -2
  519. package/dist/chunk-RVLDN63O.js +0 -4
  520. package/dist/chunk-RXOXSKY3.js +0 -2
  521. package/dist/chunk-S7OYBOCK.js +0 -2
  522. package/dist/chunk-SMNXQT5Z.js +0 -3
  523. package/dist/chunk-SRAFT254.js +0 -2
  524. package/dist/chunk-T7YQSHPQ.js +0 -3
  525. package/dist/chunk-UJCOIXDY.js +0 -2
  526. package/dist/chunk-UJPRPGCO.js +0 -13
  527. package/dist/chunk-WCCFZ7V7.js +0 -113
  528. package/dist/chunk-WUPW3UN3.js +0 -3
  529. package/dist/chunk-X54AGLVX.js +0 -2
  530. package/dist/chunk-Y2MVPNKY.js +0 -5
  531. package/dist/chunk-YKUU5AIC.js +0 -3
  532. package/dist/chunk-YLCJLTPL.js +0 -2
  533. package/dist/chunk-YTQVETEO.js +0 -2
  534. package/dist/chunk-Z4N3MZYA.js +0 -38
  535. package/dist/chunk-ZJOOT3BG.js +0 -2
  536. package/dist/command-descriptors-DSS46KXI.js +0 -642
  537. package/dist/diff-gate-types-B0QYpDv1.d.ts +0 -11
  538. package/dist/direct-navigation-6YHV6IB5.js +0 -3
  539. package/dist/queries/diff-gate.d.ts +0 -253
  540. package/dist/queries/diff-gate.js +0 -2
  541. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +0 -154
  542. package/docs/analyzer-validation-ledger.md +0 -516
  543. package/docs/schemas/outcome-event-record.schema.json +0 -95
  544. package/skills/_shared/SKILL.md +0 -101
  545. package/skills/_shared/agents/openai.yaml +0 -4
  546. package/skills/_shared/references/agent-contract-catalog.md +0 -105
  547. package/skills/_shared/references/command-catalog.md +0 -118
  548. package/skills/_shared/references/detector-precision-and-diffgate.md +0 -59
  549. package/skills/_shared/references/evidence-and-dead-code.md +0 -25
  550. package/skills/scip-audit/SKILL.md +0 -77
  551. package/skills/scip-audit/agents/openai.yaml +0 -4
  552. package/skills/scip-audit/references/claims.md +0 -98
  553. package/skills/scip-audit/references/cleanup.md +0 -100
  554. package/skills/scip-audit/references/directory.md +0 -222
  555. package/skills/scip-audit/references/frontend.md +0 -130
  556. package/skills/scip-audit/references/integrity.md +0 -154
  557. package/skills/scip-audit/references/maintainability.md +0 -162
  558. package/skills/scip-audit/references/twin-drift.md +0 -104
  559. package/skills/scip-diagnose/SKILL.md +0 -52
  560. package/skills/scip-diagnose/agents/openai.yaml +0 -4
  561. package/skills/scip-diagnose/references/debug.md +0 -117
  562. package/skills/scip-diagnose/references/probe-reachability.md +0 -77
  563. package/skills/scip-diagnose/references/root-cause.md +0 -145
  564. package/skills/scip-diagnose/references/triage.md +0 -119
  565. package/skills/scip-explore/references/diagrams.md +0 -40
  566. package/skills/scip-explore/references/language-playbook.md +0 -49
  567. package/skills/scip-improve/SKILL.md +0 -56
  568. package/skills/scip-improve/agents/openai.yaml +0 -4
  569. package/skills/scip-improve/references/cleanup-batches.md +0 -53
  570. package/skills/scip-improve/references/directory-moves.md +0 -53
  571. package/skills/scip-improve/references/doc-reconcile.md +0 -30
  572. package/skills/scip-improve/references/frontend-extraction.md +0 -39
  573. package/skills/scip-improve/references/maintainability-mechanism.md +0 -43
  574. package/skills/scip-improve/references/twin-drift.md +0 -35
  575. package/skills/scip-plan/references/api-impact.md +0 -19
  576. package/skills/scip-plan/references/conductor.md +0 -41
  577. package/skills/scip-plan/references/high-assurance.md +0 -43
  578. package/skills/scip-plan/references/hyper-optimization.md +0 -50
  579. package/skills/scip-plan/references/tla-model.md +0 -88
  580. package/skills/scip-setup/references/bootstrap-workflow.md +0 -119
  581. package/skills/scip-setup/references/language-verification.md +0 -61
  582. package/skills/scip-setup/references/lifecycle-commands.md +0 -119
  583. package/skills/scip-setup/references/per-repo-triage.md +0 -24
  584. package/skills/scip-verify/SKILL.md +0 -229
  585. package/skills/scip-verify/agents/openai.yaml +0 -4
  586. package/skills/scip-verify/references/calibrate-detectors.md +0 -170
package/dist/reindex.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,f as qt,g as Ut,h as Wt,l as Ht,m as Vr,n as Br,p as zt,q as qr,r as Ur,s as Wr,t as Hr}from"./chunk-JN4NMBEX.js";import{a as jr}from"./chunk-7PIO7NKH.js";import"./chunk-AQOFWNQJ.js";import{C as Nt,D as Fr,E as Gt,F as $t,G as Ar,H as _r,I as Vt,K as Bt,P as Or,R as Cr,a as Sr,b as ue,c as X,d as j,e as de,f as br,g as Ye,h as _t,i as M,j as Rr,l as xr,m as ve,n as Lt,o as Ke,q as ie,r as Pe,s as le,t as Ee,u as pe,v as Ct,w as jt,x as Tr,y as Dr,z as Mt}from"./chunk-7WPLAODU.js";import{a as mr,b as xe,c as J,d as Y,e as x,g as He,h as At,i as yr,k as ze,l as K,m as Ie,n as Je,q as Ot,r as Er,w as et,z as Lr}from"./chunk-BS2NMXQZ.js";import{a as Ze}from"./chunk-C43RDDP4.js";import"./chunk-UJPRPGCO.js";import{F as wr,G as kr}from"./chunk-GH74ASD6.js";import{B as Ir,E as vr,H as Qe,I as Pr,a as lr,b as pr,c as Ue,d as Re,e as z,f as Dt,g as gr,h as Ft,i as fr,v as we,w as ke}from"./chunk-WCCFZ7V7.js";import{a as Xe}from"./chunk-NGEXCJJW.js";import"./chunk-7S5E7KWT.js";import{f as A,g as B,h as _,k as w,l as v,m as k,p as hr,q as We}from"./chunk-2KAZEZ6M.js";import{e as be,f as dr}from"./chunk-C3KV2II6.js";import{execFileSync as Vl}from"child_process";import{createHash as Bl}from"crypto";import{copyFileSync as kt,existsSync as G,mkdirSync as Pt,mkdtempSync as ql,readdirSync as Wa,renameSync as Ha,rmSync as ye,statSync as Ul}from"fs";import{basename as vt,dirname as b,extname as Wl,join as D,resolve as Ma}from"path";import{platform as Hl}from"os";import cs from"better-sqlite3";import{execFileSync as us}from"child_process";import{existsSync as ds,readdirSync as ls}from"fs";import{extname as tt,join as ps}from"path";function Q(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>zr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function zr(e){let t=new Set((e.extensions??wr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ds(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=jr(e.projectRoot),r=gs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new cs(e.dbPath);try{let o=ms(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let l=0;for(let p of d){if(o.has(p))continue;let m=vr(e.projectRoot,p,{inputKind:"auxiliary source file"}),g=a.run(hs(p),p,m);l+=Number(g.changes)}return l})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function gs(e,t){let n=fs(e,t);if(n)return n;let r=[],i=o=>{let a=o?ps(e,o):e,s;try{s=ls(a,{withFileTypes:!0})}catch{return}for(let c of s){if(kr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(tt(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function fs(e,t){try{return us("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 ms(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 hs(e){return tt(e).toLowerCase()===".vue"?"vue":tt(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Ss}from"crypto";import{existsSync as bs}from"fs";import{dirname as Rs,join as Yr}from"path";function Jt(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 nt(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=Jt(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"),Jr(r,i,a)):a.size>0?Jr(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ys(r,t,i),reasons:[]}}function Jr(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ys(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 u=r.get(c)??new Set;u.add(a),r.set(c,u)}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 xs="<global-symbols>";function Is(e){let t=[];for(let n of e.all(`
1
+ import{a as q}from"./chunk-IGKKTHJR.js";import{a as wi,b as Ei,c as lt,d as fn,h as gn,i as Ai,j as Ci,l as mn,m as _i}from"./chunk-S73HBCGI.js";import{a as Pi}from"./chunk-2COFMIVK.js";import{e as ki,f as Ti,g as Di,i as Fi}from"./chunk-YRVERHJR.js";import"./chunk-7TWP3MCP.js";import{A as vi,a as Pe,b as Ve,c as we,d as on,e as an,f as hi,g as yi,h as sn,k as cn,l as Si,m as un,n as dn,o as bi,p as Ri,q as xi,r as ln,t as pn,y as Ii}from"./chunk-ZDVDSDFG.js";import"./chunk-RGCJ4646.js";import"./chunk-ELNRLMC5.js";import"./chunk-LPGDO2XA.js";import{A as Qt,B as st,D as Zt,E as ge,F as $e,G as rn,H as mi,a as Br,b as Me,c as W,d as ie,e as v,f as Wr,g as G,h as rt,i as Kt,j as qr,k as Hr,l as fe,m as ot,p as xe,q as $,r as Ie,s as zr,t as at,u as Xt,v as V,w as Jr,y as Yr,z as Ge}from"./chunk-MYUKI5VN.js";import"./chunk-35IW3P4H.js";import"./chunk-YUKYB54I.js";import{b as pi,c as fi,d as gi}from"./chunk-7COHFNJK.js";import"./chunk-5IZTXSOL.js";import"./chunk-I3U2FN2T.js";import{K as di,L as li,a as ct}from"./chunk-AA7K3XLM.js";import{g as X,p as Kr,r as M,s as me,t as Xr}from"./chunk-DMQ7ZKJG.js";import{a as ve,c as ai,h as si,l as ci,m as dt,n as ui,o as nn}from"./chunk-7HU2IJ2T.js";import{$ as ei,A as O,B as re,C as j,F as T,G as E,H as L,K as Ur,L as nt,Q as it,R as oe,S as Ne,U as Qr,V as Zr,Y as ut,aa as ti,b as Ht,ca as ni,da as ri,e as zt,ea as ii,f as Mr,fa as oi,g as et,h as Nr,ha as en,i as Gr,ia as tn,j as tt,k as A,u as je,v as ne,w as Jt,x as $r,y as Yt,z as Vr}from"./chunk-MO226P4Q.js";import{createHash as Hp}from"crypto";import{existsSync as N,mkdirSync as Vt,mkdtempSync as zp,readdirSync as Ls,renameSync as js,rmSync as _e,statSync as Jp}from"fs";import{basename as $t,dirname as S,extname as Yp,join as C,resolve as ks}from"path";import{platform as Kp}from"os";import{execFileSync as Qs}from"child_process";import{constants as Zs,copyFileSync as Oi,statSync as ec}from"fs";import{platform as tc}from"os";var nc=Object.freeze({size:e=>ec(e).size,clone:ic,copy:(e,t)=>Oi(e,t)}),rc=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function he(e,t,n=nc){let r=n.size(e);try{return n.clone(e,t),{method:"reflink",bytes:r}}catch(i){if(!ac(i))throw i}return n.copy(e,t),{method:"copy",bytes:r}}function ic(e,t){if(tc()!=="darwin"){Oi(e,t,Zs.COPYFILE_FICLONE_FORCE);return}try{Qs("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw oc(n)}}function oc(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 ac(e){let t=e?.code;return t!==void 0&&rc.has(t)}function Li(){return{reflinkedBytes:0,fallbackCopiedBytes:0}}function ye(e,t){t.method==="reflink"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}import sc from"better-sqlite3";import{execFileSync as cc}from"child_process";import{existsSync as uc,readdirSync as dc}from"fs";import{extname as pt,join as lc}from"path";function ae(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>ji({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function ji(e){let t=new Set((e.extensions??di).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!uc(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Pi(e.projectRoot),r=pc(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new sc(e.dbPath);try{let o=gc(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let l=0;for(let p of d){if(o.has(p))continue;let g=si(e.projectRoot,p,{inputKind:"auxiliary source file"}),f=a.run(mc(p),p,g);l+=Number(f.changes)}return l})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function pc(e,t){let n=fc(e,t);if(n)return n;let r=[],i=o=>{let a=o?lc(e,o):e,s;try{s=dc(a,{withFileTypes:!0})}catch{return}for(let c of s){if(li.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(pt(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function fc(e,t){try{return cc("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(pt(r).toLowerCase())).sort()}catch{return null}}function gc(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 mc(e){return pt(e).toLowerCase()===".vue"?"vue":pt(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as hc,join as yc}from"path";function Mi(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new q({projectRoot:t,dbPath:n,indexPath:e.indexPath??yc(hc(n),"index.scip")}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?Fi(i):null;e.reuseExisting&&u?.extractorVersion===ki?(o=u,a=!0):(o=Ti(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},profileSpan:M}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Di(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(u=>`${u.id} ${u.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}import{createHash as bc}from"crypto";import{existsSync as Rc}from"fs";import{dirname as xc,join as Gi}from"path";function hn(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 ft(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=hn(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"),Ni(r,i,a)):a.size>0?Ni(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:Sc(r,t,i),reasons:[]}}function Ni(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Sc(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 u=r.get(c)??new Set;u.add(a),r.set(c,u)}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 Ic="<global-symbols>";function vc(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:Yt(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
30
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:yn(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:Yt(n,[n.chunk_index,n.role])});for(let n of e.all(`
45
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:yn(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,9 +56,8 @@ 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:xs,kind:"global-symbol",values:Yt(n)});return vs(t)}function vs(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=Ss("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 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:Ic,kind:"global-symbol",values:yn(n)});return Pc(t)}function Pc(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=bc("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 wc(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 Sn(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 bn(e,t=Ac){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 Ui(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=tt(e.previousSnapshot,e.currentSnapshot),l=new Set(u),p=d.changes.length>0&&!hn(d).fullProject&&d.changes.every(R=>l.has(R.path)),g=ft(d,p?t.dependencyGraph(s):new Map,u),f=wc(t.factDigests(s),t.factDigests(c)),m=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?m:i()).toISOString(),durationMs:Math.max(0,m-o),manifest:d,plan:g,comparison:f,evaluation:Sn(g,f,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{$i(s),$i(c)}}function Vi(e,t,n,r=Date.now()){return Ui(e,t,r,0,n)}function Ec(e){let t=xc(e);return{latestPath:Gi(t,"affected-shadow-latest.json"),historyPath:Gi(t,"affected-shadow.jsonl")}}function Bi(e,t,n=Cc){let r=Ec(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var kc=8*1024*1024,Tc=Ai;function Dc(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 Fc(e,t,n=kc){Ci(e,Dc(t),{maxSegmentBytes:n,previousSuffix:Tc})}function yn(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 Ac={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:v,databaseExists:e=>Rc(e),openDatabase:(e,t,n)=>new q({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>ct(e),dependencyGraph:e=>pi(e),factDigests:e=>vc(e)},Cc={appendHistory:Fc,writeLatest:(e,t)=>xe(e,t,{spacing:2,trailingNewline:!0})};function Ui(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 $i(e){try{e?.close()}catch{}}import{execFileSync as _c}from"child_process";import{existsSync as Oc,readdirSync as qi}from"fs";import{extname as Hi,join as zi}from"path";var Ji=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Lc=[{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 Rn(e){let t=[],n=jc(e),r=$c(e);for(let i of Lc){if(Mc(e,i.files)){t.push(i.language);continue}if(Nc(n,i.globs)){t.push(i.language);continue}Bc(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Wi(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Wi(t,"c"),t}function jc(e){try{return qi(e)}catch{return[]}}function Mc(e,t){return t?.length?t.some(n=>Oc(zi(e,n))):!1}function Nc(e,t){return t?.length?e.some(n=>t.some(r=>Gc(n,r))):!1}function Gc(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 $c(e){let t=Vc(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=qi(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=zi(i,a.name);if(a.isDirectory()){Ji.has(a.name)||r.push(s);continue}let c=Hi(a.name).toLowerCase();c&&n.add(c)}}return n}function Vc(e){try{let t=Qr(e,26214400,()=>_c("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 Zr(t)){if(r.split("/").some(o=>Ji.has(o)))continue;let i=Hi(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Bc(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Wi(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as Uc}from"fs";import{isAbsolute as Yi,join as Wc,resolve as qc}from"path";var gt="@sourcegraph/scip-typescript@0.4.0",Ki="scip-python-plus@0.7.5",Xi="github.com/sourcegraph/scip-go@v0.2.7",Qi="scip-dotnet@0.2.14",Hc="scip_dart@1.6.2",eo={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",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar"]}:{binary:n,args:["index","--output",e,"--no-progress-bar"]},markerFiles:[...A.typescript],installMethods:[{label:"npm",identity:gt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",gt]}],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"]}),markerFiles:[...A.javascript],installMethods:[{label:"npm",identity:gt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",gt]}],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:[...A.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:[...A.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:[...A.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Pe.language,indexerBinary:Pe.indexerBinary,checkCommand:`${Pe.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Pe.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...A.rust],installMethods:[],installUrl:Pe.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:[...A.python],installMethods:[{label:"npm",identity:Ki,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Ki]}],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",Yi(r)?r:qc(e,r)),{binary:n,args:i}},markerFiles:[...A.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:[...A.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:[...A.go],installMethods:[{label:"go install",identity:Xi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Xi]}],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:[...A.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:[...A.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",Zi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...A.csharp],installMethods:[{label:"dotnet",identity:Qi,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",Zi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...A.vb],installMethods:[{label:"dotnet",identity:Qi,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:[...A.dart],installMethods:[{label:"dart pub",identity:Hc,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})=>Yi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...A.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function to(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function mt(e){return eo[e]}function Zi(e,t){let n;try{n=Uc(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Wc(e,i);return null}import{writeFileSync as In}from"fs";import{create as Be}from"@bufbuild/protobuf";import{deserializeSCIP as vn,serializeSCIP as Pn,DocumentSchema as Zc,IndexSchema as io,MetadataSchema as eu,SymbolInformationSchema as tu}from"@c4312/scip";import{writeFileSync as zc}from"fs";import{create as no}from"@bufbuild/protobuf";import{deserializeSCIP as Jc,DocumentSchema as Yc,IndexSchema as Kc,serializeSCIP as Xc,SymbolRole as Qc}from"@c4312/scip";function ro(e){let t;try{t=Jc(T(e,{inputKind:"SCIP sanitization input",maxBytes:j}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=xn(t);return n.removedDefinitionOccurrences>0&&zc(e,Xc(n.index)),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function xn(e){let t=new Set;for(let o of e.documents){Mr(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&Qc.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(no(Yc,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:no(Kc,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function wn(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=ru(e),n=iu(e.flatMap(i=>i.documents??[])),r=so(e.flatMap(i=>i.externalSymbols??[]));return Be(io,{metadata:t,documents:n,externalSymbols:r})}function En(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>vn(T(i,{inputKind:"SCIP merge input",maxBytes:j}))),r=wn(n);return In(t,Pn(r)),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function oo(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=M("reindex.publish.scip-output.deserialize",()=>e.map(o=>vn(T(o,{inputKind:"SCIP merge input",maxBytes:j})))),r=M("reindex.publish.scip-output.merge",()=>wn(n)),i=M("reindex.publish.scip-output.sanitize",()=>xn(r));return M("reindex.publish.scip-output.serialize",()=>In(t,Pn(i.index))),{documentCount:i.index.documents.length,externalSymbolCount:i.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:i.removedDefinitionOccurrences,touchedDocuments:i.touchedDocuments}}function nu(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 Be(io,{metadata:Be(eu,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function ao(e,t,n){let r=vn(T(e,{inputKind:"SCIP normalization input",maxBytes:j})),i=nu(r,t,n);In(e,Pn(i))}function ru(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 iu(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Be(Zc,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ou([...r.occurrences,...n.occurrences]),symbols:so([...r.symbols,...n.symbols]),text:su(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ou(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 so(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Be(tu,{symbol:r.symbol,documentation:cu([...r.documentation,...n.documentation]),relationships:au([...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 au(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 su(e,t){return e?t?e.length>=t.length?e:t:e:t}function cu(e){return[...new Set(e)]}import{createHash as uu}from"crypto";import{existsSync as co,rmSync as uo}from"fs";import{resolve as du}from"path";import fo from"better-sqlite3";var lu={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}]},pu={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 go(e){let t=v(),n=fu(e.affectedFiles);if(gu(e.previousDbPath,e.miniDbPath,e.candidateDbPath),uo(e.candidateDbPath,{force:!0}),!co(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!co(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");lo(e.previousDbPath,"previous SQLite generation",!1),lo(e.miniDbPath,"incremental SQLite mini database");let r=he(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ye(e.writeTelemetry,r);let i=null;try{i=new fo(e.candidateDbPath,{fileMustExist:!0}),i.pragma("busy_timeout = 5000"),i.pragma("foreign_keys = ON"),i.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),kn(i,"main","candidate SQLite generation"),kn(i,"incremental","incremental SQLite mini database"),mu(i,n);let{priorAffectedCount:o}=hu(i,n.length),a=Tn(i,"main",!0),s=se(i,"SELECT COUNT(*) AS value FROM main.documents");i.transaction(()=>{yu(i),Su(i),bu(i),e.onStage?.("after-delete"),Ru(i),e.onStage?.("after-symbol-reconciliation"),xu(i),e.onStage?.("after-insert"),Iu(i),vu(i,n.length,s,o),e.onStage?.("before-commit")}).immediate(),mo(i,"main","candidate SQLite generation");let d=[...Pu(i)].filter(([l,p])=>a.get(l)!==p).map(([l])=>l).sort();return i.exec("DETACH DATABASE incremental"),i.close(),i=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:d,durationMs:v()-t}}catch(o){try{i?.close()}finally{uo(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}function fu(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 gu(e,t,n){let r=[e,t,n].map(i=>du(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function lo(e,t,n=!0){let r=new fo(e,{readonly:!0,fileMustExist:!0});try{kn(r,"main",t),n&&mo(r,"main",t)}finally{r.close()}}function kn(e,t,n){for(let[r,i]of Object.entries(lu)){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(pu)){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}`)}po(e,t,"documents",["relative_path"],n),po(e,t,"global_symbols",["symbol"],n)}function po(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 mo(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 mu(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 hu(e,t){let n=se(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=se(e,`SELECT COUNT(*) AS value
62
61
  FROM main.documents d
63
62
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
64
63
  FROM temp.incremental_affected_paths p
@@ -68,7 +67,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
68
67
  FROM incremental.documents d
69
68
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
70
69
  WHERE p.relative_path IS NULL
71
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function yc(e){e.exec(`
70
+ LIMIT 1`).pluck().get();if(n!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:r}}function yu(e){e.exec(`
72
71
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
73
72
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
74
73
  SELECT g.symbol
@@ -95,7 +94,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
95
94
  FROM incremental.mentions m
96
95
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
97
96
  WHERE m.role = 1;
98
- `)}function Sc(e){let t=e.prepare(`WITH changed_symbols AS (
97
+ `)}function Su(e){let t=e.prepare(`WITH changed_symbols AS (
99
98
  SELECT symbol FROM temp.incremental_old_defined_symbols
100
99
  UNION
101
100
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -118,7 +117,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
118
117
  SELECT u.symbol
119
118
  FROM unaffected_definitions u
120
119
  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(`
120
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function bu(e){e.exec(`
122
121
  DELETE FROM main.mentions
123
122
  WHERE chunk_id IN (
124
123
  SELECT c.id
@@ -140,7 +139,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
140
139
  );
141
140
  DELETE FROM main.documents
142
141
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
143
- `)}function Rc(e){e.exec(`
142
+ `)}function Ru(e){e.exec(`
144
143
  UPDATE main.global_symbols
145
144
  SET display_name = NULL,
146
145
  kind = NULL,
@@ -182,7 +181,7 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
182
181
  WHERE source.symbol = main.global_symbols.symbol
183
182
  )
184
183
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
185
- `)}function xc(e){let t=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Z(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)
184
+ `)}function xu(e){let t=se(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=se(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=se(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
185
  SELECT id + ?, language, relative_path, position_encoding, text
187
186
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
188
187
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -197,15 +196,15 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
197
196
  r.start_line, r.start_char, r.end_line, r.end_char
198
197
  FROM incremental.defn_enclosing_ranges r
199
198
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
200
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Ic(e){e.exec(`
199
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Iu(e){e.exec(`
201
200
  DELETE FROM main.global_symbols
202
201
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
203
202
  AND NOT EXISTS (
204
203
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
205
204
  );
206
- `)}function vc(e,t,n){let r=Z(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Z(e,`SELECT COUNT(*) AS value
205
+ `)}function vu(e,t,n,r){let i=se(e,"SELECT COUNT(*) AS value FROM main.documents"),o=se(e,`SELECT COUNT(*) AS value
207
206
  FROM main.documents d
208
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Pc(e){let t=sn(e,"main",!0),n=sn(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 sn(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
207
+ 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");let s=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),c=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(s!==void 0||c!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Pu(e){let t=Tn(e,"main",!0),n=Tn(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 Tn(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
208
  FROM ${t}.documents d
210
209
  ${r}
211
210
  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 +226,12 @@ import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,
227
226
  JOIN ${t}.documents d ON d.id = c.document_id
228
227
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
229
228
  ${r}
230
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let m=JSON.stringify([d,p]),g=c.get(p.relative_path)??[];g.push(m),c.set(p.relative_path,g)}let u=new Map;for(let[d,l]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=cc("sha256");for(let m of l.sort())p.update(m).update(`
231
- `);u.set(d,p.digest("hex"))}return u}function Z(e,t){return e.prepare(t).get().value}import wc from"better-sqlite3";var ot="idx_mentions_definitions",kc=["symbol_id","chunk_id"];function cn(e){let t=new wc(e),n=[],r=[],i=[];try{return t.transaction(()=>{Ec(t,n),at(t,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Pi(t,"global_symbols").some(s=>s.name!=="idx_global_symbols_symbol"&&s.unique&&s.columns.join("\0")==="symbol")?(t.exec('DROP INDEX "idx_global_symbols_symbol"'),r.push("idx_global_symbols_symbol")):at(t,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=at(t,"idx_chunks_doc_id"),a=Pi(t,"chunks").some(s=>s.name!=="idx_chunks_doc_id"&&s.columns.length>1&&s.columns[0]==="document_id");o?.join("\0")==="document_id"&&a?(t.exec('DROP INDEX "idx_chunks_doc_id"'),r.push("idx_chunks_doc_id")):o&&i.push("idx_chunks_doc_id"),t.exec("ANALYZE")})(),{added:n,removed:r,retained:i,analyzed:!0}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{t.close()}}function Ec(e,t){let n=wi(e,ot);if(n){let r=n.columns.join("\0")===kc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${ot} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${ot}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(ot)}function Pi(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 wi(e,t)?.columns??null}function wi(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 Tc}from"fs";function q(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Ei(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Fi(e.cachePath,e.readFingerprint(),r),r}async function Ti(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Fi(e.cachePath,e.readFingerprint(),r),r}function Di(e,t){try{let n=JSON.parse(v(e,{maxBytes:A,inputKind:"post-index augmentation cache"}));return ki(n.fingerprint)===ki(t)?{result:n.result}:null}catch{return null}}function Fi(e,t,n){Tc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
232
- `)}function ki(e){return JSON.stringify(e)}import{createHash as Dc}from"crypto";import{existsSync as un,readdirSync as Fc}from"fs";import{dirname as dn,join as st,relative as Ac,resolve as ln,sep as Ai}from"path";function _i(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=ji(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Li(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=ji(s,e);c&&c!==i&&a.add(c)}}return _c(e,r)}function Oi(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 pn(e){if(e===".")return"root";let t=Dc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ci(e,t){let n=ln(e),r={};for(let i of t)r[i]=Lc(n,i);return r}function ji(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 _c(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 Lc(e,t){let n=t==="."?e:st(e,t),r=Oc(n),i=Cc(n),o=i?jc(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 Oc(e){let t=st(e,"package.json");if(!un(t))return{name:void 0,dependencyNames:[],failed:!1};let n=gn(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 Cc(e){let t=st(e,"tsconfig.json");if(un(t))return t;let n;try{n=Fc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?st(e,n[0]):void 0}function jc(e,t){let n=gn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Mc(n.value,e,t),i=Mi(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Mc(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=dn(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=Ni(s,i,n);c&&o.add(c)}return[...o]}function Mi(e,t,n,r){let i=Nc(t);if(i)return{pathsTargets:Gc(i,dn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=$c(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=gn(o);return a.ok?Mi(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Nc(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 Gc(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=Ni(o,t,n);a&&r.add(a)}return[...r]}function $c(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=ln(dn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Ai).includes("node_modules")&&be(n,i)&&un(i))return i}function Ni(e,t,n){let r=e.replace(/\/?\*+$/,""),i=ln(t,r===""?".":r);if(!be(n,i))return;let a=Ac(n,i).split(Ai).join("/");return a===""?".":a}function Vc(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]!==`
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
- ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
235
- `)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,skipped:{language:e.language,reason:d}},retryable:kd(s)}}finally{vd(r)}if(!Rt(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let a;try{a=bd(e.scipPath).size}catch{a=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,outputBytes:a},retryable:!1}}function wd(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Ur.indexer}function kd(e){return e instanceof Wr?e.kind==="spawn"&&ea(e.cause):ea(e)}function ea(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as ia}from"child_process";import{homedir as ra,platform as Ed}from"os";import{delimiter as Td,join as xt}from"path";function Xn(e,t){let n=e.installMethods,r=Ee(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(!Ot(i.prerequisite))continue;let o=Dd(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{ia(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Ed()==="win32"});let a=pe(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 Dd(e){if(e.binary==="npm")return Kn("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Kn("go",["env","GOBIN"]);if(t)return t;let n=Kn("go",["env","GOPATH"]);if(n)return xt(n.split(Td)[0],"bin")}return e.binary==="dotnet"?xt(process.env.DOTNET_CLI_HOME??ra(),".dotnet","tools"):e.binary==="dart"?xt(process.env.PUB_CACHE??xt(ra(),".pub-cache"),"bin"):e.destination}function Kn(e,t){try{return ia(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import Ea from"better-sqlite3";import{existsSync as Ta}from"fs";import{dirname as Da,join as Fa,resolve as Aa}from"path";import{randomUUID as Ad}from"crypto";import{mkdtempSync as _d,rmSync as Ld,statSync as aa}from"fs";import{tmpdir as Od}from"os";import{join as sa}from"path";import{Worker as Cd}from"worker_threads";function Fd(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function he(){return{skippedReferences:0,skippedReferenceReasons:Fd(),skippedReferenceSamples:[]}}function It(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 jd=3e5,ca=64*1024*1024,Md={createResultDirectory:()=>_d(sa(Od(),"scip-query-vue-workers-")),spawn:(e,t)=>new Cd(e,{workerData:t}),resultSize:e=>aa(e).size,readResult:e=>v(e,{maxBytes:ca,inputKind:"Vue worker result"}),removeResultDirectory:e=>Ld(e,{recursive:!0,force:!0})};function ua(e){return e.length>=8&&la(e.length)>1}async function da(e,t=Md){let n=la(e.vueFiles.length),r=Kd(e.vueFiles),i=Qd(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??Jd(),s=e.maxResultBytes??Yd();oa("timeoutMs",a),oa("maxResultBytes",s);let c=Ad(),u=t.createResultDirectory(),d=[],l,p,m;try{for(let f=0;f<i.length;f++){let y=f,R=i[f]??[],F=R.map(T=>T.taskId),E=sa(u,`${y}.json`),P=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:R,resultPath:E,runId:c,workerId:y,taskIds:F});d.push({workerId:y,taskIds:F,resultPath:E,handle:P,completion:Nd(P,y)})}await Gd(d,a);let g=d.sort((f,y)=>f.workerId-y.workerId).map(f=>Vd(f,c,s,t));m={occurrences:g.flatMap(f=>f.occurrences),...he()};for(let f of g)It(m,f)}catch(g){l=g}finally{let g=await $d(d);if(g.length===0)try{t.removeResultDirectory(u)}catch(f){g.push(f)}if(g.length>0){let f=l===void 0?g:[l,...g];p=new AggregateError(f,`Vue worker cleanup failed: ${zd(f[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!m)throw new Error("Vue workers completed without producing a merged result.");return m}function Nd(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 Gd(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 $d(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Vd(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(!Ge(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(!Hd(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||!Bd(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Bd(e){if(!Ge(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(qd)||!U(e.skippedReferences)||!Ge(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!U(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Ud)}function qd(e){return Ge(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&U(e.symbolId)}function Ud(e){return Ge(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.token=="string"&&Wd(e.reason)}function Wd(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function U(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hd(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function oa(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function zd(e){return e instanceof Error?e.message:String(e)}function la(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 Jd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:jd}function Yd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:ca}function Kd(e){let t=Xd(),n=[];for(let r of e){let i=pa(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 Xd(){return Number.POSITIVE_INFINITY}function Qd(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Zd(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 Zd(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,pa(e.fileName)-e.startOffset)}function pa(e){try{return aa(e).size}catch{return 1}}import{createRequire as el}from"module";import{existsSync as tl}from"fs";import{dirname as ga,extname as nl,join as fa,relative as rl,resolve as il}from"path";import{pathToFileURL as ol}from"url";function al(e){e.transaction(()=>{e.prepare(`
229
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let g=JSON.stringify([d,p]),f=c.get(p.relative_path)??[];f.push(g),c.set(p.relative_path,f)}let u=new Map;for(let[d,l]of[...c].sort(([p],[g])=>p.localeCompare(g))){let p=uu("sha256");for(let g of l.sort())p.update(g).update(`
230
+ `);u.set(d,p.digest("hex"))}return u}function se(e,t){return e.prepare(t).get().value}import wu from"better-sqlite3";var ht="idx_mentions_definitions",Eu=["symbol_id","chunk_id"];function Dn(e){let t=new wu(e),n=[],r=[],i=[];try{return t.transaction(()=>{ku(t,n),yt(t,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&ho(t,"global_symbols").some(s=>s.name!=="idx_global_symbols_symbol"&&s.unique&&s.columns.join("\0")==="symbol")?(t.exec('DROP INDEX "idx_global_symbols_symbol"'),r.push("idx_global_symbols_symbol")):yt(t,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=yt(t,"idx_chunks_doc_id"),a=ho(t,"chunks").some(s=>s.name!=="idx_chunks_doc_id"&&s.columns.length>1&&s.columns[0]==="document_id");o?.join("\0")==="document_id"&&a?(t.exec('DROP INDEX "idx_chunks_doc_id"'),r.push("idx_chunks_doc_id")):o&&i.push("idx_chunks_doc_id"),t.exec("ANALYZE")})(),{added:n,removed:r,retained:i,analyzed:!0}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{t.close()}}function ku(e,t){let n=yo(e,ht);if(n){let r=n.columns.join("\0")===Eu.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${ht} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${ht}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(ht)}function ho(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:yt(e,n.name)??[]}))}function yt(e,t){return yo(e,t)?.columns??null}function yo(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 Tu}from"fs";function H(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function bo(e){let t=e.readFingerprint(),n=xo(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Io(e.cachePath,e.readFingerprint(),r),r}async function Ro(e){let t=e.readFingerprint(),n=xo(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Io(e.cachePath,e.readFingerprint(),r),r}function xo(e,t){try{let n=JSON.parse(E(e,{maxBytes:O,inputKind:"post-index augmentation cache"}));return So(n.fingerprint)===So(t)?{result:n.result}:null}catch{return null}}function Io(e,t,n){Tu(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
231
+ `)}function So(e){return JSON.stringify(e)}import Du from"better-sqlite3";var Fu=25,Au=new Set(["typescript","javascript"]);function St(e,t,n){let r=null;try{r=new Du(e,{readonly:!0,fileMustExist:!0});let i=new Set(r.prepare("SELECT relative_path FROM documents").pluck().all().map(Ht)),o=Cu(t,n),a=new Set([...o.values()].flatMap(d=>[...d])),s=[...a].filter(d=>!i.has(d)).sort();if(s.length===0)return{state:"complete",expectedDocumentCount:a.size,actualDocumentCount:i.size};let c=new Set(s),u=n.filter(d=>[...o.get(d)??[]].some(l=>c.has(l)));return{state:"incomplete",expectedDocumentCount:a.size,actualDocumentCount:i.size,missingDocumentCount:s.length,missingPaths:s.slice(0,Fu),affectedLanguages:u}}catch(i){return{state:"unavailable",reason:i instanceof Error?i.message:String(i)}}finally{r?.close()}}function Cu(e,t){let n=new Map,r=t.filter(i=>Au.has(i));for(let i of r)n.set(i,new Set);for(let i of e.files){let o=Ht(i.path);for(let a of r)et(o,[a])==="source"&&n.get(a).add(o)}return n}import{createHash as _u}from"crypto";import{existsSync as Fn,readdirSync as Ou}from"fs";import{dirname as An,join as bt,relative as Lu,resolve as Cn,sep as vo}from"path";function Po(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=To(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function wo(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=To(s,e);c&&c!==i&&a.add(c)}}return ju(e,r)}function Eo(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 _n(e){if(e===".")return"root";let t=_u("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function ko(e,t){let n=Cn(e),r={};for(let i of t)r[i]=Mu(n,i);return r}function To(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 ju(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 Mu(e,t){let n=t==="."?e:bt(e,t),r=Nu(n),i=Gu(n),o=i?$u(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 Nu(e){let t=bt(e,"package.json");if(!Fn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=On(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 Gu(e){let t=bt(e,"tsconfig.json");if(Fn(t))return t;let n;try{n=Ou(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?bt(e,n[0]):void 0}function $u(e,t){let n=On(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Vu(n.value,e,t),i=Do(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Vu(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=An(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=Fo(s,i,n);c&&o.add(c)}return[...o]}function Do(e,t,n,r){let i=Bu(t);if(i)return{pathsTargets:Uu(i,An(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Wu(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=On(o);return a.ok?Do(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Bu(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 Uu(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=Fo(o,t,n);a&&r.add(a)}return[...r]}function Wu(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=Cn(An(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(vo).includes("node_modules")&&zt(n,i)&&Fn(i))return i}function Fo(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Cn(t,r===""?".":r);if(!zt(n,i))return;let a=Lu(n,i).split(vo).join("/");return a===""?".":a}function qu(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]!==`
232
+ `;)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 On(e){try{let t=E(e,{maxBytes:O,inputKind:"TypeScript project manifest"}),n=JSON.parse(qu(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as la,randomUUID as Td}from"crypto";import{existsSync as ue,lstatSync as Zn,mkdirSync as Te,mkdtempSync as pa,readdirSync as fa,realpathSync as ga,renameSync as Se,rmSync as ce,statSync as Tt}from"fs";import{dirname as er,join as h,resolve as tr}from"path";import{setTimeout as Dd}from"timers/promises";import{pathToFileURL as sa}from"url";import{deserializeSCIP as ma}from"@c4312/scip";import Fd from"better-sqlite3";import{lstatSync as sd,readdirSync as cd}from"fs";import{join as ud,relative as dd,resolve as Vn,sep as ld}from"path";import{existsSync as Co,readdirSync as _o,rmSync as Oo}from"fs";import{join as Ee}from"path";import{create as jo,fromBinary as Mo,toBinary as lm}from"@bufbuild/protobuf";import{deserializeSCIP as Ln,DocumentSchema as No,IndexSchema as Go,serializeSCIP as $o}from"@c4312/scip";import{existsSync as Hu,mkdirSync as zu,renameSync as Ju,writeFileSync as Yu}from"fs";import{join as Ku}from"path";function Ao(e){zu(e.blobDir,{recursive:!0});let t=Ku(e.blobDir,`${e.blobHash}.scipdoc`);if(Hu(t)){let r=T(t,{maxBytes:re,inputKind:e.inputKind});if(r.byteLength!==e.bytes.byteLength||X(r)!==e.blobHash)throw new Error(`existing ${e.inputKind} is corrupt: ${e.relativePath}`);return}let n=`${t}.${process.pid}.${Date.now()}.tmp`;Yu(n,e.bytes),Ju(n,t)}var jn=1,Ue="typescript-scip-fragments";function Vo(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=Rt(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=Mo(No,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=$o(jo(Go,{documents:n,externalSymbols:[]})),i=Ln(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Xu(e){let t=Ee(e,Ue);return{rootDir:t,blobDir:Ee(t,"blobs"),generationDir:Ee(t,"generations")}}function Bo(e){let t=Qu(e);return Zu(t.baseIndex,t.completeDocuments,"assembled")}function Qu(e){let t=Ln(e.baseIndexBytes);rd(t.metadata,id(e)),nd(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=Rt(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=Rt(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=Lo(c,u.bytes);i.push(d),o.push(d)}for(let s of[...n.keys()].sort()){let c=n.get(s);if(c.bytes===null)throw new Error(`TypeScript fragment deletion has no prior document: ${s}`);if(r.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);r.add(s);let u=Lo(s,c.bytes);i.push(u),o.push(u)}return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function Lo(e,t){let n=Mo(No,t);if(n.relativePath!==e)throw new Error(`TypeScript fragment path mismatch: expected ${e}, got ${n.relativePath}`);return n}function Zu(e,t,n){let r=$o(jo(Go,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Ln(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Uo(e,t){let n=Xu(e);if(!Co(n.generationDir))return;let r=new Set(t.map(a=>td(a))),i=_o(n.generationDir).filter(a=>a.endsWith(".json")),o=new Set;for(let a of i.filter(s=>r.has(s))){let s=ed(E(Ee(n.generationDir,a),{maxBytes:O,inputKind:"TypeScript fragment manifest"}));for(let c of s.documents)o.add(`${c.blobHash}.scipdoc`)}for(let a of i)r.has(a)||Oo(Ee(n.generationDir,a),{force:!0});if(Co(n.blobDir))for(let a of _o(n.blobDir))o.has(a)||Oo(Ee(n.blobDir,a),{force:!0})}function ed(e){let t=JSON.parse(e);if(t.version!==jn||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(Rt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function td(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${X(e)}.json`}function nd(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function rd(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 id(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Rt(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 xt,readdirSync as Mn,rmSync as Wo}from"fs";import{join as z}from"path";var It=1;var We="typescript-scip-overlays";function Ho(e){let t=Yo(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=$n(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,od(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:It,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 ad(e.cacheDir,i),i}function zo(e){let t=Yo(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=T(z(qe(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:re,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||X(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 Bo({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Jo(e,t){let n=qe(e),r=z(n,"generations");if(!xt(r))return;let i=new Set(t.map(Gn)),o=new Set;for(let s of Mn(r).filter(c=>i.has(c))){let c=Nn(E(z(r,s),{maxBytes:O,inputKind:"TypeScript overlay manifest"}));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Mn(r))i.has(s)||Wo(z(r,s),{force:!0});let a=z(n,"blobs");if(xt(a))for(let s of Mn(a))o.has(s)||Wo(z(a,s),{force:!0})}function Yo(e,t){let n=z(qe(e),"generations",Gn(t));if(!xt(n))return null;let r=Nn(E(n,{maxBytes:O,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function od(e,t){let n=$n(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=X(r);return Ao({blobDir:z(qe(e),"blobs"),blobHash:i,bytes:r,relativePath:n,inputKind:"TypeScript overlay blob"}),{relativePath:n,blobHash:i,byteLength:r.byteLength}}function ad(e,t){let n=z(qe(e),"generations",Gn(t.generationIdentity));if(xt(n)){let r=Nn(E(n,{maxBytes:O,inputKind:"TypeScript overlay manifest"}));if(qo(r)!==qo(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}xe(n,t,{spacing:2,trailingNewline:!0})}function Nn(e){let t=JSON.parse(e);if(t.version!==It||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($n(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function qe(e){return z(e,We)}function Gn(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${X(e)}.json`}function qo(e){return X(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function $n(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 He=1,Bn="language-indexes",Ko=["index.db","index.scip","meta.json"],Xo=[Bn,Ue,We];function vt(e){let t=[];for(let n of Ko)pd(e,n),t.push(n);for(let n of Xo)Qo(e,n,t);return{version:He,files:t.sort()}}function Pt(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(!Ko.includes(e)&&!Xo.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function J(e,t){let n=Pt(t),r=Vn(e),i=Vn(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${ld}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Qo(e,t,n){let r=ud(e,t),i;try{i=cd(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()?Qo(e,a,n):o.isFile()&&n.push(Pt(a))}}function pd(e,t){let n=J(e,t),r;try{r=sd(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(dd(Vn(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as zn}from"crypto";import{closeSync as fd,existsSync as w,mkdirSync as gd,openSync as md,readSync as hd,readdirSync as Jn,renameSync as Hn,rmSync as ze,statSync as ke}from"fs";import{basename as na,dirname as Y,join as I,relative as Zo}from"path";var yd=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function Et(e){let t=V(e.outputDb),n=xd(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=Qn({generationRoot:t,databasePath:e.tempOutputDb,indexPath:w(r)?r:void 0,metadataPath:w(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:Ie,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},s=$(I(t,"state.json"),a,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||qn(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),qn(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),qn(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,u={...a,stableMirrors:Xn(e.outputDb,e.outputScip)};$(I(t,"state.json"),u,{spacing:2,trailingNewline:!0});let d=ra(e.outputDb,{now:e.now}),l=Ne(i.directorySync,s.directorySync);return{currentGeneration:c,...n?{previousGeneration:n}:{},retention:d,achievedDurability:l==="synced"?"directory-durable":"file-flushed",directorySync:l}}function Yn(e,t,n,r=()=>new Date){if(!w(e))return null;let i=Ge(e),o=I(V(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Qt(e,i.currentGeneration))return i;let a=V(e),s=!i&&w(o)?vd(n,e,t):void 0;if(s&&!st(a,s))return null;let c=Qn({generationRoot:a,databasePath:e,indexPath:w(t)?t:void 0,metadataPath:w(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),u={version:Ie,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Xn(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return $(I(a,"state.json"),u,{spacing:2,trailingNewline:!0}),u}function Kn(e,t,n=()=>new Date){if(!w(e)||!w(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=Ge(e),i=V(e),o=Qn({generationRoot:i,databasePath:e,indexPath:w(I(Y(e),"index.scip"))?I(Y(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?oa(e,r.currentGeneration):void 0,s={version:Ie,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Xn(e,I(Y(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return $(I(V(e),"state.json"),s,{spacing:2,trailingNewline:!0}),ra(e,{now:n}),s}function ra(e,t={}){let n=Sd(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=fe(Jr(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=Ge(e),s=bd(e),c=Yr(e,s.map(R=>R.identity),{isProcessAlive:t.isProcessAlive??ie,readProcessIdentity:t.readProcessIdentity??W}),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((R,D)=>R+D.logicalBytes,0),p=0,g=0;for(let R of s){if(d<=n.maxGenerations&&l<=n.maxLogicalBytes)break;u.has(R.identity)||(t.onBeforeRemove?.(R.identity),ze(R.path,{recursive:!0,force:!0}),d-=1,l-=R.logicalBytes,p+=1,g+=R.logicalBytes)}let f=d>n.maxGenerations||l>n.maxLogicalBytes,m={state:f?"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:g,limits:n,at:i,...f?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return ea(e,m),m}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{ea(e,s)}catch{}return s}finally{o.release()}}function Sd(e={}){let t={...yd,...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 bd(e){let t=V(e);return w(t)?Jn(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=I(t,n.name),i=st(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):ia(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:ke(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function ia(e){let t=0;for(let n of Jn(e,{withFileTypes:!0})){let r=I(e,n.name);n.isDirectory()?t+=ia(r):n.isFile()&&(t+=ke(r).size)}return t}function ea(e,t){xe(I(V(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function B(e,t=I(Y(e),"meta.json")){let n=I(V(e),"state.json");if(!w(n))return{state:"legacy",statePath:n};let r=Ge(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Qt(e,r.currentGeneration),o=i!==null,a=i?Rd(e,t,i,r):!1,s=r.previousGeneration?w(I(Y(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 Rd(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==$e(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==$e(I(Y(e),"index.scip")))||!ta(e,n.database))return!1;let i=I(Y(e),"index.scip");if(n.index&&!ta(i,n.index))return!1;if(!n.metadata)return!w(t);if(!w(t))return!1;let o=I(V(e),n.identity,n.metadata.file);return w(o)&&ge(L(t,"reindex metadata"))===ge(L(o,"immutable reindex metadata"))}function ta(e,t){return w(e)&&ke(e).isFile()&&ke(e).size===t.size}function xd(e){let t=Yn(e.outputDb,e.outputScip,e.metaPath);return t?oa(e.outputDb,t.currentGeneration):void 0}function Xn(e,t){return{databaseFileIdentity:$e(e),...w(t)?{indexFileIdentity:$e(t)}:{}}}function oa(e,t){let n=I(V(e),t),r=I(n,na(e)),i=I(n,"meta.json");return{generationIdentity:t,databasePath:Zo(Y(e),r),...w(i)?{metadataPath:Zo(Y(e),i)}:{}}}function Id(e){if(w(e))for(let t of Jn(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&ze(I(e,t.name),{recursive:!0,force:!0})}function vd(e,t,n=I(Y(t),"index.scip")){let r=zn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(wt(t)),w(n)&&r.update(`\0${wt(n)}`),w(e)&&r.update(`\0${ge(L(e,"reindex metadata"))}`),r.digest("hex")}function Qn(e){let t=Un(e.databasePath),n=e.indexPath?Un(e.indexPath):void 0,r=e.metadataPath?Un(e.metadataPath):void 0,i=e.forcedIdentity??Pd(t,n,e.metadataPath),o=I(e.generationRoot,i),a=I(o,Xt);if(w(a)){let u=st(e.generationRoot,i);if(u&&aa(o,u.database,t)&&Ed(o,u.index,n)&&kd(o,u.metadata,e.metadataPath))return{identity:i,directorySync:oe(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[it(e.generationRoot)];Id(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;ze(c,{recursive:!0,force:!0}),gd(c,{recursive:!0});try{s.push(Wn(e.databasePath,I(c,t.file))),n&&e.indexPath&&s.push(Wn(e.indexPath,I(c,n.file))),r&&e.metadataPath&&s.push(Wn(e.metadataPath,I(c,r.file)));let u=$(I(c,Xt),{version:zr,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});u.directorySync!=="not-requested"&&s.push(u.directorySync),s.push(oe(c)),Hn(c,o),s.push(oe(e.generationRoot))}finally{ze(c,{recursive:!0,force:!0})}return{identity:i,directorySync:Ne(...s)}}function Pd(e,t,n){let r=zn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ge(L(n,"reindex metadata"))}`),r.digest("hex")}function Un(e){return{file:na(e),size:ke(e).size,sha256:wt(e)}}function wt(e){let t=zn("sha256"),n=md(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=wd(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{fd(n)}return t.digest("hex")}function wd(e,t){let n=0;for(;n<t.length;){let r=hd(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function Wn(e,t){return ot(e,t,{mode:292})}function aa(e,t,n){let r=I(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&w(r)&&ke(r).size===t.size&&wt(r)===t.sha256}function Ed(e,t,n){return!t||!n?t===n:aa(e,t,n)}function kd(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=I(e,t.file);return w(r)&&ge(L(r,"stored reindex metadata"))===ge(L(n,"candidate reindex metadata"))}function qn(e,t){ze(`${t}.tmp-replace`,{force:!0}),Hn(e,`${t}.tmp-replace`),Hn(`${t}.tmp-replace`,t)}var nr=1,ca="SCIP_QUERY_SHARED_CACHE",Ad=2,kt=JSON.stringify({cliVersion:ti,artifactCatalogVersion:He,postIndexAugmentationSchemaVersion:Ad,sqliteGenerationStoreVersion:Ie,typescriptFragmentStoreVersion:jn,typescriptOverlayStoreVersion:It}),rr="manifest.json",Cd="shared-cache.json";var ir=[Bn,Ue,We];function Dt(e,t){if(!e.clean||!e.treeOid)return;let n=Ea(JSON.stringify({version:nr,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:kt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:kt,generationId:n,repositoryCacheDir:ii(e.repositoryId)}}function ha(e,t,n){if(process.env[ca]==="0")return`${ca}=0`;if(!oi(n))return"explicit cache or database override";if(tn(er(t))!==tn(ri(e))||t!==h(er(t),"index.db"))return"index database is outside the managed worktree cache"}function Q(e,t=!0){let n=ar(e),r;try{r=Ia(E(h(n,rr),{inputKind:"shared-generation manifest",maxBytes:O}))}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=J(n,i.path),a=Tt(o);if(!a.isFile()||a.size!==i.size||nt(o,{inputKind:"shared-generation artifact",maxBytes:j})!==i.sha256)return null}}catch{return null}return r}function ya(e,t,n){if(!e.treeOid)return null;let r=nn(t,n),i=h(ni(),"repositories",e.repositoryId),o;try{let c=Zn(i);if(!c.isDirectory()||c.isSymbolicLink())return null;o=ga(i)}catch{return null}let a=h(o,"generations"),s=[];try{for(let c of fa(a)){if(!/^[a-f0-9]{64}$/.test(c))continue;let u=h(a,c),d;try{d=Zn(u)}catch{continue}if(!(!d.isDirectory()||d.isSymbolicLink()))try{let l=Ia(E(h(u,rr),{inputKind:"shared-generation baseline manifest",maxBytes:O}));l.generationId===c&&l.repositoryId===e.repositoryId&&l.treeOid===e.treeOid&&l.producerIdentity===kt&&jd(l.fingerprint,r)&&s.push(l)}catch{continue}}}catch{return null}s.sort((c,u)=>Date.parse(u.createdAt)-Date.parse(c.createdAt)||c.generationId.localeCompare(u.generationId));for(let c of s){let u={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:c.fingerprint,producerIdentity:c.producerIdentity,generationId:c.generationId,repositoryCacheDir:o},d=Q(u);if(d)return{snapshot:u,manifest:d}}return null}function Sa(e){let t=fe(h(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 _d(e)}finally{t.release()}}function _d(e){let t=Q(e.snapshot);if(t)return ua(e.snapshot,t);if(!wa(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=da(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=vt(e.sourceCacheDir),i=h(e.snapshot.repositoryCacheDir,"generations"),o=[it(i)],a=pa(h(i,`.tmp-${process.pid}-`));try{let s=[];for(let f of r.files){let m=J(e.sourceCacheDir,f),R=J(a,f);o.push(Ye(m,R,292)),e.onPublicationStage?.("after-artifact-flushed",f);let D=Tt(R).size;s.push({path:f,size:D,sha256:nt(R,{inputKind:"staged shared-generation artifact",maxBytes:j})})}let c=ma(T(h(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:j})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let u=sr(e.sourceProjectRoot);if(c!==u)throw new Error("shared SCIP generation root does not match its source worktree");if(da(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let d={version:nr,artifactCatalogVersion:He,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((f,m)=>f.path.localeCompare(m.path))},l=$(h(a,rr),d,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(oe(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=ar(e.snapshot);try{if(ue(p)&&!Q(e.snapshot)){let f=`${p}.corrupt-${process.pid}-${Date.now()}`;Se(p,f),ce(f,{recursive:!0,force:!0})}Se(a,p)}catch(f){let m=Q(e.snapshot);if(m)return ua(e.snapshot,m);throw f}e.onPublicationStage?.("after-generation-renamed"),o.push(oe(i)),e.onPublicationStage?.("after-generations-directory-synced");let g=Ne(...o);return{kind:"published",manifest:d,achievedDurability:g==="synced"?"directory-durable":"file-flushed",directorySync:g}}finally{ce(a,{recursive:!0,force:!0})}}function ua(e,t){let n=oe(h(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function Ft(e){let t=ar(e.snapshot);Te(e.targetCacheDir,{recursive:!0});let n=fe(h(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=pa(h(e.targetCacheDir,".shared-hydrate-")),$d(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=J(t,c.path),d=J(r,c.path);if(Ye(u,d),Tt(d).size!==c.size||nt(d,{inputKind:"hydrated shared-generation artifact",maxBytes:j})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=sr(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&ao(J(r,c.path),e.manifest.scipProjectRoot,a);if(!wa(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Md(e.targetCacheDir,r),o=!0,Nd(r,e.targetCacheDir,i),Et({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=B(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}`);e.persistLease!==!1&&or(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Gd(e.targetCacheDir,i),a}finally{r&&ce(r,{recursive:!0,force:!0}),n.release()}}async function ba(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??v,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(Q(e))return{kind:"generation-ready"};let u=rt(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 Dd(Math.min(r,d))}return Q(e)?{kind:"generation-ready"}:{kind:"timeout"}}function or(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:xa(i)};return va(e.repositoryCacheDir,o,!0),o}function Ra(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:xa(r)};return va(e.repositoryCacheDir,i,!0),i}function xa(e){return Ea(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:tr(e.projectRoot),localCacheDir:tr(e.localCacheDir)}))}function Ia(e){let t=JSON.parse(e);if(t.version!==nr||t.artifactCatalogVersion!==He||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!==kt||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(Pt(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 Ye(e,t,n=384){return ot(e,t,{mode:n})}function Od(e,t,n){Te(e,{recursive:!0}),$(h(e,Cd),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function da(e){try{let t=vt(e),n=la("sha256");for(let r of t.files){let i=J(e,r),o=Tt(i).size;n.update(r).update("\0").update(String(o)).update("\0"),Ur(i,{inputKind:"source-generation artifact",maxBytes:j},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Ld(e){try{let t=ne(E(h(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:O}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function jd(e,t){let n=nn(e.languages,e);return JSON.stringify(n)===JSON.stringify(t)}function ar(e){return h(e.repositoryCacheDir,"generations",e.generationId)}function va(e,t,n){let r=Hr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!ue(h(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=h(e,"worktrees");Te(i,{recursive:!0}),$(h(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Od(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Md(e,t){let n=h(t,".rollback"),r=new Map,i=new Map;Te(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=h(e,s),u=ue(c);r.set(s,u),u&&Ye(c,h(n,"stable",s))}for(let s of ir){let c=h(e,s),u=ue(c);if(u){let d=Zn(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,at),a=ue(o);return a&&Pa(o,h(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Nd(e,t,n){for(let r of ir){let i=h(t,r);if(n.managedDirectories.get(r)){let a=h(n.root,"managed",r);Te(er(a),{recursive:!0}),Se(i,a)}let o=h(e,r);ue(o)&&Se(o,i)}}function Gd(e,t){for(let i of ir){let o=h(e,i),a=h(t.root,"managed",i);t.managedDirectories.get(i)?ue(a)&&(ce(o,{recursive:!0,force:!0}),Se(a,o)):ce(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=h(e,i);if(!o){ce(a,{force:!0});continue}let s=`${a}.shared-restore-${Td()}`;Ye(h(t.root,"stable",i),s),ce(a,{force:!0}),Se(s,a)}let n=h(e,at);ce(n,{recursive:!0,force:!0});let r=h(t.root,"sqlite-generations");t.generationStoreExisted&&ue(r)&&Se(r,n)}function Pa(e,t){Te(t,{recursive:!0});for(let n of fa(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()?Pa(r,i):n.isFile()&&Ye(r,i)}}function $d(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 wa(e,t,n,r=!0,i=!0){try{let o=Ld(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=vt(e),s=B(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 Fd(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=sr(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let g=ma(T(J(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:j})).metadata?.projectRoot;return g!==u&&Je(`source validation rejected SCIP root for ${p}: ${String(g)}`),g===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 sr(e){try{return sa(ga(e)).href}catch{return sa(tr(e)).href}}function Ea(e){return la("sha256").update(e).digest("hex")}import{createHash as dl}from"crypto";import{existsSync as hr,writeFileSync as Ba}from"fs";import{join as ll}from"path";import{createRequire as Vd}from"module";import{dirname as pr,isAbsolute as Bd,relative as Da,resolve as le,sep as ur}from"path";var de=Vd(import.meta.url),Ud=1,ka="0.4.0";function Wd(){try{let e=Fa();if(!e.available)return e;let{packageRoot:t}=e,n=de.resolve("typescript",{paths:[t]}),r=de(n),{FileIndexer:i}=de(le(t,"dist/src/FileIndexer.js")),{Input:o}=de(le(t,"dist/src/Input.js")),{Packages:a}=de(le(t,"dist/src/Packages.js")),s=de(le(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:gr(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function fr(){let e=Fa();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Fa(){try{let e=de.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=pr(e),r=de.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:Ca(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Aa(e){let t=e.runtime===void 0?Wd():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:gr(e.runtime)};return t.available?{available:!0,emitter:new dr(e,t.runtime)}:t}var dr=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=le(t.workspaceRoot),this.tsconfigPath=le(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??Hd(this.workspaceRoot,pr(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=gr(n);let r=cr(n.typescript,this.tsconfigPath);this.config=r,this.host=new lr(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(Fe(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=At(t.modifiedFiles),i=At(t.affectedFiles),o=cr(this.runtime.typescript,this.tsconfigPath);this.config=o,this.includedFiles=new Set(o.fileNames.map(Fe));let a=this.program,s=new Map;for(let u of r){let d=De(this.workspaceRoot,u),l=a.getSourceFile(d);l&&(s.set(u,l),this.stats.symbolEntriesPruned+=Ta(this.symbolTable,l),this.stats.symbolEntriesPruned+=Ta(this.constructorTable,l)),this.host.invalidate(d)}this.program=this.runtime.typescript.createProgram(o.fileNames,o.options,this.host.compilerHost,a),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i);for(let[u,d]of s)this.program.getSourceFile(De(this.workspaceRoot,u))===d?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;let c=i.map(u=>{let d=De(this.workspaceRoot,u),l=this.program.getSourceFile(d);if(!l)throw new Error(`affected TypeScript source is unavailable: ${u}`);return this.emitSourceFile(l)});return this.result(c,n)}fragment(t){return this.fragments.get(Ct(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=At(t.modifiedFiles),i=At(t.affectedFiles);this.validateIncrementalPaths(r,i);let o=i.map(a=>{let s=this.program.getSourceFile(De(this.workspaceRoot,a));if(!s)throw new Error(`affected TypeScript source is unavailable: ${a}`);return this.emitSourceFile(s)});return this.result(o,n)}initializeProgram(){let t=this.config??cr(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Fe)),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){if(t.length===0)throw new Error("incremental TypeScript document update requires a modified file");if(n.length===0)throw new Error("incremental TypeScript document update requires an affected file");for(let r of t){let i=De(this.workspaceRoot,r);if(!this.program?.getSourceFile(i))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${r}`)}for(let r of n){let i=De(this.workspaceRoot,r);if(!this.includedFiles.has(Fe(i)))throw new Error(`affected TypeScript file is outside the configured project: ${r}`)}}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=Ct(Da(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:qd(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function qd(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 lr=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,u)=>{let d=Fe(a);if(this.sourceFiles.has(d))return this.sourceFiles.get(d);let l=o(a,s,c,u);return this.sourceFiles.set(d,l),l}}}invalidate(t){this.sourceFiles.delete(Fe(t))}};function cr(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,pr(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function gr(e){return Ca(e.packageVersion,e.typescript.version)}function Ca(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Ud}`}function Hd(e,t){return Ct(Da(e,t))||"."}function De(e,t){if(Bd(t))throw new Error(`expected a project-relative path: ${t}`);let n=le(e,t),r=e.endsWith(ur)?e:`${e}${ur}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function At(e){return[...new Set(e.map(Ct))].sort()}function Ct(e){return e.split(ur).join("/").replace(/^\.\//,"")}function Fe(e){return le(e)}function Ta(e,t){let n=0;for(let r of e.keys())if(zd(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function zd(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as Jd}from"crypto";import{dirname as Yd,join as _a}from"path";var Ae=4;var Kd="typescript-index";function Oa(e){let t=_a(e,Kd),n=Si(t);return{...n,requestDir:n.legacyRequestDir}}function La(e){try{let t=$r(ne(L(_a(Yd(e),"meta.json"),"reindex metadata")));return t?Jd("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as el}from"crypto";import{existsSync as tl}from"fs";import{randomUUID as Xd}from"crypto";import{getHeapStatistics as Qd}from"v8";import{resolve as Zd}from"path";var _t=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=Zd(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??Aa,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??v,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:Qd().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,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:Ae,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 Dh=`typescript-index-${process.pid}-${Xd()}`,ja=W(process.pid),Fh={pid:process.pid,...ja?{processIdentity:ja}:{}};var nl=12e4,rl=5,Ke=class extends Error{name="TypeScriptIndexMemoryPressureError"},Ot=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;localHost=null;constructor(t,n={}){this.projectRoot=ei(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??cl(),this.runtime=n.runtime??ul,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally}request(t){let n=xi(this.cacheDir),r=Oa(this.cacheDir),i=ln(n.statePath);if(!Ma(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??v)()+this.timeoutMs,c=un("typescript-index-v4",{baseGeneration:this.baseGeneration,request:t}),u=dn(c),d=bi(r,{mailboxVersion:cn,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ae,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??v)()<=s;){if(tl(d.responsePath))return il(E(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=ln(n.statePath);if(!Ma(l,this.projectRoot,this.runtime))return this.requestLocally(t);this.runtime.sleep(rl)}return this.requestLocally(t)}requestLocally(t){return this.emitLocally?mr(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new _t({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),mr(Na(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Ma(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===Ae&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Ri&&(!e.processIdentity||r!=null&&Me(e.processIdentity,r))}function il(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ae||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 ol(s)?new Ke(s):new Error(s)}return mr(Na(a.response,i),i,o)}function ol(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 mr(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 Na(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(al)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:sl(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 al(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 sl(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function cl(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:nl}var ul={now:Date.now,monotonicNow:v,randomId:el,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ie,readProcessIdentity:W};function pl(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=tt(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let r=n.changes.filter(m=>m.inputKind==="source"&&pn(m.path));if(r.some(m=>m.kind!=="modified"&&m.kind!=="added"))return{eligible:!1,reason:"TypeScript project membership changed"};if(r.length===0)return{eligible:!1,reason:"change is not a modified TypeScript source file"};let i=r.filter(m=>m.kind==="added").map(m=>m.path),o=r.filter(m=>m.kind==="modified"),a={...n,changes:r},s=fl(o,i,e.graph,e.projectFiles);if(!s.eligible)return s;let c=s.plan,u=gl(c,t,e.graph);if(!u)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let d=Ga(e.currentSnapshot,e.projectFiles,e.producerIdentity),l=Ga(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(d!==l)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let p=Va(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!p)return{eligible:!1,reason:"prior document identity unavailable"};let g=Va(e.currentSnapshot,[...new Set([...e.projectFiles,...i])],e.graph,e.producerIdentity,c.affectedFiles);if(!g)return{eligible:!1,reason:"next document identity unavailable"};let f=u.length===1?u[0]:void 0;return{eligible:!0,manifest:a,plan:c,projectIdentity:d,previousFragmentGeneration:$a(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:$a(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:p,nextDocumentIdentities:g,projects:u,...f?{tsconfigPath:f.tsconfigPath,projectArgument:f.projectArgument}:{}}}function fl(e,t,n,r){if(e.length===0)return t.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...t].sort(),affectedFiles:[...t].sort(),reasons:[]}};let i=ft({version:1,changes:[...e],projectIdentityChanged:!1,uncertainty:[]},n,r);return i.mode!=="closure"||i.affectedFiles.length===0?{eligible:!1,reason:i.reasons.length>0?`affected set widened: ${i.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...i.changedFiles,...t])].sort(),affectedFiles:[...new Set([...i.affectedFiles,...t])].sort(),reasons:[]}}}function gl(e,t,n){let r=new Map;for(let o of e.affectedFiles){let a=ml(o,t);if(!a)return null;let s=r.get(a)??[];s.push(o),r.set(a,s)}let i=[];for(let[o,a]of[...r].sort(([s],[c])=>s.localeCompare(c))){let s=new Set(a),c=e.changedFiles.filter(u=>s.has(u)||a.some(d=>hl(d,u,n)));if(c.length===0)return null;i.push({projectArgument:o,tsconfigPath:o==="."?"tsconfig.json":`${o}/tsconfig.json`,modifiedFiles:c,affectedFiles:[...a].sort()})}return i}function ml(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)=>Lt(a)-Lt(o)||o.localeCompare(a)),i=r[0];return r[1]&&Lt(r[1])===Lt(i)?null:i}function Lt(e){return e==="."?0:e.split("/").filter(Boolean).length}function hl(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 Ua(e){let t=v();try{if(!hr(e.previousDbPath)||!hr(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=fr();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new q({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s,c;try{a=ct(o,{includeIgnored:!1}).filter(pn).sort(),c=fi(o),s=c.graph}finally{o.close()}let u=performance.now()-n,d=pl({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?ve(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:hr(ll(e.projectRoot,"tsconfig.json"))});if(!d.eligible)throw new Error(d.reason);let l=La(e.previousDbPath);if(!l)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new Ot({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:l}),g=d.projects.map(y=>p.request({kind:"emit-documents",tsconfigPath:y.tsconfigPath,projectArgument:y.projectArgument,projectIdentity:d.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:y.modifiedFiles,affectedFiles:y.affectedFiles})),f=g.flatMap(y=>y.fragments),m=performance.now()-n;n=performance.now();let R=Vo(f),D=performance.now()-n;n=performance.now(),Ho({cacheDir:e.cacheDir,previousGenerationIdentity:d.previousFragmentGeneration,nextGenerationIdentity:d.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:f});let _=performance.now()-n;n=performance.now(),Ba(e.candidateAffectedScipPath,R);let x=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!1,durationMs:v()-t,cold:g.some(y=>y.cold),changedFiles:d.plan.changedFiles,affectedFiles:d.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:d.previousFragmentGeneration,nextFragmentGeneration:d.nextFragmentGeneration,manifest:d.manifest,plan:d.plan,projectFileCount:a.length,dependencyGraphSnapshot:c,referenceFragmentsByFile:new Map(f.map(y=>[y.relativePath,y.referenceFragments])),timings:{runtimeMs:i,graphMs:u,requestMs:m,serviceMs:g.reduce((y,k)=>y+k.durationMs,0),assemblyMs:D,fragmentStoreMs:_,writeMs:x}};return e.onStatus(`Incremental TypeScript index emitted ${P.affectedFiles.length} affected document(s) across ${d.projects.length} project(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${u.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${D.toFixed(0)}ms, fragments ${_.toFixed(0)}ms, write ${x.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Ke)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}. Falling back to the whole-project indexer.`),null}}function yr(e){let t=fr();if(!t.available)throw new Error(t.reason);let n=zo({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:T(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:j}),packageVersion:t.packageVersion});Ba(e.candidateShardPath,n)}function Ga(e,t,n){let r=e.files.filter(i=>{let o=et(i.path,e.languages);return o==="config"||o==="ambient"}).map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Sr(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function $a(e,t){return Sr(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Va(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Ii({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,Sr(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function Sr(e){return dl("sha256").update(e).digest("hex")}import{closeSync as yl,existsSync as jt,fstatSync as Sl,lstatSync as bl,openSync as Rl,renameSync as xr,rmSync as Mt,statSync as xl,writeSync as Il}from"fs";import{cpus as vl}from"os";import{join as Ir}from"path";var br=Symbol("no-error");async function Wa(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=br,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===br&&(s=l),c=!1}}});if(await Promise.all(u),s!==br)throw s;return r}function Pl(e,t){if(e.temporaryRootConfigContent===void 0)return null;let n=Ir(t,"tsconfig.json"),r=Buffer.from(e.temporaryRootConfigContent,"utf8"),i;try{i=Rl(n,"wx",384)}catch(o){if(o.code==="EEXIST")return null;throw o}try{Il(i,r);let o=Sl(i);return{path:n,content:r,device:o.dev,inode:o.ino}}finally{yl(i)}}function wl(e){if(e)try{let t=bl(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=T(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Mt(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function El(e,t,n){if(!e.defaultOutputPath)return;let r=Ir(t,e.defaultOutputPath);n!==r&&jt(r)&&xr(r,n)}function kl(e,t,n){if(!e.defaultOutputPath)return null;let r=Ir(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Mt(i,{force:!0}),jt(r)?(xr(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Tl(e){e&&(Mt(e.defaultOutputPath,{force:!0}),e.backupPath&&jt(e.backupPath)&&xr(e.backupPath,e.defaultOutputPath))}function Dl(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,vl().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ha(e,t,n,r,i){G(i,"Reindex cancelled by its owner.");let o=e.filter(d=>d.config.defaultOutputPath),a=e.filter(d=>!d.config.defaultOutputPath),s=[],c=Dl(a.length,r),u=await Wa(a,c,d=>Rr(d,t,n,i));if(c>1){let d=new Map;for(let l of u.filter(p=>p.result.skipped&&p.retryable)){let p=a.find(g=>g.id===l.result.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),G(i,"Reindex cancelled by its owner."),d.set(p.id,(await Rr(p,t,n,i)).result))}s.push(...u.map(({result:l})=>d.get(l.id)??l))}else s.push(...u.map(({result:d})=>d));for(let d of o)G(i,"Reindex cancelled by its owner."),s.push((await Rr(d,t,n,i)).result);return s.sort((d,l)=>e.findIndex(p=>p.id===d.id)-e.findIndex(p=>p.id===l.id))}async function Rr(e,t,n,r){G(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Mt(e.scipPath,{force:!0});let i=kl(e.config,t,e.scipPath),o=Pl(e,t),a=[e.binary,...e.args].join(" "),s=v();try{e.trustedProjectTool&&yi(t,e.trustedProjectTool);let u=mi(e.binary,e.args),d=await lt({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Fl(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(d.status!==0){let l=d.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${d.status}${l?`:
233
+ ${l}`:""}`)}El(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw Wr(r,"Reindex cancelled by its owner.");let d=u instanceof Error?u.message:String(u),l=`${e.resolvedBinary} indexer failed: ${d.split(`
234
+ `)[0]}`,p=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:v()-s,command:a,skipped:{language:e.language,reason:p}},retryable:Al(u)}}finally{Tl(i),wl(o)}if(!jt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:v()-s,command:a,skipped:{language:e.language,reason:d}},retryable:!1}}let c;try{c=xl(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:v()-s,command:a,outputBytes:c},retryable:!1}}function Fl(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):wi.indexer}function Al(e){return e instanceof Ei?e.kind==="spawn"&&qa(e.cause):qa(e)}function qa(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Ja}from"child_process";import{homedir as za,platform as Cl}from"os";import{delimiter as _l,join as Nt}from"path";function Pr(e,t){let n=e.installMethods,r=Ve(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(!rn(i.prerequisite))continue;let o=Ol(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Ja(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Cl()==="win32"});let a=we(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 Ol(e){if(e.binary==="npm")return vr("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=vr("go",["env","GOBIN"]);if(t)return t;let n=vr("go",["env","GOPATH"]);if(n)return Nt(n.split(_l)[0],"bin")}return e.binary==="dotnet"?Nt(process.env.DOTNET_CLI_HOME??za(),".dotnet","tools"):e.binary==="dart"?Nt(process.env.PUB_CACHE??Nt(za(),".pub-cache"),"bin"):e.destination}function vr(e,t){try{return Ja(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import ys from"better-sqlite3";import{existsSync as Ss}from"fs";import{dirname as bs,join as Rs,resolve as xs}from"path";import{randomUUID as jl}from"crypto";import{mkdtempSync as Ml,rmSync as Nl,statSync as Ka}from"fs";import{tmpdir as Gl}from"os";import{join as Xa}from"path";import{Worker as $l}from"worker_threads";function Ll(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Ce(){return{skippedReferences:0,skippedReferenceReasons:Ll(),skippedReferenceSamples:[]}}function Gt(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 Vl=3e5,Qa=64*1024*1024,Bl={createResultDirectory:()=>Ml(Xa(Gl(),"scip-query-vue-workers-")),spawn:(e,t)=>new $l(e,{workerData:t}),resultSize:e=>Ka(e).size,readResult:e=>E(e,{maxBytes:Qa,inputKind:"Vue worker result"}),removeResultDirectory:e=>Nl(e,{recursive:!0,force:!0})};function Za(e){return e.length>=8&&ts(e.length)>1}async function es(e,t=Bl){let n=ts(e.vueFiles.length),r=tp(e.vueFiles),i=rp(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??Zl(),s=e.maxResultBytes??ep();Ya("timeoutMs",a),Ya("maxResultBytes",s);let c=jl(),u=t.createResultDirectory(),d=[],l,p,g;try{for(let m=0;m<i.length;m++){let R=m,D=i[m]??[],_=D.map(y=>y.taskId),x=Xa(u,`${R}.json`),P=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:D,resultPath:x,runId:c,workerId:R,taskIds:_});d.push({workerId:R,taskIds:_,resultPath:x,handle:P,completion:Ul(P,R)})}await Wl(d,a);let f=d.sort((m,R)=>m.workerId-R.workerId).map(m=>Hl(m,c,s,t));g={occurrences:f.flatMap(m=>m.occurrences),...Ce()};for(let m of f)Gt(g,m)}catch(f){l=f}finally{let f=await ql(d);if(f.length===0)try{t.removeResultDirectory(u)}catch(m){f.push(m)}if(f.length>0){let m=l===void 0?f:[l,...f];p=new AggregateError(m,`Vue worker cleanup failed: ${Ql(m[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!g)throw new Error("Vue workers completed without producing a merged result.");return g}function Ul(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 Wl(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 ql(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Hl(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(!Xe(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(!Xl(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||!zl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function zl(e){if(!Xe(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Jl)||!Z(e.skippedReferences)||!Xe(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!Z(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Yl)}function Jl(e){return Xe(e)&&typeof e.sourceFile=="string"&&Z(e.sourceLine)&&Z(e.sourceStartChar)&&Z(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&Z(e.symbolId)}function Yl(e){return Xe(e)&&typeof e.sourceFile=="string"&&Z(e.sourceLine)&&Z(e.sourceStartChar)&&Z(e.sourceEndChar)&&typeof e.token=="string"&&Kl(e.reason)}function Kl(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function Z(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Ya(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Ql(e){return e instanceof Error?e.message:String(e)}function ts(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 Zl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Vl}function ep(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Qa}function tp(e){let t=np(),n=[];for(let r of e){let i=ns(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 np(){return Number.POSITIVE_INFINITY}function rp(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:ip(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 ip(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,ns(e.fileName)-e.startOffset)}function ns(e){try{return Ka(e).size}catch{return 1}}import{createRequire as op}from"module";import{existsSync as ap}from"fs";import{dirname as rs,extname as sp,join as is,relative as cp,resolve as up}from"path";import{pathToFileURL as dp}from"url";function lp(e){e.transaction(()=>{e.prepare(`
236
235
  DELETE FROM mentions
237
236
  WHERE chunk_id IN (
238
237
  SELECT c.id
@@ -247,12 +246,12 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
247
246
  FROM documents
248
247
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
249
248
  )
250
- `).run()})()}function Zn(e,t){return e.prepare(`
249
+ `).run()})()}function Er(e,t){return e.prepare(`
251
250
  SELECT relative_path AS relativePath
252
251
  FROM documents
253
252
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
254
253
  ORDER BY relative_path
255
- `).all().map(r=>il(t,r.relativePath))}function ma(e,t){let{vueCore:n,ts:r,volarTs:i}=sl(e),{parsed:o,vueOptions:a}=cl(n,r,t),s=ga(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=ul(n,r,c),d=dl(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),p=r.createLanguageService(l);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function sl(e){let t=el(ol(fa(e,"package.json")).href);return{vueCore:Qn(t,"@vue/language-core",e),ts:Qn(t,"typescript",e),volarTs:Qn(t,"@volar/typescript",e)}}function cl(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,ga(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function ul(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!tl(o))return;let a=v(o,{maxBytes:B,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??hl(o))});return r.current=i,i}function dl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Qn(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 ha(e,t,n){let r=ll(e);return i=>{if(!i.name)return null;let o=W(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 u=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:pl(c.starts,s.line,2,i.name)}}function ll(e){let t=e.prepare(`
254
+ `).all().map(r=>up(t,r.relativePath))}function os(e,t){let{vueCore:n,ts:r,volarTs:i}=pp(e),{parsed:o,vueOptions:a}=fp(n,r,t),s=rs(t),c=n.createVueLanguagePlugin(r,o.options,a,g=>g),u=gp(n,r,c),d=mp(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,u,g=>g,d),p=r.createLanguageService(l);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function pp(e){let t=op(dp(is(e,"package.json")).href);return{vueCore:wr(t,"@vue/language-core",e),ts:wr(t,"typescript",e),volarTs:wr(t,"@volar/typescript",e)}}function fp(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,rs(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function gp(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!ap(o))return;let a=E(o,{maxBytes:re,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??xp(o))});return r.current=i,i}function mp(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function wr(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 as(e,t,n){let r=hp(e);return i=>{if(!i.name)return null;let o=ee(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 u=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:yp(c.starts,s.line,2,i.name)}}function hp(e){let t=e.prepare(`
256
255
  SELECT
257
256
  d.relative_path AS relativePath,
258
257
  der.start_line AS startLine,
@@ -263,22 +262,22 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
263
262
  JOIN documents d ON d.id = der.document_id
264
263
  JOIN global_symbols gs ON gs.id = der.symbol_id
265
264
  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 pl(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 u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function er(e,t,n){let r=bl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
265
+ `).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 yp(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 u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function kr(e,t,n){let r=Pp(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
267
266
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
268
267
  VALUES (?, ?, ?, ?)
269
- `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=W(t,u),l=wa(r.name,r.version,d);o.run(l,"default",7,`Vue component|${d}`);let p=Rl(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function ya(e,t,n,r,i){return e.transaction(()=>(al(e),gl(e,t,n,r),fl(e,i)))()}function gl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
268
+ `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=ee(t,u),l=ms(r.name,r.version,d);o.run(l,"default",7,`Vue component|${d}`);let p=wp(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function ss(e,t,n,r,i){return e.transaction(()=>(lp(e),Sp(e,t,n,r),bp(e,i)))()}function Sp(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
270
269
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
271
270
  VALUES (?, ?, ?, ?, X'00')
272
271
  `),a=e.prepare(`
273
272
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
274
273
  VALUES (?, ?, 1)
275
- `);for(let s of n){let c=r.get(s);if(!c)continue;let u=W(t,s),d=i.get(u);if(!d)continue;let l=o.run(d.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function Sa(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(tr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ba(e){let t=new Set,n=[];for(let r of e){let i=Ra(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ra(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function fl(e,t){let n=Sl(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
274
+ `);for(let s of n){let c=r.get(s);if(!c)continue;let u=ee(t,s),d=i.get(u);if(!d)continue;let l=o.run(d.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function cs(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(Tr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function us(e){let t=new Set,n=[];for(let r of e){let i=ds(r);t.has(i)||(t.add(i),n.push(r))}return n}function ds(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function bp(e,t){let n=vp(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
276
275
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
277
276
  VALUES (?, ?, ?, ?, X'00')
278
277
  `),i=e.prepare(`
279
278
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
280
279
  VALUES (?, ?, 0)
281
- `),o=new Set,a=0,s=0;for(let c of t){let u=Ra(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let l=r.run(d,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*xa(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 Ia(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function tr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function ml(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 va(e,t){return W(e,t).startsWith("node_modules/")}function W(e,t){return rl(e,t).replaceAll("\\","/")}function hl(e){switch(nl(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 Pa(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=v(t,{maxBytes:B,inputKind:"Vue source file"}),r={text:n,lineStarts:yl(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:ml}}function yl(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Sl(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 bl(e){try{let t=JSON.parse(v(fa(e,"package.json"),{maxBytes:A,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Rl(e,t,n,r){let i=W(n,r),o=wa(t.name,t.version,i);return e.get(o)?.id??null}function wa(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function _a(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Pl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Il(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),q(_a({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function vl(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),wl(e)}function Pl(e){let t=Aa(e.projectRoot,e.tsconfig);if(!Ta(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ea(e.dbPath);try{let r=Zn(n,e.projectRoot),i=Fa(Da(e.dbPath),"augment-vue-meta.json");return Ei({cachePath:i,readFingerprint:()=>Ca(n,e.projectRoot,e.tsconfig),compute:()=>kl({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 wl(e){let t=Aa(e.projectRoot,e.tsconfig);if(!Ta(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ea(e.dbPath);try{let r=Zn(n,e.projectRoot),i=Fa(Da(e.dbPath),"augment-vue-meta.json");return await Ti({cachePath:i,readFingerprint:()=>Ca(n,e.projectRoot,e.tsconfig),compute:()=>El({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 kl(e){let t=er(e.db,e.projectRoot,e.vueFiles),n=Oa(e,t);return La(e,t,n)}async function El(e){let t=er(e.db,e.projectRoot,e.vueFiles),n=ua(e.vueFiles)?await da({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Oa(e,t);return La(e,t,n)}function La(e,t,n){let r=ba(n.occurrences),i=ya(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:jl(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Cl(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Oa(e,t){let n=Tl({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Dl({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ca(e,t,n){let r=e.prepare(`
280
+ `),o=new Set,a=0,s=0;for(let c of t){let u=ds(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let l=r.run(d,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*ls(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 ps(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Tr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Rp(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 fs(e,t){return ee(e,t).startsWith("node_modules/")}function ee(e,t){return cp(e,t).replaceAll("\\","/")}function xp(e){switch(sp(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 gs(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=E(t,{maxBytes:re,inputKind:"Vue source file"}),r={text:n,lineStarts:Ip(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Rp}}function Ip(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function vp(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 Pp(e){try{let t=JSON.parse(E(is(e,"package.json"),{maxBytes:O,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function wp(e,t,n,r){let i=ee(n,r),o=ms(t.name,t.version,i);return e.get(o)?.id??null}function ms(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Is(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Dp({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function kp(e){return H(ae(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),H(Is({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Tp(e){return H(ae(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Fp(e)}function Dp(e){let t=xs(e.projectRoot,e.tsconfig);if(!Ss(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ys(e.dbPath);try{let r=Er(n,e.projectRoot),i=Rs(bs(e.dbPath),"augment-vue-meta.json");return bo({cachePath:i,readFingerprint:()=>ws(n,e.projectRoot,e.tsconfig),compute:()=>Ap({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 Fp(e){let t=xs(e.projectRoot,e.tsconfig);if(!Ss(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ys(e.dbPath);try{let r=Er(n,e.projectRoot),i=Rs(bs(e.dbPath),"augment-vue-meta.json");return await Ro({cachePath:i,readFingerprint:()=>ws(n,e.projectRoot,e.tsconfig),compute:()=>Cp({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 Ap(e){let t=kr(e.db,e.projectRoot,e.vueFiles),n=Ps(e,t);return vs(e,t,n)}async function Cp(e){let t=kr(e.db,e.projectRoot,e.vueFiles),n=Za(e.vueFiles)?await es({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Ps(e,t);return vs(e,t,n)}function vs(e,t,n){let r=us(n.occurrences),i=ss(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Vp(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:$p(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Ps(e,t){let n=_p({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Op({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function ws(e,t,n){let r=e.prepare(`
282
281
  SELECT
283
282
  (SELECT COUNT(*) FROM documents) AS documents,
284
283
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -287,13 +286,13 @@ ${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
287
286
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
288
287
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
289
288
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
290
- `).get();return{version:3,tsconfig:n,files:Qe(t),db:r}}function Tl(e){let t=Pa();return{projectRoot:e.projectRoot,context:ma(e.projectRoot,e.configPath),symbolLookup:ha(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Dl(e){let t=[],n=he(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Fl(e,i);t.push(...o.occurrences),It(n,o)}return{occurrences:t,...n}}function Fl(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return ka(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 ka(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=W(e.projectRoot,t.fileName),s=[...xa(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:Nl(s),processedStarts:new Set};return Al({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Al(e){let t=[],n=he();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||_l(e.sourceInfo.text,r.start))continue;let i=Ia(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!va(e.projectRoot,d.fileName));if(!a){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=W(e.projectRoot,a.fileName),c=Ll(e.sourceFile,r.text,s);if(c){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=Sa(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ja(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Ml(t,e,r,i,s,u)}return{occurrences:t,...n}}function _l(e,t){let n=e.lastIndexOf(`
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.
289
+ `).get();return{version:3,tsconfig:n,files:ci(t),db:r}}function _p(e){let t=gs();return{projectRoot:e.projectRoot,context:os(e.projectRoot,e.configPath),symbolLookup:as(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Op(e){let t=[],n=Ce(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Lp(e,i);t.push(...o.occurrences),Gt(n,o)}return{occurrences:t,...n}}function Lp(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return hs(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 hs(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=ee(e.projectRoot,t.fileName),s=[...ls(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:Up(s),processedStarts:new Set};return jp({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function jp(e){let t=[],n=Ce();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Mp(e.sourceInfo.text,r.start))continue;let i=ps(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!fs(e.projectRoot,d.fileName));if(!a){Dr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=ee(e.projectRoot,a.fileName),c=Np(e.sourceFile,r.text,s);if(c){Dr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=cs(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){Dr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Es(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Bp(t,e,r,i,s,u)}return{occurrences:t,...n}}function Mp(e,t){let n=e.lastIndexOf(`
290
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Np(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function hs(e,t,n){let r=Ce();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:ee(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Dr(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 Fr(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 Gp(e,t){let n=Fr(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=Fr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function $p(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(...Fr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Vp(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Gp(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Bp(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Wp(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&&(Es(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function Es(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 Up(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Wp(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=qp(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function qp(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 zS(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Zp(e),a=Date.now(),s=v();Vt(S(o.outputScip),{recursive:!0}),Vt(S(o.outputDb),{recursive:!0});let c=e.languages??Rn(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=Ut(o.metaPath),d=M("reindex.fingerprint",()=>ui(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,Zt(o.outputDb)),{languages:c.length}),l=d.fingerprint,p=d.mode==="delta"?e.changeJournal?.entries.filter(y=>y.kind!=="add").length??0:0,g=Math.max(0,(u?.files.length??0)-p);r(d.mode==="delta"?`Project fingerprint revalidated ${d.changedPaths.length} changed path(s), reused ${g} accepted file fingerprint(s), and accepted ${l.files.length} input(s)`:`Project fingerprint used full scan: ${d.reason}`);let f,m;if(e.skipIfUnchanged!==!1&&!ha(t,o.outputDb)&&ks(o.outputScip)===ks(C(S(o.outputDb),"index.scip"))){let y=ut(t);if(f=y?.clean?Dt(y,l):void 0,y&&!y.clean&&!Qp(o)){let k=ya(y,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath});if(k)try{Ft({snapshot:k.snapshot,manifest:k.manifest,targetCacheDir:S(o.outputDb),targetProjectRoot:t,persistLease:!1}),Ra(k.snapshot,S(o.outputDb)),r(`Forked shared baseline ${k.snapshot.generationId.slice(0,12)} for dirty worktree reindex`)}catch(F){r(`Shared baseline fork failed; continuing locally: ${be(F)}`)}}else if(f){let k=Q(f);if(k){if(!Xp(o,l))try{Ft({snapshot:f,manifest:k,targetCacheDir:S(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${f.generationId.slice(0,12)}`)}catch(F){r(`Shared generation attach failed; continuing locally: ${be(F)}`)}}else{let F=await ba(f);if(F.kind==="owner")m=F.release;else if(F.kind==="generation-ready"){let pe=Q(f);if(pe)try{Ft({snapshot:f,manifest:pe,targetCacheDir:S(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${f.generationId.slice(0,12)} after waiting`)}catch(te){r(`Shared generation attach failed after waiting; continuing locally: ${be(te)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let D=fe(C(S(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!D)throw m?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${S(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 _;try{_=await me("reindex.lock",()=>Tf(C(S(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(y){throw D.release(),m?.(),y}let x=null,P=Li();try{d.mode==="delta"&&Zt(o.outputDb)!==e.changeJournal?.baseGeneration&&(l=dt(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),d={mode:"full",fingerprint:l,reason:"accepted-generation-changed-before-lock"},f=void 0,m?.(),m=void 0,r("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Yn(o.outputDb,o.outputScip,o.metaPath);let y=rf(S(o.outputDb));y.removed>0&&r(`Removed ${y.removed} abandoned reindex workspace(s)`);for(let Ze of y.errors)r(`Could not remove abandoned reindex workspace: ${Ze}`);let k=null,F=M("reindex.reuse-check",()=>(k=ef({opts:e,paths:o,languages:c,fingerprint:l,start:a,monotonicStart:s,onStatus:r}),k),()=>({languages:c.length,reused:k!==null}));if(F){Ts({snapshot:f,paths:o,projectRoot:t,fingerprint:l,onStatus:r});let Ze=mn(o.outputDb,F);return Ze.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${Ze.reason}`),en(t,S(o.outputDb)),F}await me("reindex.scip-cli-ready",()=>Rf(i,r));let pe=nf(o);x=pe.runDir;let te,b=await me("reindex.fresh",async()=>(te=await of({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:pe,fingerprint:l,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r,writeTelemetry:P}),te),()=>({languages:c.length,reused:te?.reused,skipped:te?.skipped.length}));Ts({snapshot:f,paths:o,projectRoot:t,fingerprint:l,onStatus:r});let K=mn(o.outputDb,b);return K.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${K.reason}`),en(t,S(o.outputDb)),b}catch(y){let k=qt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:y instanceof Error?y.message:String(y)});Xs(o.metaPath,k);let F=_i(o.outputDb,k);throw F.state==="failed"&&r(`Warning: failed reindex activity telemetry was not recorded: ${F.reason}`),y}finally{x&&_e(x,{recursive:!0,force:!0}),_(),D.release(),m?.()}}function Ts(e){if(e.snapshot)try{let t=ut(e.projectRoot),n=t?Dt(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=Sa({snapshot:e.snapshot,sourceCacheDir:S(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=ut(e.projectRoot);return(i?Dt(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});or(e.snapshot,S(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: ${be(t)}`)}}function Xp(e,t){if(!N(e.outputScip)||!N(e.outputDb)||!Ks(e.metaPath,t))return!1;let n=B(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Qp(e){if(!N(e.outputScip)||!N(e.outputDb)||!Re(e.metaPath))return!1;let t=B(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function be(e){return e instanceof Error?e.message:String(e)}function _r(e,t,n,r,i,o){try{H(Mi({indexPath:n,reuseExisting:i,affectedFiles:o}),{projectRoot:e,dbPath:t,onStatus:r})}catch(a){r(`Runtime-boundary extraction unavailable: ${a instanceof Error?a.message:String(a)}.`)}}function Zp(e){let t=e.outputScip??C(e.projectRoot,"index.scip"),n=e.outputDb??C(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:C(S(n),"meta.json")}}function ef(e){let t=B(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!N(e.paths.outputScip)||!N(e.paths.outputDb)||!Ks(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;let n=St(e.paths.outputDb,e.fingerprint,e.languages);if(n.state!=="complete")return e.onStatus(Or("Accepted SQLite index",n)),null;H(ae(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),_r(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),B(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Kn(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation"));let r=v()-e.monotonicStart,i=qt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Xs(e.paths.metaPath,i),e.onStatus(`Index unchanged; reused existing SQLite index in ${(r/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:r,reused:!0,skipped:[],lastRefresh:i,shards:tf(e.paths,e.languages,e.opts,e.fingerprint)}}function tf(e,t,n,r){let i=Js(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Qe(i[o]),outputBytes:Oe(Lr(e.outputDb,o)),durationMs:0}))}function nf(e){let t=zp(C(S(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:C(t,$t(e.outputScip)),tempOutputDb:C(t,$t(e.outputDb)),tempMetaPath:C(t,$t(e.metaPath))}}function rf(e){let t=[],n;try{n=Ls(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[be(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{_e(C(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${be(o)}`)}return{removed:r,errors:t}}async function of(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await me("reindex.language-indexers",async()=>(n=await sf(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(", ")}`),af({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let g=M("reindex.publish",()=>hf(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),f=g.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:g,shards:c,writeTelemetry:e.writeTelemetry}}let l=await me("reindex.publish",()=>mf(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(g=>g.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c,writeTelemetry:e.writeTelemetry}}function af(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!N(e.run.paths.outputScip)||!N(e.run.paths.outputDb))return!1;let t=B(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 sf(e,t){let n=pf({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[b,K]of n)K.reused&&(r.push({language:b,scipPath:K.scipPath}),i.add(b));for(let b of i)e.onStatus(`Reusing cached ${b} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=B(e.paths.outputDb,e.paths.metaPath),s=Re(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d,l=o&&!o.reused&&c?Ua({projectRoot:e.projectRoot,cacheDir:S(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:Ut(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:b=>{d=b}}):null,p=new Set(l?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1)for(let b of e.languages){if(i.has(b)||p.has(b))continue;let K=n.get(b);K&&N(K.scipPath)&&(r.push({language:b,scipPath:K.scipPath}),i.add(b),e.onStatus(`Skipping expensive ${b} full rebuild because the watch full-rebuild budget is exhausted.`))}let g=l||i.has("typescript")?void 0:cf(e,n),{preparedRuns:f,skippedLanguages:m,languageOutputScipPaths:R}=xf({languages:e.languages.filter(b=>!i.has(b)&&!p.has(b)),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:g?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),D=g?f.filter(b=>b.language!=="typescript"||g.missedProjectIds.has(b.id)):f,_=await Ha(D,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(Kr())for(let b of _)Xr({type:"span",name:`reindex.language-indexer.${b.id}`,durationMs:Math.round(b.durationMs),ok:!b.skipped,language:b.language,indexerCommand:b.command,outputBytes:b.outputBytes,measurement:"indexer-run-result"});let x=[];if(g){df(e.paths.outputDb,_,e.writeTelemetry);let b=R.typescript??e.tempPaths.tempOutputScip;x=lf({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:b,reusedProjects:g.reusedProjects,writeTelemetry:e.writeTelemetry})}let P=[..._,...x],{indexedOutputs:y}=vf(P,m),k=l?[{language:"typescript",scipPath:l.scipPath}]:[],F=[...r,...k,...y];Pf(F,m,e.languages,e.opts.allowPartial,e.onStatus);let pe=l?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:l.scipPath,outputScipPath:l.scipPath,durationMs:l.durationMs,command:"watch-service:typescript-index",outputBytes:Oe(l.scipPath)??void 0,producedOutputBytes:Oe(l.affectedScipPath)??void 0}]:[],te=ff(n,[..._,...pe],g?{outputDb:e.paths.outputDb,classification:g.classification}:void 0,d);return{indexedOutputs:F,skippedLanguages:m,reusedLanguages:[...i],languageFingerprints:gf(n,e.languages),shards:te,typescriptProjectShardContext:g?{projects:g.allProjects,fingerprints:g.fingerprints}:void 0,incrementalTypeScript:l??void 0}}function cf(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ve(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=ko(e.projectRoot,r),o=Po(n.fingerprint.files,r),a=wo(r,i),s=Eo(r,o,a),c=Re(e.paths.metaPath),d=uf(c,s,f=>N(Wt(e.paths.outputDb,f))),l=[...d.entries()].filter(([,f])=>f.reused).map(([f])=>f),p=new Set(l),g=new Set(r.filter(f=>!p.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:l,missedProjectIds:g}}function uf(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===je&&Yt(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(U(a)!==U(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 df(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Wt(e,i);Vt(S(o),{recursive:!0}),ye(n,he(r.scipPath,o))}}function lf(e){return e.reusedProjects.map((t,n)=>{let r=Wt(e.outputDb,t),i=Le(e.tempOutputScip,"typescript-project-cached",n);return ye(e.writeTelemetry,he(r,i)),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Oe(i)??void 0}})}function pf(e){let t=Re(e.paths.metaPath),n=Js(e.projectFingerprint,e.languages,e),r=t&&N(e.paths.outputDb)?St(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Lr(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!==je){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Yt(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(!N(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}if(U(c)!==U(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:Or("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function ff(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:Qe(a.fingerprint),outputBytes:Oe(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?Qe(c.fingerprint):a?Qe(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:Qe(a.fingerprint),outputBytes:Oe(Wt(n.outputDb,o)),durationMs:0});return i}function Qe(e){return Hp("sha256").update(U(e)).digest("hex").slice(0,16)}function Oe(e){try{return Jp(e).size}catch{return null}}function gf(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function mf(e,t,n,r,i,o,a,s){G(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=M("reindex.publish.scip-output",()=>{let x=bf({run:e,indexedOutputs:n,incrementalTypeScript:s});return Ds(e.paths.outputDb,x,e.writeTelemetry),Fs(x,e.tempPaths.tempOutputScip,e.onStatus)}));let d=await me("reindex.publish.sqlite-output",()=>wf({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if(G(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),yr({cacheDir:S(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let x=n.map(P=>P.language==="typescript"?{language:P.language,scipPath:s.candidateScipPath}:P);return Ds(e.paths.outputDb,x,e.writeTelemetry),u=Fs(x,e.tempPaths.tempOutputScip,e.onStatus),u}}));G(e.opts.signal,"Reindex cancelled by its owner."),M("reindex.publish.auxiliary-documents",()=>{H(ae(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),M("reindex.publish.runtime-boundaries",()=>_r(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,!1,s?.affectedFiles));let l=M("reindex.publish.sqlite-layout",()=>Dn(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(", ")}`),$s(e,e.tempPaths.tempOutputDb,n.map(x=>x.language)),d.mode==="incremental"&&s){let x=null,P=null;try{x=new q({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),P=new q({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let y=vi(x,e.fingerprint,s.referenceFragmentsByFile,P);e.onStatus(`Cached exact TypeScript reference fragments for ${y} affected document(s).`)}catch(y){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${y instanceof Error?y.message:String(y)}.`)}finally{x?.close(),P?.close()}}let p=Ut(e.paths.metaPath),g=d.mode==="incremental"&&s?kf(s,d.changedDocumentPaths):bn({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=qt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(x=>x.language),skipped:[...r]}),m=d.mode==="incremental"&&d.scipCompanion==="deferred",{metadata:R,pruneProjects:D}=Ns({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:f});R.scipCompanion=m?"deferred":"current",Gs(e),Vs(e.paths.outputDb,D),jr(e.tempPaths.tempMetaPath,R);let _=Et({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}:{}}});if(_.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${_.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),d.mode==="incremental"&&s){let x=null;try{x=new q({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let P=gi(x,s.dependencyGraphSnapshot,s.affectedFiles);e.onStatus(P?`Carried the dependency graph forward by replacing ${s.affectedFiles.length} affected document(s).`:"Dependency graph carry-forward was ineligible; the next graph consumer will rebuild it.")}catch(P){e.onStatus(`Dependency graph carry-forward unavailable: ${P instanceof Error?P.message:String(P)}. The next graph consumer will rebuild it.`)}finally{x?.close()}}return Jo(S(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Uo(S(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[]),Ms(e.paths.outputDb,g,e.onStatus),f}function hf(e,t,n,r,i,o){let a=Ut(e.paths.metaPath),s=null;try{ye(e.writeTelemetry,he(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=Vi("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}H(ae(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),_r(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Dn(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(e,e.paths.outputDb,t.map(p=>p.language)),s??=bn({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=qt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:d,pruneProjects:l}=Ns({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return Gs(e),Vs(e.paths.outputDb,l),jr(e.paths.metaPath,d),Kn(e.paths.outputDb,e.paths.metaPath),Ms(e.paths.outputDb,s,e.onStatus),u}function Ut(e){return Gr(Re(e)?.fingerprint)}function Ms(e,t,n){try{Bi(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 Ns(e){let t=yf({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:je,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 Gs(e){G(e.opts.signal,"Reindex cancelled by its owner.");let t=dt(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath});if(U(t)!==U(e.fingerprint))throw new Error("Project inputs changed during reindex; refusing to publish artifacts built from a different filesystem snapshot.")}function $s(e,t,n){let r=St(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Or("Candidate SQLite index",r)} Refusing to publish it.`)}function Or(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 yf(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=Re(e.metaPath),n=t?.version===je?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 Vs(e,t){let n=Ys(e);if(t===null){_e(n,{recursive:!0,force:!0});return}let r;try{r=Ls(n)}catch{return}for(let i of Sf(r,t))_e(C(n,i),{force:!0})}function Sf(e,t){let n=new Set(t.map(r=>`${_n(r)}.scip`));return e.filter(r=>!n.has(r))}function bf(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];let n=B(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":Re(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=Le(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),yr({cacheDir:S(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 Ds(e,t,n){for(let r of t){let i=Lr(e,r.language);Vt(S(i),{recursive:!0}),r.scipPath!==i&&ye(n,he(r.scipPath,i))}}async function Rf(e,t){if(!fn()){if(Kp()==="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
291
  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..."),!Ht(t))throw new Error(`The scip CLI is required but could not be installed.
294
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function fp(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Be(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=mp({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ka(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function mp(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[ir({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Ne(e.projectRoot,e.typescriptProjects);return t.length===0?[ir({...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)=>ir({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Be(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function ir(e){let t=it(e.language),n=Ee(t),r=jt(t,e.projectRoot),i=e.trustProjectTools&&r?Tr(t,e.projectRoot):null,o=pe(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&&!Ct(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...`),!Xn(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??pe(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});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:Mt(t,e.env,a),...i?{trustedProjectTool:i}:{}}}}function hp(e,t){let n=new Map;for(let i of e)if(i.skipped)Ka(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)on(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Ha(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Ka(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 yp(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
292
+ Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!gn(t))throw new Error(`The scip CLI is required but could not be installed.
293
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function xf(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Le(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=If({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Bs(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function If(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Ar({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??ve(e.projectRoot,e.typescriptProjects);return t.length===0?[Ar({...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)=>Ar({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Le(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Ar(e){let t=mt(e.language),n=Ve(t),r=an(t,e.projectRoot),i=e.trustProjectTools&&r?hi(t,e.projectRoot):null,o=we(t);if(!i&&!o&&r){let d=`${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}: ${d}`),{skipped:{language:e.language,reason:d}}}if(!i&&!o&&!on(t)){if(e.skipAutoInstall){let d=`${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}: ${d}`),{skipped:{language:e.language,reason:d}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Pr(t,e.onStatus)){let d=`${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}: ${d}`),{skipped:{language:e.language,reason:d}}}}let a=i?.canonicalPath??we(t);if(!a){let d=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${d}`),{skipped:{language:e.language,reason:d}}}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}),u=to({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let d=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${d}`),{skipped:{language:e.language,reason:d}}}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:sn(t,e.env,a),...u===void 0?{}:{temporaryRootConfigContent:u},...i?{trustedProjectTool:i}:{}}}}function vf(e,t){let n=new Map;for(let i of e)if(i.skipped)Bs(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)En(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&js(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Bs(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 Pf(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
295
294
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
296
295
  `+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
296
  `+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};
297
+ `))}function Fs(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=oo(e.map(o=>o.scipPath),t);return Ws(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&js(e[0].scipPath,t);return!1}async function wf(e){let t;if(Ef(e)){let i=C(e.run.tempPaths.runDir,"typescript-affected.db");try{Us(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();await As(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus,!0,e.run.opts.signal),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=go({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles,writeTelemetry:e.run.writeTelemetry});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){G(e.run.opts.signal,"Reindex cancelled by its owner."),t=o instanceof Error?o.message:String(o),_e(i,{force:!0}),_e(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=await e.materializeFullFallback());let r=performance.now();return await As(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 Ef(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!N(e.run.paths.outputDb)||!N(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 kf(e,t){let n=v(),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:v()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Sn(e.plan,o,e.projectFileCount)}}async function As(e,t,n,r,i=!1,o){if(G(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!N(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Us(e,r);let a=fn();if(!a)throw new Error("scip CLI is not available");let s=await lt({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){G(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 Us(e,t){let n=ro(e);Ws(n,t)}function Ws(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Le(e,t,n){let r=Yp(e)||".scip",i=$t(e,r);return C(S(e),`${i}.${n+1}.${t}${r}`)}async function Tf(e,t){for(let n=0;n<2;n++){let r=Df(e,t);if(r)return r;let i=Ff(e);if(i&&zs(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Cf(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: ${be(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${S(e)}; refusing to steal an active lock.`);let a=Kt(e,{parseLegacy:Bt});if(!qr(e,a,{parseLegacy:Bt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${S(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${S(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${S(e)}.`)}function Df(e,t){let n=W(process.pid),r=rt(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:Bt});if(r.kind==="acquired"&&r.reclaimed){let i=qs(r.reclaimed,e);i&&zs(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 ${S(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Ff(e){return qs(Kt(e,{parseLegacy:Bt}),e)}var Bt=e=>{let t=Hs(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qs(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:S(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Hs(e.parsed,t)}function Hs(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=Br(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:S(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function zs(e,t){return e?.kind==="manual-cli"&&Af(t?.trigger)}function Af(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Cf(e){return!ie(e.pid)||(Cr(e),Cs(e,"SIGTERM"),await _s(e,2e3))?!0:(Cr(e),Cs(e,"SIGKILL"),_s(e,1e3))}function Cs(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ie(e.pid))return;Cr(e)}try{process.kill(e.pid,t)}catch{}}async function _s(e,t){let n=v()+t;for(;v()<n;){if(Os(e))return!0;await _f(50)}return Os(e)}function Cr(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=W(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Me(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Os(e){if(!ie(e.pid))return!0;if(!e.processIdentity)return!1;let t=W(e.pid);return t!==null&&!Me(e.processIdentity,t)}function _f(e){return new Promise(t=>setTimeout(t,e))}function Js(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?ai(n.typescriptProjects):[],o=r==="clojure"?Of(n.clojureConfigPath):void 0,a=[...mt(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"&&Lf(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Nr(c.path,r,a))}]}))}function Of(e){return e?.trim()||void 0}function Lf(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Lr(e,t){return C(S(e),"language-indexes",`${t}.scip`)}function Ys(e){return C(S(e),"language-indexes","typescript-projects")}function Wt(e,t){return C(Ys(e),`${_n(t)}.scip`)}function Re(e){try{return Jt(ne(L(e,"reindex metadata")))}catch{return null}}function Ks(e,t){try{let n=ne(L(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&Vr(r)&&U(r.fingerprint)===U(t)&&U([...r.indexedLanguages??[]].sort())===U(t.languages)}catch{return!1}}function jr(e,t){$(e,t,{spacing:2,trailingNewline:!0})}function Xs(e,t){try{let n=Jt(ne(L(e,"reindex metadata")));if(!n)return;jr(e,{...n,lastRefresh:t})}catch{}}function qt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:v()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function U(e){return JSON.stringify(e)}export{eo as INDEXER_CONFIGS,ji as augmentAuxiliaryDocuments,kp as augmentVueResolvedReferences,Tp as augmentVueResolvedReferencesAsync,ae as auxiliaryDocumentsAugmentationStage,Ve as describeIndexerBinary,Rn as detectLanguages,mt as getIndexerConfig,sn as getIndexerExecutionEnv,rn as isBinaryAvailable,on as isIndexerInstalled,En as mergeScipFiles,wn as mergeScipIndexes,zS as reindex,we as resolveIndexerBinary,an as resolveProjectLocalIndexerBinary,H as runPostIndexAugmentation,Pr as tryInstallIndexer,gn as tryInstallScipCli,Is as vueResolvedReferencesAugmentationStage};
299
298
  //# sourceMappingURL=reindex.js.map