scip-query 0.23.0 → 0.24.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 (432) hide show
  1. package/CHANGELOG.md +244 -1
  2. package/README.md +2 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-H3P6BR5G.js +2 -0
  5. package/dist/call-graph-VTG2CUOQ.js +2 -0
  6. package/dist/call-graph-evidence-BociKRpF.d.ts +19 -0
  7. package/dist/chunk-2BMSSRBH.js +2 -0
  8. package/dist/{chunk-WIWY3CRX.js → chunk-2GJSD5GY.js} +2 -2
  9. package/dist/{chunk-W5OXRYGE.js → chunk-2M2LSIMY.js} +3 -3
  10. package/dist/{chunk-2LDBDR6J.js → chunk-2N6WBNDC.js} +2 -2
  11. package/dist/{chunk-HOENASQM.js → chunk-2USA3S3P.js} +2 -2
  12. package/dist/chunk-2VAHDDLM.js +133 -0
  13. package/dist/chunk-2XWIUW5Z.js +455 -0
  14. package/dist/chunk-3D4BOXW6.js +20 -0
  15. package/dist/{chunk-BBCIS4DX.js → chunk-3LO4FST5.js} +2 -2
  16. package/dist/chunk-3WTY4LP2.js +3 -0
  17. package/dist/{chunk-UXW33INU.js → chunk-3Z5AMSK6.js} +2 -2
  18. package/dist/{chunk-4ILJCCXV.js → chunk-44IETFOU.js} +2 -2
  19. package/dist/chunk-4FR6GQIT.js +2 -0
  20. package/dist/chunk-4KBTHJLP.js +2 -0
  21. package/dist/{chunk-SSK6LDPC.js → chunk-5BIKR67W.js} +2 -2
  22. package/dist/{chunk-IHGQTTVW.js → chunk-5PROPLHI.js} +2 -2
  23. package/dist/{chunk-TA3QKLLU.js → chunk-5V7EPTII.js} +2 -2
  24. package/dist/{chunk-JS4PGXMV.js → chunk-62LPZCBQ.js} +2 -2
  25. package/dist/{chunk-DBRSYFXR.js → chunk-64O2JHQA.js} +2 -2
  26. package/dist/chunk-6D4F5VWG.js +10 -0
  27. package/dist/{chunk-BHVUJOCQ.js → chunk-6ERFBC3X.js} +2 -2
  28. package/dist/{chunk-ILTDAWEF.js → chunk-6ILKOOGH.js} +2 -2
  29. package/dist/chunk-6MFXCMZC.js +2 -0
  30. package/dist/chunk-6O7FACKB.js +2 -0
  31. package/dist/{chunk-XDQMU3BT.js → chunk-6TS3KOXR.js} +2 -2
  32. package/dist/{chunk-YI2AWIHC.js → chunk-76QOU4PK.js} +2 -2
  33. package/dist/{chunk-7CYG22FH.js → chunk-7DUI77BN.js} +2 -2
  34. package/dist/{chunk-IDFEUFKS.js → chunk-7F7T6DCR.js} +2 -2
  35. package/dist/chunk-7H6VHWWJ.js +2 -0
  36. package/dist/chunk-7HXT6YLU.js +5 -0
  37. package/dist/{chunk-DIRJWYBM.js → chunk-7R4V5ES6.js} +4 -4
  38. package/dist/{chunk-SZHGTCPP.js → chunk-7RIRIADH.js} +2 -2
  39. package/dist/chunk-7ZLWLOGT.js +2 -0
  40. package/dist/{chunk-M2O5NY6W.js → chunk-A4WEAK35.js} +2 -2
  41. package/dist/chunk-AADQLOQ4.js +38 -0
  42. package/dist/{chunk-OLNV6I6U.js → chunk-AN76MGUE.js} +2 -2
  43. package/dist/chunk-ANLNLY66.js +2 -0
  44. package/dist/chunk-ATXPTSEI.js +81 -0
  45. package/dist/{chunk-YPWBKGFU.js → chunk-AX7IDVFT.js} +2 -2
  46. package/dist/chunk-B7MPDEAK.js +3 -0
  47. package/dist/chunk-BBB5FBX4.js +2 -0
  48. package/dist/{chunk-6I6L7Z62.js → chunk-BHKK5RJY.js} +2 -2
  49. package/dist/chunk-BJWFVAA5.js +2 -0
  50. package/dist/{chunk-UHFYCMZO.js → chunk-BKZYTLGE.js} +2 -2
  51. package/dist/chunk-BL6DCHQP.js +2 -0
  52. package/dist/{chunk-TEBQMNVI.js → chunk-BOW7SSQH.js} +2 -2
  53. package/dist/{chunk-OWOOWNJ5.js → chunk-C4RHHCKL.js} +2 -2
  54. package/dist/{chunk-N2ZSIIGR.js → chunk-C7C6AKAT.js} +6 -6
  55. package/dist/chunk-CD6M6LS2.js +16 -0
  56. package/dist/chunk-CFE6PSG6.js +2 -0
  57. package/dist/{chunk-6V5CNXL6.js → chunk-CFNIGQMT.js} +2 -2
  58. package/dist/{chunk-GUFSG5TX.js → chunk-CKBUBRYD.js} +2 -2
  59. package/dist/{chunk-4WNW27SX.js → chunk-CZW5MZ5B.js} +2 -2
  60. package/dist/chunk-DBBZ63ZX.js +2 -0
  61. package/dist/{chunk-HCXEQRFF.js → chunk-DBN7DMJB.js} +2 -2
  62. package/dist/{chunk-6PQNKL3G.js → chunk-DUULLZHZ.js} +2 -2
  63. package/dist/{chunk-Z4CDXYNQ.js → chunk-DV5Y5NOS.js} +2 -2
  64. package/dist/chunk-DZOIKCTM.js +3 -0
  65. package/dist/chunk-E4PKTOL3.js +2 -0
  66. package/dist/{chunk-EG2CPZMJ.js → chunk-E65ELFKU.js} +2 -2
  67. package/dist/{chunk-CNO7TOKL.js → chunk-E7QR35ST.js} +2 -2
  68. package/dist/{chunk-3D3QG236.js → chunk-EFSXAINW.js} +2 -2
  69. package/dist/{chunk-IL676XCC.js → chunk-EHVEIEQN.js} +2 -2
  70. package/dist/{chunk-BE7ZZTMC.js → chunk-EHYDXE3Z.js} +2 -2
  71. package/dist/{chunk-LXABEJX3.js → chunk-EP63Y6LD.js} +2 -2
  72. package/dist/{chunk-QU5XRYB5.js → chunk-EPX6NQN6.js} +2 -2
  73. package/dist/{chunk-FESCRNVV.js → chunk-ETC674NS.js} +2 -2
  74. package/dist/{chunk-OSSESPDX.js → chunk-F5GSBHC6.js} +2 -2
  75. package/dist/chunk-FH3DGXC6.js +2 -0
  76. package/dist/{chunk-YEN6CYC7.js → chunk-FI7VGOR4.js} +2 -2
  77. package/dist/chunk-FJF6VO2P.js +2 -0
  78. package/dist/{chunk-FRUSVINH.js → chunk-FLMTCX5R.js} +2 -2
  79. package/dist/chunk-FVFDOIM3.js +2 -0
  80. package/dist/{chunk-PJFGPYTU.js → chunk-G2HU5WRN.js} +2 -2
  81. package/dist/{chunk-FIQRSHVM.js → chunk-G4ALYS4J.js} +2 -2
  82. package/dist/{chunk-UVGEWT4Y.js → chunk-G56I7K4W.js} +2 -2
  83. package/dist/{chunk-WOIKCX6A.js → chunk-GC4DG2V5.js} +2 -2
  84. package/dist/chunk-GG45PK4S.js +4 -0
  85. package/dist/{chunk-XBGWL66K.js → chunk-GHNPACNP.js} +2 -2
  86. package/dist/{chunk-IICPE7B2.js → chunk-GINH3YQU.js} +2 -2
  87. package/dist/{chunk-HLZTEXRA.js → chunk-GTZZVLKJ.js} +2 -2
  88. package/dist/chunk-GXXW5ZHH.js +2 -0
  89. package/dist/{chunk-B5D7QPBE.js → chunk-HAXXKRTD.js} +2 -2
  90. package/dist/chunk-HEZWBAZY.js +2 -0
  91. package/dist/chunk-HMEWLMML.js +2 -0
  92. package/dist/{chunk-QUU5OBVK.js → chunk-HOBOVYPO.js} +2 -2
  93. package/dist/{chunk-XGZEP6GR.js → chunk-HRFQ6GW5.js} +2 -2
  94. package/dist/{chunk-MPQ4OTBM.js → chunk-HX4X7KG3.js} +2 -2
  95. package/dist/{chunk-FDLOBR6P.js → chunk-HYT2R7LX.js} +2 -2
  96. package/dist/chunk-IKQVBVQL.js +40 -0
  97. package/dist/chunk-J6GLBBRK.js +4 -0
  98. package/dist/{chunk-ZTI4SBFV.js → chunk-J7A4PWFX.js} +2 -2
  99. package/dist/{chunk-OSR2GEHQ.js → chunk-JCSAZ35V.js} +2 -2
  100. package/dist/{chunk-ESIQ66Z7.js → chunk-JDU2IV3A.js} +2 -2
  101. package/dist/chunk-JFMI5SGB.js +4 -0
  102. package/dist/{chunk-W6STWDQI.js → chunk-JJP37RGX.js} +2 -2
  103. package/dist/chunk-JZ2A7LDM.js +5 -0
  104. package/dist/chunk-KNLQGXVH.js +80 -0
  105. package/dist/chunk-KVQCECPR.js +2 -0
  106. package/dist/{chunk-SQXRS7BG.js → chunk-KXXORBZ2.js} +2 -2
  107. package/dist/{chunk-DIUFNHRJ.js → chunk-L5KYH6U3.js} +2 -2
  108. package/dist/chunk-L6XHYJPZ.js +21 -0
  109. package/dist/{chunk-2GRUZAQF.js → chunk-L7KTFEAV.js} +2 -2
  110. package/dist/{chunk-QBE3YX64.js → chunk-LDXHR5EL.js} +2 -2
  111. package/dist/{chunk-HEHOQQKH.js → chunk-MHGDSBFX.js} +2 -2
  112. package/dist/{chunk-PWWAJSKV.js → chunk-MLQVVDG3.js} +2 -2
  113. package/dist/chunk-MOKUWRHO.js +3 -0
  114. package/dist/{chunk-VQILFTEH.js → chunk-MPYAPMNE.js} +2 -2
  115. package/dist/{chunk-UICY4GTQ.js → chunk-MV6SPXCR.js} +2 -2
  116. package/dist/{chunk-HYO3NP5Q.js → chunk-MZPXPSUJ.js} +2 -2
  117. package/dist/{chunk-VZRNID6A.js → chunk-N55KIE46.js} +2 -2
  118. package/dist/{chunk-YF5IB2LF.js → chunk-NB4D3BNM.js} +2 -2
  119. package/dist/{chunk-VVZSBTSU.js → chunk-NGKBOT6G.js} +2 -2
  120. package/dist/{chunk-NJITK2GP.js → chunk-NJGKXKQF.js} +2 -2
  121. package/dist/chunk-NJQISBL4.js +8 -0
  122. package/dist/{chunk-T4N4P2K5.js → chunk-NJT3ZEKY.js} +2 -2
  123. package/dist/{chunk-FPYLNQPT.js → chunk-NKMKZP6A.js} +2 -2
  124. package/dist/chunk-NODFZ6ED.js +2 -0
  125. package/dist/{chunk-BRV7PIFF.js → chunk-NSM5IEVW.js} +2 -2
  126. package/dist/{chunk-3WR4E3A3.js → chunk-NTGUVNR2.js} +2 -2
  127. package/dist/{chunk-VUPHCS7Y.js → chunk-NU3KFF2O.js} +2 -2
  128. package/dist/chunk-NWLVNU66.js +557 -0
  129. package/dist/{chunk-D4N5SQ2M.js → chunk-NYKZMCRC.js} +2 -2
  130. package/dist/{chunk-VNLGKHS6.js → chunk-O6BUXZEH.js} +2 -2
  131. package/dist/chunk-ODPDP7A4.js +3 -0
  132. package/dist/{chunk-JTQVMR42.js → chunk-OHIV323X.js} +2 -2
  133. package/dist/chunk-OIAPEKMT.js +3 -0
  134. package/dist/chunk-OIOC5EHF.js +3 -0
  135. package/dist/{chunk-YBGKCQIS.js → chunk-ONPPQM4G.js} +2 -2
  136. package/dist/{chunk-64BFSI5I.js → chunk-OUHEZBYI.js} +2 -2
  137. package/dist/{chunk-L6PJPETJ.js → chunk-OVGYW7UD.js} +2 -2
  138. package/dist/{chunk-I55I7XXP.js → chunk-OYKU4B3Y.js} +2 -2
  139. package/dist/{chunk-J66VOFW6.js → chunk-POBJ6FR2.js} +2 -2
  140. package/dist/{chunk-CWFP7GM5.js → chunk-PSZPMMWN.js} +2 -2
  141. package/dist/chunk-PXTRBKRK.js +3 -0
  142. package/dist/{chunk-HKGFPJ4T.js → chunk-Q5JRIHT3.js} +2 -2
  143. package/dist/{chunk-P42EIXTA.js → chunk-Q7ATHARX.js} +2 -2
  144. package/dist/{chunk-JYR66JN5.js → chunk-Q7CSKIDM.js} +2 -2
  145. package/dist/{chunk-TRNAEQ6P.js → chunk-QBQE7ZJ5.js} +2 -2
  146. package/dist/{chunk-DULC3QFP.js → chunk-QH22UIXP.js} +2 -2
  147. package/dist/chunk-QXCKQTKR.js +60 -0
  148. package/dist/{chunk-ODDUPDP7.js → chunk-RBAD4GJ2.js} +5 -5
  149. package/dist/{chunk-IZDPJ2QI.js → chunk-RMDPFPNW.js} +2 -2
  150. package/dist/chunk-ROPJDEJZ.js +4 -0
  151. package/dist/{chunk-EKV5HX33.js → chunk-RVZC6TJE.js} +2 -2
  152. package/dist/{chunk-XFA4SSO3.js → chunk-S4QZBKSR.js} +2 -2
  153. package/dist/{chunk-D2DHWI3D.js → chunk-SCPMZ73U.js} +2 -2
  154. package/dist/{chunk-PZL5T7SU.js → chunk-SIAP5RGI.js} +2 -2
  155. package/dist/{chunk-7IWV2EG3.js → chunk-SIX4RFR3.js} +2 -2
  156. package/dist/{chunk-DYGHBZ2N.js → chunk-SKKXTABJ.js} +2 -2
  157. package/dist/{chunk-F7DY272B.js → chunk-SSRFUQBD.js} +2 -2
  158. package/dist/chunk-SYVJEEUJ.js +3 -0
  159. package/dist/{chunk-FGA2U4OR.js → chunk-T3CZAZSI.js} +2 -2
  160. package/dist/chunk-T3I6NHBH.js +2 -0
  161. package/dist/{chunk-EQHFIL6T.js → chunk-T6DWDI5E.js} +2 -2
  162. package/dist/chunk-T6HRIROJ.js +7 -0
  163. package/dist/{chunk-GSP44ENC.js → chunk-TAA7HXHE.js} +2 -2
  164. package/dist/{chunk-BQGB4HBD.js → chunk-TJ2JQYT3.js} +2 -2
  165. package/dist/{chunk-XPDPNWTQ.js → chunk-TULNMD5T.js} +19 -19
  166. package/dist/chunk-U2FPY5XA.js +3 -0
  167. package/dist/chunk-U3SXIMII.js +38 -0
  168. package/dist/{chunk-NOGJXYFO.js → chunk-U6KCHXJ4.js} +2 -2
  169. package/dist/chunk-UH3XSKS5.js +9 -0
  170. package/dist/{chunk-AFHTBORT.js → chunk-UIFUZVCC.js} +2 -2
  171. package/dist/{chunk-7BWFZPPZ.js → chunk-UXKURIVI.js} +2 -2
  172. package/dist/{chunk-2E7CX53V.js → chunk-V2RBODHL.js} +2 -2
  173. package/dist/{chunk-KLFEXGQA.js → chunk-VBKUWB6N.js} +2 -2
  174. package/dist/{chunk-WUN6KBHV.js → chunk-VBV6ALJE.js} +2 -2
  175. package/dist/{chunk-GZIUDL6G.js → chunk-VDGFWCQV.js} +2 -2
  176. package/dist/chunk-VDSDOEWF.js +2 -0
  177. package/dist/{chunk-WDNVY4E7.js → chunk-VZPWVCLN.js} +2 -2
  178. package/dist/chunk-WDSFQDPN.js +2 -0
  179. package/dist/{chunk-CIYLO6SI.js → chunk-WFA35BGR.js} +2 -2
  180. package/dist/{chunk-LMZ5PRUV.js → chunk-WLMP3OCW.js} +2 -2
  181. package/dist/{chunk-3SVF22I5.js → chunk-WSA52GOR.js} +2 -2
  182. package/dist/{chunk-VMPRET3I.js → chunk-X3YVZAKZ.js} +2 -2
  183. package/dist/{chunk-GYIZ4NXB.js → chunk-X6OGVFIT.js} +2 -2
  184. package/dist/{chunk-6HFCYNYE.js → chunk-XKXTR6ZI.js} +2 -2
  185. package/dist/{chunk-6VVV4WRR.js → chunk-Y5DFAW5W.js} +2 -2
  186. package/dist/chunk-YSYPDRD5.js +3 -0
  187. package/dist/{chunk-TQPCBMWT.js → chunk-ZFVPWH62.js} +2 -2
  188. package/dist/chunk-ZGIHTH27.js +2 -0
  189. package/dist/{chunk-OR2E3AGZ.js → chunk-ZGIQN2SX.js} +2 -2
  190. package/dist/{chunk-WNTFFKAX.js → chunk-ZHG4WAHR.js} +2 -2
  191. package/dist/{chunk-DTZCKZEU.js → chunk-ZKB2XUEN.js} +2 -2
  192. package/dist/chunk-ZLMXIQLC.js +21 -0
  193. package/dist/chunk-ZMCQIHI4.js +2 -0
  194. package/dist/cli-main.js +2 -2
  195. package/dist/code-TAVIKWJI.js +2 -0
  196. package/dist/code-result-json-5FEFQCAQ.js +2 -0
  197. package/dist/{command-descriptors-P34VABY5.js → command-descriptors-7BKH53Y3.js} +124 -124
  198. package/dist/dataflow-GFBTVDH3.js +2 -0
  199. package/dist/dependence-slice-GWGQCODG.js +2 -0
  200. package/dist/deps-4QHVDPYA.js +2 -0
  201. package/dist/direct-navigation-4UBC6HNW.js +3 -0
  202. package/dist/entry-map-QCTF4RVY.js +2 -0
  203. package/dist/files-M2UBF5HJ.js +2 -0
  204. package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
  205. package/dist/{health-CPp2Jf1Z.d.ts → health-BI2a9WPy.d.ts} +60 -2
  206. package/dist/hierarchy-2UIHRLW4.js +2 -0
  207. package/dist/imports-WIE3YZOB.js +2 -0
  208. package/dist/index.d.ts +1 -1
  209. package/dist/index.js +1 -1
  210. package/dist/members-YKD636DA.js +2 -0
  211. package/dist/methods-VDF4IMYG.js +2 -0
  212. package/dist/output-continuation-command-4UMDOOLO.js +3 -0
  213. package/dist/output-pagination-2GME6OPY.js +19 -0
  214. package/dist/postinstall.js +1 -1
  215. package/dist/project-reindex-XEQTRCV5.js +3 -0
  216. package/dist/queries/affected.js +1 -1
  217. package/dist/queries/anchors.d.ts +1 -1
  218. package/dist/queries/anchors.js +1 -1
  219. package/dist/queries/architecture.js +1 -1
  220. package/dist/queries/bottlenecks.js +1 -1
  221. package/dist/queries/by-kind.js +1 -1
  222. package/dist/queries/call-graph.d.ts +2 -0
  223. package/dist/queries/call-graph.js +1 -1
  224. package/dist/queries/change-surface.js +1 -1
  225. package/dist/queries/cleanup-plan.js +1 -1
  226. package/dist/queries/co-change.d.ts +20 -2
  227. package/dist/queries/co-change.js +1 -1
  228. package/dist/queries/code.js +1 -1
  229. package/dist/queries/complexity-hotspots.js +1 -1
  230. package/dist/queries/complexity.js +1 -1
  231. package/dist/queries/context.js +1 -1
  232. package/dist/queries/convergence.js +1 -1
  233. package/dist/queries/coupling.js +1 -1
  234. package/dist/queries/cycles.js +1 -1
  235. package/dist/queries/dataflow.js +1 -1
  236. package/dist/queries/dead.d.ts +2 -0
  237. package/dist/queries/dead.js +1 -1
  238. package/dist/queries/decorative-checkers.js +1 -1
  239. package/dist/queries/deep-chains.js +1 -1
  240. package/dist/queries/dependence-slice.js +1 -1
  241. package/dist/queries/dependency-depth.js +1 -1
  242. package/dist/queries/deps.js +1 -1
  243. package/dist/queries/diff-impact.js +1 -1
  244. package/dist/queries/doc-drift.js +1 -1
  245. package/dist/queries/drift.js +1 -1
  246. package/dist/queries/duplicate-bodies.d.ts +28 -1
  247. package/dist/queries/duplicate-bodies.js +1 -1
  248. package/dist/queries/entry-map.d.ts +1 -1
  249. package/dist/queries/entry-map.js +1 -1
  250. package/dist/queries/evidence.js +1 -1
  251. package/dist/queries/extract-candidates.d.ts +50 -23
  252. package/dist/queries/extract-candidates.js +1 -1
  253. package/dist/queries/fan.js +1 -1
  254. package/dist/queries/files.js +1 -1
  255. package/dist/queries/health.d.ts +1 -1
  256. package/dist/queries/health.js +1 -1
  257. package/dist/queries/hierarchy.js +1 -1
  258. package/dist/queries/hotspots.js +1 -1
  259. package/dist/queries/imports.js +1 -1
  260. package/dist/queries/incomplete-migration.js +1 -1
  261. package/dist/queries/index.d.ts +4 -3
  262. package/dist/queries/index.js +1 -1
  263. package/dist/queries/isolated.js +1 -1
  264. package/dist/queries/locality-candidates.js +1 -1
  265. package/dist/queries/members.js +1 -1
  266. package/dist/queries/methods.js +1 -1
  267. package/dist/queries/not-implemented.js +1 -1
  268. package/dist/queries/outline.js +1 -1
  269. package/dist/queries/passthrough-candidates.d.ts +9 -1
  270. package/dist/queries/passthrough-candidates.js +1 -1
  271. package/dist/queries/plan-context.js +1 -1
  272. package/dist/queries/react-component-duplicates.d.ts +19 -3
  273. package/dist/queries/react-component-duplicates.js +1 -1
  274. package/dist/queries/react-hook-candidates.d.ts +22 -3
  275. package/dist/queries/react-hook-candidates.js +1 -1
  276. package/dist/queries/react-large-component-pressure.d.ts +17 -3
  277. package/dist/queries/react-large-component-pressure.js +1 -1
  278. package/dist/queries/recent-duplicates.js +1 -1
  279. package/dist/queries/redundant-reexports.js +1 -1
  280. package/dist/queries/reference-neighborhood.js +1 -1
  281. package/dist/queries/reference-reachability.js +1 -1
  282. package/dist/queries/refs.js +1 -1
  283. package/dist/queries/self-audit.d.ts +7 -1
  284. package/dist/queries/self-audit.js +1 -1
  285. package/dist/queries/similar-chains.js +1 -1
  286. package/dist/queries/similar-files.js +1 -1
  287. package/dist/queries/similar-signatures.js +1 -1
  288. package/dist/queries/similar.js +1 -1
  289. package/dist/queries/slice.js +1 -1
  290. package/dist/queries/source-inspection.js +1 -1
  291. package/dist/queries/source-search.js +1 -1
  292. package/dist/queries/stale-abstractions.js +1 -1
  293. package/dist/queries/surface.js +1 -1
  294. package/dist/queries/symbols.js +1 -1
  295. package/dist/queries/system-map.d.ts +1 -1
  296. package/dist/queries/system-map.js +1 -1
  297. package/dist/queries/system.js +1 -1
  298. package/dist/queries/test-quality.js +1 -1
  299. package/dist/queries/trace.js +1 -1
  300. package/dist/queries/twin-ab.js +1 -1
  301. package/dist/queries/twin-drift.d.ts +22 -6
  302. package/dist/queries/twin-drift.js +1 -1
  303. package/dist/queries/unused-imports.js +1 -1
  304. package/dist/queries/unused-params.js +1 -1
  305. package/dist/queries/value-flow.js +1 -1
  306. package/dist/queries/vue-component-duplicates.js +1 -1
  307. package/dist/queries/vue-composable-candidates.js +1 -1
  308. package/dist/queries/vue-large-view-pressure.js +1 -1
  309. package/dist/queries/wrapper-candidates.d.ts +16 -1
  310. package/dist/queries/wrapper-candidates.js +1 -1
  311. package/dist/query-service-fastpath.js +5 -5
  312. package/dist/query-service-server.js +2 -2
  313. package/dist/refs-JNK5CLM7.js +2 -0
  314. package/dist/refs-pagination-6BLRYGMV.js +2 -0
  315. package/dist/reindex-worker.js +10 -10
  316. package/dist/reindex.js +18 -18
  317. package/dist/runtime.js +4 -4
  318. package/dist/rust-semantic-session-server.js +1 -1
  319. package/dist/rust-semantic-session-worker.js +1 -1
  320. package/dist/rust-semantic-worker.js +1 -1
  321. package/dist/slice-PHPVNCWX.js +2 -0
  322. package/dist/surface-MQX5MPIV.js +2 -0
  323. package/dist/{symbol-resolution-WD5EU5JE.js → symbol-resolution-DBLVXLBC.js} +2 -2
  324. package/dist/system-JOPKV4OG.js +2 -0
  325. package/dist/trace-I2P2YFH4.js +2 -0
  326. package/dist/typescript-mailbox-worker.js +1 -1
  327. package/dist/value-flow-JJVMF7NP.js +2 -0
  328. package/dist/watch-server.js +3 -3
  329. package/docs/COMMAND_REFERENCE.md +2 -2
  330. package/docs/DETECTOR_GUIDE.md +51 -12
  331. package/docs/accuracy-audit-checklist.md +36 -13
  332. package/docs/locality-analyzer-design.md +9 -9
  333. package/package.json +2 -2
  334. package/skills/conductor/SKILL.md +110 -0
  335. package/skills/conductor/agents/openai.yaml +4 -0
  336. package/skills/principal-maintainability-review/SKILL.md +273 -0
  337. package/skills/principal-maintainability-review/agents/openai.yaml +4 -0
  338. package/skills/scip-calibrate/SKILL.md +102 -0
  339. package/skills/scip-calibrate/agents/openai.yaml +4 -0
  340. package/skills/scip-claim-audit/SKILL.md +113 -0
  341. package/skills/scip-claim-audit/agents/openai.yaml +4 -0
  342. package/skills/scip-probe-reachability/SKILL.md +93 -0
  343. package/skills/scip-probe-reachability/agents/openai.yaml +4 -0
  344. package/skills/scip-root-cause/SKILL.md +160 -0
  345. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  346. package/skills/scip-system-compression/SKILL.md +252 -0
  347. package/skills/scip-system-compression/agents/openai.yaml +4 -0
  348. package/skills/scip-system-compression/references/compression-atlas.md +116 -0
  349. package/skills/scip-system-compression/references/compression-patterns.md +87 -0
  350. package/skills/scip-twin-drift/SKILL.md +109 -0
  351. package/skills/scip-twin-drift/agents/openai.yaml +4 -0
  352. package/dist/by-kind-XI2CSWEY.js +0 -2
  353. package/dist/call-graph-UONR6JR5.js +0 -2
  354. package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
  355. package/dist/chunk-2R3V3PSD.js +0 -4
  356. package/dist/chunk-2WC2OEDO.js +0 -4
  357. package/dist/chunk-3FHOF22C.js +0 -21
  358. package/dist/chunk-3JKSW6LJ.js +0 -2
  359. package/dist/chunk-3L2ZBPEX.js +0 -133
  360. package/dist/chunk-3PJABJSU.js +0 -2
  361. package/dist/chunk-4FTZ4P5G.js +0 -2
  362. package/dist/chunk-4UX2F3JX.js +0 -2
  363. package/dist/chunk-5ENOG4VP.js +0 -61
  364. package/dist/chunk-66DVSJQG.js +0 -455
  365. package/dist/chunk-AVRYW5OZ.js +0 -2
  366. package/dist/chunk-BDUVI7TO.js +0 -3
  367. package/dist/chunk-CEEZJXEF.js +0 -2
  368. package/dist/chunk-CJZXN4NU.js +0 -2
  369. package/dist/chunk-COF23M5F.js +0 -2
  370. package/dist/chunk-DHUIOLDT.js +0 -2
  371. package/dist/chunk-DRENNWRG.js +0 -2
  372. package/dist/chunk-E5R6AQ73.js +0 -40
  373. package/dist/chunk-E73UNJTF.js +0 -38
  374. package/dist/chunk-EVFUMY4R.js +0 -3
  375. package/dist/chunk-FBN2FGXG.js +0 -2
  376. package/dist/chunk-FFRKR4EQ.js +0 -2
  377. package/dist/chunk-GAS2LJMP.js +0 -3
  378. package/dist/chunk-HVF5VBG6.js +0 -2
  379. package/dist/chunk-JGKUET5J.js +0 -3
  380. package/dist/chunk-JWTGMPIT.js +0 -80
  381. package/dist/chunk-KFOYCQAJ.js +0 -9
  382. package/dist/chunk-KYSDI3GE.js +0 -5
  383. package/dist/chunk-LDVT66YM.js +0 -2
  384. package/dist/chunk-LQRQN2XA.js +0 -2
  385. package/dist/chunk-MNV5FSBW.js +0 -3
  386. package/dist/chunk-MV3CDXPI.js +0 -38
  387. package/dist/chunk-N5B2NILC.js +0 -5
  388. package/dist/chunk-NOYBFVJA.js +0 -554
  389. package/dist/chunk-NWQXSFFU.js +0 -3
  390. package/dist/chunk-OLIWTZI3.js +0 -3
  391. package/dist/chunk-PP7KNN7L.js +0 -2
  392. package/dist/chunk-PU7T5QYQ.js +0 -2
  393. package/dist/chunk-QGVTFRY2.js +0 -7
  394. package/dist/chunk-QOJONDS7.js +0 -2
  395. package/dist/chunk-RBLQNW26.js +0 -20
  396. package/dist/chunk-RTQ7NEKG.js +0 -81
  397. package/dist/chunk-TPFHAQ2G.js +0 -2
  398. package/dist/chunk-TQZV7KV4.js +0 -2
  399. package/dist/chunk-TY7CRN3Z.js +0 -2
  400. package/dist/chunk-W7CXK74K.js +0 -2
  401. package/dist/chunk-WB3WYIRE.js +0 -4
  402. package/dist/chunk-WK46TNUM.js +0 -3
  403. package/dist/chunk-WYCTJDVR.js +0 -2
  404. package/dist/chunk-XRYABF57.js +0 -8
  405. package/dist/chunk-YPWHBBIS.js +0 -2
  406. package/dist/chunk-YSH6U3L4.js +0 -3
  407. package/dist/chunk-YU5DZUZI.js +0 -10
  408. package/dist/chunk-YWO5DDRC.js +0 -16
  409. package/dist/chunk-ZF5KHH7C.js +0 -2
  410. package/dist/chunk-ZOHS7AQV.js +0 -21
  411. package/dist/code-MI6F2TTU.js +0 -2
  412. package/dist/code-result-json-FXALY4HE.js +0 -2
  413. package/dist/dataflow-4KEMJPC6.js +0 -2
  414. package/dist/dependence-slice-R7FPWD5M.js +0 -2
  415. package/dist/deps-7EMQUYUT.js +0 -2
  416. package/dist/direct-navigation-6YO234F2.js +0 -3
  417. package/dist/entry-map-KOOLR26E.js +0 -2
  418. package/dist/files-OPIPJIGZ.js +0 -2
  419. package/dist/hierarchy-QPD2CAER.js +0 -2
  420. package/dist/imports-M6HUXRXC.js +0 -2
  421. package/dist/members-I5MEFOCT.js +0 -2
  422. package/dist/methods-5JYGGHXA.js +0 -2
  423. package/dist/output-continuation-command-UPQAAKBP.js +0 -3
  424. package/dist/output-pagination-3OFL2MJV.js +0 -19
  425. package/dist/project-reindex-UKKQ5PLS.js +0 -3
  426. package/dist/refs-PSU4JZZW.js +0 -2
  427. package/dist/refs-pagination-JG6CJMRC.js +0 -2
  428. package/dist/slice-HYRATV64.js +0 -2
  429. package/dist/surface-VTGDYWF5.js +0 -2
  430. package/dist/system-LRQNFOR2.js +0 -2
  431. package/dist/trace-F4B6OLL4.js +0 -2
  432. package/dist/value-flow-VRPZY72V.js +0 -2
package/dist/reindex.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F as qr,G as Hr,H as zr,I as Jr,J as Yr,K as Xr,L as Xe,M as Y,N as Ke,P as Kr,Q as qt,R as Qr,S as Zr,T as Qe,U as ei,V as ti,W as ni,a as Tr,b as wr,c as qe,d as He,e as kr,f as _r,g as Fr,h as Cr,j as Or,l as Dr,m as Bt,n as ze,o as Nr,p as $r,q as Ut,r as re,s as ie,t as Je,u as Vr,v as ns,w as Gt,x as Br,y as Ur}from"./chunk-WNTFFKAX.js";import{a as zn,b as $,c as Jn,d as kt,e as Yn,g as Xn,u as _t,x as Er}from"./chunk-5ENOG4VP.js";import{e as Ar,f as Mr,g as Lr,i as jr}from"./chunk-VUPHCS7Y.js";import"./chunk-WOIKCX6A.js";import{a as Se,b as ke,c as be,d as At,e as Mt,f as Sr,g as br,h as Lt,k as jt,l as Rr,m as Nt,n as $t,o as xr,p as Pr,q as vr,r as Vt,t as Re,z as Ir}from"./chunk-WB3WYIRE.js";import"./chunk-DYGHBZ2N.js";import"./chunk-KK7GPALL.js";import"./chunk-OSSESPDX.js";import{a as qn,b as we,c as J,d as ge,e as F,i as $e,j as Kn,k as Dt,l as yr}from"./chunk-TRNAEQ6P.js";import"./chunk-NJITK2GP.js";import"./chunk-YUKYB54I.js";import{b as mr,c as Ge,d as We,e as fr,f as gr,g as hr}from"./chunk-TEBQMNVI.js";import"./chunk-N2ZSIIGR.js";import"./chunk-ODDUPDP7.js";import{L as dr,M as pr,a as Ue}from"./chunk-ZOHS7AQV.js";import"./chunk-FESCRNVV.js";import{A as lr,g as sr,j as Ot,q as cr,v as ur,y as I,z as B}from"./chunk-JWTGMPIT.js";import{A as Tt,Aa as nr,B as Wn,C as me,D as wt,E as Ne,Ea as rr,Fa as ir,Ga as or,H as fe,Ha as ar,I as N,J as U,K as Hn,Z as Ve,ca as Qn,da as ne,e as It,ea as he,fa as ye,g as Le,ga as Zn,h as Bn,ha as er,i as Et,ia as Ft,j as Un,ka as Be,l as z,m as M,sa as Ct,va as tr,w as pe,x as te,y as je,z as Gn}from"./chunk-N5B2NILC.js";import{createHash as fd}from"crypto";import{existsSync as j,mkdirSync as yt,mkdtempSync as gd,readdirSync as Aa,renameSync as Ma,rmSync as se,statSync as An}from"fs";import{basename as gt,dirname as v,extname as hd,join as D,resolve as Pa}from"path";import{platform as va}from"os";function ri(e){let t=e?.match(/--max[-_]old[-_]space[-_]size(?:=|\s+)(\d+)/u);if(!t)return;let n=Number.parseInt(t[1],10);return Number.isInteger(n)&&n>0?n:void 0}function ii(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}import{execFileSync as rs}from"child_process";import{constants as is,copyFileSync as oi,linkSync as os,rmSync as as,statSync as ss}from"fs";import{platform as cs}from"os";var us=Object.freeze({size:e=>ss(e).size,clone:ms,copy:(e,t)=>oi(e,t),link:(e,t)=>os(e,t),remove:e=>as(e,{force:!0})}),ls=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),ds=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function oe(e,t,n=us,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(o){if(!gs(o))throw o}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(o){if(!ps(o))throw o}return n.copy(e,t),{method:"copy",bytes:i}}function ps(e){let t=e?.code;return typeof t=="string"&&ls.has(t)}function ms(e,t){if(cs()!=="darwin"){oi(e,t,is.COPYFILE_FICLONE_FORCE);return}try{rs("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw fs(n)}}function fs(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 gs(e){let t=e?.code;return t!==void 0&&ds.has(t)}function ai(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ae(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function Ze(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import hs from"better-sqlite3";import{execFileSync as ys}from"child_process";import{existsSync as Ss,readdirSync as bs}from"fs";import{extname as et,join as Rs}from"path";function X(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>si({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function si(e){let t=new Set((e.extensions??dr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Ss(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Er(e.projectRoot),r=xs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new hs(e.dbPath);try{let o=vs(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
1
+ import{a as V}from"./chunk-GINH3YQU.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F as qr,G as Hr,H as zr,I as Jr,J as Yr,K as Xr,L as Xe,M as G,N as Ke,P as Kr,Q as qt,R as Qr,S as Zr,T as Qe,U as ei,V as ti,W as ni,a as Tr,b as wr,c as qe,d as He,e as kr,f as _r,g as Cr,h as Fr,j as Or,l as Dr,m as Bt,n as ze,o as Nr,p as $r,q as Ut,r as ie,s as oe,t as Je,u as Vr,v as ns,w as Gt,x as Br,y as Ur}from"./chunk-ZHG4WAHR.js";import{a as Er}from"./chunk-QXCKQTKR.js";import{a as zn,b as $,c as Jn,d as kt,e as Yn,g as Xn,u as _t}from"./chunk-SYVJEEUJ.js";import{e as Ar,f as Mr,g as Lr,i as jr}from"./chunk-NU3KFF2O.js";import"./chunk-GC4DG2V5.js";import{C as Ir,a as Se,b as ke,c as be,d as At,e as Mt,f as Sr,g as br,h as Lt,k as jt,l as Rr,m as Nt,n as $t,o as xr,p as Pr,q as vr,r as Vt,t as Re}from"./chunk-J6GLBBRK.js";import"./chunk-SKKXTABJ.js";import"./chunk-KK7GPALL.js";import"./chunk-F5GSBHC6.js";import{a as qn,b as we,c as Y,d as ge,e as C,i as $e,j as Kn,k as Dt,l as yr}from"./chunk-QBQE7ZJ5.js";import"./chunk-FLMTCX5R.js";import"./chunk-YUKYB54I.js";import{b as mr,c as Ge,d as We,e as fr,f as gr,g as hr}from"./chunk-BOW7SSQH.js";import"./chunk-C7C6AKAT.js";import"./chunk-RBAD4GJ2.js";import{M as dr,N as pr,a as Ue}from"./chunk-ZLMXIQLC.js";import"./chunk-ETC674NS.js";import{A as lr,g as sr,j as Ot,q as cr,v as ur,y as I,z as B}from"./chunk-KNLQGXVH.js";import{A as Tt,B as Wn,Ba as nr,C as me,D as wt,E as Ne,Fa as rr,Ga as ir,H as fe,Ha as or,I as N,Ia as ar,J as U,K as Hn,Z as Ve,ca as Qn,da as re,e as It,ea as he,fa as ye,g as Le,ga as Zn,h as Bn,ha as er,i as Et,ia as Ct,j as Un,ka as Be,l as J,m as M,ta as Ft,w as pe,wa as tr,x as ne,y as je,z as Gn}from"./chunk-JZ2A7LDM.js";import{createHash as fd}from"crypto";import{existsSync as j,mkdirSync as yt,mkdtempSync as gd,readdirSync as Aa,renameSync as Ma,rmSync as ce,statSync as An}from"fs";import{basename as gt,dirname as v,extname as hd,join as D,resolve as Pa}from"path";import{platform as va}from"os";function ri(e){let t=e?.match(/--max[-_]old[-_]space[-_]size(?:=|\s+)(\d+)/u);if(!t)return;let n=Number.parseInt(t[1],10);return Number.isInteger(n)&&n>0?n:void 0}function ii(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}import{execFileSync as rs}from"child_process";import{constants as is,copyFileSync as oi,linkSync as os,rmSync as as,statSync as ss}from"fs";import{platform as cs}from"os";var us=Object.freeze({size:e=>ss(e).size,clone:ms,copy:(e,t)=>oi(e,t),link:(e,t)=>os(e,t),remove:e=>as(e,{force:!0})}),ls=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),ds=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function ae(e,t,n=us,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(o){if(!gs(o))throw o}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(o){if(!ps(o))throw o}return n.copy(e,t),{method:"copy",bytes:i}}function ps(e){let t=e?.code;return typeof t=="string"&&ls.has(t)}function ms(e,t){if(cs()!=="darwin"){oi(e,t,is.COPYFILE_FICLONE_FORCE);return}try{rs("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw fs(n)}}function fs(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 gs(e){let t=e?.code;return t!==void 0&&ds.has(t)}function ai(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function se(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function Ze(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import hs from"better-sqlite3";import{execFileSync as ys}from"child_process";import{existsSync as Ss,readdirSync as bs}from"fs";import{extname as et,join as Rs}from"path";function X(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>si({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function si(e){let t=new Set((e.extensions??dr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Ss(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Er(e.projectRoot),r=xs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new hs(e.dbPath);try{let o=vs(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
2
  VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let m of l){if(o.has(m))continue;let f=nr(e.projectRoot,m,{inputKind:"auxiliary source file"}),y=a.run(Is(m),m,f);d+=Number(y.changes)}return d})(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 xs(e,t){let n=Ps(e,t);if(n)return n;let r=[],i=o=>{let a=o?Rs(e,o):e,s;try{s=bs(a,{withFileTypes:!0})}catch{return}for(let c of s){if(pr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(et(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function Ps(e,t){try{return ys("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(et(r).toLowerCase())).sort()}catch{return null}}function vs(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 Is(e){return et(e).toLowerCase()===".vue"?"vue":et(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Es,join as Ts}from"path";function ci(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new V({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ts(Es(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?jr(i):null;e.reuseExisting&&u?.extractorVersion===Ar?(o=u,a=!0):(o=await Mr(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:I}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Lr(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}}}function _e(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 Fe(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=_e(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"),ui(r,i,a)):a.size>0?ui(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ws(r,t,i),reasons:[]}}function ui(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ws(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()}import{createHash as ks}from"crypto";import{existsSync as _s}from"fs";import{dirname as Fs,join as li}from"path";var Cs="<global-symbols>";function Os(e){let t=[];for(let n of e.all(`
3
+ `).filter(r=>r&&t.has(et(r).toLowerCase())).sort()}catch{return null}}function vs(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 Is(e){return et(e).toLowerCase()===".vue"?"vue":et(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Es,join as Ts}from"path";function ci(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new V({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ts(Es(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?jr(i):null;e.reuseExisting&&u?.extractorVersion===Ar?(o=u,a=!0):(o=await Mr(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:I}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Lr(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}}}function _e(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 Ce(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=_e(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"),ui(r,i,a)):a.size>0?ui(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ws(r,t,i),reasons:[]}}function ui(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ws(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()}import{createHash as ks}from"crypto";import{existsSync as _s}from"fs";import{dirname as Cs,join as li}from"path";var Fs="<global-symbols>";function Os(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(`
@@ -56,8 +56,8 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
56
56
  ) AND NOT EXISTS (
57
57
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
58
58
  )
59
- `))t.push({relativePath:Cs,kind:"global-symbol",values:Ht(n)});return Ds(t)}function Ds(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=ks("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 As(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 zt(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 Jt(e,t=Vs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return fi(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&z(e.previousSnapshot,e.currentSnapshot).changes.length===0)return a("no-input-changes");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(),l=z(e.previousSnapshot,e.currentSnapshot),d=new Set(u),m=l.changes.length>0&&!_e(l).fullProject&&l.changes.every(k=>d.has(k.path)),f=Fe(l,m?t.dependencyGraph(s):new Map,u),y=As(t.factDigests(s),t.factDigests(c)),b=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?b:i()).toISOString(),durationMs:Math.max(0,b-o),manifest:l,plan:f,comparison:y,evaluation:zt(f,y,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{di(s),di(c)}}function pi(e,t,n,r=Date.now()){return fi(e,t,r,0,n)}function Ms(e){let t=Fs(e);return{latestPath:li(t,"affected-shadow-latest.json"),historyPath:li(t,"affected-shadow.jsonl")}}function mi(e,t,n=Bs){let r=Ms(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Ls=8*1024*1024,js=Nr;function Ns(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 $s(e,t,n=Ls){$r(e,Ns(t),{maxSegmentBytes:n,previousSuffix:js})}function Ht(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 Vs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:F,databaseExists:e=>_s(e),openDatabase:(e,t,n)=>new V({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ue(e),dependencyGraph:e=>mr(e),factDigests:e=>Os(e)},Bs={appendHistory:$s,writeLatest:(e,t)=>$e(e,t,{spacing:2,trailingNewline:!0})};function fi(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 di(e){try{e?.close()}catch{}}import{readdirSync as Us}from"fs";import{isAbsolute as gi,join as Gs,resolve as Ws}from"path";var tt="@sourcegraph/scip-typescript@0.4.0",hi="scip-python-plus@0.7.5",yi="github.com/sourcegraph/scip-go@v0.2.7",Si="scip-dotnet@0.2.14",qs="scip_dart@1.6.2",Ri={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...M.typescript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...M.javascript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],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:[...M.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:[...M.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:[...M.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Se.language,indexerBinary:Se.indexerBinary,checkCommand:`${Se.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Se.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...M.rust],installMethods:[],installUrl:Se.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:[...M.python],installMethods:[{label:"npm",identity:hi,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",hi]}],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",gi(r)?r:Ws(e,r)),{binary:n,args:i}},markerFiles:[...M.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:[...M.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:[...M.go],installMethods:[{label:"go install",identity:yi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",yi]}],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:[...M.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:[...M.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",bi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.csharp],installMethods:[{label:"dotnet",identity:Si,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",bi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.vb],installMethods:[{label:"dotnet",identity:Si,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:[...M.dart],installMethods:[{label:"dart pub",identity:qs,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})=>gi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...M.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function xi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function nt(e){return Ri[e]}function bi(e,t){let n;try{n=Us(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Gs(e,i);return null}import{createHash as Hs}from"crypto";import{existsSync as Xt,rmSync as Pi,statSync as zs}from"fs";import{resolve as Js}from"path";import Ei from"better-sqlite3";var Ys={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}]},Xs={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 Ti(e){let t=F(),n=vi(e.affectedFiles),r=vi(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Qs(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Xt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Xt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");I("reindex.publish.sqlite-patch.validate-inputs",()=>{Yt(e.previousDbPath,"previous SQLite generation",!1),Yt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?I("reindex.publish.sqlite-patch.reuse-candidate",()=>Yt(e.candidateDbPath,"incremental SQLite candidate",!1)):I("reindex.publish.sqlite-patch.clone",()=>{Pi(e.candidateDbPath,{force:!0});let s=oe(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ae(e.writeTelemetry,s)});let a=null;try{a=I("reindex.publish.sqlite-patch.open",()=>{let f=new Ei(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Kt(f,"main","candidate SQLite generation"),Kt(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=I("reindex.publish.sqlite-patch.prepare",()=>(tc(a,n,r),{...nc(a,n.length,r.length),previousFactDigests:Qt(a,"main",!0)})),u=K(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{I("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>rc(a)),I("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>ic(a)),I("reindex.publish.sqlite-patch.transaction.delete",()=>oc(a)),e.onStage?.("after-delete"),I("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>ac(a)),e.onStage?.("after-symbol-reconciliation"),I("reindex.publish.sqlite-patch.transaction.insert",()=>sc(a)),e.onStage?.("after-insert"),I("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>cc(a,e.trustedPriorGeneration===!0)),I("reindex.publish.sqlite-patch.transaction.validate",()=>uc(a,o,u,s)),e.onStage?.("before-commit")});I("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&Ze(e.writeTelemetry,2*Ks(e.candidateDbPath)),I("reindex.publish.sqlite-patch.integrity",()=>ec(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=I("reindex.publish.sqlite-patch.validate-facts",()=>lc(a)),m=[...new Set([...c.keys(),...d.keys()])].filter(f=>c.get(f)!==d.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:m,durationMs:F()-t}}catch(s){try{a?.close()}finally{Pi(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Ks(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Xt(r)&&(t+=zs(r).size)}return t}function vi(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Qs(e,t,n){let r=[e,t,n].map(i=>Js(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Yt(e,t,n=!0){let r=new Ei(e,{readonly:!0,fileMustExist:!0});try{Kt(r,"main",t),n&&Zs(r,"main",t)}finally{r.close()}}function Kt(e,t,n){for(let[r,i]of Object.entries(Ys)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Xs)){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}`)}Ii(e,t,"documents",["relative_path"],n),Ii(e,t,"global_symbols",["symbol"],n)}function Ii(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 Zs(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 ec(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function tc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function nc(e,t,n){let r=K(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=K(e,`SELECT COUNT(*) AS value
59
+ `))t.push({relativePath:Fs,kind:"global-symbol",values:Ht(n)});return Ds(t)}function Ds(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=ks("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 As(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 zt(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 Jt(e,t=Vs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return fi(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&J(e.previousSnapshot,e.currentSnapshot).changes.length===0)return a("no-input-changes");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(),l=J(e.previousSnapshot,e.currentSnapshot),d=new Set(u),m=l.changes.length>0&&!_e(l).fullProject&&l.changes.every(k=>d.has(k.path)),f=Ce(l,m?t.dependencyGraph(s):new Map,u),y=As(t.factDigests(s),t.factDigests(c)),b=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?b:i()).toISOString(),durationMs:Math.max(0,b-o),manifest:l,plan:f,comparison:y,evaluation:zt(f,y,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{di(s),di(c)}}function pi(e,t,n,r=Date.now()){return fi(e,t,r,0,n)}function Ms(e){let t=Cs(e);return{latestPath:li(t,"affected-shadow-latest.json"),historyPath:li(t,"affected-shadow.jsonl")}}function mi(e,t,n=Bs){let r=Ms(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Ls=8*1024*1024,js=Nr;function Ns(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 $s(e,t,n=Ls){$r(e,Ns(t),{maxSegmentBytes:n,previousSuffix:js})}function Ht(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 Vs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:C,databaseExists:e=>_s(e),openDatabase:(e,t,n)=>new V({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ue(e),dependencyGraph:e=>mr(e),factDigests:e=>Os(e)},Bs={appendHistory:$s,writeLatest:(e,t)=>$e(e,t,{spacing:2,trailingNewline:!0})};function fi(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 di(e){try{e?.close()}catch{}}import{readdirSync as Us}from"fs";import{isAbsolute as gi,join as Gs,resolve as Ws}from"path";var tt="@sourcegraph/scip-typescript@0.4.0",hi="scip-python-plus@0.7.5",yi="github.com/sourcegraph/scip-go@v0.2.7",Si="scip-dotnet@0.2.14",qs="scip_dart@1.6.2",Ri={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...M.typescript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...M.javascript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],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:[...M.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:[...M.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:[...M.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Se.language,indexerBinary:Se.indexerBinary,checkCommand:`${Se.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Se.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...M.rust],installMethods:[],installUrl:Se.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:[...M.python],installMethods:[{label:"npm",identity:hi,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",hi]}],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",gi(r)?r:Ws(e,r)),{binary:n,args:i}},markerFiles:[...M.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:[...M.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:[...M.go],installMethods:[{label:"go install",identity:yi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",yi]}],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:[...M.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:[...M.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",bi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.csharp],installMethods:[{label:"dotnet",identity:Si,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",bi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.vb],installMethods:[{label:"dotnet",identity:Si,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:[...M.dart],installMethods:[{label:"dart pub",identity:qs,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})=>gi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...M.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function xi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function nt(e){return Ri[e]}function bi(e,t){let n;try{n=Us(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Gs(e,i);return null}import{createHash as Hs}from"crypto";import{existsSync as Xt,rmSync as Pi,statSync as zs}from"fs";import{resolve as Js}from"path";import Ei from"better-sqlite3";var Ys={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}]},Xs={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 Ti(e){let t=C(),n=vi(e.affectedFiles),r=vi(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Qs(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Xt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Xt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");I("reindex.publish.sqlite-patch.validate-inputs",()=>{Yt(e.previousDbPath,"previous SQLite generation",!1),Yt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?I("reindex.publish.sqlite-patch.reuse-candidate",()=>Yt(e.candidateDbPath,"incremental SQLite candidate",!1)):I("reindex.publish.sqlite-patch.clone",()=>{Pi(e.candidateDbPath,{force:!0});let s=ae(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&se(e.writeTelemetry,s)});let a=null;try{a=I("reindex.publish.sqlite-patch.open",()=>{let f=new Ei(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Kt(f,"main","candidate SQLite generation"),Kt(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=I("reindex.publish.sqlite-patch.prepare",()=>(tc(a,n,r),{...nc(a,n.length,r.length),previousFactDigests:Qt(a,"main",!0)})),u=K(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{I("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>rc(a)),I("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>ic(a)),I("reindex.publish.sqlite-patch.transaction.delete",()=>oc(a)),e.onStage?.("after-delete"),I("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>ac(a)),e.onStage?.("after-symbol-reconciliation"),I("reindex.publish.sqlite-patch.transaction.insert",()=>sc(a)),e.onStage?.("after-insert"),I("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>cc(a,e.trustedPriorGeneration===!0)),I("reindex.publish.sqlite-patch.transaction.validate",()=>uc(a,o,u,s)),e.onStage?.("before-commit")});I("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&Ze(e.writeTelemetry,2*Ks(e.candidateDbPath)),I("reindex.publish.sqlite-patch.integrity",()=>ec(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=I("reindex.publish.sqlite-patch.validate-facts",()=>lc(a)),m=[...new Set([...c.keys(),...d.keys()])].filter(f=>c.get(f)!==d.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:m,durationMs:C()-t}}catch(s){try{a?.close()}finally{Pi(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Ks(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Xt(r)&&(t+=zs(r).size)}return t}function vi(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Qs(e,t,n){let r=[e,t,n].map(i=>Js(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Yt(e,t,n=!0){let r=new Ei(e,{readonly:!0,fileMustExist:!0});try{Kt(r,"main",t),n&&Zs(r,"main",t)}finally{r.close()}}function Kt(e,t,n){for(let[r,i]of Object.entries(Ys)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Xs)){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}`)}Ii(e,t,"documents",["relative_path"],n),Ii(e,t,"global_symbols",["symbol"],n)}function Ii(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 Zs(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 ec(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function tc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function nc(e,t,n){let r=K(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=K(e,`SELECT COUNT(*) AS value
61
61
  FROM main.documents d
62
62
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
63
63
  FROM temp.incremental_affected_paths p
@@ -244,9 +244,9 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
244
244
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
245
245
  ${r}
246
246
  ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,d]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let m of d){let f=JSON.stringify([l,m]),y=c.get(m.relative_path)??[];y.push(f),c.set(m.relative_path,y)}let u=new Map;for(let[l,d]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=Hs("sha256");for(let f of d.sort())m.update(f).update(`
247
- `);u.set(l,m.digest("hex"))}return u}function K(e,t){return e.prepare(t).get().value}import dc from"better-sqlite3";var rt="idx_mentions_definitions",pc=["symbol_id","chunk_id"];function Zt(e,t={}){let n=new dc(e),r=[],i=[],o=[];try{return n.transaction(()=>{mc(n,r),it(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&wi(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):it(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=it(n,"idx_chunks_doc_id"),s=wi(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");a?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):a&&o.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:o,analyzed:t.analyze!==!1}}catch(a){if(a.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw a}finally{n.close()}}function mc(e,t){let n=ki(e,rt);if(n){let r=n.columns.join("\0")===pc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${rt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${rt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(rt)}function wi(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:it(e,n.name)??[]}))}function it(e,t){return ki(e,t)?.columns??null}function ki(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 fc}from"fs";function G(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Fi(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Ci(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Ai(e.cachePath,e.readFingerprint(),r),r}async function Oi(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 Ai(e.cachePath,e.readFingerprint(),r),r}function Di(e,t){try{let n=JSON.parse(N(e,{maxBytes:me,inputKind:"post-index augmentation cache"}));return _i(n.fingerprint)===_i(t)?{result:n.result}:null}catch{return null}}function Ai(e,t,n){fc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
247
+ `);u.set(l,m.digest("hex"))}return u}function K(e,t){return e.prepare(t).get().value}import dc from"better-sqlite3";var rt="idx_mentions_definitions",pc=["symbol_id","chunk_id"];function Zt(e,t={}){let n=new dc(e),r=[],i=[],o=[];try{return n.transaction(()=>{mc(n,r),it(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&wi(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):it(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=it(n,"idx_chunks_doc_id"),s=wi(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");a?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):a&&o.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:o,analyzed:t.analyze!==!1}}catch(a){if(a.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw a}finally{n.close()}}function mc(e,t){let n=ki(e,rt);if(n){let r=n.columns.join("\0")===pc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${rt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${rt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(rt)}function wi(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:it(e,n.name)??[]}))}function it(e,t){return ki(e,t)?.columns??null}function ki(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 fc}from"fs";function W(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Ci(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Fi(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Ai(e.cachePath,e.readFingerprint(),r),r}async function Oi(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 Ai(e.cachePath,e.readFingerprint(),r),r}function Di(e,t){try{let n=JSON.parse(N(e,{maxBytes:me,inputKind:"post-index augmentation cache"}));return _i(n.fingerprint)===_i(t)?{result:n.result}:null}catch{return null}}function Ai(e,t,n){fc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
248
248
  `)}function _i(e){return JSON.stringify(e)}import{createHash as gc}from"crypto";import{existsSync as en,readdirSync as hc}from"fs";import{dirname as tn,join as ot,relative as yc,resolve as nn,sep as Mi}from"path";function Li(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Vi(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function ji(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=Vi(s,e);c&&c!==i&&a.add(c)}}return Sc(e,r)}function Ni(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 rn(e){if(e===".")return"root";let t=gc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function $i(e,t){let n=nn(e),r={};for(let i of t)r[i]=bc(n,i);return r}function Vi(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 Sc(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 bc(e,t){let n=t==="."?e:ot(e,t),r=Rc(n),i=xc(n),o=i?Pc(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 Rc(e){let t=ot(e,"package.json");if(!en(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 xc(e){let t=ot(e,"tsconfig.json");if(en(t))return t;let n;try{n=hc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?ot(e,n[0]):void 0}function Pc(e,t){let n=on(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=vc(n.value,e,t),i=Bi(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function vc(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=tn(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=Ui(s,i,n);c&&o.add(c)}return[...o]}function Bi(e,t,n,r){let i=Ic(t);if(i)return{pathsTargets:Ec(i,tn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Tc(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=on(o);return a.ok?Bi(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Ic(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 Ec(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=Ui(o,t,n);a&&r.add(a)}return[...r]}function Tc(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=nn(tn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Mi).includes("node_modules")&&It(n,i)&&en(i))return i}function Ui(e,t,n){let r=e.replace(/\/?\*+$/,""),i=nn(t,r===""?".":r);if(!It(n,i))return;let a=yc(n,i).split(Mi).join("/");return a===""?".":a}function wc(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
249
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function on(e){try{let t=N(e,{maxBytes:me,inputKind:"TypeScript project manifest"}),n=JSON.parse(wc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import kc from"better-sqlite3";import{zstdCompressSync as _c}from"zlib";import{setImmediate as Gi}from"timers/promises";var Q=class extends Error{},Fc=200,sn=2,Wi=1,Cc=2,Oc=3,Dc=4,Ac=5,Mc=6,Yi=1,Xi=2,Ki=3,Lc=7,jc=1,Nc=3,$c=5,Vc=6,Bc=8,Uc=1,qi=64,Gc=[`CREATE TABLE documents (
249
+ `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function on(e){try{let t=N(e,{maxBytes:me,inputKind:"TypeScript project manifest"}),n=JSON.parse(wc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import kc from"better-sqlite3";import{zstdCompressSync as _c}from"zlib";import{setImmediate as Gi}from"timers/promises";var Q=class extends Error{},Cc=200,sn=2,Wi=1,Fc=2,Oc=3,Dc=4,Ac=5,Mc=6,Yi=1,Xi=2,Ki=3,Lc=7,jc=1,Nc=3,$c=5,Vc=6,Bc=8,Uc=1,qi=64,Gc=[`CREATE TABLE documents (
250
250
  id INTEGER PRIMARY KEY,
251
251
  language TEXT,
252
252
  relative_path TEXT NOT NULL UNIQUE,
@@ -286,11 +286,11 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
286
286
  end_char INTEGER NOT NULL,
287
287
  FOREIGN KEY (document_id) REFERENCES documents(id),
288
288
  FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
289
- )`],Wc=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function an(e){return e.startsWith("local ")}function Hi(e,t,n,r){let i=t,o=0,a=0;for(;i<n;){let s=e[i];i+=1,a<53&&(o+=(s&127)*2**a),(s&128)===0?(r.push(o),o=0,a=0):a+=7}}function zi(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function qc(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function Hc(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of re(e,n,r))u.fieldNumber===Yi?u.wireType===2?Hi(e,u.valueStart,u.valueEnd,i):u.wireType===0&&i.push(u.varint):u.fieldNumber===Xi&&u.wireType===2?a=xe.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===Ki&&u.wireType===0?s=u.varint:u.fieldNumber===Lc&&(u.wireType===2?Hi(e,u.valueStart,u.valueEnd,o):u.wireType===0&&o.push(u.varint));let c=zi(i);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:a,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:zi(o)}:null}function zc(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of re(e,t,n))if(i.wireType===2){let o=()=>xe.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===jc?r.symbol=o():i.fieldNumber===Nc?r.documentation.push(o()):i.fieldNumber===Vc?r.displayName=o():i.fieldNumber===Bc&&(r.enclosingSymbol=o())}else i.fieldNumber===$c&&i.wireType===0&&(r.kind=i.varint);return r}var xe=new TextDecoder;function Jc(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function Yc(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(a=>ie(a)));n.push(Je(Yi),ie(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(Je(Xi),ie(i.length),i),e.roles!==0&&n.push(ie(Ki*8),ie(e.roles));let o=Buffer.concat(n);return Buffer.concat([Je(sn),ie(o.length),o])}function Xc(e,t){let n=[];for(let r of t)r.merged?n.push(Yc(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return _c(Buffer.concat(n))}async function Qi(e,t,n={}){let r=n.chunkSize??Fc,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new kc(t);try{o.pragma("synchronous = normal"),o.pragma("temp_store = memory"),o.pragma("foreign_keys = ON"),o.pragma("journal_mode = WAL");for(let E of Gc)o.exec(E);let a=o.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),s=o.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),c=o.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),u=o.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),l=o.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)"),d=new Map,m=new Map,f=1,y=1,b=1,k=(E,C,w,h,S)=>{let g=b;return b+=1,m.set(E,g),u.run(g,E,C,w,h,S),i.globalSymbols+=1,g};o.exec("BEGIN IMMEDIATE");let O=!1;try{let E=0;for(let w of re(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=null,g=null,_=null,R=[];for(let p of re(e,w.valueStart,w.valueEnd))p.wireType===2?p.fieldNumber===Wi?h=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Oc?R.push(zc(e,p.valueStart,p.valueEnd)):p.fieldNumber===Dc?S=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Ac&&(g=xe.decode(e.subarray(p.valueStart,p.valueEnd))):p.fieldNumber===Mc&&p.wireType===0&&(_=Kc(p.varint));if(h==="")throw new Q("relative path must not be empty");if(d.has(h)){i.duplicateDocumentsSkipped+=1;continue}let P=f;f+=1,a.run(P,S===""?null:S,h,_,g===""?null:g),d.set(h,P),i.documents+=1;let T=new Map;for(let p of R){if(p.symbol==="")throw new Q(`empty symbol in SymbolInformation for document ${h}`);let x=T.get(p.symbol);if(!x){T.set(p.symbol,p);continue}for(let A of p.documentation)x.documentation.includes(A)||x.documentation.push(A)}for(let p of[...T.values()].sort((x,A)=>x.symbol<A.symbol?-1:x.symbol>A.symbol?1:0))an(p.symbol)||m.has(p.symbol)||k(p.symbol,p.displayName===""?null:p.displayName,p.kind===0?null:p.kind,p.documentation.length===0?null:p.documentation.join(`
290
- `),p.enclosingSymbol===""?null:p.enclosingSymbol)}let C=new Set;E=0;for(let w of re(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=[];for(let R of re(e,w.valueStart,w.valueEnd))if(R.wireType===2){if(R.fieldNumber===Wi)h=xe.decode(e.subarray(R.valueStart,R.valueEnd));else if(R.fieldNumber===Cc){let P=Hc(e,R.fieldStart,R.valueStart,R.valueEnd);P?S.push(P):i.illegalOccurrencesDropped+=1}}if(C.has(h))continue;C.add(h);let g=d.get(h);if(g===void 0)continue;S.sort(qc);let _=[];for(let R of S){let P=_[_.length-1];if(P&&P.startLine===R.startLine&&P.startChar===R.startChar&&P.endLine===R.endLine&&P.endChar===R.endChar&&P.symbol===R.symbol){P.roles|=R.roles,P.merged=!0,i.mergedOccurrences+=1;continue}_.push(R)}i.occurrences+=_.length;for(let R of _){if((R.roles&Uc)===0||an(R.symbol)||!R.enclosing)continue;let[P,T,p,x]=R.enclosing;if(P<0||T<0||p<P||p===P&&x<T)throw new Q(`bad enclosing range for symbol ${R.symbol} in ${h}`);let A=m.get(R.symbol);if(A===void 0)throw new Q(`symbol ${R.symbol} has definition occurrence, but no SymbolInformation`);c.run(g,A,P,T,p,x),i.enclosingRanges+=1}for(let[R,P]of Jc(_,r).entries()){let T=y;y+=1,s.run(T,g,R,P[0].startLine,P[P.length-1].startLine,Xc(e,P)),i.chunks+=1;let p=new Map;for(let x of P){if(an(x.symbol))continue;let A=p.get(x.symbol);A||p.set(x.symbol,A=new Set),A.add(x.roles),m.has(x.symbol)||k(x.symbol,null,null,null,null)}for(let[x,A]of p){let H=m.get(x);for(let vt of A)l.run(T,H,vt),i.mentions+=1}}}o.exec("COMMIT"),O=!0}finally{if(!O)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let E of Wc)o.exec(E);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function Kc(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new Q(`unknown position encoding ${e}`)}function Ji(e){if(e?.aborted)throw new Q("SCIP SQLite conversion aborted")}import{readdirSync as Qc,rmSync as Zc}from"fs";import{cpus as eu,totalmem as tu}from"os";import{join as at}from"path";var nu=2048,ru=6*1024**3,iu=4;function cn(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:nu}function eo(e,t){return e>Math.floor(t*1.5)}var ou=1.25;function to(e,t,n){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard targetFiles must be a positive safe integer; received ${t}.`);let r=Math.max(1,Math.ceil(e/t));if(r<=1||n<=1)return r;let i=Math.floor(t*ou),o=new Set([r,n*Math.floor(r/n),n*Math.ceil(r/n)]),a=c=>Math.ceil(c/n)*Math.ceil(e/c),s=r;for(let c of o)c<1||Math.ceil(e/c)>i||(a(c)<a(s)||a(c)===a(s)&&c<s)&&(s=c);return s}function au(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((u,l)=>u.localeCompare(l));if(t===1||r.length<=t)return r.length<=t&&t>1?r.map(u=>[u]):r.length>0?[r]:[];let i=r.map(u=>Math.max(1,n(u))),o=i.reduce((u,l)=>u+l,0),a=[],s=[],c=0;for(let u=0;u<r.length;u+=1){s.push(r[u]),c+=i[u];let l=t-a.length-1,d=r.length-u-1;l>0&&d>=l&&(c>=o*(a.length+1)/t||d===l)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function no(e){let t=e.targetFiles??cn(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return au(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=at(e.projectRoot,Zn(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
291
- `;return{configPath:o,content:a,inputPaths:r}})}var ro="typescript-shard-costs.json",Zi=4;function io(e){let t;try{t=JSON.parse(Hn(at(e,ro),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(i=>typeof i=="object"&&i!==null&&typeof i.firstPath=="string"&&typeof i.lastPath=="string"&&Number.isFinite(i.totalBytes)&&i.totalBytes>0&&Number.isFinite(i.durationMs)&&i.durationMs>0)?{version:1,samples:n}:null}function oo(e,t){$e(at(e,ro),t)}function ao(e){let t=(e?.samples??[]).filter(o=>o.totalBytes>0&&o.durationMs>0);if(t.length<2)return(o,a)=>a;let n=t.map(o=>o.durationMs/o.totalBytes).sort((o,a)=>o-a),r=n[Math.floor(n.length/2)];if(!(r>0))return(o,a)=>a;let i=[...t].sort((o,a)=>o.firstPath.localeCompare(a.firstPath));return(o,a)=>{for(let s of i){if(o.localeCompare(s.firstPath)<0)break;if(o.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return a*Math.min(Zi,Math.max(1/Zi,c))}return a}}function so(e,t){let n=[];for(let r of e){let i=r.inputPaths[0],o=r.inputPaths[r.inputPaths.length-1];if(i===void 0||o===void 0||!(r.durationMs>0))return null;let a=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:i,lastPath:o,totalBytes:a,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function co(e=process.env,t={totalmemBytes:tu(),cpuCount:eu().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/ru),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(iu,r,i))}function uo(e){let t;try{t=Qc(e)}catch{return}for(let n of t)if(er(n))try{Zc(at(e,n))}catch{}}import{createHash as bn}from"crypto";import{existsSync as Sn,writeFileSync as ko}from"fs";import{join as _u}from"path";import{createRequire as su}from"module";import{dirname as mn,isAbsolute as cu,relative as mo,resolve as ee,sep as ln}from"path";var Z=su(import.meta.url),uu=1,lo="0.4.0";function lu(){try{let e=fo();if(!e.available)return e;let{packageRoot:t}=e,n=Z.resolve("typescript",{paths:[t]}),r=Z(n),{FileIndexer:i}=Z(ee(t,"dist/src/FileIndexer.js")),{Input:o}=Z(ee(t,"dist/src/Input.js")),{Packages:a}=Z(ee(t,"dist/src/Packages.js")),s=Z(ee(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:gn(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function fn(){let e=fo();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function fo(){try{let e=Z.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==lo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${lo}`};let n=mn(e),r=Z.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(U(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:ho(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function go(e){let t=e.runtime===void 0?lu():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:gn(e.runtime)};return t.available?{available:!0,emitter:new dn(e,t.runtime)}:t}var dn=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=ee(t.workspaceRoot),this.tsconfigPath=ee(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??pu(this.workspaceRoot,mn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=gn(n);let r=un(n.typescript,this.tsconfigPath);this.config=r,this.host=new pn(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(Ie(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=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=un(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Ie));let s=this.program,c=new Map;for(let u of[...r,...i]){let l=Pe(this.workspaceRoot,u),d=s.getSourceFile(l);d&&(c.set(u,d),this.stats.symbolEntriesPruned+=po(this.symbolTable,d),this.stats.symbolEntriesPruned+=po(this.constructorTable,d)),this.host.invalidate(l)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[u,l]of c)this.program.getSourceFile(Pe(this.workspaceRoot,u))===l?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(st(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??un(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Ie)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Pe(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Pe(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Pe(this.workspaceRoot,n);if(!this.includedFiles.has(Ie(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Pe(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=st(mo(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:du(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function du(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 pn=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 l=Ie(a);if(this.sourceFiles.has(l))return this.sourceFiles.get(l);let d=o(a,s,c,u);return this.sourceFiles.set(l,d),d}}}invalidate(t){this.sourceFiles.delete(Ie(t))}};function un(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,mn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function gn(e){return ho(e.packageVersion,e.typescript.version)}function ho(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${uu}`}function pu(e,t){return st(mo(e,t))||"."}function Pe(e,t){if(cu(t))throw new Error(`expected a project-relative path: ${t}`);let n=ee(e,t),r=e.endsWith(ln)?e:`${e}${ln}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function ve(e){return[...new Set(e.map(st))].sort()}function st(e){return e.split(ln).join("/").replace(/^\.\//,"")}function Ie(e){return ee(e)}function po(e,t){let n=0;for(let r of e.keys())if(mu(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function mu(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as fu}from"crypto";import{dirname as gu,join as yo}from"path";var Ee=5;var hu="typescript-index";function So(e){let t=yo(e,hu),n=Rr(t);return{...n,requestDir:n.legacyRequestDir}}function bo(e){try{let t=Gn(te(U(yo(gu(e),"meta.json"),"reindex metadata")));return t?fu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Ru}from"crypto";import{existsSync as xo,rmSync as hn}from"fs";import{join as xu}from"path";import{randomUUID as yu}from"crypto";import{getHeapStatistics as Su}from"v8";import{resolve as bu}from"path";var ct=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=bu(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??go,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??F,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:Su().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:Ee,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 Nm=`typescript-index-${process.pid}-${yu()}`,Ro=J(process.pid),$m={pid:process.pid,...Ro?{processIdentity:Ro}:{}};var Pu=12e4,vu=5,Ce=class extends Error{name="TypeScriptIndexMemoryPressureError"},ut=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Qn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??wu(),this.runtime=n.runtime??ku,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=vr(this.cacheDir),r=So(this.cacheDir),i=Vt(n.statePath);if(!Po(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??F)()+this.timeoutMs,c=Nt("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),l=xr(r,{mailboxVersion:jt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ee,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??F)()<=s;){if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}let d=Vt(n.statePath);if(!Po(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(vu)}if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{hn(xu(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?yn(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new ct({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),yn(Io(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Po(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===Ee&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Pr&&(!e.processIdentity||r!=null&&we(e.processIdentity,r))}function vo(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ee||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 Iu(s)?new Ce(s):new Error(s)}return yn(Io(a.response,i),i,o)}function Iu(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 yn(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 Io(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(Eu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Tu(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 Eu(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 Tu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function wu(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Pu}var ku={now:Date.now,monotonicNow:F,randomId:Ru,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ge,readProcessIdentity:J};var Fu=128,Cu=256;function Ou(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=he(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=z(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(g=>g.inputKind==="source"&&Re(g.path)),o=_o(r,n),a={...r,changes:o},s=i.filter(g=>g.kind==="added").map(g=>g.path),c=i.filter(g=>g.kind==="deleted").map(g=>g.path),u=i.filter(g=>g.kind==="modified"),l=dt(e.currentSnapshot,e.producerIdentity,n),d=dt(e.previousSnapshot,e.producerIdentity,n),m=Fo(r,o,l,d),f=!m&&Oo(r);if(i.length===0&&!m)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let y=e.currentSnapshot.files.filter(g=>Le(g.path,e.currentSnapshot.languages)==="source"&&Re(g.path)).map(g=>g.path).sort(),b=new Set(y),k=m?e.projectFiles.filter(g=>!b.has(g)).sort():[...c].sort(),O=m?a:{...r,changes:i},E=m?{eligible:!0,plan:{...Fe(a,e.graph,[...new Set([...y,...k])]),mode:"full-project"}}:Au(u,s,k,e.graph,e.projectFiles);if(!E.eligible)return E;let C=E.plan,w=new Set(k),h=Mu(C,t,e.graph,w);if(!h)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let S=h.length===1?h[0]:void 0;return{eligible:!0,manifest:O,plan:C,projectIdentity:l,previousFragmentGeneration:wo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:wo(e.currentSnapshot,e.producerIdentity),projects:h,deletedFiles:k,replaceProject:m,dependencyGraphUnchanged:f,...S?{tsconfigPath:S.tsconfigPath,projectArgument:S.projectArgument}:{}}}function _o(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Re(n.path)||n.inputKind==="config"&&(!ye(n.path)||t.has(n.path))&&Du(n)||n.inputKind==="ambient")}function Du(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Fo(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>Cu||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function Au(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Eo(n,r,i)])].sort(),reasons:[]}};let o=Fe({version:1,changes:e.filter(Co),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...Eo(n,r,i)])].sort(),reasons:[]}}}function Co(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Oo(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Re(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!Co(n))}function Mu(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Lu(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(m=>!r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),l=e.changedFiles.filter(m=>r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),d=s.filter(m=>!r.has(m));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function Eo(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function Lu(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 To(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 Do(e){let t=F();try{if(!Sn(e.previousDbPath)||!Sn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=fn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=Nu(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?ne(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=he(s),u,l,d;try{u=Ue(o,{includeIgnored:!1}).filter(Re).sort();let T=a?z(a,e.currentSnapshot):null,p=T&&a&&Fo(T,_o(T,c),dt(e.currentSnapshot,r.producerIdentity,c),dt(a,r.producerIdentity,c)),x=T!==null&&!p&&Oo(T);p?(d=We(o,"none")??void 0,l=new Map):x?l=new Map:(d=Ge(o),l=d.graph)}finally{o.close()}let m=performance.now()-n,f=Ou({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:u,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Sn(_u(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let y=bo(e.previousDbPath);if(!y)throw new Error("published TypeScript base generation unavailable");n=performance.now();let b=new ut({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:y},{requireService:!0}),k=f.projects.flatMap(T=>{let p=ju(T.affectedFiles,Fu);return(p.length>0?p:[[]]).map((A,H)=>({project:T,affectedFiles:A,removedFiles:H===0?T.removedFiles:[],firstForProject:H===0}))}),O=[],E=new Map,C=[],w=!1,h=0,S=0,g=0,_=f.previousFragmentGeneration;for(let[T,p]of k.entries()){let x=b.request({kind:"emit-documents",tsconfigPath:p.project.tsconfigPath,projectArgument:p.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:p.firstForProject?p.project.modifiedFiles:[],removedFiles:p.firstForProject?p.project.removedFiles:[],affectedFiles:p.affectedFiles});w||=x.cold,C.push(x.durationMs);let A=p.removedFiles.map(Me=>({relativePath:Me,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),H=[...x.fragments,...A];if(!f.replaceProject)for(let Me of H)E.set(Me.relativePath,Me.referenceFragments);let vt=performance.now(),Za=Wr(x.fragments);h+=performance.now()-vt;let $n=T===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${T}.scip`,es=performance.now();ko($n,Za),g+=performance.now()-es;let ts=performance.now(),Vn=T===k.length-1?f.nextFragmentGeneration:$u({previousGenerationIdentity:_,targetGenerationIdentity:f.nextFragmentGeneration,fragments:H});Hr({cacheDir:e.cacheDir,previousGenerationIdentity:_,nextGenerationIdentity:Vn,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:T===0?e.baseShardCurrent:!1,fragments:H,allowProjectIdentityChange:f.replaceProject&&T===0,allowLegacyProjectIdentityMigration:!0}),S+=performance.now()-ts,_=Vn,O.push({scipPath:$n,affectedFiles:[...p.affectedFiles,...p.removedFiles].sort(),deletedFiles:[...p.removedFiles].sort()})}let R=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:O,completeScipUpdated:!1,durationMs:F()-t,cold:w,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:u.length,dependencyGraphSnapshot:d,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:E,timings:{runtimeMs:i,graphMs:m,requestMs:R,serviceMs:C.reduce((T,p)=>T+p,0),assemblyMs:h,fragmentStoreMs:S,writeMs:g}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${O.length} bounded batch(es) across ${f.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 ${m.toFixed(0)}ms, request ${R.toFixed(0)}ms, assembly ${h.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${g.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Ce)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function ju(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Nu(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Be(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function $u(e){let t=bn("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(bn("sha256").update(n.bytes).digest()));return t.digest("hex")}function Rn(e){let t=fn();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fe(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ne}),packageVersion:t.packageVersion});ko(e.candidateShardPath,n)}function dt(e,t,n){let r=e.files.filter(i=>{let o=Le(i.path,e.languages);return o==="ambient"||o==="config"&&(!ye(i.path)||n.has(i.path))}).map(i=>{let a=Le(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${Ao(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function wo(e,t){return Ao(JSON.stringify({version:1,producerIdentity:t,snapshot:Un(e)}))}function Ao(e){return bn("sha256").update(e).digest("hex")}import{closeSync as Vu,existsSync as pt,fstatSync as Bu,lstatSync as Uu,openSync as Gu,renameSync as vn,rmSync as Oe,statSync as Wu,writeSync as qu}from"fs";import{cpus as Hu}from"os";import{join as In}from"path";var xn=Symbol("no-error");async function Mo(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=xn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===xn&&(s=d),c=!1}}});if(await Promise.all(u),s!==xn)throw s;return r}var Lo=8*1024;function jo(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Gu(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Oe(e,{force:!0}),o=i()}try{qu(o,r);let a=Bu(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{Vu(o)}}function zu(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=jo(In(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=jo(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())Vo(i);throw r}}function Vo(e){if(e)try{let t=Uu(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=fe(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Oe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Ju(e,t,n){if(!e.defaultOutputPath)return;let r=In(t,e.defaultOutputPath);n!==r&&pt(r)&&vn(r,n)}function Yu(e,t,n){if(!e.defaultOutputPath)return null;let r=In(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Oe(i,{force:!0}),pt(r)?(vn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Xu(e){e&&(Oe(e.defaultOutputPath,{force:!0}),e.backupPath&&pt(e.backupPath)&&vn(e.backupPath,e.defaultOutputPath))}function Ku(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,Hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bo(e,t,n,r,i){$(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await No(s,Ku(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await No(a,u,t,n,i))}for(let u of o)$(i,"Reindex cancelled by its owner."),c.push((await Pn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function No(e,t,n,r,i){let o=await Mo(e,Math.max(1,t),s=>Pn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),$(i,"Reindex cancelled by its owner."),a.set(c.id,(await Pn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function Pn(e,t,n,r){$(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Oe(e.scipPath,{force:!0});let i=Yu(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=F();try{o=zu(e,t),e.trustedProjectTool&&br(t,e.trustedProjectTool);let u=yr(e.binary,e.args),l=await qe({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Qu(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
289
+ )`],Wc=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function an(e){return e.startsWith("local ")}function Hi(e,t,n,r){let i=t,o=0,a=0;for(;i<n;){let s=e[i];i+=1,a<53&&(o+=(s&127)*2**a),(s&128)===0?(r.push(o),o=0,a=0):a+=7}}function zi(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function qc(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function Hc(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of ie(e,n,r))u.fieldNumber===Yi?u.wireType===2?Hi(e,u.valueStart,u.valueEnd,i):u.wireType===0&&i.push(u.varint):u.fieldNumber===Xi&&u.wireType===2?a=xe.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===Ki&&u.wireType===0?s=u.varint:u.fieldNumber===Lc&&(u.wireType===2?Hi(e,u.valueStart,u.valueEnd,o):u.wireType===0&&o.push(u.varint));let c=zi(i);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:a,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:zi(o)}:null}function zc(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of ie(e,t,n))if(i.wireType===2){let o=()=>xe.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===jc?r.symbol=o():i.fieldNumber===Nc?r.documentation.push(o()):i.fieldNumber===Vc?r.displayName=o():i.fieldNumber===Bc&&(r.enclosingSymbol=o())}else i.fieldNumber===$c&&i.wireType===0&&(r.kind=i.varint);return r}var xe=new TextDecoder;function Jc(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function Yc(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(a=>oe(a)));n.push(Je(Yi),oe(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(Je(Xi),oe(i.length),i),e.roles!==0&&n.push(oe(Ki*8),oe(e.roles));let o=Buffer.concat(n);return Buffer.concat([Je(sn),oe(o.length),o])}function Xc(e,t){let n=[];for(let r of t)r.merged?n.push(Yc(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return _c(Buffer.concat(n))}async function Qi(e,t,n={}){let r=n.chunkSize??Cc,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new kc(t);try{o.pragma("synchronous = normal"),o.pragma("temp_store = memory"),o.pragma("foreign_keys = ON"),o.pragma("journal_mode = WAL");for(let E of Gc)o.exec(E);let a=o.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),s=o.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),c=o.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),u=o.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),l=o.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)"),d=new Map,m=new Map,f=1,y=1,b=1,k=(E,F,w,h,S)=>{let g=b;return b+=1,m.set(E,g),u.run(g,E,F,w,h,S),i.globalSymbols+=1,g};o.exec("BEGIN IMMEDIATE");let O=!1;try{let E=0;for(let w of ie(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=null,g=null,_=null,R=[];for(let p of ie(e,w.valueStart,w.valueEnd))p.wireType===2?p.fieldNumber===Wi?h=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Oc?R.push(zc(e,p.valueStart,p.valueEnd)):p.fieldNumber===Dc?S=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Ac&&(g=xe.decode(e.subarray(p.valueStart,p.valueEnd))):p.fieldNumber===Mc&&p.wireType===0&&(_=Kc(p.varint));if(h==="")throw new Q("relative path must not be empty");if(d.has(h)){i.duplicateDocumentsSkipped+=1;continue}let P=f;f+=1,a.run(P,S===""?null:S,h,_,g===""?null:g),d.set(h,P),i.documents+=1;let T=new Map;for(let p of R){if(p.symbol==="")throw new Q(`empty symbol in SymbolInformation for document ${h}`);let x=T.get(p.symbol);if(!x){T.set(p.symbol,p);continue}for(let A of p.documentation)x.documentation.includes(A)||x.documentation.push(A)}for(let p of[...T.values()].sort((x,A)=>x.symbol<A.symbol?-1:x.symbol>A.symbol?1:0))an(p.symbol)||m.has(p.symbol)||k(p.symbol,p.displayName===""?null:p.displayName,p.kind===0?null:p.kind,p.documentation.length===0?null:p.documentation.join(`
290
+ `),p.enclosingSymbol===""?null:p.enclosingSymbol)}let F=new Set;E=0;for(let w of ie(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=[];for(let R of ie(e,w.valueStart,w.valueEnd))if(R.wireType===2){if(R.fieldNumber===Wi)h=xe.decode(e.subarray(R.valueStart,R.valueEnd));else if(R.fieldNumber===Fc){let P=Hc(e,R.fieldStart,R.valueStart,R.valueEnd);P?S.push(P):i.illegalOccurrencesDropped+=1}}if(F.has(h))continue;F.add(h);let g=d.get(h);if(g===void 0)continue;S.sort(qc);let _=[];for(let R of S){let P=_[_.length-1];if(P&&P.startLine===R.startLine&&P.startChar===R.startChar&&P.endLine===R.endLine&&P.endChar===R.endChar&&P.symbol===R.symbol){P.roles|=R.roles,P.merged=!0,i.mergedOccurrences+=1;continue}_.push(R)}i.occurrences+=_.length;for(let R of _){if((R.roles&Uc)===0||an(R.symbol)||!R.enclosing)continue;let[P,T,p,x]=R.enclosing;if(P<0||T<0||p<P||p===P&&x<T)throw new Q(`bad enclosing range for symbol ${R.symbol} in ${h}`);let A=m.get(R.symbol);if(A===void 0)throw new Q(`symbol ${R.symbol} has definition occurrence, but no SymbolInformation`);c.run(g,A,P,T,p,x),i.enclosingRanges+=1}for(let[R,P]of Jc(_,r).entries()){let T=y;y+=1,s.run(T,g,R,P[0].startLine,P[P.length-1].startLine,Xc(e,P)),i.chunks+=1;let p=new Map;for(let x of P){if(an(x.symbol))continue;let A=p.get(x.symbol);A||p.set(x.symbol,A=new Set),A.add(x.roles),m.has(x.symbol)||k(x.symbol,null,null,null,null)}for(let[x,A]of p){let z=m.get(x);for(let vt of A)l.run(T,z,vt),i.mentions+=1}}}o.exec("COMMIT"),O=!0}finally{if(!O)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let E of Wc)o.exec(E);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function Kc(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new Q(`unknown position encoding ${e}`)}function Ji(e){if(e?.aborted)throw new Q("SCIP SQLite conversion aborted")}import{readdirSync as Qc,rmSync as Zc}from"fs";import{cpus as eu,totalmem as tu}from"os";import{join as at}from"path";var nu=2048,ru=6*1024**3,iu=4;function cn(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:nu}function eo(e,t){return e>Math.floor(t*1.5)}var ou=1.25;function to(e,t,n){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard targetFiles must be a positive safe integer; received ${t}.`);let r=Math.max(1,Math.ceil(e/t));if(r<=1||n<=1)return r;let i=Math.floor(t*ou),o=new Set([r,n*Math.floor(r/n),n*Math.ceil(r/n)]),a=c=>Math.ceil(c/n)*Math.ceil(e/c),s=r;for(let c of o)c<1||Math.ceil(e/c)>i||(a(c)<a(s)||a(c)===a(s)&&c<s)&&(s=c);return s}function au(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((u,l)=>u.localeCompare(l));if(t===1||r.length<=t)return r.length<=t&&t>1?r.map(u=>[u]):r.length>0?[r]:[];let i=r.map(u=>Math.max(1,n(u))),o=i.reduce((u,l)=>u+l,0),a=[],s=[],c=0;for(let u=0;u<r.length;u+=1){s.push(r[u]),c+=i[u];let l=t-a.length-1,d=r.length-u-1;l>0&&d>=l&&(c>=o*(a.length+1)/t||d===l)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function no(e){let t=e.targetFiles??cn(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return au(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=at(e.projectRoot,Zn(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
291
+ `;return{configPath:o,content:a,inputPaths:r}})}var ro="typescript-shard-costs.json",Zi=4;function io(e){let t;try{t=JSON.parse(Hn(at(e,ro),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(i=>typeof i=="object"&&i!==null&&typeof i.firstPath=="string"&&typeof i.lastPath=="string"&&Number.isFinite(i.totalBytes)&&i.totalBytes>0&&Number.isFinite(i.durationMs)&&i.durationMs>0)?{version:1,samples:n}:null}function oo(e,t){$e(at(e,ro),t)}function ao(e){let t=(e?.samples??[]).filter(o=>o.totalBytes>0&&o.durationMs>0);if(t.length<2)return(o,a)=>a;let n=t.map(o=>o.durationMs/o.totalBytes).sort((o,a)=>o-a),r=n[Math.floor(n.length/2)];if(!(r>0))return(o,a)=>a;let i=[...t].sort((o,a)=>o.firstPath.localeCompare(a.firstPath));return(o,a)=>{for(let s of i){if(o.localeCompare(s.firstPath)<0)break;if(o.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return a*Math.min(Zi,Math.max(1/Zi,c))}return a}}function so(e,t){let n=[];for(let r of e){let i=r.inputPaths[0],o=r.inputPaths[r.inputPaths.length-1];if(i===void 0||o===void 0||!(r.durationMs>0))return null;let a=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:i,lastPath:o,totalBytes:a,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function co(e=process.env,t={totalmemBytes:tu(),cpuCount:eu().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/ru),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(iu,r,i))}function uo(e){let t;try{t=Qc(e)}catch{return}for(let n of t)if(er(n))try{Zc(at(e,n))}catch{}}import{createHash as bn}from"crypto";import{existsSync as Sn,writeFileSync as ko}from"fs";import{join as _u}from"path";import{createRequire as su}from"module";import{dirname as mn,isAbsolute as cu,relative as mo,resolve as ee,sep as ln}from"path";var Z=su(import.meta.url),uu=1,lo="0.4.0";function lu(){try{let e=fo();if(!e.available)return e;let{packageRoot:t}=e,n=Z.resolve("typescript",{paths:[t]}),r=Z(n),{FileIndexer:i}=Z(ee(t,"dist/src/FileIndexer.js")),{Input:o}=Z(ee(t,"dist/src/Input.js")),{Packages:a}=Z(ee(t,"dist/src/Packages.js")),s=Z(ee(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:gn(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function fn(){let e=fo();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function fo(){try{let e=Z.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==lo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${lo}`};let n=mn(e),r=Z.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(U(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:ho(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function go(e){let t=e.runtime===void 0?lu():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:gn(e.runtime)};return t.available?{available:!0,emitter:new dn(e,t.runtime)}:t}var dn=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=ee(t.workspaceRoot),this.tsconfigPath=ee(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??pu(this.workspaceRoot,mn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=gn(n);let r=un(n.typescript,this.tsconfigPath);this.config=r,this.host=new pn(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(Ie(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=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=un(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Ie));let s=this.program,c=new Map;for(let u of[...r,...i]){let l=Pe(this.workspaceRoot,u),d=s.getSourceFile(l);d&&(c.set(u,d),this.stats.symbolEntriesPruned+=po(this.symbolTable,d),this.stats.symbolEntriesPruned+=po(this.constructorTable,d)),this.host.invalidate(l)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[u,l]of c)this.program.getSourceFile(Pe(this.workspaceRoot,u))===l?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(st(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??un(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Ie)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Pe(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Pe(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Pe(this.workspaceRoot,n);if(!this.includedFiles.has(Ie(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Pe(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=st(mo(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:du(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function du(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 pn=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 l=Ie(a);if(this.sourceFiles.has(l))return this.sourceFiles.get(l);let d=o(a,s,c,u);return this.sourceFiles.set(l,d),d}}}invalidate(t){this.sourceFiles.delete(Ie(t))}};function un(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,mn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function gn(e){return ho(e.packageVersion,e.typescript.version)}function ho(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${uu}`}function pu(e,t){return st(mo(e,t))||"."}function Pe(e,t){if(cu(t))throw new Error(`expected a project-relative path: ${t}`);let n=ee(e,t),r=e.endsWith(ln)?e:`${e}${ln}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function ve(e){return[...new Set(e.map(st))].sort()}function st(e){return e.split(ln).join("/").replace(/^\.\//,"")}function Ie(e){return ee(e)}function po(e,t){let n=0;for(let r of e.keys())if(mu(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function mu(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as fu}from"crypto";import{dirname as gu,join as yo}from"path";var Ee=5;var hu="typescript-index";function So(e){let t=yo(e,hu),n=Rr(t);return{...n,requestDir:n.legacyRequestDir}}function bo(e){try{let t=Gn(ne(U(yo(gu(e),"meta.json"),"reindex metadata")));return t?fu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Ru}from"crypto";import{existsSync as xo,rmSync as hn}from"fs";import{join as xu}from"path";import{randomUUID as yu}from"crypto";import{getHeapStatistics as Su}from"v8";import{resolve as bu}from"path";var ct=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=bu(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??go,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??C,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:Su().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:Ee,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 $m=`typescript-index-${process.pid}-${yu()}`,Ro=Y(process.pid),Vm={pid:process.pid,...Ro?{processIdentity:Ro}:{}};var Pu=12e4,vu=5,Fe=class extends Error{name="TypeScriptIndexMemoryPressureError"},ut=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Qn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??wu(),this.runtime=n.runtime??ku,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=vr(this.cacheDir),r=So(this.cacheDir),i=Vt(n.statePath);if(!Po(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??C)()+this.timeoutMs,c=Nt("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),l=xr(r,{mailboxVersion:jt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ee,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??C)()<=s;){if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}let d=Vt(n.statePath);if(!Po(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(vu)}if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{hn(xu(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?yn(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new ct({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),yn(Io(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Po(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===Ee&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Pr&&(!e.processIdentity||r!=null&&we(e.processIdentity,r))}function vo(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ee||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 Iu(s)?new Fe(s):new Error(s)}return yn(Io(a.response,i),i,o)}function Iu(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 yn(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 Io(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(Eu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Tu(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 Eu(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 Tu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function wu(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Pu}var ku={now:Date.now,monotonicNow:C,randomId:Ru,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ge,readProcessIdentity:Y};var Cu=128,Fu=256;function Ou(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=he(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=J(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(g=>g.inputKind==="source"&&Re(g.path)),o=_o(r,n),a={...r,changes:o},s=i.filter(g=>g.kind==="added").map(g=>g.path),c=i.filter(g=>g.kind==="deleted").map(g=>g.path),u=i.filter(g=>g.kind==="modified"),l=dt(e.currentSnapshot,e.producerIdentity,n),d=dt(e.previousSnapshot,e.producerIdentity,n),m=Co(r,o,l,d),f=!m&&Oo(r);if(i.length===0&&!m)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let y=e.currentSnapshot.files.filter(g=>Le(g.path,e.currentSnapshot.languages)==="source"&&Re(g.path)).map(g=>g.path).sort(),b=new Set(y),k=m?e.projectFiles.filter(g=>!b.has(g)).sort():[...c].sort(),O=m?a:{...r,changes:i},E=m?{eligible:!0,plan:{...Ce(a,e.graph,[...new Set([...y,...k])]),mode:"full-project"}}:Au(u,s,k,e.graph,e.projectFiles);if(!E.eligible)return E;let F=E.plan,w=new Set(k),h=Mu(F,t,e.graph,w);if(!h)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let S=h.length===1?h[0]:void 0;return{eligible:!0,manifest:O,plan:F,projectIdentity:l,previousFragmentGeneration:e.previousOverlayGeneration??wo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:wo(e.currentSnapshot,e.producerIdentity),projects:h,deletedFiles:k,replaceProject:m,dependencyGraphUnchanged:f,...S?{tsconfigPath:S.tsconfigPath,projectArgument:S.projectArgument}:{}}}function _o(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Re(n.path)||n.inputKind==="config"&&(!ye(n.path)||t.has(n.path))&&Du(n)||n.inputKind==="ambient")}function Du(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Co(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>Fu||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function Au(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Eo(n,r,i)])].sort(),reasons:[]}};let o=Ce({version:1,changes:e.filter(Fo),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...Eo(n,r,i)])].sort(),reasons:[]}}}function Fo(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Oo(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Re(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!Fo(n))}function Mu(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Lu(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(m=>!r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),l=e.changedFiles.filter(m=>r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),d=s.filter(m=>!r.has(m));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function Eo(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function Lu(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 To(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 Do(e){let t=C();try{if(!Sn(e.previousDbPath)||!Sn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=fn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=Nu(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?re(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=he(s),u,l,d;try{u=Ue(o,{includeIgnored:!1}).filter(Re).sort();let T=a?J(a,e.currentSnapshot):null,p=T&&a&&Co(T,_o(T,c),dt(e.currentSnapshot,r.producerIdentity,c),dt(a,r.producerIdentity,c)),x=T!==null&&!p&&Oo(T);p?(d=We(o,"none")??void 0,l=new Map):x?l=new Map:(d=Ge(o),l=d.graph)}finally{o.close()}let m=performance.now()-n,f=Ou({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:u,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Sn(_u(e.projectRoot,"tsconfig.json")),...e.previousOverlayGeneration===void 0?{}:{previousOverlayGeneration:e.previousOverlayGeneration}});if(!f.eligible)throw new Error(f.reason);let y=bo(e.previousDbPath);if(!y)throw new Error("published TypeScript base generation unavailable");n=performance.now();let b=new ut({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:y},{requireService:!0}),k=f.projects.flatMap(T=>{let p=ju(T.affectedFiles,Cu);return(p.length>0?p:[[]]).map((A,z)=>({project:T,affectedFiles:A,removedFiles:z===0?T.removedFiles:[],firstForProject:z===0}))}),O=[],E=new Map,F=[],w=!1,h=0,S=0,g=0,_=f.previousFragmentGeneration;for(let[T,p]of k.entries()){let x=b.request({kind:"emit-documents",tsconfigPath:p.project.tsconfigPath,projectArgument:p.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:p.firstForProject?p.project.modifiedFiles:[],removedFiles:p.firstForProject?p.project.removedFiles:[],affectedFiles:p.affectedFiles});w||=x.cold,F.push(x.durationMs);let A=p.removedFiles.map(Me=>({relativePath:Me,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),z=[...x.fragments,...A];if(!f.replaceProject)for(let Me of z)E.set(Me.relativePath,Me.referenceFragments);let vt=performance.now(),Za=Wr(x.fragments);h+=performance.now()-vt;let $n=T===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${T}.scip`,es=performance.now();ko($n,Za),g+=performance.now()-es;let ts=performance.now(),Vn=T===k.length-1?f.nextFragmentGeneration:$u({previousGenerationIdentity:_,targetGenerationIdentity:f.nextFragmentGeneration,fragments:z});Hr({cacheDir:e.cacheDir,previousGenerationIdentity:_,nextGenerationIdentity:Vn,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:T===0?e.baseShardCurrent:!1,fragments:z,allowProjectIdentityChange:f.replaceProject&&T===0,allowLegacyProjectIdentityMigration:!0}),S+=performance.now()-ts,_=Vn,O.push({scipPath:$n,affectedFiles:[...p.affectedFiles,...p.removedFiles].sort(),deletedFiles:[...p.removedFiles].sort()})}let R=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:O,completeScipUpdated:!1,durationMs:C()-t,cold:w,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:u.length,dependencyGraphSnapshot:d,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:E,timings:{runtimeMs:i,graphMs:m,requestMs:R,serviceMs:F.reduce((T,p)=>T+p,0),assemblyMs:h,fragmentStoreMs:S,writeMs:g}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${O.length} bounded batch(es) across ${f.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 ${m.toFixed(0)}ms, request ${R.toFixed(0)}ms, assembly ${h.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${g.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Fe)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function ju(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Nu(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Be(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function $u(e){let t=bn("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(bn("sha256").update(n.bytes).digest()));return t.digest("hex")}function Rn(e){let t=fn();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fe(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ne}),packageVersion:t.packageVersion});ko(e.candidateShardPath,n)}function dt(e,t,n){let r=e.files.filter(i=>{let o=Le(i.path,e.languages);return o==="ambient"||o==="config"&&(!ye(i.path)||n.has(i.path))}).map(i=>{let a=Le(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${Ao(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function wo(e,t){return Ao(JSON.stringify({version:1,producerIdentity:t,snapshot:Un(e)}))}function Ao(e){return bn("sha256").update(e).digest("hex")}import{closeSync as Vu,existsSync as pt,fstatSync as Bu,lstatSync as Uu,openSync as Gu,renameSync as vn,rmSync as Oe,statSync as Wu,writeSync as qu}from"fs";import{cpus as Hu}from"os";import{join as In}from"path";var xn=Symbol("no-error");async function Mo(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=xn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===xn&&(s=d),c=!1}}});if(await Promise.all(u),s!==xn)throw s;return r}var Lo=8*1024;function jo(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Gu(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Oe(e,{force:!0}),o=i()}try{qu(o,r);let a=Bu(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{Vu(o)}}function zu(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=jo(In(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=jo(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())Vo(i);throw r}}function Vo(e){if(e)try{let t=Uu(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=fe(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Oe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Ju(e,t,n){if(!e.defaultOutputPath)return;let r=In(t,e.defaultOutputPath);n!==r&&pt(r)&&vn(r,n)}function Yu(e,t,n){if(!e.defaultOutputPath)return null;let r=In(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Oe(i,{force:!0}),pt(r)?(vn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Xu(e){e&&(Oe(e.defaultOutputPath,{force:!0}),e.backupPath&&pt(e.backupPath)&&vn(e.backupPath,e.defaultOutputPath))}function Ku(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,Hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bo(e,t,n,r,i){$(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await No(s,Ku(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await No(a,u,t,n,i))}for(let u of o)$(i,"Reindex cancelled by its owner."),c.push((await Pn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function No(e,t,n,r,i){let o=await Mo(e,Math.max(1,t),s=>Pn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),$(i,"Reindex cancelled by its owner."),a.set(c.id,(await Pn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function Pn(e,t,n,r){$(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Oe(e.scipPath,{force:!0});let i=Yu(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=C();try{o=zu(e,t),e.trustedProjectTool&&br(t,e.trustedProjectTool);let u=yr(e.binary,e.args),l=await qe({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Qu(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
292
292
  ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex cancelled by its owner.");let l=u instanceof Error?u.message:String(u),d=l.length<=Lo?l:`${l.slice(0,Lo)}
293
- [indexer failure detail truncated]`,m=`${e.resolvedBinary} indexer failed: ${d}`,f=e.label===e.language?m:`${e.label}: ${m}`;return n(`Skipping ${e.label}: ${m}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:Zu(u)}}finally{Xu(i);for(let u of o.reverse())Vo(u)}if(!pt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=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:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=Wu(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:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Qu(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Tr.indexer}function Zu(e){return e instanceof wr?e.kind==="spawn"&&$o(e.cause):$o(e)}function $o(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Go}from"child_process";import{homedir as Uo,platform as el}from"os";import{delimiter as tl,join as mt}from"path";function Tn(e,t){let n=e.installMethods,r=ke(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(!Dt(i.prerequisite))continue;let o=nl(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Go(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:el()==="win32"});let a=be(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 nl(e){if(e.binary==="npm")return En("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=En("go",["env","GOBIN"]);if(t)return t;let n=En("go",["env","GOPATH"]);if(n)return mt(n.split(tl)[0],"bin")}return e.binary==="dotnet"?mt(process.env.DOTNET_CLI_HOME??Uo(),".dotnet","tools"):e.binary==="dart"?mt(process.env.PUB_CACHE??mt(Uo(),".pub-cache"),"bin"):e.destination}function En(e,t){try{return Go(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import pa from"better-sqlite3";import{existsSync as ma}from"fs";import{dirname as fa,join as ga,resolve as ha}from"path";import{randomUUID as il}from"crypto";import{mkdtempSync as ol,rmSync as al,statSync as qo}from"fs";import{tmpdir as sl}from"os";import{join as Ho}from"path";import{Worker as cl}from"worker_threads";function rl(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Te(){return{skippedReferences:0,skippedReferenceReasons:rl(),skippedReferenceSamples:[]}}function ft(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 ul=3e5,zo=64*1024*1024,ll={createResultDirectory:()=>ol(Ho(sl(),"scip-query-vue-workers-")),spawn:(e,t)=>new cl(e,{workerData:t}),resultSize:e=>qo(e).size,readResult:e=>N(e,{maxBytes:zo,inputKind:"Vue worker result"}),removeResultDirectory:e=>al(e,{recursive:!0,force:!0})};function Jo(e){return e.length>=8&&Xo(e.length)>1}async function Yo(e,t=ll){let n=Xo(e.vueFiles.length),r=vl(e.vueFiles),i=El(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??xl(),s=e.maxResultBytes??Pl();Wo("timeoutMs",a),Wo("maxResultBytes",s);let c=il(),u=t.createResultDirectory(),l=[],d,m,f;try{for(let b=0;b<i.length;b++){let k=b,O=i[b]??[],E=O.map(h=>h.taskId),C=Ho(u,`${k}.json`),w=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:O,resultPath:C,runId:c,workerId:k,taskIds:E});l.push({workerId:k,taskIds:E,resultPath:C,handle:w,completion:dl(w,k)})}await pl(l,a);let y=l.sort((b,k)=>b.workerId-k.workerId).map(b=>fl(b,c,s,t));f={occurrences:y.flatMap(b=>b.occurrences),...Te()};for(let b of y)ft(f,b)}catch(y){d=y}finally{let y=await ml(l);if(y.length===0)try{t.removeResultDirectory(u)}catch(b){y.push(b)}if(y.length>0){let b=d===void 0?y:[d,...y];m=new AggregateError(b,`Vue worker cleanup failed: ${Rl(b[0])}`)}}if(m)throw m;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function dl(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 pl(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 ml(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function fl(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(!De(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(!bl(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||!gl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function gl(e){if(!De(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(hl)||!W(e.skippedReferences)||!De(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!W(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(yl)}function hl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&W(e.symbolId)}function yl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.token=="string"&&Sl(e.reason)}function Sl(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function W(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Wo(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Rl(e){return e instanceof Error?e.message:String(e)}function Xo(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 xl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:ul}function Pl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:zo}function vl(e){let t=Il(),n=[];for(let r of e){let i=Ko(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 Il(){return Number.POSITIVE_INFINITY}function El(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Tl(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 Tl(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ko(e.fileName)-e.startOffset)}function Ko(e){try{return qo(e).size}catch{return 1}}import{createRequire as wl}from"module";import{existsSync as kl}from"fs";import{dirname as Qo,extname as _l,join as Zo,relative as Fl,resolve as Cl}from"path";import{pathToFileURL as Ol}from"url";function Dl(e){e.transaction(()=>{e.prepare(`
293
+ [indexer failure detail truncated]`,m=`${e.resolvedBinary} indexer failed: ${d}`,f=e.label===e.language?m:`${e.label}: ${m}`;return n(`Skipping ${e.label}: ${m}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:Zu(u)}}finally{Xu(i);for(let u of o.reverse())Vo(u)}if(!pt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=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:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=Wu(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:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Qu(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Tr.indexer}function Zu(e){return e instanceof wr?e.kind==="spawn"&&$o(e.cause):$o(e)}function $o(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Go}from"child_process";import{homedir as Uo,platform as el}from"os";import{delimiter as tl,join as mt}from"path";function Tn(e,t){let n=e.installMethods,r=ke(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(!Dt(i.prerequisite))continue;let o=nl(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Go(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:el()==="win32"});let a=be(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 nl(e){if(e.binary==="npm")return En("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=En("go",["env","GOBIN"]);if(t)return t;let n=En("go",["env","GOPATH"]);if(n)return mt(n.split(tl)[0],"bin")}return e.binary==="dotnet"?mt(process.env.DOTNET_CLI_HOME??Uo(),".dotnet","tools"):e.binary==="dart"?mt(process.env.PUB_CACHE??mt(Uo(),".pub-cache"),"bin"):e.destination}function En(e,t){try{return Go(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import pa from"better-sqlite3";import{existsSync as ma}from"fs";import{dirname as fa,join as ga,resolve as ha}from"path";import{randomUUID as il}from"crypto";import{mkdtempSync as ol,rmSync as al,statSync as qo}from"fs";import{tmpdir as sl}from"os";import{join as Ho}from"path";import{Worker as cl}from"worker_threads";function rl(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Te(){return{skippedReferences:0,skippedReferenceReasons:rl(),skippedReferenceSamples:[]}}function ft(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 ul=3e5,zo=64*1024*1024,ll={createResultDirectory:()=>ol(Ho(sl(),"scip-query-vue-workers-")),spawn:(e,t)=>new cl(e,{workerData:t}),resultSize:e=>qo(e).size,readResult:e=>N(e,{maxBytes:zo,inputKind:"Vue worker result"}),removeResultDirectory:e=>al(e,{recursive:!0,force:!0})};function Jo(e){return e.length>=8&&Xo(e.length)>1}async function Yo(e,t=ll){let n=Xo(e.vueFiles.length),r=vl(e.vueFiles),i=El(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??xl(),s=e.maxResultBytes??Pl();Wo("timeoutMs",a),Wo("maxResultBytes",s);let c=il(),u=t.createResultDirectory(),l=[],d,m,f;try{for(let b=0;b<i.length;b++){let k=b,O=i[b]??[],E=O.map(h=>h.taskId),F=Ho(u,`${k}.json`),w=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:O,resultPath:F,runId:c,workerId:k,taskIds:E});l.push({workerId:k,taskIds:E,resultPath:F,handle:w,completion:dl(w,k)})}await pl(l,a);let y=l.sort((b,k)=>b.workerId-k.workerId).map(b=>fl(b,c,s,t));f={occurrences:y.flatMap(b=>b.occurrences),...Te()};for(let b of y)ft(f,b)}catch(y){d=y}finally{let y=await ml(l);if(y.length===0)try{t.removeResultDirectory(u)}catch(b){y.push(b)}if(y.length>0){let b=d===void 0?y:[d,...y];m=new AggregateError(b,`Vue worker cleanup failed: ${Rl(b[0])}`)}}if(m)throw m;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function dl(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 pl(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 ml(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function fl(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(!De(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(!bl(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||!gl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function gl(e){if(!De(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(hl)||!q(e.skippedReferences)||!De(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!q(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(yl)}function hl(e){return De(e)&&typeof e.sourceFile=="string"&&q(e.sourceLine)&&q(e.sourceStartChar)&&q(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&q(e.symbolId)}function yl(e){return De(e)&&typeof e.sourceFile=="string"&&q(e.sourceLine)&&q(e.sourceStartChar)&&q(e.sourceEndChar)&&typeof e.token=="string"&&Sl(e.reason)}function Sl(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function q(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Wo(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Rl(e){return e instanceof Error?e.message:String(e)}function Xo(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 xl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:ul}function Pl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:zo}function vl(e){let t=Il(),n=[];for(let r of e){let i=Ko(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 Il(){return Number.POSITIVE_INFINITY}function El(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Tl(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 Tl(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ko(e.fileName)-e.startOffset)}function Ko(e){try{return qo(e).size}catch{return 1}}import{createRequire as wl}from"module";import{existsSync as kl}from"fs";import{dirname as Qo,extname as _l,join as Zo,relative as Cl,resolve as Fl}from"path";import{pathToFileURL as Ol}from"url";function Dl(e){e.transaction(()=>{e.prepare(`
294
294
  DELETE FROM mentions
295
295
  WHERE chunk_id IN (
296
296
  SELECT c.id
@@ -310,7 +310,7 @@ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex
310
310
  FROM documents
311
311
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
312
312
  ORDER BY relative_path
313
- `).all().map(r=>Cl(t,r.relativePath))}function ea(e,t){let{vueCore:n,ts:r,volarTs:i}=Al(e),{parsed:o,vueOptions:a}=Ml(n,r,t),s=Qo(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Ll(n,r,c),l=jl(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),m=r.createLanguageService(d);return{ts:r,language:u,languageService:m,fileNames:o.fileNames,configDir:s}}function Al(e){let t=wl(Ol(Zo(e,"package.json")).href);return{vueCore:wn(t,"@vue/language-core",e),ts:wn(t,"typescript",e),volarTs:wn(t,"@volar/typescript",e)}}function Ml(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,Qo(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ll(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!kl(o))return;let a=N(o,{maxBytes:wt,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Gl(o))});return r.current=i,i}function jl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function wn(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 ta(e,t,n){let r=Nl(e);return i=>{if(!i.name)return null;let o=q(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(d=>d.line===s.line&&d.displayName===i.name);if(u)return u.symbolId;let l=c.containingByLine.get(s.line);return l&&l.displayName===i.name?l.symbolId:$l(c.starts,s.line,2,i.name)}}function Nl(e){let t=e.prepare(`
313
+ `).all().map(r=>Fl(t,r.relativePath))}function ea(e,t){let{vueCore:n,ts:r,volarTs:i}=Al(e),{parsed:o,vueOptions:a}=Ml(n,r,t),s=Qo(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Ll(n,r,c),l=jl(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),m=r.createLanguageService(d);return{ts:r,language:u,languageService:m,fileNames:o.fileNames,configDir:s}}function Al(e){let t=wl(Ol(Zo(e,"package.json")).href);return{vueCore:wn(t,"@vue/language-core",e),ts:wn(t,"typescript",e),volarTs:wn(t,"@volar/typescript",e)}}function Ml(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,Qo(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ll(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!kl(o))return;let a=N(o,{maxBytes:wt,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Gl(o))});return r.current=i,i}function jl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function wn(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 ta(e,t,n){let r=Nl(e);return i=>{if(!i.name)return null;let o=H(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(d=>d.line===s.line&&d.displayName===i.name);if(u)return u.symbolId;let l=c.containingByLine.get(s.line);return l&&l.displayName===i.name?l.symbolId:$l(c.starts,s.line,2,i.name)}}function Nl(e){let t=e.prepare(`
314
314
  SELECT
315
315
  d.relative_path AS relativePath,
316
316
  der.start_line AS startLine,
@@ -324,19 +324,19 @@ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex
324
324
  `).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 $l(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 _n(e,t,n){let r=Hl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
325
325
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
326
326
  VALUES (?, ?, ?, ?)
327
- `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=q(t,u),d=la(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let m=zl(i,r,t,u);m&&(a++,s.set(u,m))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function na(e,t,n,r,i){return e.transaction(()=>(Dl(e),Vl(e,t,n,r),Bl(e,i)))()}function Vl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
327
+ `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=H(t,u),d=la(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let m=zl(i,r,t,u);m&&(a++,s.set(u,m))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function na(e,t,n,r,i){return e.transaction(()=>(Dl(e),Vl(e,t,n,r),Bl(e,i)))()}function Vl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
328
328
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
329
329
  VALUES (?, ?, ?, ?, X'00')
330
330
  `),a=e.prepare(`
331
331
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
332
332
  VALUES (?, ?, 1)
333
- `);for(let s of n){let c=r.get(s);if(!c)continue;let u=q(t,s),l=i.get(u);if(!l)continue;let d=o.run(l.id,-1,0,0);a.run(Number(d.lastInsertRowid),c)}}function ra(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(Fn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ia(e){let t=new Set,n=[];for(let r of e){let i=oa(r);t.has(i)||(t.add(i),n.push(r))}return n}function oa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Bl(e,t){let n=ql(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
333
+ `);for(let s of n){let c=r.get(s);if(!c)continue;let u=H(t,s),l=i.get(u);if(!l)continue;let d=o.run(l.id,-1,0,0);a.run(Number(d.lastInsertRowid),c)}}function ra(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(Cn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ia(e){let t=new Set,n=[];for(let r of e){let i=oa(r);t.has(i)||(t.add(i),n.push(r))}return n}function oa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Bl(e,t){let n=ql(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
334
334
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
335
335
  VALUES (?, ?, ?, ?, X'00')
336
336
  `),i=e.prepare(`
337
337
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
338
338
  VALUES (?, ?, 0)
339
- `),o=new Set,a=0,s=0;for(let c of t){let u=oa(c);if(o.has(u))continue;o.add(u);let l=n.get(c.sourceFile);if(!l)continue;let d=r.run(l,s++,c.sourceLine,c.sourceLine),m=i.run(Number(d.lastInsertRowid),c.symbolId);a+=Number(m.changes)}return a}function*aa(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 sa(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Fn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ul(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 ca(e,t){return q(e,t).startsWith("node_modules/")}function q(e,t){return Fl(e,t).replaceAll("\\","/")}function Gl(e){switch(_l(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 ua(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=N(t,{maxBytes:wt,inputKind:"Vue source file"}),r={text:n,lineStarts:Wl(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ul}}function Wl(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ql(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 Hl(e){try{let t=JSON.parse(N(Zo(e,"package.json"),{maxBytes:me,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function zl(e,t,n,r){let i=q(n,r),o=la(t.name,t.version,i);return e.get(o)?.id??null}function la(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ya(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Kl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Yl(e){return G(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),G(ya({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Xl(e){return G(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Ql(e)}function Kl(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return Ci({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>Zl({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 Ql(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return await Oi({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>ed({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 Zl(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=ba(e,t);return Sa(e,t,n)}async function ed(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=Jo(e.vueFiles)?await Yo({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):ba(e,t);return Sa(e,t,n)}function Sa(e,t,n){let r=ia(n.occurrences),i=na(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:ud(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:cd(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function ba(e,t){let n=td({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return nd({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ra(e,t,n){let r=e.prepare(`
339
+ `),o=new Set,a=0,s=0;for(let c of t){let u=oa(c);if(o.has(u))continue;o.add(u);let l=n.get(c.sourceFile);if(!l)continue;let d=r.run(l,s++,c.sourceLine,c.sourceLine),m=i.run(Number(d.lastInsertRowid),c.symbolId);a+=Number(m.changes)}return a}function*aa(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 sa(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Cn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ul(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 ca(e,t){return H(e,t).startsWith("node_modules/")}function H(e,t){return Cl(e,t).replaceAll("\\","/")}function Gl(e){switch(_l(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 ua(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=N(t,{maxBytes:wt,inputKind:"Vue source file"}),r={text:n,lineStarts:Wl(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ul}}function Wl(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ql(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 Hl(e){try{let t=JSON.parse(N(Zo(e,"package.json"),{maxBytes:me,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function zl(e,t,n,r){let i=H(n,r),o=la(t.name,t.version,i);return e.get(o)?.id??null}function la(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ya(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Kl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Yl(e){return W(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),W(ya({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Xl(e){return W(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Ql(e)}function Kl(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return Fi({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>Zl({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 Ql(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return await Oi({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>ed({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 Zl(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=ba(e,t);return Sa(e,t,n)}async function ed(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=Jo(e.vueFiles)?await Yo({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):ba(e,t);return Sa(e,t,n)}function Sa(e,t,n){let r=ia(n.occurrences),i=na(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:ud(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:cd(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function ba(e,t){let n=td({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return nd({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ra(e,t,n){let r=e.prepare(`
340
340
  SELECT
341
341
  (SELECT COUNT(*) FROM documents) AS documents,
342
342
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -345,13 +345,13 @@ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex
345
345
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
346
346
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
347
347
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
348
- `).get();return{version:3,tsconfig:n,files:rr(t),db:r}}function td(e){let t=ua();return{projectRoot:e.projectRoot,context:ea(e.projectRoot,e.configPath),symbolLookup:ta(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function nd(e){let t=[],n=Te(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=rd(e,i);t.push(...o.occurrences),ft(n,o)}return{occurrences:t,...n}}function rd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return da(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 da(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=q(e.projectRoot,t.fileName),s=[...aa(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:dd(s),processedStarts:new Set};return id({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function id(e){let t=[],n=Te();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||od(e.sourceInfo.text,r.start))continue;let i=sa(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!ca(e.projectRoot,l.fileName));if(!a){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=q(e.projectRoot,a.fileName),c=ad(e.sourceFile,r.text,s);if(c){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ra(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}xa(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),ld(t,e,r,i,s,u)}return{occurrences:t,...n}}function od(e,t){let n=e.lastIndexOf(`
349
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ad(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function da(e,t,n){let r=Te();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:q(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Cn(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 On(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 sd(e,t){let n=On(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=On(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function cd(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(...On(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ud(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return sd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function ld(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of pd(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&&(xa(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function xa(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 dd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pd(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 l=md(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function md(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Fn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function ph(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??ri(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=bd(e),a=Date.now(),s=F();yt(v(o.outputScip),{recursive:!0}),yt(v(o.outputDb),{recursive:!0});let c=e.languages??Ut(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let u=bt(o.metaPath),l=I("reindex.fingerprint",()=>ar(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,_t(o.outputDb)),{languages:c.length}),d=l.fingerprint,m=l.mode==="delta"?e.changeJournal?.entries.filter(S=>S.kind!=="add").length??0:0,f=Math.max(0,(u?.files.length??0)-m);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${d.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let y=await yd({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),b=y.snapshot,k=y.releaseBuildLock,O=Ja(e.trigger),E=Xn(D(v(o.outputDb),"cache-lifecycle.lock"),{waitMs:O?1e3:3e4});if(!E)throw k?.(),new ze(O?`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let C;try{C=await B("reindex.lock",()=>Xd(D(v(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(S){throw E.release(),k?.(),S}let w=null,h=ai();try{l.mode==="delta"&&_t(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=ir(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},b=void 0,k?.(),k=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Xr(o.outputDb,o.outputScip,o.metaPath);let S=vd(v(o.outputDb));S.removed>0&&n(`Removed ${S.removed} abandoned reindex workspace(s)`);for(let x of S.errors)n(`Could not remove abandoned reindex workspace: ${x}`);let g=null,_=await B("reindex.reuse-check",async()=>(g=await Rd({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),g),()=>({languages:c.length,reused:g!==null}));if(_){Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let x=Wt(o.outputDb,_);return x.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${x.reason}`),Ct(t,v(o.outputDb)),_}kr()&&await B("reindex.scip-cli-ready",()=>Vd(i,n));let R=Pd(o);w=R.runDir;let P,T=await B("reindex.fresh",async()=>(P=await Id({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:h}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let p=Wt(o.outputDb,T);return p.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${p.reason}`),Ct(t,v(o.outputDb)),T}catch(S){let g=Pt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:S instanceof Error?S.message:String(S)});Qa(o.metaPath,g);let _=Gr(o.outputDb,g);throw _.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${_.reason}`),S}finally{w&&se(w,{recursive:!0,force:!0}),C(),E.release(),k?.()}}async function yd(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Kr(a,n.outputDb)&&Pa(n.outputScip)===Pa(D(v(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Ve(a),u=c?.clean?Ke(c,i):void 0;if(c&&!c.clean&&!Ta(n))return Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=qt(u);if(l){if(!Sd(n,i))try{Qe({snapshot:u,manifest:l,targetCacheDir:v(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(m){o(`Shared generation attach failed; continuing locally: ${ce(m)}`)}return{snapshot:u,releaseBuildLock:void 0}}c&&!Ta(n)&&Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let d=await ei(u);if(d.kind==="owner")return{snapshot:u,releaseBuildLock:d.release};if(d.kind==="generation-ready"){let m=qt(u);if(m)try{Qe({snapshot:u,manifest:m,targetCacheDir:v(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${ce(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:u,releaseBuildLock:void 0}}function Ia(e){let t=Qr(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Qe({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:v(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ni(t.snapshot,v(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ce(n)}`)}}function Ea(e){if(e.snapshot)try{let t=Ve(e.projectRoot),n=t?Ke(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=Zr({snapshot:e.snapshot,sourceCacheDir:v(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ve(e.projectRoot);return(i?Ke(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});ti(e.snapshot,v(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ce(t)}`)}}function Sd(e,t){if(!j(e.outputScip)||!j(e.outputDb)||Ka(e.metaPath,t)===null)return!1;let n=Y(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ta(e){if(!j(e.outputScip)||!j(e.outputDb)||!de(e.metaPath))return!1;let t=Y(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ce(e){return e instanceof Error?e.message:String(e)}async function Mn(e,t,n,r,i,o,a,s=!1){try{await Fi(ci({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function bd(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(v(n),"meta.json")}}async function Rd(e){let t=Y(e.paths.outputDb,e.paths.metaPath),n=Ka(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=Ye(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Ln("Accepted SQLite index",r)),null;G(X(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),Y(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ip(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=F()-e.monotonicStart,o=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Qa(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:xd(e.paths,e.languages,e.opts,e.fingerprint)}}function xd(e,t,n,r){let i=jn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(i[o]),outputBytes:ue(Nn(e.outputDb,o)),durationMs:0}))}function Pd(e){let t=gd(D(v(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,gt(e.outputScip)),tempOutputDb:D(t,gt(e.outputDb)),tempMetaPath:D(t,gt(e.metaPath))}}function vd(e){let t=[],n;try{n=Aa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{se(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ce(o)}`)}return{removed:r,errors:t}}async function Id(e){let t={...process.env,NODE_OPTIONS:ii(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await B("reindex.language-indexers",async()=>(n=await Td(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:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ed({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await B("reindex.publish",()=>Ld(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),y=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(y/1e3).toFixed(1)}s`),{languages:i.map(b=>b.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:y,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await B("reindex.publish",()=>Ad(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),m=d.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Ed(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=Y(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 Td(e,t){let n=e.opts.skipIfUnchanged===!1,r=Cd({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});if(n)for(let[p,x]of r)x.reused&&r.set(p,{...x,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[p,x]of r)x.reused&&(i.push({language:p,scipPath:x.scipPath}),o.add(p));for(let p of o)e.onStatus(`Reusing cached ${p} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=Y(e.paths.outputDb,e.paths.metaPath),c=de(e.paths.metaPath),u=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d;n&&a&&!a.reused&&(d="forced reindex rebuilds from the compilers");let m=!n&&a&&!a.reused&&u?Do({projectRoot:e.projectRoot,cacheDir:v(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:bt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:p=>{d=p}}):null,f=new Set(m?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let p=e.languages.filter(x=>!o.has(x)&&!f.has(x));if(p.length>0){let x=p.length===1&&p[0]==="typescript"&&d?`: ${d}`:"";throw new Error(`Incremental indexing is unavailable for ${p.join(", ")}${x}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let y=m||o.has("typescript")?void 0:wd(e,r),b=y&&n?{...y,classification:new Map([...y.classification].map(([p,x])=>[p,x.reused?{...x,reused:!1,reason:"forced reindex requested"}:x])),reusedProjects:[],missedProjectIds:new Set(y.allProjects.map(p=>`typescript:${p}`))}:y,{preparedRuns:k,skippedLanguages:O,languageOutputScipPaths:E}=Bd({languages:e.languages.filter(p=>!o.has(p)&&!f.has(p)),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:b?.allProjects,typescriptShardCostDir:v(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),C=b?k.filter(p=>p.language!=="typescript"||b.missedProjectIds.has(p.id)):k,w=await Bo(C,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(ur())for(let p of w)lr({type:"span",name:`reindex.language-indexer.${p.id}`,durationMs:Math.round(p.durationMs),ok:!p.skipped,language:p.language,indexerCommand:p.command,outputBytes:p.outputBytes,measurement:"indexer-run-result"});Gd(v(e.paths.outputDb),e.projectRoot,C,w);let h=[];if(b){_d(e.paths.outputDb,w,e.writeTelemetry);let p=E.typescript??e.tempPaths.tempOutputScip;h=Fd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:p,reusedProjects:b.reusedProjects,writeTelemetry:e.writeTelemetry})}let S=[...w,...h],{indexedOutputs:g}=qd(S,O),_=m?[{language:"typescript",scipPath:m.scipPath}]:[],R=[...i,..._,...g];Hd(R,O,e.languages,e.opts.allowPartial,e.onStatus);let P=m?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:m.scipPath,outputScipPath:m.scipPath,durationMs:m.durationMs,command:"watch-service:typescript-index",outputBytes:ue(m.scipPath)??void 0,producedOutputBytes:ue(m.affectedScipPath)??void 0}]:[],T=Od(r,[...w,...P],b?{outputDb:e.paths.outputDb,classification:b.classification}:void 0,d);return{indexedOutputs:R,skippedLanguages:O,reusedLanguages:[...o],languageFingerprints:Dd(r,e.languages),shards:T,typescriptProjectShardContext:b?{projects:b.allProjects,fingerprints:b.fingerprints}:void 0,incrementalTypeScript:m??void 0}}function wd(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=$i(e.projectRoot,r),o=Li(n.fingerprint.files,r),a=ji(r,i),s=Ni(r,o,a),c=de(e.paths.metaPath),l=kd(c,s,y=>j(Rt(e.paths.outputDb,y))),d=[...l.entries()].filter(([,y])=>y.reused).map(([y])=>y),m=new Set(d),f=new Set(r.filter(y=>!m.has(y)).map(y=>`typescript:${y}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function kd(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===pe&&Tt(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(L(a)!==L(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 _d(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Rt(e,i);yt(v(o),{recursive:!0}),ae(n,oe(r.scipPath,o,void 0,{shareImmutable:!0}))}}function Fd(e){return e.reusedProjects.map((t,n)=>{let r=Rt(e.outputDb,t),i=le(e.tempOutputScip,"typescript-project-cached",n);return ae(e.writeTelemetry,oe(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ue(i)??void 0}})}function Cd(e){let t=de(e.paths.metaPath),n=jn(e.projectFingerprint,e.languages,e),r=t&&j(e.paths.outputDb)?Ye(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Nn(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!==pe){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Tt(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(!j(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let u=o==="typescript"?tp(e.projectRoot,c):c;if(L(u)!==L(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:Ln("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function Od(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:Ae(a.fingerprint),outputBytes:ue(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?Ae(c.fingerprint):a?Ae(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:Ae(a.fingerprint),outputBytes:ue(Rt(n.outputDb,o)),durationMs:0});return i}function Ae(e){return fd("sha256").update(L(e)).digest("hex").slice(0,16)}function ue(e){try{return An(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Ad(e,t,n,r,i,o,a,s){$(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=I("reindex.publish.scip-output",()=>{let h=$d({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return wa(e.paths.outputDb,h,e.writeTelemetry),ka(h,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await B("reindex.publish.sqlite-output",()=>zd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if($(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..."),Rn({cacheDir:v(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(S=>S.language==="typescript"?{language:S.language,scipPath:s.candidateScipPath}:S);return wa(e.paths.outputDb,h,e.writeTelemetry),u=ka(h,e.tempPaths.tempOutputScip,e.onStatus),u}}));$(e.opts.signal,"Reindex cancelled by its owner."),I("reindex.publish.auxiliary-documents",()=>{G(X(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await B("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project",S=s?.dependencyGraphUnchanged===!0;h?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):S&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Mn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,S,S?void 0:h?s?.changedFiles:s?.affectedFiles,D(v(e.paths.outputDb),sr),h)});let d=I("reindex.publish.sqlite-layout",()=>Zt(e.tempPaths.tempOutputDb,{analyze:Md(s,l.mode)}));d.added.length>0&&e.onStatus(`Added SQLite query indexes: ${d.added.join(", ")}`),d.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${d.removed.join(", ")}`),I("reindex.publish.coverage",()=>Va(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let m,f=null;l.mode==="incremental"&&s&&I("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let g=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=Ot(g),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{g.close()}return}let h=null,S=null;try{h=I("reindex.publish.reference-fragments.open-candidate",()=>new V({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),S=I("reindex.publish.reference-fragments.open-evidence",()=>new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),m=s.dependencyGraphSnapshot?I("reindex.publish.reference-fragments.dependency-graph",()=>gr(h,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let g=new Set(s.deletedFiles),_=g.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!g.has(P))),R=I("reindex.publish.reference-fragments.seed",()=>Ir(h,e.fingerprint,_,S,m,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${R.affectedFiles} affected document(s) and carried ${R.carriedFiles} unaffected document(s) forward.`),R.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${R.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(g){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${g instanceof Error?g.message:String(g)}.`)}finally{h?.close(),S?.close()}});let y=bt(e.paths.metaPath);l.mode==="incremental"&&s||await La({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let b=I("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?Yd(s,l.changedDocumentPaths):Jt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),k=Pt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]}),O=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:E,pruneProjects:C}=Na({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:k});E.scipCompanion=O?"deferred":"current",I("reindex.publish.metadata",()=>{$a(e),Ba(e.paths.outputDb,C),xt(e.tempPaths.tempMetaPath,E)});let w=I("reindex.publish.generation-handoff",()=>Yr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return w.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${w.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&I("reindex.publish.dependency-graph",()=>{let h=null;try{h=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let S=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,g=!1;if(s.dependencyGraphUnchanged){let _=Ot(h),R=f&&_?cr(h,"file-dependency-graph",f,_):0;g=R>0,e.onStatus(g?`Carried ${R} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?g=fr(h,s.dependencyGraphSnapshot,S,m):Ge(h);s.dependencyGraphUnchanged||e.onStatus(g?`Carried the dependency graph forward by replacing ${S.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(S){e.onStatus(`Dependency graph carry-forward unavailable: ${S instanceof Error?S.message:String(S)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),I("reindex.publish.cleanup",()=>{Jr(v(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),qr(v(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),I("reindex.publish.shadow-telemetry",()=>ja(e.paths.outputDb,b,e.onStatus)),k}function Md(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Ld(e,t,n,r,i,o){let a=bt(e.paths.metaPath),s=null;try{ae(e.writeTelemetry,oe(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(m){s=pi("reused","oracle-error",`Could not snapshot the prior database: ${m instanceof Error?m.message:String(m)}`)}G(X(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Zt(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(", ")}`),Va(e,e.paths.outputDb,t.map(m=>m.language)),s==null&&await La({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Jt({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=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(m=>m.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Na({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return $a(e),Ba(e.paths.outputDb,d),xt(e.paths.metaPath,l),Xe(e.paths.outputDb,e.paths.metaPath),ja(e.paths.outputDb,s,e.onStatus),u}async function La(e){if(!j(e.previousDbPath))return;let t=z(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||_e(t).fullProject)return;let n=null;try{if(n=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),We(n))return;let r=await B("reindex.publish.affected-shadow.warm-sources",()=>hr(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function bt(e){return Et(de(e)?.fingerprint)}function ja(e,t,n){try{mi(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 Na(e){let t=jd({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:pe,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 $a(e){$(e.opts.signal,"Reindex cancelled by its owner.");let t=or(e.projectRoot,e.fingerprint);if(L(t)===L(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>L(n.get(o))!==L(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Va(e,t,n){let r=Ye(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Ln("Candidate SQLite index",r)} Refusing to publish it.`)}function Ln(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 jd(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=de(e.metaPath),n=t?.version===pe?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 Ba(e,t){let n=Xa(e);if(t===null){se(n,{recursive:!0,force:!0});return}let r;try{r=Aa(n)}catch{return}for(let i of Nd(r,t))se(D(n,i),{force:!0})}function Nd(e,t){let n=new Set(t.map(r=>`${rn(r)}.scip`));return e.filter(r=>!n.has(r))}function $d(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=Y(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":de(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..."),Rn({cacheDir:v(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function wa(e,t,n){for(let r of t){let i=Nn(e,r.language);yt(v(i),{recursive:!0}),r.scipPath!==i&&ae(n,oe(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Vd(e,t){let n=Fr();if(n){if(n.source==="path"&&va()!=="win32"){let r=Or();Cr(r)||(e?t(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${He} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`):(t(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${He}.`),await Dr(t)))}return}if(va()==="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.
348
+ `).get();return{version:3,tsconfig:n,files:rr(t),db:r}}function td(e){let t=ua();return{projectRoot:e.projectRoot,context:ea(e.projectRoot,e.configPath),symbolLookup:ta(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function nd(e){let t=[],n=Te(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=rd(e,i);t.push(...o.occurrences),ft(n,o)}return{occurrences:t,...n}}function rd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return da(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 da(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=H(e.projectRoot,t.fileName),s=[...aa(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:dd(s),processedStarts:new Set};return id({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function id(e){let t=[],n=Te();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||od(e.sourceInfo.text,r.start))continue;let i=sa(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!ca(e.projectRoot,l.fileName));if(!a){Fn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=H(e.projectRoot,a.fileName),c=ad(e.sourceFile,r.text,s);if(c){Fn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ra(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){Fn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}xa(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),ld(t,e,r,i,s,u)}return{occurrences:t,...n}}function od(e,t){let n=e.lastIndexOf(`
349
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ad(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function da(e,t,n){let r=Te();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:H(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Fn(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 On(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 sd(e,t){let n=On(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=On(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function cd(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(...On(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ud(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return sd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function ld(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of pd(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&&(xa(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function xa(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 dd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pd(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 l=md(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function md(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Cn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function mh(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??ri(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=bd(e),a=Date.now(),s=C();yt(v(o.outputScip),{recursive:!0}),yt(v(o.outputDb),{recursive:!0});let c=e.languages??Ut(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let u=bt(o.metaPath),l=I("reindex.fingerprint",()=>ar(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,_t(o.outputDb)),{languages:c.length}),d=l.fingerprint,m=l.mode==="delta"?e.changeJournal?.entries.filter(S=>S.kind!=="add").length??0:0,f=Math.max(0,(u?.files.length??0)-m);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${d.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let y=await yd({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),b=y.snapshot,k=y.releaseBuildLock,O=Ja(e.trigger),E=Xn(D(v(o.outputDb),"cache-lifecycle.lock"),{waitMs:O?1e3:3e4});if(!E)throw k?.(),new ze(O?`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let F;try{F=await B("reindex.lock",()=>Kd(D(v(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(S){throw E.release(),k?.(),S}let w=null,h=ai();try{l.mode==="delta"&&_t(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=ir(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},b=void 0,k?.(),k=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Xr(o.outputDb,o.outputScip,o.metaPath);let S=vd(v(o.outputDb));S.removed>0&&n(`Removed ${S.removed} abandoned reindex workspace(s)`);for(let x of S.errors)n(`Could not remove abandoned reindex workspace: ${x}`);let g=null,_=await B("reindex.reuse-check",async()=>(g=await Rd({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),g),()=>({languages:c.length,reused:g!==null}));if(_){Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let x=Wt(o.outputDb,_);return x.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${x.reason}`),Ft(t,v(o.outputDb)),_}kr()&&await B("reindex.scip-cli-ready",()=>Bd(i,n));let R=Pd(o);w=R.runDir;let P,T=await B("reindex.fresh",async()=>(P=await Id({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:h}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let p=Wt(o.outputDb,T);return p.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${p.reason}`),Ft(t,v(o.outputDb)),T}catch(S){let g=Pt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:S instanceof Error?S.message:String(S)});Qa(o.metaPath,g);let _=Gr(o.outputDb,g);throw _.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${_.reason}`),S}finally{w&&ce(w,{recursive:!0,force:!0}),F(),E.release(),k?.()}}async function yd(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Kr(a,n.outputDb)&&Pa(n.outputScip)===Pa(D(v(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Ve(a),u=c?.clean?Ke(c,i):void 0;if(c&&!c.clean&&!Ta(n))return Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=qt(u);if(l){if(!Sd(n,i))try{Qe({snapshot:u,manifest:l,targetCacheDir:v(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(m){o(`Shared generation attach failed; continuing locally: ${ue(m)}`)}return{snapshot:u,releaseBuildLock:void 0}}c&&!Ta(n)&&Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let d=await ei(u);if(d.kind==="owner")return{snapshot:u,releaseBuildLock:d.release};if(d.kind==="generation-ready"){let m=qt(u);if(m)try{Qe({snapshot:u,manifest:m,targetCacheDir:v(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${ue(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:u,releaseBuildLock:void 0}}function Ia(e){let t=Qr(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Qe({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:v(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ni(t.snapshot,v(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ue(n)}`)}}function Ea(e){if(e.snapshot)try{let t=Ve(e.projectRoot),n=t?Ke(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=Zr({snapshot:e.snapshot,sourceCacheDir:v(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ve(e.projectRoot);return(i?Ke(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});ti(e.snapshot,v(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ue(t)}`)}}function Sd(e,t){if(!j(e.outputScip)||!j(e.outputDb)||Ka(e.metaPath,t)===null)return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ta(e){if(!j(e.outputScip)||!j(e.outputDb)||!te(e.metaPath))return!1;let t=G(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ue(e){return e instanceof Error?e.message:String(e)}async function Mn(e,t,n,r,i,o,a,s=!1){try{await Ci(ci({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function bd(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(v(n),"meta.json")}}async function Rd(e){let t=G(e.paths.outputDb,e.paths.metaPath),n=Ka(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=Ye(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Ln("Accepted SQLite index",r)),null;W(X(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),G(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(op(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=C()-e.monotonicStart,o=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Qa(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:xd(e.paths,e.languages,e.opts,e.fingerprint)}}function xd(e,t,n,r){let i=jn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(i[o]),outputBytes:le(Nn(e.outputDb,o)),durationMs:0}))}function Pd(e){let t=gd(D(v(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,gt(e.outputScip)),tempOutputDb:D(t,gt(e.outputDb)),tempMetaPath:D(t,gt(e.metaPath))}}function vd(e){let t=[],n;try{n=Aa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ue(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{ce(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ue(o)}`)}return{removed:r,errors:t}}async function Id(e){let t={...process.env,NODE_OPTIONS:ii(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await B("reindex.language-indexers",async()=>(n=await Td(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:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ed({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await B("reindex.publish",()=>Ld(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),y=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(y/1e3).toFixed(1)}s`),{languages:i.map(b=>b.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:y,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await B("reindex.publish",()=>Ad(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),m=d.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Ed(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=G(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 Td(e,t){let n=e.opts.skipIfUnchanged===!1,r=Fd({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});if(n)for(let[p,x]of r)x.reused&&r.set(p,{...x,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[p,x]of r)x.reused&&(i.push({language:p,scipPath:x.scipPath}),o.add(p));for(let p of o)e.onStatus(`Reusing cached ${p} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=G(e.paths.outputDb,e.paths.metaPath),c=te(e.paths.metaPath),u=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d;n&&a&&!a.reused&&(d="forced reindex rebuilds from the compilers");let m=!n&&a&&!a.reused&&u?Do({projectRoot:e.projectRoot,cacheDir:v(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:de(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:de(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:bt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,...s.state==="current"&&s.generation.publication?.scipCompanion==="deferred"&&s.generation.publication.typescriptOverlayGeneration?{previousOverlayGeneration:s.generation.publication.typescriptOverlayGeneration}:{},onStatus:e.onStatus,onUnavailable:p=>{d=p}}):null,f=new Set(m?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let p=e.languages.filter(x=>!o.has(x)&&!f.has(x));if(p.length>0){let x=p.length===1&&p[0]==="typescript"&&d?`: ${d}`:"";throw new Error(`Incremental indexing is unavailable for ${p.join(", ")}${x}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let y=m||o.has("typescript")?void 0:wd(e,r),b=y&&n?{...y,classification:new Map([...y.classification].map(([p,x])=>[p,x.reused?{...x,reused:!1,reason:"forced reindex requested"}:x])),reusedProjects:[],missedProjectIds:new Set(y.allProjects.map(p=>`typescript:${p}`))}:y,{preparedRuns:k,skippedLanguages:O,languageOutputScipPaths:E}=Ud({languages:e.languages.filter(p=>!o.has(p)&&!f.has(p)),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:b?.allProjects,typescriptShardCostDir:v(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),F=b?k.filter(p=>p.language!=="typescript"||b.missedProjectIds.has(p.id)):k,w=await Bo(F,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(ur())for(let p of w)lr({type:"span",name:`reindex.language-indexer.${p.id}`,durationMs:Math.round(p.durationMs),ok:!p.skipped,language:p.language,indexerCommand:p.command,outputBytes:p.outputBytes,measurement:"indexer-run-result"});Wd(v(e.paths.outputDb),e.projectRoot,F,w);let h=[];if(b){_d(e.paths.outputDb,w,e.writeTelemetry);let p=E.typescript??e.tempPaths.tempOutputScip;h=Cd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:p,reusedProjects:b.reusedProjects,writeTelemetry:e.writeTelemetry})}let S=[...w,...h],{indexedOutputs:g}=Hd(S,O),_=m?[{language:"typescript",scipPath:m.scipPath}]:[],R=[...i,..._,...g];zd(R,O,e.languages,e.opts.allowPartial,e.onStatus);let P=m?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:m.scipPath,outputScipPath:m.scipPath,durationMs:m.durationMs,command:"watch-service:typescript-index",outputBytes:le(m.scipPath)??void 0,producedOutputBytes:le(m.affectedScipPath)??void 0}]:[],T=Od(r,[...w,...P],b?{outputDb:e.paths.outputDb,classification:b.classification}:void 0,d);return{indexedOutputs:R,skippedLanguages:O,reusedLanguages:[...o],languageFingerprints:Dd(r,e.languages),shards:T,typescriptProjectShardContext:b?{projects:b.allProjects,fingerprints:b.fingerprints}:void 0,incrementalTypeScript:m??void 0}}function wd(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=re(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=$i(e.projectRoot,r),o=Li(n.fingerprint.files,r),a=ji(r,i),s=Ni(r,o,a),c=te(e.paths.metaPath),l=kd(c,s,y=>j(Rt(e.paths.outputDb,y))),d=[...l.entries()].filter(([,y])=>y.reused).map(([y])=>y),m=new Set(d),f=new Set(r.filter(y=>!m.has(y)).map(y=>`typescript:${y}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function kd(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===pe&&Tt(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(L(a)!==L(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 _d(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Rt(e,i);yt(v(o),{recursive:!0}),se(n,ae(r.scipPath,o,void 0,{shareImmutable:!0}))}}function Cd(e){return e.reusedProjects.map((t,n)=>{let r=Rt(e.outputDb,t),i=de(e.tempOutputScip,"typescript-project-cached",n);return se(e.writeTelemetry,ae(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:le(i)??void 0}})}function Fd(e){let t=te(e.paths.metaPath),n=jn(e.projectFingerprint,e.languages,e),r=t&&j(e.paths.outputDb)?Ye(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Nn(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!==pe){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Tt(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(!j(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let u=o==="typescript"?np(e.projectRoot,c):c;if(L(u)!==L(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:Ln("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function Od(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:Ae(a.fingerprint),outputBytes:le(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?Ae(c.fingerprint):a?Ae(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:Ae(a.fingerprint),outputBytes:le(Rt(n.outputDb,o)),durationMs:0});return i}function Ae(e){return fd("sha256").update(L(e)).digest("hex").slice(0,16)}function le(e){try{return An(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Ad(e,t,n,r,i,o,a,s){$(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=I("reindex.publish.scip-output",()=>{let h=Vd({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return wa(e.paths.outputDb,h,e.writeTelemetry),ka(h,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await B("reindex.publish.sqlite-output",()=>Jd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if($(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..."),Rn({cacheDir:v(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(S=>S.language==="typescript"?{language:S.language,scipPath:s.candidateScipPath}:S);return wa(e.paths.outputDb,h,e.writeTelemetry),u=ka(h,e.tempPaths.tempOutputScip,e.onStatus),u}}));$(e.opts.signal,"Reindex cancelled by its owner."),I("reindex.publish.auxiliary-documents",()=>{W(X(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await B("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project",S=s?.dependencyGraphUnchanged===!0;h?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):S&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Mn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,S,S?void 0:h?s?.changedFiles:s?.affectedFiles,D(v(e.paths.outputDb),sr),h)});let d=I("reindex.publish.sqlite-layout",()=>Zt(e.tempPaths.tempOutputDb,{analyze:Md(s,l.mode)}));d.added.length>0&&e.onStatus(`Added SQLite query indexes: ${d.added.join(", ")}`),d.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${d.removed.join(", ")}`),I("reindex.publish.coverage",()=>Va(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let m,f=null;l.mode==="incremental"&&s&&I("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let g=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=Ot(g),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{g.close()}return}let h=null,S=null;try{h=I("reindex.publish.reference-fragments.open-candidate",()=>new V({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),S=I("reindex.publish.reference-fragments.open-evidence",()=>new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),m=s.dependencyGraphSnapshot?I("reindex.publish.reference-fragments.dependency-graph",()=>gr(h,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let g=new Set(s.deletedFiles),_=g.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!g.has(P))),R=I("reindex.publish.reference-fragments.seed",()=>Ir(h,e.fingerprint,_,S,m,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${R.affectedFiles} affected document(s) and carried ${R.carriedFiles} unaffected document(s) forward.`),R.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${R.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(g){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${g instanceof Error?g.message:String(g)}.`)}finally{h?.close(),S?.close()}});let y=bt(e.paths.metaPath);l.mode==="incremental"&&s||await La({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let b=I("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?Xd(s,l.changedDocumentPaths):Jt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),k=Pt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]}),O=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:E,pruneProjects:F}=Na({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:k});E.scipCompanion=O?"deferred":"current",I("reindex.publish.metadata",()=>{$a(e),Ba(e.paths.outputDb,F),xt(e.tempPaths.tempMetaPath,E)});let w=I("reindex.publish.generation-handoff",()=>Yr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return w.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${w.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&I("reindex.publish.dependency-graph",()=>{let h=null;try{h=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let S=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,g=!1;if(s.dependencyGraphUnchanged){let _=Ot(h),R=f&&_?cr(h,"file-dependency-graph",f,_):0;g=R>0,e.onStatus(g?`Carried ${R} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?g=fr(h,s.dependencyGraphSnapshot,S,m):Ge(h);s.dependencyGraphUnchanged||e.onStatus(g?`Carried the dependency graph forward by replacing ${S.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(S){e.onStatus(`Dependency graph carry-forward unavailable: ${S instanceof Error?S.message:String(S)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),I("reindex.publish.cleanup",()=>{Jr(v(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),qr(v(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),I("reindex.publish.shadow-telemetry",()=>ja(e.paths.outputDb,b,e.onStatus)),k}function Md(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Ld(e,t,n,r,i,o){let a=bt(e.paths.metaPath),s=null;try{se(e.writeTelemetry,ae(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(m){s=pi("reused","oracle-error",`Could not snapshot the prior database: ${m instanceof Error?m.message:String(m)}`)}W(X(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Zt(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(", ")}`),Va(e,e.paths.outputDb,t.map(m=>m.language)),s==null&&await La({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Jt({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=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(m=>m.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Na({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return l.scipCompanion=jd(e.paths),$a(e),Ba(e.paths.outputDb,d),xt(e.paths.metaPath,l),Xe(e.paths.outputDb,e.paths.metaPath),ja(e.paths.outputDb,s,e.onStatus),u}function jd(e){let t=te(e.metaPath)?.scipCompanion;if(t)return t;let n=G(e.outputDb,e.metaPath);return n.state==="current"&&n.generation.publication?.scipCompanion==="deferred"?"deferred":"current"}async function La(e){if(!j(e.previousDbPath))return;let t=J(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||_e(t).fullProject)return;let n=null;try{if(n=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),We(n))return;let r=await B("reindex.publish.affected-shadow.warm-sources",()=>hr(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function bt(e){return Et(te(e)?.fingerprint)}function ja(e,t,n){try{mi(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 Na(e){let t=Nd({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:pe,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 $a(e){$(e.opts.signal,"Reindex cancelled by its owner.");let t=or(e.projectRoot,e.fingerprint);if(L(t)===L(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>L(n.get(o))!==L(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Va(e,t,n){let r=Ye(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Ln("Candidate SQLite index",r)} Refusing to publish it.`)}function Ln(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 Nd(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=te(e.metaPath),n=t?.version===pe?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 Ba(e,t){let n=Xa(e);if(t===null){ce(n,{recursive:!0,force:!0});return}let r;try{r=Aa(n)}catch{return}for(let i of $d(r,t))ce(D(n,i),{force:!0})}function $d(e,t){let n=new Set(t.map(r=>`${rn(r)}.scip`));return e.filter(r=>!n.has(r))}function Vd(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=G(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":te(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=de(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Rn({cacheDir:v(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function wa(e,t,n){for(let r of t){let i=Nn(e,r.language);yt(v(i),{recursive:!0}),r.scipPath!==i&&se(n,ae(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Bd(e,t){let n=Cr();if(n){if(n.source==="path"&&va()!=="win32"){let r=Or();Fr(r)||(e?t(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${He} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`):(t(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${He}.`),await Dr(t)))}return}if(va()==="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.
350
350
  To install the reviewed version, run: scip-query reindex --install-missing
351
351
  Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await Bt(t))throw new Error(`The scip CLI is required but could not be installed.
352
- Install manually from: https://github.com/sourcegraph/scip/releases/tag/${He}`)}function Bd(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=Ud({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ua(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Ud(e){if(e.language!=="typescript")return[ht({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??ne(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[ht({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let o=t?`typescript:${r}`:"typescript",a=t?`typescript (${r})`:"typescript",s=t?le(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:o,label:a,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let u=Wd(e,c);if(u)return u}return[ht({...c,...t?{projectPath:r}:{}})]}))}function Gd(e,t,n,r){let i=n.filter(s=>s.shardInputPaths!==void 0);if(i.length===0)return;let o=new Map(r.filter(s=>!s.skipped).map(s=>[s.id,s.durationMs])),a=[];for(let s of i){let c=o.get(s.id);if(c===void 0||!(c>0))return;a.push({inputPaths:s.shardInputPaths,durationMs:c})}try{let s=so(a,c=>{try{return An(D(t,c)).size}catch{return 1}});s&&oo(e,s)}catch{}}function Wd(e,t){let n=cn(),r=Ft(e.projectRoot,"single");if(!r||!eo(r.size,n))return null;uo(e.projectRoot);let i=co(),o=to(r.size,n,i),a=e.typescriptShardCostDir?io(e.typescriptShardCostDir):null,s=ao(a),c=no({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:o,weightOf:l=>{let d=1;try{d=An(D(e.projectRoot,l)).size}catch{}return s(l,d)}}),u=Math.min(i,c.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${c.length} ${a?"cost-balanced":"byte-balanced"} compiler shard(s), ${u} at a time.`),c.map((l,d)=>ht({...t,id:`typescript-compiler-shard:${d}`,label:`typescript compiler shard ${d+1}/${c.length}`,scipPath:le(e.tempOutputScip,"typescript-compiler-shard",d),projectPath:l.configPath,temporaryProjectConfigs:[{path:l.configPath,content:l.content}],boundedConcurrency:u,outputComposition:"protobuf-concatenate",shardInputPaths:l.inputPaths}))}function ht(e){let t=nt(e.language),n=ke(t),r=Mt(t,e.projectRoot),i=e.trustProjectTools&&r?Sr(t,e.projectRoot):null,o=be(t);if(!i&&!o&&r){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!i&&!o&&!At(t)){if(e.skipAutoInstall){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Tn(t,e.onStatus)){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}}let a=i?.canonicalPath??be(t);if(!a){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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=xi({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let l=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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:Lt(t,e.env,a),...u===void 0?{}:{temporaryRootConfigContent:u},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{},...e.shardInputPaths===void 0?{}:{shardInputPaths:e.shardInputPaths},...i?{trustedProjectTool:i}:{}}}}function qd(e,t){let n=new Set(e.filter(o=>o.skipped&&o.outputComposition).map(o=>`${o.language}\0${o.outputScipPath}`)),r=new Map;for(let o of e)if(o.skipped)Ua(t,o.skipped);else{let a=`${o.language}\0${o.outputScipPath}`;if(n.has(a))continue;let s=r.get(a)??{language:o.language,outputScipPath:o.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(o.scipPath),o.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(a,s)}let i=[];for(let o of r.values())if(o.scipPaths.length>1)o.concatenate?Br(o.scipPaths,o.outputScipPath):Gt(o.scipPaths,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath});else{let a=o.scipPaths[0];a!==o.outputScipPath&&Ma(a,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath})}return{indexedOutputs:i}}function Ua(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 Hd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
352
+ Install manually from: https://github.com/sourcegraph/scip/releases/tag/${He}`)}function Ud(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?de(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=Gd({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ua(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Gd(e){if(e.language!=="typescript")return[ht({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??re(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[ht({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let o=t?`typescript:${r}`:"typescript",a=t?`typescript (${r})`:"typescript",s=t?de(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:o,label:a,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let u=qd(e,c);if(u)return u}return[ht({...c,...t?{projectPath:r}:{}})]}))}function Wd(e,t,n,r){let i=n.filter(s=>s.shardInputPaths!==void 0);if(i.length===0)return;let o=new Map(r.filter(s=>!s.skipped).map(s=>[s.id,s.durationMs])),a=[];for(let s of i){let c=o.get(s.id);if(c===void 0||!(c>0))return;a.push({inputPaths:s.shardInputPaths,durationMs:c})}try{let s=so(a,c=>{try{return An(D(t,c)).size}catch{return 1}});s&&oo(e,s)}catch{}}function qd(e,t){let n=cn(),r=Ct(e.projectRoot,"single");if(!r||!eo(r.size,n))return null;uo(e.projectRoot);let i=co(),o=to(r.size,n,i),a=e.typescriptShardCostDir?io(e.typescriptShardCostDir):null,s=ao(a),c=no({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:o,weightOf:l=>{let d=1;try{d=An(D(e.projectRoot,l)).size}catch{}return s(l,d)}}),u=Math.min(i,c.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${c.length} ${a?"cost-balanced":"byte-balanced"} compiler shard(s), ${u} at a time.`),c.map((l,d)=>ht({...t,id:`typescript-compiler-shard:${d}`,label:`typescript compiler shard ${d+1}/${c.length}`,scipPath:de(e.tempOutputScip,"typescript-compiler-shard",d),projectPath:l.configPath,temporaryProjectConfigs:[{path:l.configPath,content:l.content}],boundedConcurrency:u,outputComposition:"protobuf-concatenate",shardInputPaths:l.inputPaths}))}function ht(e){let t=nt(e.language),n=ke(t),r=Mt(t,e.projectRoot),i=e.trustProjectTools&&r?Sr(t,e.projectRoot):null,o=be(t);if(!i&&!o&&r){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!i&&!o&&!At(t)){if(e.skipAutoInstall){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Tn(t,e.onStatus)){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}}let a=i?.canonicalPath??be(t);if(!a){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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=xi({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let l=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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:Lt(t,e.env,a),...u===void 0?{}:{temporaryRootConfigContent:u},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{},...e.shardInputPaths===void 0?{}:{shardInputPaths:e.shardInputPaths},...i?{trustedProjectTool:i}:{}}}}function Hd(e,t){let n=new Set(e.filter(o=>o.skipped&&o.outputComposition).map(o=>`${o.language}\0${o.outputScipPath}`)),r=new Map;for(let o of e)if(o.skipped)Ua(t,o.skipped);else{let a=`${o.language}\0${o.outputScipPath}`;if(n.has(a))continue;let s=r.get(a)??{language:o.language,outputScipPath:o.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(o.scipPath),o.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(a,s)}let i=[];for(let o of r.values())if(o.scipPaths.length>1)o.concatenate?Br(o.scipPaths,o.outputScipPath):Gt(o.scipPaths,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath});else{let a=o.scipPaths[0];a!==o.outputScipPath&&Ma(a,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath})}return{indexedOutputs:i}}function Ua(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 zd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
353
353
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
354
354
  `+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.
355
355
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
356
- `))}function ka(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ur(e.map(o=>o.scipPath),t);return Wa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ma(e[0].scipPath,t);return!1}async function zd(e){let t;if(Jd(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,u]of i.entries()){let l=D(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ga(u.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${u.affectedFiles.length-u.deletedFiles.length} emitted, ${u.deletedFiles.length} removed) to SQLite...`);let d=performance.now();await _a(u.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-d,Ze(e.run.writeTelemetry,ue(l)??0);let m=Ti({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:u.affectedFiles,deletedFiles:u.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=m.durationMs;for(let f of m.changedDocumentPaths)o.add(f);se(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if($(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),se(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await _a(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 Jd(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!j(e.run.paths.outputDb)||!j(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 Yd(e,t){let n=F(),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:F()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:zt(e.plan,o,e.projectFileCount)}}async function _a(e,t,n,r,i=!1,o){if($(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ga(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=_r();if(!a)throw new Error("scip CLI is not available");let s=await qe({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()}`:""}`)}else se(t,{force:!0}),await Qi(fe(e,{maxBytes:Ne,inputKind:"SCIP index"}),t,{signal:o})}catch(a){$(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 Ga(e,t){let n=Vr(e);Wa(n,t)}function Wa(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=hd(e)||".scip",i=gt(e,r);return D(v(e),`${i}.${n+1}.${t}${r}`)}async function Xd(e,t){for(let n=0;n<2;n++){let r=Kd(e,t);if(r)return r;let i=Qd(e);if(i&&za(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Zd(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: ${ce(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${v(e)}; refusing to steal an active lock.`);let a=kt(e,{parseLegacy:St});if(!Yn(e,a,{parseLegacy:St}))throw new Error(`Reindex lock ownership changed before preemption completed for ${v(e)}.`);continue}throw new ze(`Another scip-query reindex is already running for ${v(e)}.`)}throw new ze(`Could not acquire scip-query reindex lock for ${v(e)}.`)}function Kd(e,t){let n=J(process.pid),r=Jn(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:St});if(r.kind==="acquired"&&r.reclaimed){let i=qa(r.reclaimed,e);i&&za(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${v(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Qd(e){return qa(kt(e,{parseLegacy:St}),e)}var St=e=>{let t=Ha(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qa(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ha(e.parsed,t)}function Ha(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=qn(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function za(e,t){return e?.kind==="manual-cli"&&Ja(t?.trigger)}function Ja(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Zd(e){return!ge(e.pid)||(Dn(e),Fa(e,"SIGTERM"),await Ca(e,2e3))?!0:(Dn(e),Fa(e,"SIGKILL"),Ca(e,1e3))}function Fa(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ge(e.pid))return;Dn(e)}try{process.kill(e.pid,t)}catch{}}async function Ca(e,t){let n=F()+t;for(;F()<n;){if(Oa(e))return!0;await ep(50)}return Oa(e)}function Dn(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(!we(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Oa(e){if(!ge(e.pid))return!0;if(!e.processIdentity)return!1;let t=J(e.pid);return t!==null&&!we(e.processIdentity,t)}function ep(e){return new Promise(t=>setTimeout(t,e))}function jn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?tr(n.typescriptProjects):[],o=r==="clojure"?np(n.clojureConfigPath):void 0,a=[...nt(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"&&rp(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Bn(c.path,r,a)).map(c=>Ya(c,r))}]}))}function Ya(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function tp(e,t){let n=Et(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ne(e,n.typescriptProjects):["."],i=he(r);return{...n,files:n.files.filter(o=>!ye(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Be(e,o.path,o.hash);return Ya(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function np(e){return e?.trim()||void 0}function rp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Nn(e,t){return D(v(e),"language-indexes",`${t}.scip`)}function Xa(e){return D(v(e),"language-indexes","typescript-projects")}function Rt(e,t){return D(Xa(e),`${rn(t)}.scip`)}function de(e){try{return je(te(U(e,"reindex metadata")))}catch{return null}}function Ka(e,t){try{let n=te(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!Wn(r)||L([...r.indexedLanguages??[]].sort())!==L(t.languages)?null:L(r.fingerprint)===L(t)?"exact":L(Da(r.fingerprint))===L(Da(t))?"operational-config-compatible":null}catch{return null}}function Da(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function ip(e,t,n,r){let i=je(te(U(e,"reindex metadata")));i&&xt(e,{...i,fingerprint:t,...i.version===pe?{languageFingerprints:jn(t,n,r)}:{}})}function xt(e,t){Kn(e,t,{spacing:2,trailingNewline:!0})}function Qa(e,t){try{let n=je(te(U(e,"reindex metadata")));if(!n)return;xt(e,{...n,lastRefresh:t})}catch{}}function Pt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:F()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{Ri as INDEXER_CONFIGS,si as augmentAuxiliaryDocuments,Yl as augmentVueResolvedReferences,Xl as augmentVueResolvedReferencesAsync,X as auxiliaryDocumentsAugmentationStage,ke as describeIndexerBinary,Ut as detectLanguages,nt as getIndexerConfig,Lt as getIndexerExecutionEnv,Dt as isBinaryAvailable,At as isIndexerInstalled,Gt as mergeScipFiles,ns as mergeScipIndexes,ph as reindex,be as resolveIndexerBinary,Mt as resolveProjectLocalIndexerBinary,G as runPostIndexAugmentation,Tn as tryInstallIndexer,Bt as tryInstallScipCli,ya as vueResolvedReferencesAugmentationStage};
356
+ `))}function ka(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ur(e.map(o=>o.scipPath),t);return Wa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ma(e[0].scipPath,t);return!1}async function Jd(e){let t;if(Yd(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,u]of i.entries()){let l=D(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ga(u.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${u.affectedFiles.length-u.deletedFiles.length} emitted, ${u.deletedFiles.length} removed) to SQLite...`);let d=performance.now();await _a(u.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-d,Ze(e.run.writeTelemetry,le(l)??0);let m=Ti({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:u.affectedFiles,deletedFiles:u.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=m.durationMs;for(let f of m.changedDocumentPaths)o.add(f);ce(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if($(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),ce(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await _a(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 Yd(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!j(e.run.paths.outputDb)||!j(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 Xd(e,t){let n=C(),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:C()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:zt(e.plan,o,e.projectFileCount)}}async function _a(e,t,n,r,i=!1,o){if($(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ga(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=_r();if(!a)throw new Error("scip CLI is not available");let s=await qe({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()}`:""}`)}else ce(t,{force:!0}),await Qi(fe(e,{maxBytes:Ne,inputKind:"SCIP index"}),t,{signal:o})}catch(a){$(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 Ga(e,t){let n=Vr(e);Wa(n,t)}function Wa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function de(e,t,n){let r=hd(e)||".scip",i=gt(e,r);return D(v(e),`${i}.${n+1}.${t}${r}`)}async function Kd(e,t){for(let n=0;n<2;n++){let r=Qd(e,t);if(r)return r;let i=Zd(e);if(i&&za(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await ep(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: ${ue(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${v(e)}; refusing to steal an active lock.`);let a=kt(e,{parseLegacy:St});if(!Yn(e,a,{parseLegacy:St}))throw new Error(`Reindex lock ownership changed before preemption completed for ${v(e)}.`);continue}throw new ze(`Another scip-query reindex is already running for ${v(e)}.`)}throw new ze(`Could not acquire scip-query reindex lock for ${v(e)}.`)}function Qd(e,t){let n=Y(process.pid),r=Jn(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:St});if(r.kind==="acquired"&&r.reclaimed){let i=qa(r.reclaimed,e);i&&za(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${v(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Zd(e){return qa(kt(e,{parseLegacy:St}),e)}var St=e=>{let t=Ha(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qa(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ha(e.parsed,t)}function Ha(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=qn(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function za(e,t){return e?.kind==="manual-cli"&&Ja(t?.trigger)}function Ja(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function ep(e){return!ge(e.pid)||(Dn(e),Ca(e,"SIGTERM"),await Fa(e,2e3))?!0:(Dn(e),Ca(e,"SIGKILL"),Fa(e,1e3))}function Ca(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ge(e.pid))return;Dn(e)}try{process.kill(e.pid,t)}catch{}}async function Fa(e,t){let n=C()+t;for(;C()<n;){if(Oa(e))return!0;await tp(50)}return Oa(e)}function Dn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=Y(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!we(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Oa(e){if(!ge(e.pid))return!0;if(!e.processIdentity)return!1;let t=Y(e.pid);return t!==null&&!we(e.processIdentity,t)}function tp(e){return new Promise(t=>setTimeout(t,e))}function jn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?tr(n.typescriptProjects):[],o=r==="clojure"?rp(n.clojureConfigPath):void 0,a=[...nt(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"&&ip(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Bn(c.path,r,a)).map(c=>Ya(c,r))}]}))}function Ya(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function np(e,t){let n=Et(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?re(e,n.typescriptProjects):["."],i=he(r);return{...n,files:n.files.filter(o=>!ye(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Be(e,o.path,o.hash);return Ya(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function rp(e){return e?.trim()||void 0}function ip(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Nn(e,t){return D(v(e),"language-indexes",`${t}.scip`)}function Xa(e){return D(v(e),"language-indexes","typescript-projects")}function Rt(e,t){return D(Xa(e),`${rn(t)}.scip`)}function te(e){try{return je(ne(U(e,"reindex metadata")))}catch{return null}}function Ka(e,t){try{let n=ne(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!Wn(r)||L([...r.indexedLanguages??[]].sort())!==L(t.languages)?null:L(r.fingerprint)===L(t)?"exact":L(Da(r.fingerprint))===L(Da(t))?"operational-config-compatible":null}catch{return null}}function Da(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function op(e,t,n,r){let i=je(ne(U(e,"reindex metadata")));i&&xt(e,{...i,fingerprint:t,...i.version===pe?{languageFingerprints:jn(t,n,r)}:{}})}function xt(e,t){Kn(e,t,{spacing:2,trailingNewline:!0})}function Qa(e,t){try{let n=je(ne(U(e,"reindex metadata")));if(!n)return;xt(e,{...n,lastRefresh:t})}catch{}}function Pt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:C()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{Ri as INDEXER_CONFIGS,si as augmentAuxiliaryDocuments,Yl as augmentVueResolvedReferences,Xl as augmentVueResolvedReferencesAsync,X as auxiliaryDocumentsAugmentationStage,ke as describeIndexerBinary,Ut as detectLanguages,nt as getIndexerConfig,Lt as getIndexerExecutionEnv,Dt as isBinaryAvailable,At as isIndexerInstalled,Gt as mergeScipFiles,ns as mergeScipIndexes,mh as reindex,be as resolveIndexerBinary,Mt as resolveProjectLocalIndexerBinary,W as runPostIndexAugmentation,Tn as tryInstallIndexer,Bt as tryInstallScipCli,ya as vueResolvedReferencesAugmentationStage};
357
357
  //# sourceMappingURL=reindex.js.map