scip-query 0.24.0 → 0.26.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 (661) hide show
  1. package/CHANGELOG.md +247 -1
  2. package/README.md +111 -124
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-PRVFAGTQ.js +2 -0
  5. package/dist/call-graph-DVPAQV2F.js +2 -0
  6. package/dist/{call-graph-evidence-BociKRpF.d.ts → call-graph-evidence-CUtj8V2I.d.ts} +1 -1
  7. package/dist/chunk-2FSBGL5P.js +2 -0
  8. package/dist/chunk-2HLAFUCY.js +2 -0
  9. package/dist/chunk-2IWUT6CJ.js +3 -0
  10. package/dist/chunk-2KNN7GTQ.js +2 -0
  11. package/dist/chunk-2LHXRE2B.js +8 -0
  12. package/dist/{chunk-E65ELFKU.js → chunk-2YXE77TJ.js} +2 -2
  13. package/dist/chunk-36SGVCGX.js +2 -0
  14. package/dist/chunk-3ABBFPTP.js +2 -0
  15. package/dist/chunk-3IVFU4FD.js +3 -0
  16. package/dist/chunk-3JIQS44J.js +7 -0
  17. package/dist/chunk-3ZRB6DNK.js +7 -0
  18. package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
  19. package/dist/{chunk-BHKK5RJY.js → chunk-4BHGBMNO.js} +2 -2
  20. package/dist/chunk-4BP3UBDG.js +2 -0
  21. package/dist/chunk-4D6RO7G4.js +2 -0
  22. package/dist/chunk-4FEWQ6RH.js +2 -0
  23. package/dist/chunk-4IGEOBG7.js +2 -0
  24. package/dist/chunk-4QZXBUKC.js +2 -0
  25. package/dist/chunk-4WBDEVX2.js +4 -0
  26. package/dist/chunk-4WCUBZU3.js +8 -0
  27. package/dist/chunk-4WTUBQ36.js +40 -0
  28. package/dist/chunk-4XQ4O6IM.js +3 -0
  29. package/dist/chunk-55UQAMZO.js +4 -0
  30. package/dist/chunk-5D2LVK7O.js +125 -0
  31. package/dist/chunk-5IYJ56TT.js +2 -0
  32. package/dist/chunk-5PLMJC7Q.js +2 -0
  33. package/dist/chunk-5TNQJUR2.js +5 -0
  34. package/dist/chunk-62BDNPMI.js +2 -0
  35. package/dist/chunk-64DZ5TXR.js +7 -0
  36. package/dist/chunk-65245JCM.js +2 -0
  37. package/dist/chunk-6FFVZZL4.js +2 -0
  38. package/dist/chunk-6KO5JHAR.js +2 -0
  39. package/dist/chunk-6LRXOOSX.js +2 -0
  40. package/dist/chunk-6LSEIIF7.js +2 -0
  41. package/dist/chunk-6YMNWD3H.js +6 -0
  42. package/dist/chunk-72AD6ZRR.js +5 -0
  43. package/dist/chunk-73AAKPUC.js +4 -0
  44. package/dist/chunk-76CZ77DF.js +2 -0
  45. package/dist/chunk-7VPEEAAG.js +2 -0
  46. package/dist/chunk-7WTPQ4NX.js +14 -0
  47. package/dist/chunk-7Y5T6XDP.js +2 -0
  48. package/dist/chunk-A2IIGFMJ.js +5 -0
  49. package/dist/chunk-AB5KCTEV.js +2 -0
  50. package/dist/chunk-AC566WBP.js +6 -0
  51. package/dist/chunk-AGWFSTXC.js +3 -0
  52. package/dist/chunk-AOSIYPTA.js +2 -0
  53. package/dist/chunk-AUVEWPIF.js +2 -0
  54. package/dist/chunk-B56T42J3.js +25 -0
  55. package/dist/chunk-BIQEF5NE.js +2 -0
  56. package/dist/chunk-BL6XJKTA.js +3 -0
  57. package/dist/chunk-BMKOQJRI.js +2 -0
  58. package/dist/chunk-BOZ4EXBB.js +3 -0
  59. package/dist/chunk-BUTWYEPH.js +2 -0
  60. package/dist/chunk-BZB4QPIP.js +2 -0
  61. package/dist/{chunk-6ILKOOGH.js → chunk-CE357GEE.js} +4 -4
  62. package/dist/chunk-CFN45HFP.js +2 -0
  63. package/dist/chunk-CFYMZFXT.js +368 -0
  64. package/dist/chunk-CN5EH7O3.js +2 -0
  65. package/dist/chunk-D254DNNQ.js +4 -0
  66. package/dist/chunk-D3FDISIC.js +2 -0
  67. package/dist/chunk-D3NX5XIE.js +3 -0
  68. package/dist/chunk-DA7RPPDF.js +3 -0
  69. package/dist/chunk-DDMC3FON.js +3 -0
  70. package/dist/chunk-DIO3FUSG.js +2 -0
  71. package/dist/chunk-DJ2NNSUK.js +3 -0
  72. package/dist/chunk-DKYQIM3C.js +18 -0
  73. package/dist/{chunk-OHIV323X.js → chunk-DOOEL2IV.js} +2 -2
  74. package/dist/chunk-DVFP6PZI.js +2 -0
  75. package/dist/chunk-E3FDPXZK.js +2 -0
  76. package/dist/chunk-E7YNJLCB.js +2 -0
  77. package/dist/chunk-EFGW5JPH.js +2 -0
  78. package/dist/chunk-EJVTR244.js +13 -0
  79. package/dist/chunk-EOV7RTRZ.js +2 -0
  80. package/dist/chunk-ETOIKRHO.js +2 -0
  81. package/dist/chunk-EYK3ZAO2.js +3 -0
  82. package/dist/chunk-F2V2LPET.js +52 -0
  83. package/dist/chunk-F4LUHJTF.js +2 -0
  84. package/dist/chunk-F4PUT6IT.js +2 -0
  85. package/dist/chunk-F56GCXXS.js +5 -0
  86. package/dist/chunk-FC2EVQRM.js +2 -0
  87. package/dist/chunk-FL7NBMHP.js +3 -0
  88. package/dist/chunk-FMRN2TRL.js +3 -0
  89. package/dist/chunk-FVULPZDF.js +20 -0
  90. package/dist/chunk-GCKCF5FL.js +43 -0
  91. package/dist/chunk-GH2PYF46.js +2 -0
  92. package/dist/chunk-GHJAGXIP.js +2 -0
  93. package/dist/{chunk-2GJSD5GY.js → chunk-GMVSHUKZ.js} +2 -2
  94. package/dist/chunk-GS6KDO4R.js +2 -0
  95. package/dist/chunk-GUUBXNN7.js +2 -0
  96. package/dist/chunk-GVWX5T43.js +80 -0
  97. package/dist/chunk-GZKFETP5.js +2 -0
  98. package/dist/chunk-H4EQHO6J.js +9 -0
  99. package/dist/chunk-H73WY2RM.js +2 -0
  100. package/dist/chunk-H75GSPRV.js +60 -0
  101. package/dist/chunk-HDR3AHSV.js +61 -0
  102. package/dist/chunk-HQBSL74Y.js +2 -0
  103. package/dist/chunk-HRRFKWPZ.js +2 -0
  104. package/dist/chunk-HXENDJC6.js +2 -0
  105. package/dist/chunk-IIBAZNSW.js +21 -0
  106. package/dist/chunk-INLMWEUU.js +12 -0
  107. package/dist/chunk-IWQPAF4F.js +2 -0
  108. package/dist/chunk-IZJ6YUKP.js +35 -0
  109. package/dist/chunk-J2TMAIN5.js +60 -0
  110. package/dist/chunk-J5FJMODQ.js +142 -0
  111. package/dist/chunk-J7HZPIO3.js +2 -0
  112. package/dist/chunk-JEVRKFRL.js +2 -0
  113. package/dist/chunk-JFXSGAEB.js +30 -0
  114. package/dist/chunk-JVRTHGFS.js +3 -0
  115. package/dist/chunk-JYWEX7RR.js +360 -0
  116. package/dist/chunk-K3YL22N6.js +2 -0
  117. package/dist/chunk-K4CN7GXK.js +12 -0
  118. package/dist/chunk-K5TBVXU4.js +30 -0
  119. package/dist/chunk-KDDIE2DP.js +9 -0
  120. package/dist/chunk-KHWRRPV4.js +2 -0
  121. package/dist/chunk-KI6NBKDY.js +14 -0
  122. package/dist/chunk-KU3QRSTH.js +2 -0
  123. package/dist/chunk-KZBJWZJB.js +2 -0
  124. package/dist/chunk-L7GFM3NP.js +3 -0
  125. package/dist/chunk-LMO6PK3V.js +35 -0
  126. package/dist/chunk-LN4YXJJU.js +2 -0
  127. package/dist/chunk-LOVIZBJ4.js +43 -0
  128. package/dist/chunk-LPCRK4A2.js +11 -0
  129. package/dist/chunk-MMHZKBFA.js +2 -0
  130. package/dist/{chunk-A4WEAK35.js → chunk-MOQQBQRD.js} +2 -2
  131. package/dist/chunk-N2WN6I3L.js +2 -0
  132. package/dist/chunk-N3ORQT7L.js +2 -0
  133. package/dist/chunk-NAZ3RAIW.js +2 -0
  134. package/dist/chunk-NDUNO5JQ.js +2 -0
  135. package/dist/chunk-NEIWRNAZ.js +4 -0
  136. package/dist/chunk-NJJMVD65.js +2 -0
  137. package/dist/chunk-NLOQOBXI.js +20 -0
  138. package/dist/chunk-NOLZOVCU.js +2 -0
  139. package/dist/chunk-NOWINRRN.js +2 -0
  140. package/dist/chunk-NZAXKGRL.js +16 -0
  141. package/dist/chunk-O2C4UILI.js +2 -0
  142. package/dist/chunk-O3RHA6ZT.js +3 -0
  143. package/dist/chunk-O4UZSPPI.js +3 -0
  144. package/dist/chunk-OGFV2BUX.js +2 -0
  145. package/dist/chunk-OZCJXZK6.js +499 -0
  146. package/dist/chunk-P6ODM7BY.js +2 -0
  147. package/dist/{chunk-GHNPACNP.js → chunk-PAVGPRHJ.js} +2 -2
  148. package/dist/chunk-PH52RA7D.js +2 -0
  149. package/dist/chunk-PKN354TH.js +3 -0
  150. package/dist/chunk-PWOASWEG.js +11 -0
  151. package/dist/chunk-QIWXRW72.js +2 -0
  152. package/dist/chunk-QJRMOK5N.js +2 -0
  153. package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
  154. package/dist/chunk-QXEUDXBT.js +3 -0
  155. package/dist/chunk-QYUVVBMR.js +6 -0
  156. package/dist/chunk-QZ7KQZRN.js +2 -0
  157. package/dist/chunk-R6LQBUDH.js +2 -0
  158. package/dist/chunk-RBS42E55.js +20 -0
  159. package/dist/chunk-RSJKPCFX.js +26 -0
  160. package/dist/chunk-S6CZA3MV.js +2 -0
  161. package/dist/chunk-STMVAHJP.js +2 -0
  162. package/dist/chunk-SYVPTTVW.js +2 -0
  163. package/dist/chunk-T6DK3ZP7.js +2 -0
  164. package/dist/chunk-TKD34PHN.js +4 -0
  165. package/dist/chunk-TNNQFH7W.js +2 -0
  166. package/dist/chunk-TNV7SSUF.js +2 -0
  167. package/dist/chunk-TO7ZR3EH.js +8 -0
  168. package/dist/chunk-TOU3CHK4.js +2 -0
  169. package/dist/chunk-TRBI4UKT.js +2 -0
  170. package/dist/chunk-TZCVNCAN.js +4 -0
  171. package/dist/chunk-U4LZA5LL.js +3 -0
  172. package/dist/chunk-U5RIG3JP.js +3 -0
  173. package/dist/chunk-UP5KXN2I.js +2 -0
  174. package/dist/chunk-UQFR3NDH.js +5 -0
  175. package/dist/chunk-UXYXF7GV.js +2 -0
  176. package/dist/chunk-VB3GOKOS.js +2 -0
  177. package/dist/{chunk-4FR6GQIT.js → chunk-VF5JZICY.js} +2 -2
  178. package/dist/chunk-VTY3VK6E.js +2 -0
  179. package/dist/chunk-VX2O4RIS.js +2 -0
  180. package/dist/chunk-WKPV2TDZ.js +2 -0
  181. package/dist/chunk-WOFQ5DTB.js +2 -0
  182. package/dist/chunk-WS4C6TCK.js +2 -0
  183. package/dist/chunk-WXU3DGPU.js +2 -0
  184. package/dist/{chunk-ATXPTSEI.js → chunk-X6RMKHJQ.js} +7 -7
  185. package/dist/{chunk-44IETFOU.js → chunk-XHMN6ZX7.js} +2 -2
  186. package/dist/chunk-XHTVFLWW.js +2 -0
  187. package/dist/chunk-XKIDJCIK.js +2 -0
  188. package/dist/chunk-XTYTYZPT.js +2 -0
  189. package/dist/chunk-Y2JHHTTA.js +2 -0
  190. package/dist/chunk-YGVRMGYN.js +4 -0
  191. package/dist/chunk-YNQCGEQE.js +2 -0
  192. package/dist/chunk-YOQVEXVE.js +14 -0
  193. package/dist/chunk-YRT2WLYY.js +2 -0
  194. package/dist/chunk-YTAP5Y2G.js +2 -0
  195. package/dist/chunk-YTYWI7VB.js +2 -0
  196. package/dist/chunk-YULZRALL.js +2 -0
  197. package/dist/chunk-Z33WQG4Q.js +2 -0
  198. package/dist/chunk-ZGTYGDMF.js +16 -0
  199. package/dist/chunk-ZHMRSZFD.js +43 -0
  200. package/dist/chunk-ZHSP366W.js +10 -0
  201. package/dist/chunk-ZIBYCYKK.js +7 -0
  202. package/dist/chunk-ZLADLUE6.js +3 -0
  203. package/dist/chunk-ZO4YXUT6.js +4 -0
  204. package/dist/{chunk-MZPXPSUJ.js → chunk-ZR4HBC2H.js} +2 -2
  205. package/dist/cli-main.js +6 -6
  206. package/dist/cli.js +1 -1
  207. package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
  208. package/dist/code-IL5WH3NZ.js +2 -0
  209. package/dist/code-result-json-ANTBEDFP.js +4 -0
  210. package/dist/command-descriptors-HEEMDHTU.js +222 -0
  211. package/dist/deps-EOWFC6FD.js +2 -0
  212. package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
  213. package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
  214. package/dist/files-K4AI3JUM.js +2 -0
  215. package/dist/{health-BI2a9WPy.d.ts → health-BtfmNrfa.d.ts} +5 -79
  216. package/dist/hierarchy-6W5NDIFI.js +2 -0
  217. package/dist/imports-WH365QY4.js +2 -0
  218. package/dist/index.d.ts +13 -1
  219. package/dist/index.js +1 -1
  220. package/dist/members-K3PHMF5S.js +2 -0
  221. package/dist/methods-E7KVMBX4.js +2 -0
  222. package/dist/output-continuation-command-BJSY67SN.js +3 -0
  223. package/dist/output-pagination-UZJ5ACIX.js +24 -0
  224. package/dist/postinstall.js +1 -1
  225. package/dist/project-reindex-EP24WT4X.js +3 -0
  226. package/dist/queries/affected.js +1 -1
  227. package/dist/queries/architecture.d.ts +15 -4
  228. package/dist/queries/architecture.js +1 -1
  229. package/dist/queries/bottlenecks.js +1 -1
  230. package/dist/queries/by-kind.js +1 -1
  231. package/dist/queries/call-graph.d.ts +1 -1
  232. package/dist/queries/call-graph.js +1 -1
  233. package/dist/queries/change-surface.d.ts +1 -0
  234. package/dist/queries/change-surface.js +1 -1
  235. package/dist/queries/cleanup-plan.d.ts +3 -3
  236. package/dist/queries/cleanup-plan.js +1 -1
  237. package/dist/queries/co-change.js +1 -1
  238. package/dist/queries/code.d.ts +1 -1
  239. package/dist/queries/code.js +1 -1
  240. package/dist/queries/complexity.d.ts +6 -3
  241. package/dist/queries/complexity.js +1 -1
  242. package/dist/queries/context.d.ts +1 -7
  243. package/dist/queries/context.js +1 -1
  244. package/dist/queries/coupling.js +1 -1
  245. package/dist/queries/cycles.js +1 -1
  246. package/dist/queries/dead.js +1 -1
  247. package/dist/queries/decorative-checkers.js +1 -1
  248. package/dist/queries/dependence-slice.d.ts +46 -22
  249. package/dist/queries/dependence-slice.js +1 -1
  250. package/dist/queries/dependency-depth.d.ts +1 -7
  251. package/dist/queries/dependency-depth.js +1 -1
  252. package/dist/queries/deps.js +1 -1
  253. package/dist/queries/diff-impact.d.ts +3 -1
  254. package/dist/queries/diff-impact.js +1 -1
  255. package/dist/queries/doc-drift.js +1 -1
  256. package/dist/queries/drift.d.ts +1 -1
  257. package/dist/queries/drift.js +1 -1
  258. package/dist/queries/duplicate-bodies.d.ts +1 -1
  259. package/dist/queries/duplicate-bodies.js +1 -1
  260. package/dist/queries/entry-map.d.ts +2 -4
  261. package/dist/queries/entry-map.js +1 -1
  262. package/dist/queries/evidence.d.ts +121 -61
  263. package/dist/queries/evidence.js +1 -1
  264. package/dist/queries/fan.js +1 -1
  265. package/dist/queries/files.js +1 -1
  266. package/dist/queries/health.d.ts +1 -1
  267. package/dist/queries/health.js +1 -1
  268. package/dist/queries/hierarchy.d.ts +2 -2
  269. package/dist/queries/hierarchy.js +1 -1
  270. package/dist/queries/hotspots.d.ts +1 -1
  271. package/dist/queries/hotspots.js +1 -1
  272. package/dist/queries/imports.d.ts +1 -0
  273. package/dist/queries/imports.js +1 -1
  274. package/dist/queries/incomplete-migration.d.ts +3 -3
  275. package/dist/queries/incomplete-migration.js +1 -1
  276. package/dist/queries/index.d.ts +15 -64
  277. package/dist/queries/index.js +1 -1
  278. package/dist/queries/locality-candidates.d.ts +4 -4
  279. package/dist/queries/locality-candidates.js +1 -1
  280. package/dist/queries/members.d.ts +2 -2
  281. package/dist/queries/members.js +1 -1
  282. package/dist/queries/methods.js +1 -1
  283. package/dist/queries/not-implemented.d.ts +2 -6
  284. package/dist/queries/not-implemented.js +1 -1
  285. package/dist/queries/outline.js +1 -1
  286. package/dist/queries/passthrough-candidates.js +1 -1
  287. package/dist/queries/react-component-duplicates.js +1 -1
  288. package/dist/queries/react-hook-candidates.js +1 -1
  289. package/dist/queries/react-large-component-pressure.js +1 -1
  290. package/dist/queries/recent-duplicates.js +1 -1
  291. package/dist/queries/redundant-reexports.d.ts +4 -14
  292. package/dist/queries/redundant-reexports.js +1 -1
  293. package/dist/queries/refs.d.ts +4 -1
  294. package/dist/queries/refs.js +1 -1
  295. package/dist/queries/review.d.ts +188 -0
  296. package/dist/queries/review.js +2 -0
  297. package/dist/queries/similar-files.d.ts +7 -10
  298. package/dist/queries/similar-files.js +1 -1
  299. package/dist/queries/similar-signatures.js +1 -1
  300. package/dist/queries/similar.d.ts +19 -1
  301. package/dist/queries/similar.js +1 -1
  302. package/dist/queries/slice-cohesion.d.ts +205 -0
  303. package/dist/queries/slice-cohesion.js +2 -0
  304. package/dist/queries/source-inspection.d.ts +6 -202
  305. package/dist/queries/source-inspection.js +1 -1
  306. package/dist/queries/source-search.d.ts +2 -3
  307. package/dist/queries/source-search.js +1 -1
  308. package/dist/queries/stats.d.ts +1 -0
  309. package/dist/queries/stats.js +1 -1
  310. package/dist/queries/surface.js +1 -1
  311. package/dist/queries/symbols.js +1 -1
  312. package/dist/queries/system.d.ts +4 -2
  313. package/dist/queries/system.js +1 -1
  314. package/dist/queries/test-quality.d.ts +1 -1
  315. package/dist/queries/test-quality.js +1 -1
  316. package/dist/queries/twin-drift.d.ts +1 -1
  317. package/dist/queries/twin-drift.js +1 -1
  318. package/dist/queries/unused-imports.js +1 -1
  319. package/dist/queries/unused-params.d.ts +3 -15
  320. package/dist/queries/unused-params.js +1 -1
  321. package/dist/queries/vue-component-duplicates.js +1 -1
  322. package/dist/queries/vue-composable-candidates.js +1 -1
  323. package/dist/queries/vue-large-view-pressure.js +1 -1
  324. package/dist/query-service-fastpath.js +5 -5
  325. package/dist/query-service-server.js +4 -4
  326. package/dist/refs-CCBJG7WK.js +2 -0
  327. package/dist/refs-pagination-DRNLVU4S.js +2 -0
  328. package/dist/reindex-worker.js +79 -29
  329. package/dist/reindex.js +45 -45
  330. package/dist/repository-cache-worker.js +2 -0
  331. package/dist/runtime.d.ts +8 -8
  332. package/dist/runtime.js +3 -4
  333. package/dist/rust-semantic-session-server.js +1 -1
  334. package/dist/rust-semantic-session-worker.js +1 -1
  335. package/dist/rust-semantic-worker.js +1 -1
  336. package/dist/service-queries-2WAJI7R6.js +6 -0
  337. package/dist/source-inspection-91U9zdO3.d.ts +341 -0
  338. package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
  339. package/dist/stats-G7DIV6VU.js +2 -0
  340. package/dist/surface-IO55UALI.js +2 -0
  341. package/dist/system-ZBMSHJXU.js +2 -0
  342. package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
  343. package/dist/typescript-indexer.js +2 -0
  344. package/dist/typescript-mailbox-worker.js +1 -1
  345. package/dist/watch-server.js +3 -3
  346. package/docs/AGENT_GUIDE.md +19 -128
  347. package/docs/CLI_JSON_OUTPUT.md +21 -17
  348. package/docs/COMMAND_REFERENCE.md +34 -49
  349. package/docs/CURRENT_COMMANDS.md +123 -0
  350. package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
  351. package/docs/DETECTOR_GUIDE.md +27 -23
  352. package/docs/PRODUCT_VISION.md +135 -0
  353. package/docs/PROPERTY_TESTING.md +73 -0
  354. package/docs/REVIEW.md +76 -0
  355. package/docs/SKILLS.md +51 -0
  356. package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
  357. package/docs/accuracy-audit-checklist.md +34 -0
  358. package/docs/analyzer-inventory.md +2 -2
  359. package/package.json +18 -80
  360. package/scripts/evidence-product-contract.mjs +7 -3
  361. package/scripts/record-review-coverage.mjs +118 -0
  362. package/scripts/scip-windows-provenance.mjs +29 -19
  363. package/skills/scip-architecture-review/SKILL.md +57 -0
  364. package/skills/scip-architecture-review/agents/openai.yaml +4 -0
  365. package/skills/scip-architecture-review/references/design-checks.md +17 -0
  366. package/skills/scip-explore/SKILL.md +15 -59
  367. package/skills/scip-explore/agents/openai.yaml +3 -3
  368. package/skills/scip-explore/references/external-evidence.md +2 -2
  369. package/skills/scip-explore/references/information-model.md +26 -29
  370. package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
  371. package/skills/scip-integrity-audit/SKILL.md +53 -181
  372. package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
  373. package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
  374. package/skills/scip-plan/SKILL.md +39 -65
  375. package/skills/scip-plan/agents/openai.yaml +2 -2
  376. package/skills/scip-query/SKILL.md +28 -81
  377. package/skills/scip-query/agents/openai.yaml +2 -2
  378. package/skills/scip-query/references/command-guide.md +169 -0
  379. package/skills/scip-setup/SKILL.md +4 -2
  380. package/skills/scip-setup/agents/openai.yaml +3 -3
  381. package/dist/by-kind-H3P6BR5G.js +0 -2
  382. package/dist/call-graph-VTG2CUOQ.js +0 -2
  383. package/dist/chunk-26CT72HM.js +0 -2
  384. package/dist/chunk-2BMSSRBH.js +0 -2
  385. package/dist/chunk-2M2LSIMY.js +0 -7
  386. package/dist/chunk-2N6WBNDC.js +0 -29
  387. package/dist/chunk-2OOY75BW.js +0 -2
  388. package/dist/chunk-2USA3S3P.js +0 -3
  389. package/dist/chunk-2VAHDDLM.js +0 -133
  390. package/dist/chunk-2XWIUW5Z.js +0 -455
  391. package/dist/chunk-35NLDRZC.js +0 -2
  392. package/dist/chunk-3AF4TUFK.js +0 -3
  393. package/dist/chunk-3D4BOXW6.js +0 -20
  394. package/dist/chunk-3LO4FST5.js +0 -16
  395. package/dist/chunk-3WTY4LP2.js +0 -3
  396. package/dist/chunk-3Z5AMSK6.js +0 -29
  397. package/dist/chunk-4KBTHJLP.js +0 -2
  398. package/dist/chunk-5BIKR67W.js +0 -2
  399. package/dist/chunk-5PROPLHI.js +0 -2
  400. package/dist/chunk-5V7EPTII.js +0 -2
  401. package/dist/chunk-62LPZCBQ.js +0 -3
  402. package/dist/chunk-64O2JHQA.js +0 -2
  403. package/dist/chunk-6D4F5VWG.js +0 -10
  404. package/dist/chunk-6ERFBC3X.js +0 -3
  405. package/dist/chunk-6MFXCMZC.js +0 -2
  406. package/dist/chunk-6O7FACKB.js +0 -2
  407. package/dist/chunk-6TS3KOXR.js +0 -2
  408. package/dist/chunk-76QOU4PK.js +0 -3
  409. package/dist/chunk-7DUI77BN.js +0 -2
  410. package/dist/chunk-7F45LJKI.js +0 -2
  411. package/dist/chunk-7F7T6DCR.js +0 -2
  412. package/dist/chunk-7H6VHWWJ.js +0 -2
  413. package/dist/chunk-7HXT6YLU.js +0 -5
  414. package/dist/chunk-7KCZELVM.js +0 -2
  415. package/dist/chunk-7R4V5ES6.js +0 -6
  416. package/dist/chunk-7RIRIADH.js +0 -7
  417. package/dist/chunk-7ZLWLOGT.js +0 -2
  418. package/dist/chunk-AADQLOQ4.js +0 -38
  419. package/dist/chunk-AN76MGUE.js +0 -2
  420. package/dist/chunk-ANLNLY66.js +0 -2
  421. package/dist/chunk-AX7IDVFT.js +0 -2
  422. package/dist/chunk-B3X6KU75.js +0 -2
  423. package/dist/chunk-B7MPDEAK.js +0 -3
  424. package/dist/chunk-BBB5FBX4.js +0 -2
  425. package/dist/chunk-BJT7LSPK.js +0 -3
  426. package/dist/chunk-BJWFVAA5.js +0 -2
  427. package/dist/chunk-BKVWUP7Y.js +0 -2
  428. package/dist/chunk-BKZYTLGE.js +0 -35
  429. package/dist/chunk-BL6DCHQP.js +0 -2
  430. package/dist/chunk-BOW7SSQH.js +0 -43
  431. package/dist/chunk-C4RHHCKL.js +0 -7
  432. package/dist/chunk-C7C6AKAT.js +0 -117
  433. package/dist/chunk-CD6M6LS2.js +0 -16
  434. package/dist/chunk-CFE6PSG6.js +0 -2
  435. package/dist/chunk-CFNIGQMT.js +0 -2
  436. package/dist/chunk-CKBUBRYD.js +0 -2
  437. package/dist/chunk-CZW5MZ5B.js +0 -2
  438. package/dist/chunk-DBBZ63ZX.js +0 -2
  439. package/dist/chunk-DBN7DMJB.js +0 -18
  440. package/dist/chunk-DUULLZHZ.js +0 -3
  441. package/dist/chunk-DV5Y5NOS.js +0 -2
  442. package/dist/chunk-DZOIKCTM.js +0 -3
  443. package/dist/chunk-E4PKTOL3.js +0 -2
  444. package/dist/chunk-E7QR35ST.js +0 -2
  445. package/dist/chunk-EFSXAINW.js +0 -2
  446. package/dist/chunk-EHVEIEQN.js +0 -18
  447. package/dist/chunk-EHYDXE3Z.js +0 -2
  448. package/dist/chunk-EP63Y6LD.js +0 -2
  449. package/dist/chunk-EPX6NQN6.js +0 -4
  450. package/dist/chunk-ETC674NS.js +0 -5
  451. package/dist/chunk-F5GSBHC6.js +0 -3
  452. package/dist/chunk-FH3DGXC6.js +0 -2
  453. package/dist/chunk-FI7VGOR4.js +0 -16
  454. package/dist/chunk-FJF6VO2P.js +0 -2
  455. package/dist/chunk-FLMTCX5R.js +0 -2
  456. package/dist/chunk-FVFDOIM3.js +0 -2
  457. package/dist/chunk-G2HU5WRN.js +0 -2
  458. package/dist/chunk-G4ALYS4J.js +0 -2
  459. package/dist/chunk-G56I7K4W.js +0 -26
  460. package/dist/chunk-GC4DG2V5.js +0 -2
  461. package/dist/chunk-GG45PK4S.js +0 -4
  462. package/dist/chunk-GINH3YQU.js +0 -20
  463. package/dist/chunk-GTZZVLKJ.js +0 -2
  464. package/dist/chunk-GXXW5ZHH.js +0 -2
  465. package/dist/chunk-H5EXS3HM.js +0 -2
  466. package/dist/chunk-HAXXKRTD.js +0 -4
  467. package/dist/chunk-HEZWBAZY.js +0 -2
  468. package/dist/chunk-HMEWLMML.js +0 -2
  469. package/dist/chunk-HOBOVYPO.js +0 -11
  470. package/dist/chunk-HRFQ6GW5.js +0 -8
  471. package/dist/chunk-HX4X7KG3.js +0 -2
  472. package/dist/chunk-HYT2R7LX.js +0 -4
  473. package/dist/chunk-IKQVBVQL.js +0 -40
  474. package/dist/chunk-IW5XQG5G.js +0 -2
  475. package/dist/chunk-J6GLBBRK.js +0 -4
  476. package/dist/chunk-J7A4PWFX.js +0 -3
  477. package/dist/chunk-JCSAZ35V.js +0 -2
  478. package/dist/chunk-JDU2IV3A.js +0 -2
  479. package/dist/chunk-JFMEXGFE.js +0 -2
  480. package/dist/chunk-JFMI5SGB.js +0 -4
  481. package/dist/chunk-JJP37RGX.js +0 -57
  482. package/dist/chunk-JZ2A7LDM.js +0 -5
  483. package/dist/chunk-KMVGRIO2.js +0 -2
  484. package/dist/chunk-KNLQGXVH.js +0 -80
  485. package/dist/chunk-KVQCECPR.js +0 -2
  486. package/dist/chunk-KXXORBZ2.js +0 -4
  487. package/dist/chunk-L5KYH6U3.js +0 -35
  488. package/dist/chunk-L6XHYJPZ.js +0 -21
  489. package/dist/chunk-L7KTFEAV.js +0 -43
  490. package/dist/chunk-LDXHR5EL.js +0 -23
  491. package/dist/chunk-LEECKFCJ.js +0 -2
  492. package/dist/chunk-MHGDSBFX.js +0 -2
  493. package/dist/chunk-MLQVVDG3.js +0 -74
  494. package/dist/chunk-MOKUWRHO.js +0 -3
  495. package/dist/chunk-MPYAPMNE.js +0 -2
  496. package/dist/chunk-MTDBHTSF.js +0 -2
  497. package/dist/chunk-MV6SPXCR.js +0 -7
  498. package/dist/chunk-MWN53KRN.js +0 -60
  499. package/dist/chunk-MXNGIEPU.js +0 -3
  500. package/dist/chunk-N55KIE46.js +0 -2
  501. package/dist/chunk-NB4D3BNM.js +0 -2
  502. package/dist/chunk-NGKBOT6G.js +0 -23
  503. package/dist/chunk-NJGKXKQF.js +0 -2
  504. package/dist/chunk-NJQISBL4.js +0 -8
  505. package/dist/chunk-NJT3ZEKY.js +0 -16
  506. package/dist/chunk-NKMKZP6A.js +0 -2
  507. package/dist/chunk-NODFZ6ED.js +0 -2
  508. package/dist/chunk-NSM5IEVW.js +0 -2
  509. package/dist/chunk-NTGUVNR2.js +0 -3
  510. package/dist/chunk-NU3KFF2O.js +0 -57
  511. package/dist/chunk-NWLVNU66.js +0 -557
  512. package/dist/chunk-NYKZMCRC.js +0 -4
  513. package/dist/chunk-O6BUXZEH.js +0 -6
  514. package/dist/chunk-ODPDP7A4.js +0 -3
  515. package/dist/chunk-OIAPEKMT.js +0 -3
  516. package/dist/chunk-OIOC5EHF.js +0 -3
  517. package/dist/chunk-ONPPQM4G.js +0 -2
  518. package/dist/chunk-OUHEZBYI.js +0 -2
  519. package/dist/chunk-OVGYW7UD.js +0 -29
  520. package/dist/chunk-OYKU4B3Y.js +0 -2
  521. package/dist/chunk-POBJ6FR2.js +0 -5
  522. package/dist/chunk-PSZPMMWN.js +0 -2
  523. package/dist/chunk-PXTRBKRK.js +0 -3
  524. package/dist/chunk-Q5JRIHT3.js +0 -4
  525. package/dist/chunk-Q7ATHARX.js +0 -2
  526. package/dist/chunk-Q7CSKIDM.js +0 -5
  527. package/dist/chunk-QBQE7ZJ5.js +0 -3
  528. package/dist/chunk-QH22UIXP.js +0 -5
  529. package/dist/chunk-QXCKQTKR.js +0 -60
  530. package/dist/chunk-RBAD4GJ2.js +0 -13
  531. package/dist/chunk-RMDPFPNW.js +0 -2
  532. package/dist/chunk-ROPJDEJZ.js +0 -4
  533. package/dist/chunk-RVZC6TJE.js +0 -2
  534. package/dist/chunk-S4QZBKSR.js +0 -3
  535. package/dist/chunk-SCPMZ73U.js +0 -2
  536. package/dist/chunk-SIAP5RGI.js +0 -73
  537. package/dist/chunk-SIX4RFR3.js +0 -3
  538. package/dist/chunk-SKKXTABJ.js +0 -16
  539. package/dist/chunk-SSRFUQBD.js +0 -2
  540. package/dist/chunk-SYVJEEUJ.js +0 -3
  541. package/dist/chunk-T3CZAZSI.js +0 -8
  542. package/dist/chunk-T6DWDI5E.js +0 -3
  543. package/dist/chunk-T6HRIROJ.js +0 -7
  544. package/dist/chunk-TAA7HXHE.js +0 -2
  545. package/dist/chunk-TJ2JQYT3.js +0 -2
  546. package/dist/chunk-TULNMD5T.js +0 -368
  547. package/dist/chunk-U2FPY5XA.js +0 -3
  548. package/dist/chunk-U3SXIMII.js +0 -38
  549. package/dist/chunk-U6KCHXJ4.js +0 -2
  550. package/dist/chunk-UH3XSKS5.js +0 -9
  551. package/dist/chunk-UIFUZVCC.js +0 -2
  552. package/dist/chunk-UXKURIVI.js +0 -2
  553. package/dist/chunk-V2RBODHL.js +0 -2
  554. package/dist/chunk-VBKUWB6N.js +0 -2
  555. package/dist/chunk-VBV6ALJE.js +0 -2
  556. package/dist/chunk-VDGFWCQV.js +0 -2
  557. package/dist/chunk-VDSDOEWF.js +0 -2
  558. package/dist/chunk-VZPWVCLN.js +0 -20
  559. package/dist/chunk-WDSFQDPN.js +0 -2
  560. package/dist/chunk-WFA35BGR.js +0 -7
  561. package/dist/chunk-WLMP3OCW.js +0 -2
  562. package/dist/chunk-WSA52GOR.js +0 -2
  563. package/dist/chunk-WYPL7GF7.js +0 -2
  564. package/dist/chunk-X3YVZAKZ.js +0 -5
  565. package/dist/chunk-X6OGVFIT.js +0 -2
  566. package/dist/chunk-XDAUYDFT.js +0 -2
  567. package/dist/chunk-XKXTR6ZI.js +0 -9
  568. package/dist/chunk-Y5DFAW5W.js +0 -4
  569. package/dist/chunk-YSYPDRD5.js +0 -3
  570. package/dist/chunk-ZFVPWH62.js +0 -5
  571. package/dist/chunk-ZGIHTH27.js +0 -2
  572. package/dist/chunk-ZGIQN2SX.js +0 -2
  573. package/dist/chunk-ZHG4WAHR.js +0 -12
  574. package/dist/chunk-ZKB2XUEN.js +0 -4
  575. package/dist/chunk-ZLMXIQLC.js +0 -21
  576. package/dist/chunk-ZMCQIHI4.js +0 -2
  577. package/dist/code-TAVIKWJI.js +0 -2
  578. package/dist/code-result-json-5FEFQCAQ.js +0 -2
  579. package/dist/command-descriptors-7BKH53Y3.js +0 -343
  580. package/dist/dataflow-GFBTVDH3.js +0 -2
  581. package/dist/dependence-slice-GWGQCODG.js +0 -2
  582. package/dist/deps-4QHVDPYA.js +0 -2
  583. package/dist/direct-navigation-4UBC6HNW.js +0 -3
  584. package/dist/entry-map-QCTF4RVY.js +0 -2
  585. package/dist/files-M2UBF5HJ.js +0 -2
  586. package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
  587. package/dist/hierarchy-2UIHRLW4.js +0 -2
  588. package/dist/imports-WIE3YZOB.js +0 -2
  589. package/dist/members-YKD636DA.js +0 -2
  590. package/dist/methods-VDF4IMYG.js +0 -2
  591. package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
  592. package/dist/output-continuation-command-4UMDOOLO.js +0 -3
  593. package/dist/output-pagination-2GME6OPY.js +0 -19
  594. package/dist/project-reindex-XEQTRCV5.js +0 -3
  595. package/dist/queries/anchors.d.ts +0 -123
  596. package/dist/queries/anchors.js +0 -2
  597. package/dist/queries/complexity-hotspots.d.ts +0 -40
  598. package/dist/queries/complexity-hotspots.js +0 -2
  599. package/dist/queries/convergence.d.ts +0 -33
  600. package/dist/queries/convergence.js +0 -2
  601. package/dist/queries/dataflow.d.ts +0 -77
  602. package/dist/queries/dataflow.js +0 -2
  603. package/dist/queries/deep-chains.d.ts +0 -5
  604. package/dist/queries/deep-chains.js +0 -2
  605. package/dist/queries/extract-candidates.d.ts +0 -79
  606. package/dist/queries/extract-candidates.js +0 -2
  607. package/dist/queries/isolated.d.ts +0 -24
  608. package/dist/queries/isolated.js +0 -2
  609. package/dist/queries/plan-context.d.ts +0 -33
  610. package/dist/queries/plan-context.js +0 -2
  611. package/dist/queries/reference-neighborhood.d.ts +0 -4
  612. package/dist/queries/reference-neighborhood.js +0 -2
  613. package/dist/queries/reference-reachability.d.ts +0 -48
  614. package/dist/queries/reference-reachability.js +0 -2
  615. package/dist/queries/self-audit.d.ts +0 -69
  616. package/dist/queries/self-audit.js +0 -2
  617. package/dist/queries/similar-chains.d.ts +0 -48
  618. package/dist/queries/similar-chains.js +0 -2
  619. package/dist/queries/slice.d.ts +0 -4
  620. package/dist/queries/slice.js +0 -2
  621. package/dist/queries/stale-abstractions.d.ts +0 -72
  622. package/dist/queries/stale-abstractions.js +0 -2
  623. package/dist/queries/system-map.d.ts +0 -449
  624. package/dist/queries/system-map.js +0 -2
  625. package/dist/queries/trace.js +0 -2
  626. package/dist/queries/twin-ab.d.ts +0 -66
  627. package/dist/queries/twin-ab.js +0 -2
  628. package/dist/queries/value-flow.d.ts +0 -43
  629. package/dist/queries/value-flow.js +0 -2
  630. package/dist/queries/wrapper-candidates.d.ts +0 -49
  631. package/dist/queries/wrapper-candidates.js +0 -2
  632. package/dist/refs-JNK5CLM7.js +0 -2
  633. package/dist/refs-pagination-6BLRYGMV.js +0 -2
  634. package/dist/slice-PHPVNCWX.js +0 -2
  635. package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
  636. package/dist/stats-OOJ74B32.js +0 -2
  637. package/dist/surface-MQX5MPIV.js +0 -2
  638. package/dist/symbol-resolution-DBLVXLBC.js +0 -2
  639. package/dist/system-JOPKV4OG.js +0 -2
  640. package/dist/trace-I2P2YFH4.js +0 -2
  641. package/dist/value-flow-JJVMF7NP.js +0 -2
  642. package/skills/concrete-plan/SKILL.md +0 -8
  643. package/skills/concrete-plan/agents/openai.yaml +0 -4
  644. package/skills/conductor/SKILL.md +0 -110
  645. package/skills/conductor/agents/openai.yaml +0 -4
  646. package/skills/principal-maintainability-review/SKILL.md +0 -273
  647. package/skills/principal-maintainability-review/agents/openai.yaml +0 -4
  648. package/skills/scip-calibrate/SKILL.md +0 -102
  649. package/skills/scip-calibrate/agents/openai.yaml +0 -4
  650. package/skills/scip-claim-audit/SKILL.md +0 -113
  651. package/skills/scip-claim-audit/agents/openai.yaml +0 -4
  652. package/skills/scip-probe-reachability/SKILL.md +0 -93
  653. package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
  654. package/skills/scip-root-cause/SKILL.md +0 -160
  655. package/skills/scip-root-cause/agents/openai.yaml +0 -4
  656. package/skills/scip-system-compression/SKILL.md +0 -252
  657. package/skills/scip-system-compression/agents/openai.yaml +0 -4
  658. package/skills/scip-system-compression/references/compression-atlas.md +0 -116
  659. package/skills/scip-system-compression/references/compression-patterns.md +0 -87
  660. package/skills/scip-twin-drift/SKILL.md +0 -109
  661. package/skills/scip-twin-drift/agents/openai.yaml +0 -4
@@ -1,4 +0,0 @@
1
- import{b as ye}from"./chunk-FLMTCX5R.js";import{i as I,n as W}from"./chunk-RBAD4GJ2.js";import{E as O}from"./chunk-ZLMXIQLC.js";import{h as pe,k as G}from"./chunk-ETC674NS.js";import{e as me}from"./chunk-KNLQGXVH.js";var Pe=12,Te=20,re=200,oe=800,Ae=.9,Oe=64,De=me("behavior-construct-ranges"),Se={if_statement:"branch",conditional_expression:"branch",ternary_expression:"branch",switch_statement:"branch",switch_expression:"branch",switch_case:"branch",case_statement:"branch",match_statement:"branch",match_expression:"branch",match_arm:"branch",for_statement:"loop",for_in_statement:"loop",for_of_statement:"loop",while_statement:"loop",do_statement:"loop",await_expression:"await",return_statement:"return",throw_statement:"throw",raise_statement:"throw",assignment_expression:"mutation",augmented_assignment_expression:"mutation",assignment:"mutation",pair:"shape",field_initializer:"shape",spread_element:"spread",dictionary_splat:"spread",catch_clause:"catch",except_clause:"catch",finally_clause:"finally"},Z=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],ge=[...Z,"lifecycle"],Ce=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],Ie=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var _e=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function mt(e,n,t,o,r=[],s={}){let a=O(e,n);if(!a)return null;let h=G(e,n),c=Ne(e,n,t,o,r),l=te(e,n,c.startLine,c.endLine),u=l?.startLine??t,p=l?.endLine??o,N=(l?D(a.rootNode,c.startLine,c.endLine):null)??I(a.rootNode,u,p);if(!N)return null;let b=Le(N,h,u,p,r);if(!b||b.lines.length===0||b.lines.some(S=>S.text.length>oe))return null;let m=tt(h,u,p),C=nt(b);if((s.requireSavings??!0)&&C>=m*Ae)return null;let v=Z.filter(S=>b.lines.some(x=>x.signals.includes(S)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:b.constructKind,signature:b.signature,lines:b.lines,signals:v,testCases:ye(n)==="test"?st(h,u,p):[],coverage:{sourceStatements:b.sourceStatements,representedStatements:b.sourceStatements,copiedStatements:b.copiedStatements,omittedStatements:0},rawCharacters:m,outlineCharacters:C,candidateLines:b.sourceStatements,omittedLines:0}}function pt(e,n,t,o,r){if(r.length===0)return[];let s=O(e,n);if(!s)return[];let a=G(e,n),h=Ne(e,n,t,o,r),c=te(e,n,h.startLine,h.endLine),l=c?.startLine??t,u=c?.endLine??o,p=(c?D(s.rootNode,h.startLine,h.endLine):null)??I(s.rootNode,l,u);if(!p)return[];let N=Le(p,a,l,u,r);return N?N.lines.filter(b=>b.text.length<=oe&&b.signals.some(m=>["branch","loop","catch","finally"].includes(m))&&r.some(m=>m>=b.line&&m<=b.endLine)):[]}function yt(e,n,t,o){let r=O(e,n);if(!r)return null;let s=D(r.rootNode,t,o)??I(r.rootNode,t,o);if(!s)return null;let a=[],h=ae(s),c=[];return se(s,s,l=>{if(k.has(l.type)||ke.has(l.type)){$e(a,c,l);return}if(ee.has(l.type)){qe(a,c,l);return}if(z.has(l.type)){ze(a,c,l);return}j.has(l.type)&&je(a,l)}),{facts:Ue(a),terminals:we(h),unsupported:c}}function Ne(e,n,t,o,r=[]){let s=r.filter(u=>u>=t&&u<=o),a=De.get(e,n,pe(e,n)??"",()=>new Map),h=`${t}:${o}:${s.join(",")}`,c=a.get(h);if(c)return a.delete(h),a.set(h,c),{startLine:c[0],endLine:c[1]};let l=Me(e,n,t,o,s);if(a.set(h,[l.startLine,l.endLine]),a.size>Oe){let u=a.keys().next().value;u!==void 0&&a.delete(u)}return l}function Me(e,n,t,o,r){let s=O(e,n),a=[];if(r.length>0&&s){let u=[],p=r[0],N=p;for(let m of r)p=Math.min(p,m),N=Math.max(N,m);Ee(s.rootNode,p,N,m=>{Ve(m)&&m.startPosition.row>=t&&m.endPosition.row<=o&&r.every(C=>m.startPosition.row<=C&&m.endPosition.row>=C)&&u.push(m),P.has(m.type)&&m.startPosition.row>=t&&m.endPosition.row<=o&&r.every(C=>m.startPosition.row<=C&&m.endPosition.row>=C)&&a.push(m)});let b=u.sort((m,C)=>m.endPosition.row-m.startPosition.row-(C.endPosition.row-C.startPosition.row)||m.startPosition.row-C.startPosition.row)[0];if(b)return{startLine:b.startPosition.row,endLine:b.endPosition.row}}let h=te(e,n,t,o);if(h)return{startLine:h.startLine,endLine:h.endLine};if(r.length===0)return{startLine:t,endLine:o};let c=(W(e,n)?.callables??[]).filter(u=>u.startLine>=t&&u.endLine<=o&&r.every(p=>u.startLine<=p&&u.endLine>=p)).sort((u,p)=>u.endLine-u.startLine-(p.endLine-p.startLine)||u.startLine-p.startLine)[0];if(!s)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:t,endLine:o};let l=a.sort((u,p)=>u.endPosition.row-u.startPosition.row-(p.endPosition.row-p.startPosition.row)||u.startPosition.row-p.startPosition.row)[0];return l?{startLine:l.startPosition.row,endLine:l.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:t,endLine:o}}function bt(e,n,t,o,r={}){if(o-t+1<(r.minimumBodyLines??Te))return null;let a=Re(e,n,t,o,[],!1);if(!a)return null;let h=a.candidates.map(S=>({...S,signals:S.signals.filter(x=>x!=="anchor"&&x!=="signature")})).filter(S=>S.signals.length>0);if(h.length===0)return null;let c=it(h),l=h.filter(S=>S.text.length<=re);if(l.length===0)return null;let u=Ce.filter(S=>(c[S]??0)>0),p=u.filter(S=>S!=="await"),N=a.shapes.reduce((S,x)=>S+x.fields.length,0);if(p.length===0&&!((c.await??0)>0&&N>0)&&N<3)return null;let b=at(l,c),m=new Map;for(let S of u){let x=b.find(f=>f.signals.includes(S));x&&m.set(x.line,x)}if(m.size===0){let S=b.find(x=>x.signals.includes("branch"));S&&m.set(S.line,S)}let C=Math.min(10,Math.max(1,r.maxLines??m.size)),v=new Map;for(let S of m.values()){if(v.size>=C)break;v.set(S.line,S)}return v.size>=h.length&&a.shapes.length===0?null:{owner:a.callable?.name??null,startLine:t,endLine:o,lines:[...v.values()].sort((S,x)=>S.line-x.line),shapes:a.shapes,signalCounts:c,candidateLines:h.length,omittedLines:h.length-v.size}}function St(e,n,t,o){let r=Re(e,n,t,o,[],!1);return r?new Map(r.candidates.map(s=>[s.line,s.signals.filter(a=>a!=="lifecycle")])):new Map}var P=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),B=new Set(["block","body","compound_statement","declaration_list","statement_block"]),k=new Set(["if_expression","if_statement","unless","unless_statement"]),ke=new Set(["conditional_expression","ternary_expression"]),ee=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),z=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),ve=new Set(["case_statement","match_arm","switch_case","switch_default"]),j=new Set(["try_expression","try_statement"]),X=new Set(["catch_clause","except_clause","rescue"]),$=new Set(["ensure","finally_clause"]),Y=new Set(["else","else_clause"]),xe=new Set(["raise_statement","return_statement","throw_statement"]),Ye=new Set(["block_comment","comment","line_comment"]);function $e(e,n,t){let o=t.childForFieldName("condition")??le(t),r=t.childForFieldName("consequence")??t.childForFieldName("body")??t.namedChildren.find(c=>B.has(c.type)),s=t.childForFieldName("alternative")??t.namedChildren.find(c=>Y.has(c.type));if(!o||!r){n.push(ce(t,"conditional-fields-unresolved"));return}let a=F(o,"predicate",o.text),h=F(r,be(r),"consequence");if(E(e,a,h,"predicate-consequence",{branchRole:"consequence"}),J(e,a,r,"consequence"),s){let c=F(s,be(s),"alternative");E(e,a,c,"predicate-alternative",{branchRole:"alternative"}),J(e,a,s,"alternative");return}E(e,a,ie(a,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function qe(e,n,t){let o=t.childForFieldName("body")??t.namedChildren.find(a=>B.has(a.type));if(!o){n.push(ce(t,"loop-body-unresolved"));return}let r=t.childForFieldName("condition"),s=F(r??t,"predicate",r?.text??R(t,o));E(e,s,F(o,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),J(e,s,o,"iteration"),E(e,s,ie(s,"loop exits"),"loop-exit",{branchRole:"exit"})}function ze(e,n,t){let o=t.childForFieldName("body")??t.namedChildren.find(c=>B.has(c.type)),r=t.childForFieldName("value")??t.childForFieldName("condition")??t.childForFieldName("subject")??le(t),s=Ke(o??t);if(!r||s.length===0){n.push(ce(t,"switch-cases-unresolved"));return}let a=F(r,"predicate",r.text),h=!1;for(let c of s){let l=We(c);h||=l;let u=R(c,c.namedChildren.find(p=>Q(p)));E(e,a,F(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),J(e,a,c,l?"default":"case")}h||E(e,a,ie(a,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function je(e,n){let t=F(n,"scope","try");for(let o of Ge(n)){let r=$.has(o.type),s=F(o,"handler",r?"finally":R(o,U(o)));E(e,t,s,r?"finally-cleanup":"exception-handler",{branchRole:r?"finally":"catch"}),He(e,s,o,r?"finally":"catch")}}function He(e,n,t,o){for(let r of ae(t)){let s=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";E(e,n,r,s==="throw"?"handler-throw":"handler-return",{branchRole:o,terminalKind:s})}}function J(e,n,t,o){for(let r of ae(t)){let s=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";E(e,n,r,s==="throw"?"predicate-throw":"predicate-return",{branchRole:o,terminalKind:s})}}function E(e,n,t,o,r){e.push({controller:n,outcome:t,subtype:o,attributes:r})}function F(e,n,t){return{kind:n,label:q(t).slice(0,oe),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function ie(e,n){return{...e,kind:"outcome",label:n,implicit:!0}}function be(e){return xe.has(e.type)?"terminal":"outcome"}function ae(e){let n=[];return se(e,e,t=>{xe.has(t.type)&&n.push(F(t,"terminal",t.text))}),we(n)}function se(e,n,t){t(n);for(let o of n.namedChildren)o!==e&&P.has(o.type)||se(e,o,t)}function Ke(e){let n=[],t=o=>{for(let r of o.namedChildren)z.has(r.type)||(ve.has(r.type)?n.push(r):t(r))};return t(e),n}function Ge(e){let n=[],t=o=>{for(let r of o.namedChildren)j.has(r.type)||(X.has(r.type)||$.has(r.type)?n.push(r):P.has(r.type)||t(r))};return t(e),n}function We(e){let n=R(e,e.namedChildren.find(t=>Q(t))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(n)}function ce(e,n){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:n}}function Ue(e){let n=new Map;for(let t of e)n.set(`${t.controller.startLine}\0${t.controller.endLine}\0${t.outcome.startLine}\0${t.outcome.endLine}\0${t.subtype}\0${t.outcome.label}`,t);return[...n.values()]}function we(e){let n=new Map;for(let t of e)n.set(`${t.startLine}\0${t.endLine}\0${t.kind}\0${t.label}`,t);return[...n.values()]}function Ve(e){return P.has(e.type)||ee.has(e.type)||z.has(e.type)||j.has(e.type)||X.has(e.type)||$.has(e.type)}function Le(e,n,t,o,r){let a=D(e,t,o)??e,h=U(a),c=[],l=0,u=0,p=(i,d,y,g,w=!1,A=!0)=>{let K=w?y.trim():q(y);if(!K)return;let T=Math.max(t,i.startPosition.row),de=Math.min(o,i.endPosition.row);c.push({line:T,endLine:Math.max(T,de),depth:d,signals:Z.filter(he=>g.includes(he)||he==="anchor"&&r.some(fe=>fe>=T&&fe<=de)),text:K,copied:w}),A&&(l+=1,w&&(u+=1))},N=(i,d)=>{for(let y of i.namedChildren)_(y,d)},b=(i,d)=>{if(k.has(i.type)){m(i,d,"else if");return}if(Y.has(i.type)){let y=i.namedChildren.find(w=>k.has(w.type));if(y){m(y,d,"else if");return}p(i,d,"else",["branch"],!1,!1);let g=U(i)??i.namedChildren.find(w=>B.has(w.type));if(g)_(g,d+1);else for(let w of i.namedChildren)_(w,d+1);return}p(i,d,"else",["branch"],!1,!1),_(i,d+1)},m=(i,d,y=i.type.startsWith("unless")?"unless":"if")=>{let g=i.childForFieldName("condition")??le(i),w=i.childForFieldName("consequence")??i.childForFieldName("body")??i.namedChildren.find(T=>B.has(T.type)),A=i.childForFieldName("alternative")??i.namedChildren.find(T=>Y.has(T.type)),K=g?g.text:R(i,w);p(i,d,`${y} ${Ze(K)}`,M(g,["branch"])),w&&_(w,d+1),A&&b(A,d)},C=(i,d)=>{let y=i.childForFieldName("body")??i.namedChildren.find(g=>B.has(g.type));p(i,d,R(i,y),M(i,["loop"])),y&&_(y,d+1)},v=(i,d)=>{let y=i.childForFieldName("body")??i.namedChildren.find(g=>B.has(g.type));p(i,d,R(i,y),M(i,["branch"])),y&&_(y,d+1)},S=(i,d)=>{let y=i.namedChildren.find(g=>Q(g));p(i,d,R(i,y),["branch"],!1,!1);for(let g of i.namedChildren)(g===y||Q(g))&&_(g,d+1)},x=(i,d)=>{p(i,d,"try",[],!1);for(let y of i.namedChildren)B.has(y.type)?_(y,d+1):(X.has(y.type)||$.has(y.type))&&_(y,d)},f=(i,d,y)=>{let g=i.childForFieldName("body")??i.namedChildren.find(A=>B.has(A.type)),w=y==="finally"?"finally":R(i,g);p(i,d,w,[y],!1,!1),g&&_(g,d+1)},L=(i,d)=>{let y=U(i);p(i,d,R(i,y),M(i,["binding"])),y&&_(y,d+1)},_=(i,d)=>{if(i.startPosition.row>o||i.endPosition.row<t||Ye.has(i.type)||i.type==="empty_statement")return;if(B.has(i.type)){N(i,d);return}if(k.has(i.type)){m(i,d);return}if(ee.has(i.type)){C(i,d);return}if(z.has(i.type)){v(i,d);return}if(ve.has(i.type)){S(i,d);return}if(j.has(i.type)){x(i,d);return}if(X.has(i.type)){f(i,d,"catch");return}if($.has(i.type)){f(i,d,"finally");return}if(Y.has(i.type)){b(i,d);return}if(P.has(i.type)){L(i,d);return}let g=!Be(i)||et(i);p(i,d,i.text,M(i),g)};return _(h&&h!==a?h:a,0),l===0?null:{constructKind:Qe(a),signature:Je(a,h,n,t),lines:c,sourceStatements:l,copiedStatements:u}}function D(e,n,t){let o=e.namedChildren.filter(r=>r.startPosition.row<=n&&r.endPosition.row>=t);for(let r of o.sort(Xe)){let s=D(r,n,t);if(s)return s}return P.has(e.type)&&e.startPosition.row<=n&&e.endPosition.row>=t?e:null}function Xe(e,n){return e.endPosition.row-e.startPosition.row-(n.endPosition.row-n.startPosition.row)||e.startPosition.row-n.startPosition.row}function U(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(n=>B.has(n.type))??null}function Je(e,n,t,o){let r=R(e,n);return r||(t[o]??e.text).trim()}function Qe(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?ne(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?ne(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?ne(e,P)?"nested function":"module function":"source construct"}function ne(e,n){let t=e.parent;for(;t;){if(n.has(t.type))return!0;t=t.parent}return!1}function le(e){return e.namedChildren.find(n=>!B.has(n.type)&&!Y.has(n.type))??null}function R(e,n){if(!n)return q(e.text);let t=Math.max(0,n.startIndex-e.startIndex);return q(e.text.slice(0,t)).replace(/[:{]\s*$/u,"").trim()}function Ze(e){let n=q(e);return n.startsWith("(")&&n.endsWith(")")?n.slice(1,-1).trim():n}function q(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function M(e,n=[]){let t=new Set(n);return e&&H(e,o=>{let r=Se[o.type];r&&t.add(r),o.type==="call_expression"&&(t.add("call"),Fe(o)&&t.add("shape")),ue.has(o.type)&&t.add("binding")}),Z.filter(o=>t.has(o))}function et(e){let n=!1;return H(e,t=>{n||!t.text.includes(`
2
- `)||/(?:string|template|heredoc|raw_string)/u.test(t.type)&&(n=!0)}),n}function Q(e){return B.has(e.type)||k.has(e.type)||ee.has(e.type)||z.has(e.type)||j.has(e.type)||P.has(e.type)||Be(e)}function Be(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||ue.has(e.type)}function tt(e,n,t){let o=0;for(let r=n;r<=t;r+=1)o+=(e[r]?.length??0)+10;return o}function nt(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((n,t)=>n+t.text.length+t.depth*2+10,0)}function Re(e,n,t,o,r,s){let a=O(e,n);if(!a)return null;let h=G(e,n),c=te(e,n,t,o),l=s?c?.startLine??t:t,u=s?c?.endLine??o:o,N=(c?.startLine===l&&c.endLine===u?D(a.rootNode,l,u):null)??I(a.rootNode,l,u);if(!N)return null;let b=new Map,m=new Map,C=new Map,v=(f,L)=>{if(f<l||f>u)return;let _=b.get(f)??new Set;_.add(L),b.set(f,_)};c&&v(c.startLine,"signature");for(let f of r)v(f,"anchor");H(N,f=>{let L=Se[f.type];if(L&&v(f.startPosition.row,L),L==="shape"&&rt(m,f,N,l,u),f.type==="call_expression"){let i=(f.childForFieldName("function")??f.namedChild(0))?.text.split(".").at(-1);if(Fe(f)){v(f.startPosition.row,"shape");let d=V(f.text);d.length<=re&&C.set(f.startPosition.row,d)}if(i&&Ie.has(i)){v(f.startPosition.row,"lifecycle");let d=V(f.text);d.length<=re&&C.set(f.startPosition.row,d)}}ue.has(f.type)&&v(f.startPosition.row,"binding")});let S=W(e,n);for(let f of S?.callSites??[])f.line<l||f.line>u||(v(f.line,"call"),f.calleeLeaf==="catch"&&v(f.line,"catch"));let x=[...b.entries()].sort(([f],[L])=>f-L).map(([f,L])=>({line:f,signals:ge.filter(_=>L.has(_)),text:C.get(f)??V(h[f]??"")})).filter(f=>f.text.length>0||f.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:l,rangeEnd:u,sourceLines:h,candidates:x,shapes:[...m.values()].sort((f,L)=>f.startLine-L.startLine)}}function rt(e,n,t,o,r){if(n.startPosition.row<o||n.endPosition.row>r)return;let s=n.childForFieldName("key")??n.childForFieldName("name")??n.namedChild(0),a=V(s?.text??"");if(!a||a.includes(`
3
- `)||a.length>60)return;let h=ot(n,t);if(h.startPosition.row<o||h.endPosition.row>r)return;let c=`${h.startPosition.row}:${h.endPosition.row}`,l=e.get(c)??{startLine:h.startPosition.row,endLine:h.endPosition.row,fields:[]};l.fields.some(u=>u.name===a&&u.line===n.startPosition.row)||l.fields.push({name:a,line:n.startPosition.row}),e.set(c,l)}function ot(e,n){let t=e.parent;for(;t&&t!==n.parent;){if(_e.has(t.type))return t;if(t===n)break;t=t.parent}return e.parent??e}function te(e,n,t,o){return W(e,n)?.callables.filter(r=>r.startLine<=t&&r.endLine>=o).sort((r,s)=>r.endLine-r.startLine-(s.endLine-s.startLine)||r.startLine-s.startLine)[0]}function H(e,n){n(e);for(let t of e.namedChildren)H(t,n)}function Ee(e,n,t,o){o(e);for(let r of e.namedChildren)r.startPosition.row>n||r.endPosition.row<t||Ee(r,n,t,o)}function V(e){return e.trim().replace(/\s+/gu," ")}function Fe(e){if(e.type!=="call_expression")return!1;let n=e.childForFieldName("arguments")??e.namedChildren.find(o=>o.type==="arguments"||o.type==="argument_list");if(!n)return!1;let t=!1;return H(n,o=>{_e.has(o.type)&&(t=!0)}),t}function it(e){let n={};for(let t of ge){let o=e.filter(r=>r.signals.includes(t)).length;o>0&&(n[t]=o)}return n}function at(e,n){let t=new Map;for(let s of e){let a=s.signals.join(",");t.set(a,(t.get(a)??0)+1)}let o=new Set(Ce),r=s=>{let a=t.get(s.signals.join(","))??1,h=Math.min(...s.signals.map(u=>n[u]??1)),c=s.signals.some(u=>o.has(u))?3:1,l=Math.max(0,s.signals.length-1)*1e3;return c*(1e3/a+1e3/h)+l};return[...e].sort((s,a)=>r(a)-r(s)||a.line-s.line)}var ue=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function st(e,n,t){let o=[],r=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let s=n;s<=t;s+=1){let a=r.exec(e[s]??"")?.[2];if(!(!a||o.includes(a))&&(o.push(a),o.length>=Pe))break}return o}export{mt as a,pt as b,yt as c,Ne as d,bt as e,St as f};
4
- //# sourceMappingURL=chunk-Y5DFAW5W.js.map
@@ -1,3 +0,0 @@
1
- import{a as te}from"./chunk-P5XHIJHI.js";import{A as An,B as Rt,D as bt,E as ht,F as Fn,a as Cn,i as Tn,j as ge,k as Y,l as Be,m as ne,n as re,o as qe,q as gt,r as je,s as We,t as ie,u as ze,v as wn,w as kn,x as Ke,y as En,z as He}from"./chunk-J6GLBBRK.js";import{d as xn}from"./chunk-KK7GPALL.js";import{a as we,b as ke,c as Fe,d as Ne,e as j,o as Pn}from"./chunk-QBQE7ZJ5.js";import{b as vn,e as V,h as Ue,j as Dn,l as Se,v as z,w as ee}from"./chunk-C7C6AKAT.js";import{a as ye,n as Oe,w as In,y as Mn}from"./chunk-RBAD4GJ2.js";import{A as bn,E as hn,a as _e,c as Sn,d as gn,q as yt}from"./chunk-ZLMXIQLC.js";import{c as St,d as me,e as $}from"./chunk-ETC674NS.js";import{A as Le,a as pn,c as dn,d as dt,h as mt,j as Z,s as mn,u as yn,v as L,x as Rn,y as w}from"./chunk-KNLQGXVH.js";import{Ba as un,C as an,Ca as de,D as H,E as Ee,Fa as fn,H as Ae,I as q,J as cn,O as ft,ca as pt,n as pe,q as _,xa as ln}from"./chunk-JZ2A7LDM.js";import{randomUUID as qi}from"crypto";import{existsSync as ji}from"fs";import{dirname as ar}from"path";function Nn(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.available!="boolean"||e.dependencyAvailable!==void 0&&typeof e.dependencyAvailable!="boolean"||e.tsconfigPath!==void 0&&typeof e.tsconfigPath!="string"||e.tsconfigPaths!==void 0&&(!Array.isArray(e.tsconfigPaths)||!e.tsconfigPaths.every(n=>typeof n=="string"))||e.resolvedBinary!==void 0&&typeof e.resolvedBinary!="string"||e.note!==void 0&&typeof e.note!="string")return null;if(e.available===!0){if(e.reason!==void 0)return null}else if(typeof e.reason!="string"||e.reason.length===0)return null;return e}import{performance as x}from"perf_hooks";function F(t,e,n){if(t.has(e))return t.get(e);let r=n();return t.set(e,r),r}import On from"path";import{realpathSync as _n}from"fs";function mi(t,e){return t.getReferences().map(n=>{let r=n.getNode();return $e(r,e)})}function yi(t){let e=t;return typeof e.findReferences=="function"?e.findReferences():[]}function Un(t,e,n,r){let i=[];for(let s of yi(t))for(let o of mi(s,r))o.file===e.relativePath&&o.line>=e.startLine&&o.line<=e.endLine||i.push(o);for(let s of n)i.push(s);return se(i)}function Bn(t,e,n,r){let i=[],s=n?.getStart();for(let o of t.getReferences()){let a=o.getNode();oe(r,a.getSourceFile().getFilePath())===e&&(s!==void 0&&a.getStart()===s||i.push({location:$e(a,r),node:a}))}return i}function $e(t,e){let n=t.getSourceFile(),r=n.getLineAndColumnAtPos(t.getStart());return{file:oe(e,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function qn(t,e,n){let r=t.getSourceFile(),i=Mt(r,t),s=t.getText(),o=new RegExp(`\\b${ye(s)}\\b`,"g"),a=r.getFullText().split(`
2
- `),c=[];for(let f=0;f<a.length;f++){if(f===i)continue;let u=a[f]??"";o.lastIndex=0;let l;for(;(l=o.exec(u))!==null;)c.push({file:e,line:f,column:l.index})}return se(c.filter(f=>oe(n,On.join(n,f.file))===e))}function It(t){for(let e=t;e;e=e.getParent()){let n=e.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function Mt(t,e){return t.getLineAndColumnAtPos(e.getStart()).line-1}function se(t){let e=new Set,n=[];for(let r of t){let i=`${r.file}:${r.line}:${r.column}`;e.has(i)||(e.add(i),n.push(r))}return n}function oe(t,e){let n=t||process.cwd(),r=Ln(n,e);if(r)return r;try{return Ln(_n(n),_n(e))}catch{return null}}function Ln(t,e){let n=On.relative(t,e).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function jn(t,e,n,r){let i=Si(e,r);return i.size===0?new Map:gi(t,n,i)}function Si(t,e){let n=new Map;for(let r of z(t,e)){let i=V(r.symbol)??r.leaf;if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.push(r)}return n}function gi(t,e,n){let r=new Map,i=new Map;return e.forEachDescendant(s=>{for(let o of Ri(t,s)){let a=n.get(o);if(!a)continue;let c=Mt(e,s);for(let f of a){if(c<f.startLine-1||c>f.endLine+1)continue;let u=Math.abs(c-f.startLine),l=i.get(f.symbolId);l!==void 0&&l<=u||(i.set(f.symbolId,u),r.set(f.symbolId,s))}}}),r}function Ri(t,e){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();r(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();r(i)}return t.Node.isIdentifier(e)&&r(e.getText()),n}var bi=dn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Wn(t,e,n,r){let i=xt(t,e),s=vt(i.get(r)??[],n);if(s)return s;let o=[];for(let a of i.values())for(let c of a)((c.leaf||V(c.symbol)||"").includes(r)||c.symbol.includes(r))&&o.push(c);return vt(o,n)}function Dt(t,e,n,r){return vt(xt(t,e).get(r)??[],n)}function zn(t,e){let n=new Map;for(let[r,i]of xt(t,e)){let s=i[0];s&&n.set(r,s)}return n}function xt(t,e){return bi.get(t,e,()=>{let n=new Map;for(let r of z(t,e)){let i=r.leaf||V(r.symbol);if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.push({...r,leaf:i})}for(let r of n.values())r.sort((i,s)=>i.startLine-s.startLine||i.endLine-s.endLine||i.symbolId-s.symbolId);return n})}function vt(t,e){let n=null,r=Number.POSITIVE_INFINITY;for(let i of t){let s=Math.abs(i.startLine-e);(s<r||s===r&&n&&i.startLine<n.startLine)&&(n=i,r=s)}return n}import hi from"path";import{realpathSync as Ii}from"fs";function Hn(t,e){let n=new Map,r=new Map,i=null,s=()=>(i??=_e(t,{extensions:We}),i),o=f=>F(r,f,()=>w("typescript.source-file-index",()=>{let u=new Map;for(let l of f.project.getSourceFiles())Kn(u,l);return{project:f.project,sourceFiles:u}},()=>({tsconfigPath:f.tsconfigPath,indexedDocuments:s().length}))),a=(f,u)=>{let l=o(f),p=l.sourceFiles.get(u)??null;return p||(p=f.project.addSourceFileAtPathIfExists(u)??null,p&&Kn(l.sourceFiles,p)),p?{project:l.project,sourceFile:p}:null},c=f=>ie(f)?F(n,f,()=>{let u=Mi(t.config.projectRoot,f);if(!u)return null;for(let m of e){if(!m.loaded)continue;let d=o(m).sourceFiles.get(u);if(d)return{project:m.project,sourceFile:d}}let l=e.find(m=>m.fileNames?.has(u));if(l)return a(l,u);for(let m of e){if(!m.loaded)continue;let d=a(m,u);if(d)return d}let p=e[0];return p?a(p,u):null}):null;return{sourceFile:f=>c(f)?.sourceFile??null,sourceFileMatch:c,indexedTypeScriptLikeDocuments:s}}function Kn(t,e){let n=Ct(e.getFilePath());t.set(n,e);try{t.set(Ct(Ii(n)),e)}catch(r){if(!de(r))throw r}}function Mi(t,e){try{return Ct(ln(t,e,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!de(n))throw n;return null}}function Ct(t){return hi.resolve(t)}function Tt(t,e){for(let n of t)if(e===n.name||e.startsWith(`${n.name}/`))return n.name;return null}function $n(t){let e=`${t.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as Re}from"fs";import A from"path";var Pt=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function wt(t,e){let r=e?A.dirname(A.join(t,e)):t,i=A.resolve(t);for(;r.startsWith(i);){for(let o of Pt){let a=A.join(r,o);if(Re(a))return a}let s=A.dirname(r);if(s===r)break;r=s}for(let s of Pt){let o=A.join(t,s);if(Re(o))return o}return null}function Ve(t){let e=t.config.projectRoot,n=new Set(vi(e,t.config.semantic?.typescript?.tsconfigs)),r=_e(t,{includeIgnored:!1,extensions:We});for(let i of r){let s=wt(e,i);s&&n.add(A.resolve(s))}if(n.size===0){let i=wt(e);i&&n.add(A.resolve(i))}return[...n].filter(i=>!Vn(e,i)).sort((i,s)=>i.localeCompare(s))}function vi(t,e=[]){let n=new Set;for(let r of e){let i=A.isAbsolute(r)?r:A.join(t,r);Re(i)&&n.add(A.resolve(i))}for(let r of Di(t))for(let i of Pt){let s=A.join(r,i);Re(s)&&n.add(A.resolve(s))}if(n.size===0){let r=wt(t);r&&n.add(A.resolve(r))}return[...n].filter(r=>!Vn(t,r)).sort((r,i)=>r.localeCompare(i))}function Di(t){let e=A.join(t,"package.json");if(!Re(e))return[];let n;try{n=JSON.parse(cn(e,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>gn(t,i))}function Vn(t,e){let n=A.relative(t,e).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var xi=32;function nr(t,e){let n=w("typescript.provider.load",()=>ze());if(!n)return He("ts-morph is not installed");let r=w("typescript.provider.tsconfig-discovery",()=>Ve(t));if(r.length===0)return He("no tsconfig found");try{let i=w("typescript.provider.project-bundles",()=>wn(n,r),()=>({tsconfigs:r.length}));return Ci(t,n,i)}catch(i){return He(i instanceof Error?i.message:String(i),r[0],r)}}function Ci(t,e,n,r={}){return w("typescript.provider.construct",()=>new kt(t,e,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var kt=class{constructor(e,n,r){this.db=e;this.tsMorph=n;this.projects=r;this.workspacePackages=Sn(e.config.projectRoot),this.sourceFiles=Hn(e,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){let e=Ke(this.projects);return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(n=>n.tsconfigPath),projectScope:e?"file-closure":"project",...e?{note:"compiler projects are file-scoped: callees, signatures, and import usage are served per file; references and hierarchies are unavailable"}:{}}}attachBatchFiles(e){if(Ke(this.projects))for(let n of new Set(e.map(r=>r.relativePath)))this.sourceFiles.sourceFile(n)}assertProjectWide(){if(Ke(this.projects))throw new Error(kn)}importUsage(e){return F(this.importUsageCache,e,()=>{let n=this.sourceFiles.sourceFile(e);if(!n)return[];let r=Pi();return w("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,n,r),()=>({file:e,...r}))})}referencesFor(e){return F(this.referencesCache,e.symbolId,()=>{let n=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,n)})}referencesForDefinitions(e,n={}){this.assertProjectWide();let r=new Map,i=L(),s=[];for(let u of e){let l=this.referencesCache.get(u.symbolId);l?r.set(u.symbolId,l):s.push(u)}if(s.length===0)return r;let o=s,a=n.exact?[]:s.filter(u=>!Gn(u));if(a.length>=xi){let u=this.referencesForDefinitionsBySymbolScan(a);for(let l of a){let p=u.get(l.symbolId)??[];this.referencesCache.set(l.symbolId,p),r.set(l.symbolId,p)}if(o=s.filter(l=>Gn(l)),o.length===0)return r}let c=new Map;for(let u of o){let l=c.get(u.relativePath);l?l.push(u):c.set(u.relativePath,[u])}let f=[];for(let[u,l]of c){let p=Qn();w("typescript.references-map.file",()=>{let m=this.definitionNodesForFile(u);for(let d of l){i&&(p.cacheMisses+=1);let y=m.get(d.symbolId)??null;i&&(y?p.nodeHits+=1:p.nodeMisses+=1);try{let S=this.referencesForDefinitionNode(d,y,i?p:void 0);this.referencesCache.set(d.symbolId,S),r.set(d.symbolId,S)}catch{p.preciseSearchFailures+=1,f.push(d)}}},()=>({relativePath:u,definitions:l.length,...Zn(p)}))}if(f.length>0){let u=this.referencesForDefinitionsBySymbolScan(f);for(let l of f){let p=u.get(l.symbolId)??[];this.referencesCache.set(l.symbolId,p),r.set(l.symbolId,p)}}return r}referenceFragmentsForFiles(e){this.assertProjectWide();let n=ee(this.db).filter(s=>ie(s.relativePath)),r=e.filter(s=>this.sourceFiles.sourceFile(s)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return An(n,i,r)}referencesForDefinitionsBySymbolScan(e,n){let r=L(),i=Qn(),s=new Map,o=new Set(e.map(c=>c.symbolId)),a=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)s.set(c.symbolId,[]);return w("typescript.references-map.inverted-scan",()=>{let c=r?x.now():0,f=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let S of e){let g=f.get(S.symbolId)??[];if(g.length>0){let I=s.get(S.symbolId)??[];I.push(...g),s.set(S.symbolId,I)}r&&(i.packageReferenceCount+=g.length)}r&&(i.packageRefsMs+=x.now()-c);let u=new Map,l=new Map,p=this.hierarchyTargetsForDefinitions(e),m=new Set(e.map(S=>S.leaf).filter(Boolean)),d=r?x.now():0;for(let S of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(S))continue;let g=this.sourceFiles.sourceFile(S);g&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,S,o,a,p,m,u,l,s,r?i:void 0))}r&&(i.scanMs+=x.now()-d);let y=r?x.now():0;this.addHierarchyMemberReferences(e,s,r?i:void 0),r&&(i.hierarchyMs+=x.now()-y);for(let[S,g]of s){let I=se(g);s.set(S,I),r&&(i.referenceCount+=I.length)}},()=>({definitions:e.length,...Zn(i)})),s}addReferencesFromSourceFileScan(e,n,r,i,s,o,a,c,f,u){let l=this.compilerCheckerForSourceFile(e),p=e.compilerNode,m=Ei(e),d=y=>{if(this.tsMorph.ts.isIdentifier(y)){if(u&&(u.identifiers+=1),!o.has(y.text)&&!m.has(y.text)){this.tsMorph.ts.forEachChild(y,d);return}let S=this.compilerReferenceSymbol(l,y,u);if(S){let g;a.has(S)?g=a.get(S)??null:(g=this.referenceDefinitionFromCompilerSymbol(S),a.set(S,g)),u&&(g?u.targetHits+=1:u.targetMisses+=1);let I=F(c,S,()=>this.compilerSymbolKeys(S)),k=null,h=null,v=g&&r.has(g.symbolId)?i.get(g.symbolId):void 0;if(v&&(k=be(p,y),!Jn(v,n,k))){let C=p.getLineAndCharacterOfPosition(y.getStart(p));h={file:n,line:C.line,column:C.character};let D=f.get(v.symbolId)??[];D.push(h),f.set(v.symbolId,D),u&&(u.requestedHits+=1)}for(let C of I)for(let D of s.get(C)?.values()??[]){if(k??=be(p,y),Jn(D,n,k))continue;if(!h){let R=p.getLineAndCharacterOfPosition(y.getStart(p));h={file:n,line:R.line,column:R.character}}let b=f.get(D.symbolId)??[];b.push(h),f.set(D.symbolId,b),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(y,d)};d(p)}hierarchyTargetsMemo=null;hierarchyTargetsForDefinitions(e){let n=_i(e);if(this.hierarchyTargetsMemo?.key===n)return this.hierarchyTargetsMemo.targets;let r=Z(this.db),i=`definitions:${n}`,s=!1,o=w("typescript.references-map.hierarchy-targets",()=>{if(r){let c=Xn.read(this.db,i,r);if(c&&c.projectRoot===this.db.config.projectRoot)return s=!0,Ni(c,e)}let a=this.computeHierarchyTargets(e);return r&&Xn.write(this.db,i,r,{version:rr,projectRoot:this.db.config.projectRoot,entries:[...a].map(([c,f])=>[c,[...f.values()].map(u=>u.symbol)])}),a},()=>({definitions:e.length,hit:s}));return this.hierarchyTargetsMemo={key:n,targets:o},o}computeHierarchyTargets(e){let n=new Map;for(let r of e){let i=this.nodeForDefinition(r),s=i?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let o=s.parent;if(!this.isHierarchyContainer(o))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(s.name);if(c)for(let f of this.hierarchyMemberSymbols(a,o,c))for(let u of this.compilerSymbolKeys(f)){let l=n.get(u)??new Map;l.set(r.symbolId,r),n.set(u,l)}}return n}hierarchyMemberSymbols(e,n,r){let i=new Set,s=new Set,o=(a,c,f)=>{if(!s.has(a)){s.add(a),i.add(c);for(let u of f){let l=u.getProperty(r.name);l&&o(u,l,this.hierarchyAncestorTypesForType(e,u))}}};return o(e.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(e,n)),i}addHierarchyMemberReferences(e,n,r){let i=new Map;for(let s of e){let o=this.nodeForDefinition(s),a=o?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let f=this.compilerCheckerForSourceFile(o.getSourceFile()),u=f.getSymbolAtLocation(a.name);if(!u)continue;let l=a.getSourceFile(),p=l.getLineAndCharacterOfPosition(a.name.getStart(l)),m={definition:s,location:{file:s.relativePath,line:p.line,column:p.character}},d=n.get(s.symbolId)??[];for(let S of this.hierarchyMemberSymbols(f,c,u))if(S!==u)for(let g of this.compilerSymbolLocations(S))d.push(g),r&&(r.hierarchyReferences+=1);n.set(s.symbolId,d);let y=this.hierarchyRootMemberSymbols(f,c,u);for(let S of y){let g=i.get(S)??new Map;g.set(s.symbolId,m),i.set(S,g)}r&&(r.hierarchyDefinitions+=1)}for(let s of i.values())if(!(s.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:o}of s.values()){let a=n.get(o.symbolId)??[];for(let c of s.values())c.definition.symbolId!==o.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(o.symbolId,a)}}}hierarchyRootMemberSymbols(e,n,r){let i=new Set,s=new Set,o=(a,c,f)=>{if(s.has(a))return;s.add(a);let u=!1;for(let l of f){let p=l.getProperty(r.name);p&&(u=!0,o(l,p,this.hierarchyAncestorTypesForType(e,l)))}if(!u)for(let l of this.compilerSymbolKeys(c))i.add(l)};return o(e.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(e,n)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${e.name}`})}compilerSymbolLocations(e){let n=[];for(let r of e.declarations??[]){let i=r.getSourceFile(),s=oe(this.db.config.projectRoot,i.fileName);if(!s)continue;let o=r.name,a=i.getLineAndCharacterOfPosition((o??r).getStart(i));n.push({file:s,line:a.line,column:a.character})}return n}baseTypes(e,n){try{return e.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(e,n){let r=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let s of i.types)r.add(e.getTypeAtLocation(s));return[...r]}hierarchyAncestorTypesForType(e,n){let r=new Set(this.baseTypes(e,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let s of i.heritageClauses??[])for(let o of s.types)r.add(e.getTypeAtLocation(o));return[...r]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,n,r){r&&(r.symbolLookups+=1);let i=e.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return F(this.calleesCache,e.symbolId,()=>F(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let n=new Map;this.attachBatchFiles(e);let r=new Map;for(let i of e){let s=r.get(i.relativePath);s?s.push(i):r.set(i.relativePath,[i])}for(let[i,s]of r){let o=this.fileCalleesCache.get(i),a=new Set(s.map(f=>f.symbolId)),c=o??this.calleeMapForFile(i,a);for(let f of s){let u=c.get(f.symbolId)??[];this.calleesCache.set(f.symbolId,u),n.set(f.symbolId,u)}}return n}calleeCoverageForDefinitions(e){this.attachBatchFiles(e);let n=new Map,r=new Map;for(let i of e){let s=r.get(i.relativePath);s?s.push(i):r.set(i.relativePath,[i]),n.set(i.symbolId,{callSites:0,resolvedInRepository:0,resolvedExternal:0,unresolved:0})}for(let[i,s]of r){let o=this.sourceFiles.sourceFile(i);if(!o)continue;let a=this.compilerCheckerForSourceFile(o),c=o.compilerNode,f=new Map,u=l=>{if(this.tsMorph.ts.isCallExpression(l)||this.tsMorph.ts.isNewExpression(l)||er(this.tsMorph.ts,l)){let p=Yn(s,be(c,l)),m=p?n.get(p.symbolId):void 0;if(m){m.callSites+=1;let d=this.tsMorph.ts.isJsxOpeningElement(l)||this.tsMorph.ts.isJsxSelfClosingElement(l),y=d&&!this.tsMorph.ts.isJsxNamespacedName(l.tagName)?l.tagName:d?null:l.expression,S=y?this.compilerSymbolForExpression(a,y):void 0;if(!S)m.unresolved+=1;else{let g=f.get(S);g===void 0&&(g=this.definitionFromCompilerSymbol(S),f.set(S,g)),g?m.resolvedInRepository+=1:m.resolvedExternal+=1}}}this.tsMorph.ts.forEachChild(l,u)};u(c)}return n}referencesForDefinitionNode(e,n,r){let i=r?x.now():0,s=this.packageImportReferencesForDefinition(e);if(r&&(r.packageRefsMs+=x.now()-i,r.packageReferenceCount+=s.length),!n)return s;let o=r?x.now():0,a=Un(n,e,s,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=x.now()-o,r.referenceCount+=a.length),a}signatureFor(e){return F(this.signatureCache,e.symbolId,()=>{let n=this.nodeForDefinition(e);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(o=>{let a=o.getDeclarations()[0],c=a?o.getTypeAtLocation(a).getText(a):o.getValueDeclaration()?.getType().getText()??"unknown";return tr(c)}),s=r.getReturnType().getText(n);return`(${i.join(",")})=>${tr(s)}`})}importUsageForSourceFile(e,n,r){let i=[],s=new Map;for(let o of n.getImportDeclarations()){r.declarations+=1;let a=yt(this.db,e,o.getModuleSpecifierValue()),c=o.getImportClause()?.isTypeOnly()??!1;for(let f of Et(o)){r.entries+=1;let u=c?null:f.identifier?.getSymbol()?.compilerSymbol??null;!c&&f.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let l={sourcePath:a,entry:f,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(l),c||!f.localName||!u)continue;let p=s.get(f.localName);p?p.push(l):s.set(f.localName,[l])}}return s.size>0&&n.forEachDescendant(o=>{if(o.getKindName()!=="Identifier")return;let a=s.get(o.getText());if(!a||wi(o))return;r.scannedIdentifiers+=1;let c=o.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let f of a)if(f.bindingSymbol===c){f.references.push({location:$e(o,this.db.config.projectRoot),node:o}),r.matchedReferences+=1;break}}}),i.map(o=>o.typeOnlyDeclaration?Ti(e,o.sourcePath,o.entry):o.entry.identifier&&!o.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(e,o.sourcePath,o.entry)):this.valueImportUsageFromLocations(e,o.sourcePath,o.entry,o.references))}valueImportUsageForEntry(e,n,r){let i=r.identifier?r.identifier.findReferences():[],s=[];for(let o of i)for(let a of Bn(o,e,r.identifier,this.db.config.projectRoot))s.push(a);return this.valueImportUsageFromLocations(e,n,r,s)}valueImportUsageFromLocations(e,n,r,i){let s=i.some(c=>!It(c.node)),o=i.some(c=>It(c.node)),a=r.isTypeOnly;return{importer:e,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||o,isValueUsed:s,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let n=new Map,r=new Set;for(let s of e){let o=this.sourceFiles.sourceFile(s);if(o)for(let a of o.getImportDeclarations()){let c=Tt(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let s of e)this.addPackageImportReferencesForDocument(n,i,s);for(let[s,o]of n)n.set(s,se(o));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,n,r);for(let[r,i]of e)e.set(r,se(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let s of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,n,r,s)}addPackageImportReferencesForDeclaration(e,n,r,i){let s=Tt(this.workspacePackages,i.getModuleSpecifierValue());if(!s)return;let o=n.get(s);if(o)for(let a of Et(i)){if(a.kind!=="named"||!a.identifier)continue;let c=o.get(a.importedName);if(!c||c.size===0)continue;let f=qn(a.identifier,r,this.db.config.projectRoot);f.length>0&&Li(e,c,f)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let n=new Map;for(let r of this.workspacePackages){if(!e.has(r.name))continue;let i=new Map;for(let s of $n(r))this.collectPackageExports(r,s,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(e,n,r,i){if(i.has(n))return;i.add(n);let s=this.sourceFiles.sourceFile(n);if(s)for(let o of s.getExportDeclarations()){let a=o.getModuleSpecifierValue(),c=a?yt(this.db,n,a):n;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let f=o.getNamedExports();if(f.length===0){if(o.isNamespaceExport())continue;this.collectPackageExports(e,c,r,i);continue}for(let u of f){let l=u.getNameNode().getText(),p=u.getAliasNode()?.getText()??l,m=this.indexedDefinitionByLeaf(c,l);if(!m)continue;let d=r.get(p);d||(d=new Set,r.set(p,d)),d.add(m.symbolId)}}}indexedDefinitionByLeaf(e,n){return F(this.indexedDefinitionLeafCache,e,()=>zn(this.db,e)).get(n)??null}nodeForDefinition(e){return F(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return F(this.fileDefinitionNodeCache,e,()=>{let n=this.sourceFiles.sourceFile(e);return n?jn(this.tsMorph,this.db,n,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,n,r=!1){let i=e.name,s=n?x.now():0,o=e.declarations??[];n&&(n.declarationsMs+=x.now()-s,n.declarationChecks+=o.length);for(let a of o){let c=n?x.now():0,f=a.getSourceFile(),u=oe(this.db.config.projectRoot,f.fileName),l=f.getLineAndCharacterOfPosition(a.getStart(f)).line;if(n&&(n.declarationLocationMs+=x.now()-c),!u||this.db.isIgnored(u))continue;let p=n?x.now():0,m=this.compilerDeclarationName(a),d=r?Dt(this.db,u,l,i)??(m&&m!==i?Dt(this.db,u,l,m):null):Wn(this.db,u,l,i);if(n&&(n.indexedLookupMs+=x.now()-p),d)return{symbolId:d.symbolId,symbol:d.symbol,file:d.relativePath,line:d.startLine}}return null}compilerDeclarationName(e){let n=e.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(e,n){let r=L(),i=0,s=0,o=0,a=0,c=0,f=0,u=0,l=0,p=r?Ai():void 0;return w("typescript.callee-map.file",()=>{let m=r?x.now():0,d=this.sourceFiles.sourceFile(e);if(r&&(c=Math.round(x.now()-m)),!d)return new Map;let y=r?x.now():0,S=z(this.db,e).sort((b,R)=>b.startLine-R.startLine||R.endLine-b.endLine);if(r&&(f=Math.round(x.now()-y)),i=S.length,S.length===0)return new Map;let g=new Map,I=r?x.now():0,k=this.compilerCheckerForSourceFile(d),h=d.compilerNode;r&&(u=Math.round(x.now()-I));let v=new Map,C=b=>{if(this.tsMorph.ts.isCallExpression(b)||this.tsMorph.ts.isNewExpression(b)||er(this.tsMorph.ts,b)){r&&(s+=1);let R=this.semanticCalleeForCallNode(k,h,S,b,v,n,p);R&&(r&&(o+=1),ki(g,R.callerId,R.target))}this.tsMorph.ts.forEachChild(b,C)},D=r?x.now():0;C(h),r&&(l=Math.round(x.now()-D));for(let[b,R]of g)g.set(b,Oi(R));return a=g.size,g},()=>({relativePath:e,definitions:i,callNodes:s,resolvedCallees:o,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:f,checkerLookupMs:u,traversalMs:l,...p?Fi(p):{}}))}semanticCalleeForCallNode(e,n,r,i,s,o,a){let c=a?x.now():0,f=Yn(r,be(n,i));if(a&&(a.callerLookupMs+=x.now()-c),!f)return null;if(o&&!o.has(f.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=this.tsMorph.ts.isJsxOpeningElement(i)||this.tsMorph.ts.isJsxSelfClosingElement(i);if(u&&this.tsMorph.ts.isJsxNamespacedName(i.tagName))return null;let l=u?i.tagName:i.expression,p=this.compilerSymbolForExpression(e,l,a),m=null;if(p)if(a&&(a.targetSymbolHits+=1),s.has(p))a&&(a.compilerSymbolCacheHits+=1),m=s.get(p)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let d=a?x.now():0;m=this.definitionFromCompilerSymbol(p,a),a&&(a.targetLookupMs+=x.now()-d),s.set(p,m)}else a&&(a.targetMisses+=1);return m?{callerId:f.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line,callsiteLine:be(n,i),...u?{kind:"jsx-render"}:{}}}:null}compilerSymbolForExpression(e,n,r){let i=r?x.now():0,s=e.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=x.now()-i),s){if((s.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return s;try{return e.getAliasedSymbol(s)}catch{return s}}r&&(r.typeFallbacks+=1);let o=r?x.now():0,a=e.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=x.now()-o),a}compilerCheckerForSourceFile(e){let n=e.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function Et(t){let e=[],n=t.getDefaultImport();n&&e.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:t.getImportClause()?.isTypeOnly()??!1});let r=t.getNamespaceImport();r&&e.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:t.getImportClause()?.isTypeOnly()??!1});for(let i of t.getNamedImports()){let s=i.getNameNode(),a=i.getAliasNode()??(s.getKindName()==="Identifier"?s:null);e.push({identifier:a,importedName:s.getText(),localName:a?.getText()??s.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(t.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Ti(t,e,n){return{importer:t,sourcePath:e,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Pi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function wi(t){for(let e=t;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function ki(t,e,n){let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}function Ei(t){let e=new Set;for(let n of t.getImportDeclarations())for(let r of Et(n))r.localName&&e.add(r.localName);return e}function Yn(t,e){let n=null;for(let r of t)e<r.startLine||e>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function be(t,e){return t.getLineAndCharacterOfPosition(e.getStart(t)).line}function Jn(t,e,n){return e===t.relativePath&&n>=t.startLine&&n<=t.endLine}function Gn(t){return t.symbol.includes("#")?Ue(t.symbol)==="type"&&t.relativePath.endsWith(".d.ts"):!1}function Ai(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Fi(t){return{...t,callerLookupMs:Math.round(t.callerLookupMs),expressionSymbolMs:Math.round(t.expressionSymbolMs),typeSymbolMs:Math.round(t.typeSymbolMs),targetLookupMs:Math.round(t.targetLookupMs),declarationsMs:Math.round(t.declarationsMs),declarationLocationMs:Math.round(t.declarationLocationMs),indexedLookupMs:Math.round(t.indexedLookupMs)}}function Qn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}var rr=1,Xn=me({kind:"typescript-hierarchy-targets",invalidation:$("typescript-hierarchy-targets"),serialize:t=>JSON.stringify(t),deserialize:t=>{try{let e=JSON.parse(t);return e.version!==rr||typeof e.projectRoot!="string"||!Array.isArray(e.entries)?null:e}catch{return null}}});function Ni(t,e){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map;for(let[i,s]of t.entries){let o=new Map;for(let a of s){let c=n.get(a);c&&o.set(c.symbolId,c)}o.size>0&&r.set(i,o)}return r}function _i(t){let e=2166136261;for(let n of t)e^=n.symbolId,e=Math.imul(e,16777619)>>>0;return`${t.length}:${e.toString(16)}`}function Zn(t){return{...t,scanMs:Math.round(t.scanMs),packageRefsMs:Math.round(t.packageRefsMs),semanticRefsMs:Math.round(t.semanticRefsMs),hierarchyMs:Math.round(t.hierarchyMs)}}function Li(t,e,n){for(let r of e){let i=t.get(r)??[];i.push(...n),t.set(r,i)}}function er(t,e){if(!t.isJsxOpeningElement(e)&&!t.isJsxSelfClosingElement(e))return!1;let n=e.tagName;return t.isPropertyAccessExpression(n)?!0:t.isIdentifier(n)?/^[A-Z]/.test(n.text):!1}function Oi(t){let e=new Set,n=[];for(let r of t){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;e.has(i)||(e.add(i),n.push(r))}return n}function tr(t){return t.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as Ui}from"path";var Ye=3;var Bi="typescript-semantic";function ir(t){let e=Ui(t,Bi),n=Be(e);return{...n,requestDir:n.legacyRequestDir}}var Wi=12e4,zi=5;function cr(t,e,n={}){let r=n.requester??new Ft(t,n),i=null,s=null,o=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=null,c=()=>(i??=nr(t,e),i),f=(d,y,S)=>(o=!0,Yi(t)?y():(a=d instanceof Error?d.message:String(d),console.error(`TypeScript semantic service request failed (${a}); semantic enrichment is disabled for the rest of this run because the index is too large for an in-process compiler.`),S())),u=(d,y,S,g=S)=>{if(a!==null)return g();if(o)return S();try{return y(r.request(d))}catch(I){return sr(I)?g():f(I,S,g)}},l=(d,y,S,g)=>{if(a!==null)return new Map;if(o)return g();let I=k=>{try{return S(r.request(y(k)))}catch(h){if(!Ki(h))throw h;let v=Hi(k);if(!v)throw h;return new Map([...I(v[0]),...I(v[1])])}};try{return I(d)}catch(k){return sr(k)?new Map:f(k,g,()=>new Map)}},p=(d,y)=>l(d,S=>({kind:"references",definitions:[...S],...y?.exact?{exact:!0}:{}}),S=>At(S),()=>c().referencesForDefinitions?.(d,y)??new Map(d.map(S=>[S.symbolId,c().referencesFor(S)]))),m=d=>l(d,y=>({kind:"callees",definitions:[...y]}),y=>At(y),()=>c().calleesForDefinitions?.(d)??new Map(d.map(y=>[y.symbolId,c().calleesFor(y)])));return{language:"typescript",availability:()=>(s??=u({kind:"availability"},Xi,()=>c().availability(),()=>({available:!1,reason:`TypeScript semantic service declined: ${a??"unknown"}`})),s),importUsage:d=>u({kind:"import-usage",file:d},y=>y,()=>c().importUsage(d),()=>[]),referencesFor:d=>p([d]).get(d.symbolId)??[],referencesForDefinitions:p,referenceFragmentsForFiles:d=>u({kind:"reference-fragments",files:[...d]},y=>Qi(y),()=>c().referenceFragmentsForFiles?.(d)??new Map,()=>new Map),calleesFor:d=>m([d]).get(d.symbolId)??[],calleesForDefinitions:m,calleeCoverageForDefinitions:d=>l(d,y=>({kind:"callee-coverage",definitions:[...y]}),y=>At(y),()=>c().calleeCoverageForDefinitions?.(d)??new Map),signatureFor:d=>u({kind:"signature",definition:d},Zi,()=>c().signatureFor(d),()=>null),dispose:()=>i?.dispose?.()}}function Ki(t){let e=t instanceof Error?t.message:String(t);return/memory limit|heap out of memory|worker terminated|worker failed/iu.test(e)}function Hi(t){let e=[...new Set(t.map(r=>r.relativePath))].sort();if(e.length<2)return null;let n=new Set(e.slice(0,Math.ceil(e.length/2)));return[t.filter(r=>n.has(r.relativePath)),t.filter(r=>!n.has(r.relativePath))]}function sr(t){let e=t instanceof Error?t.message:String(t);return e.includes("invalid mailbox request")||e.includes("Unhandled TypeScript semantic request")||e.includes("compiler project is file-scoped")}var $i=2500,Vi=25e3,or=new WeakMap;function Yi(t){let e=or.get(t);if(e!==void 0)return e;let n=Ji(t);return or.set(t,n),n}function Ji(t){try{let e=t.get("SELECT (SELECT count(*) FROM documents) AS documents, (SELECT count(*) FROM global_symbols) AS symbols");return!e||e.documents<$i&&e.symbols<Vi}catch{return!0}}var Ft=class{constructor(e,n={}){this.db=e;this.runtime=n.runtime??ur,this.timeoutMs=n.timeoutMs??es(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=ar(e.config.dbPath),this.projectRoot=pt(e.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(e){let n=gt(this.cacheDir),r=ir(this.cacheDir),i=je(n.statePath);if(!Nt(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let s=this.db.generation.identity;if(!s)throw new Error("Published TypeScript generation identity is unavailable.");let o=this.runtime.now(),a=o+this.timeoutMs,c=(this.runtime.monotonicNow??j)()+this.timeoutMs,f=Rn(),u=ne("typescript-semantic-v3",{generation:s,profileEnvironment:f,request:e}),l=re(u),p=qe(r,{mailboxVersion:Y,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ye,id:l,generation:s,profileEnvironment:f,request:e},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??j)()<=c;){if(ji(p.responsePath))return Gi(q(p.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),l,s,u);let m=je(n.statePath);if(!Nt(m,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(zi)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function lr(t){if(process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return!1;try{let e=je(gt(ar(t.config.dbPath)).statePath);return Nt(e,pt(t.config.projectRoot),ur)}catch{return!1}}function Nt(t,e,n){let r=t?.processIdentity?n.readProcessIdentity?.(t.pid):null;return t!==null&&t.projectRoot===e&&t.typescriptSemantic?.protocolVersion===Ye&&n.isProcessAlive(t.pid)&&(!t.processIdentity||r!=null&&ke(t.processIdentity,r))}function Gi(t,e,n,r){let i=JSON.parse(t);if(i.protocolVersion!==Ye||i.id!==e||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function At(t){if(!Array.isArray(t))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(t)}function Qi(t){if(!Array.isArray(t))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(t)}function Xi(t){let e=Nn(t);if(!e)throw new Error("TypeScript semantic service wrote invalid availability.");return e}function Zi(t){if(t!==null&&typeof t!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return t}function es(){let t=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(t)&&t>0?t:Wi}var ur={now:Date.now,monotonicNow:j,randomId:qi,sleep(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)},isProcessAlive:Ne,readProcessIdentity:Fe};function fr(t){let e=new Map,n=ns(t),r=new Map;return i=>{let s=ts(i),o=r.get(s);if(o!==void 0)return o;if(!n.has(i.file))return r.set(s,i.symbol),i.symbol;let a=e.get(i.file);a||(a=rs(z(t,i.file)),e.set(i.file,a));let c=is(a,i);return r.set(s,c),c}}function ts(t){return`${t.file}\0${t.symbol}\0${t.line}`}function ns(t){return new Set(t.all("SELECT relative_path FROM documents").map(e=>e.relative_path))}function rs(t){let e=new Map,n=new Map;for(let r of t){let i=e.get(r.leaf);i?i.push(r):e.set(r.leaf,[r]);let s=n.get(r.startLine);s?s.push(r):n.set(r.startLine,[r])}return{definitions:t,byLeaf:e,byStartLine:n}}function is(t,e){if(t.definitions.length===0)return e.symbol;let n=as(e.symbol),r=ss(t.byLeaf,n),i=os(r,e.line);if(i)return i.symbol;let s=t.byStartLine.get(e.line)??[];return s.length===1?s[0].symbol:e.symbol}function ss(t,e){let n=[],r=new Set;for(let i of e)for(let s of t.get(i)??[])r.has(s.symbolId)||(r.add(s.symbolId),n.push(s));return n}function os(t,e){let n=null;for(let r of t)if(!(r.startLine>e||r.endLine<e)){if(r.startLine===e)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function as(t){let e=new Set([t]),r=t.split(/::|\.|#/).filter(Boolean).at(-1);return r&&e.add(r),e}function pr(t,e){let r=Mn(t,e).map(i=>ls(e,i));return{usage:r,positions:us(t,e,r)}}function dr(t,e){return{importUsage(n){let r=t.importUsageFacts(n);if(!e||r.positions.length===0)return r.usage;let i=e.importDefinitionsForFile(n,r.positions);return i.available?cs(r.usage,i.sourcePaths):r.usage}}}function cs(t,e){return t.map((n,r)=>{let i=e.get(String(r));return i?{...n,sourcePath:i}:n})}function ls(t,e){let n=e.isTypeOnly===!0,r=e.kind==="side-effect"||n||e.used;return{importer:t,sourcePath:e.sourcePath,importedName:e.importedName,localName:e.localName,kind:e.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:e.kind==="side-effect"||!n&&e.used,references:[]}}function us(t,e,n){let r=hn(t,e);if(!r)return[];let i=fs(r.rootNode),s=new Map;for(let a of i){let c=s.get(Lt(a.importedName,a.localName));c?c.push(a.position):s.set(Lt(a.importedName,a.localName),[a.position])}let o=[];return n.forEach((a,c)=>{let f=s.get(Lt(a.importedName,a.localName??a.importedName))?.shift();f&&o.push({...f,id:String(c),file:e})}),o}function fs(t){let e=[];for(let n of t.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&e.push(...Je(r,""))}return e.filter(n=>n.importedName!=="*")}function Je(t,e){switch(t.type){case"identifier":case"super":case"self":case"crate":return[{importedName:t.text,localName:t.text,position:_t(t,t.text)}];case"scoped_identifier":{let n=t.text.split("::").pop()??t.text;return[{importedName:n,localName:n,position:_t(t,n)}]}case"scoped_use_list":{let n=t.namedChild(0),r=t.namedChild(1);if(!n||!r)return[];let i=In(e,n.text);return r.namedChildren.flatMap(s=>Je(s,i))}case"use_list":return t.namedChildren.flatMap(n=>Je(n,e));case"use_as_clause":{let n=t.namedChild(0),r=t.namedChild(1);return!n||!r?[]:Je(n,e).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=t.namedChild(0),r="*";return[{importedName:r,localName:r,position:_t(n??t,r)}]}default:return[]}}function _t(t,e){let n=Math.max(0,t.text.lastIndexOf(e));return{id:"",file:"",line:t.startPosition.row,column:t.startPosition.column+n+ps(e)}}function ps(t){return Math.max(0,Math.min(t.length-1,1))}function Lt(t,e){return`${t}\0${e}`}import{spawnSync as Vt}from"child_process";import{existsSync as Yt}from"fs";import{fileURLToPath as yo}from"url";function Ge(t){let e=Tn(Cn,t),n=e.runnable;return n?{available:!0,dependencyAvailable:n,resolvedBinary:e.resolvedBinary??void 0,note:"rust-analyzer semantic reference queries are enabled."}:{available:!1,dependencyAvailable:n,resolvedBinary:e.resolvedBinary??void 0,reason:"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as Qs,mkdtempSync as Or,rmSync as Wt}from"fs";import{tmpdir as Ur}from"os";import{join as zt}from"path";import{fileURLToPath as rt,pathToFileURL as Xs}from"url";import{SHARE_ENV as Zs,Worker as eo}from"worker_threads";function K(t,e,n=new Set){let r=new Map;for(let i of t)n.has(i.symbolId)||r.set(i.symbolId,e.get(i.symbolId)??[]);return r}function J(t,e,n){let r=te(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(t/Math.max(1,n)));return Math.max(12e4,3e4+i*e)}import{spawn as Es}from"child_process";import{createHash as As,randomUUID as Fs}from"crypto";import{existsSync as Pr,realpathSync as Ns,rmSync as _s}from"fs";import{tmpdir as Ls}from"os";import{resolve as ce}from"path";import{execFileSync as hs}from"child_process";import{existsSync as ds}from"fs";import{deserializeSCIP as ms,SymbolRole as ys}from"@c4312/scip";import{realpathSync as wc}from"fs";import{basename as Ec,dirname as Ac,join as Fc,relative as Nc,sep as _c}from"path";import{fileURLToPath as Oc,pathToFileURL as Uc}from"url";function Qe(t){let e=new Map;for(let n of t)e.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...e.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var Ot=new WeakMap,Ss="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function mr(t,e){let n=new Map,r=Xe(),i=e.filter(o=>gr(o,r));if(i.length===0)return n;let s=Rr(t);if(!s)return n;for(let o of i){let a=Sr(s,o);a!==null&&n.set(o.symbolId,a)}return n}function yr(t,e){if(!gr(e,Xe()))return null;let n=Rr(t);return n?Sr(n,e):null}function Sr(t,e){return t.referencesBySymbol.get(e.symbol)??[]}function gr(t,e="safe"){if(!t.symbol.startsWith("rust-analyzer ")||!t.relativePath.endsWith(".rs")||Se(t.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(t.symbol))return!1;if(e==="all")return!0;let n=Ue(t.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=vn(t.symbol);return"kind"in r?!1:!gs(r)}function gs(t){for(let e=0;e<t.descriptors.length-1;e+=1)if(t.descriptors[e]?.suffix==="type")return!0;return!1}function Rr(t){if(Ot.has(t))return Ot.get(t)??null;let e=Rs(t);return Ot.set(t,e),e}function Rs(t){if(!t.generation.indexPath||!ds(t.generation.indexPath))return null;try{let e=ms(Ae(t.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Ee})),n=new Map;for(let r of e.documents??[]){let i=r.relativePath;if(!(!i||t.isIgnored(i)))for(let s of r.occurrences??[]){if(!s.symbol||(s.symbolRoles&ys.Definition)!==0)continue;let o=bs(i,s.range);if(!o)continue;let a=n.get(s.symbol)??[];a.push(o),n.set(s.symbol,a)}}for(let[r,i]of n)n.set(r,Qe(i));return{referencesBySymbol:n}}catch{return null}}function bs(t,e){if(e.length<3)return null;let n=e[0],r=e[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:t,line:n,column:r}}function Xe(){return process.env[Ss]==="all"?"all":"safe"}var br=new Map;function Ut(t){let n=Ge(t).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?Is(t,n):"unavailable"}}function Bt(t){return{...Ut(t),scipOccurrenceReferenceMode:Xe()}}function Is(t,e){let n=`${t}\0${e}`,r=br.get(n);if(r)return r;let i;try{i=hs(e,["--version"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return br.set(n,i),i}import{createHash as Ms}from"crypto";var vs=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function hr(t){let e=fn(t,{includePath:Ds});return Ms("sha256").update(JSON.stringify(e)).digest("hex")}function Ds(t){let e=t.replaceAll("\\","/"),n=e.split("/").at(-1)??e;return e.endsWith(".rs")||vs.has(n)?!0:e===".cargo/config"||e===".cargo/config.toml"||e.endsWith("/.cargo/config")||e.endsWith("/.cargo/config.toml")}import{createHash as xs}from"crypto";import{resolve as Cs}from"path";var ae=3;function jt(t){return xs("sha256").update(ge({kind:"scip-query-durable-rust-mailbox",protocolVersion:ae,sessionDir:Cs(t)})).digest("hex")}function vr(t,e){return pe(t)?t.protocolVersion!==ae?Mr(t.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(t.protocolVersion)}`):t.mailboxVersion!==Y||t.id!==e.requestId||t.operationKey!==e.operationKey||t.sessionIdentity!==e.sessionIdentity||t.deadlineAtMs!==e.deadlineAtMs?Mr("helper wrote an incompatible response identity"):typeof t.completedAtMs!="number"||!Number.isFinite(t.completedAtMs)||t.completedAtMs>e.deadlineAtMs||e.nowMs>e.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:t.ok===!1?typeof t.error!="string"||!ks(t.errorCode)?qt("helper wrote an invalid rejection response"):{ok:!1,code:t.errorCode,error:t.error}:t.ok!==!0||t.session!=="created"&&t.session!=="reused"&&t.session!=="invalidated"||!Ts(t.response,e.requestKind)?qt("helper wrote an invalid success response"):{ok:!0,session:t.session,response:t.response}:qt("helper wrote an invalid response object")}function Ts(t,e){return!pe(t)||typeof t.available!="boolean"||t.available===!1&&(typeof t.reason!="string"||t.reason.length===0)||t.available===!0&&t.reason!==void 0?!1:e==="import-definitions"?Array.isArray(t.sourcePaths)&&t.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):Ir(t.references,Ps)&&(t.incompleteReferenceSymbolIds===void 0||Array.isArray(t.incompleteReferenceSymbolIds)&&t.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(t.callees===void 0||Ir(t.callees,ws))&&(t.signatures===void 0||Array.isArray(t.signatures)&&t.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function Ir(t,e){return Array.isArray(t)&&t.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&Array.isArray(n[1])&&n[1].every(e))}function Ps(t){return pe(t)&&typeof t.file=="string"&&_(t.line)&&_(t.column)}function ws(t){return pe(t)&&typeof t.symbol=="string"&&typeof t.file=="string"&&_(t.line)&&(t.callsiteLine===void 0||_(t.callsiteLine))}function ks(t){return t==="unsupported-protocol"||t==="malformed-request"||t==="expired-request"||t==="handler-error"}function qt(t){return{ok:!1,code:"malformed-response",error:t}}function Mr(t){return{ok:!1,code:"incompatible-response",error:t}}var Os=5e3,wr=10,Us=3e4;function Dr(t,e,n,r=Nr){let i=r.engineIdentity(t),s={protocolVersion:ae,projectRoot:r.canonicalProjectRoot(t),projectFingerprint:r.projectFingerprint(t),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(e),environment:Er(r.environment())};return{key:_r(ge(s)),...s}}function Ze(t,e,n,r){if(t.protocolVersion!==ae||!n(t.pid))return!1;if(!t.processIdentity)return!0;let i=r?.(t.pid);return i!=null&&ke(t.processIdentity,i)}function kr(t,e,n){let r;try{r=ft(e,{maxBytes:H,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=_r(ge({projectRoot:ce(t),serverPath:ce(e),serverFingerprint:r})).slice(0,20);return ce(n,`scip-query-rust-session-${i}`)}function xr(t){let e=t===void 0?Number.NaN:Number(t);return Number.isInteger(e)&&e>=0?e:0}function Er(t){return Object.fromEntries(Object.entries(t).filter(([e])=>Fr(e)).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,n??null]))}function Ar(t,e){let n=e.runtime??Ks,r=e.identityRuntime??Nr,i=kr(t,e.serverPath,e.tempRoot??Ls()),s=!1,o=(a,c)=>{if(s)throw new Error("Durable Rust semantic session was already disposed.");return qs(i,e.serverPath,e.semanticWorkerPath,a,c,n,e.mailboxLimits)};return{requestSemantic(a,c){let f=Dr(t,e.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...l}=a;return o({kind:"semantic",identityKey:f.key,workerEnvironment:Tr(),request:{...l,referenceRetryTimeoutMs:Bs(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:xr(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let f=Dr(t,e.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...l}=a;return o({kind:"import-definitions",identityKey:f.key,workerEnvironment:Tr(),request:{...l,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:xr(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){s=!0}}}function Bs(t,e){return e!==void 0?e:t===void 0?Us:void 0}function qs(t,e,n,r,i,s,o={}){let a=s.now(),c=a+i,f=(s.monotonicNow??j)(),u=f+i,l=ne("rust-semantic-v3",r),p=re(l),m=Be(t),d=jt(t),y=qe(m,{mailboxVersion:Y,protocolVersion:ae,id:p,operationKey:l,clientId:s.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:d,request:r},{nowMs:a,limits:o});for(Cr(t,e,n,u,s);(s.monotonicNow??j)()<=u;){if(Pr(y.responsePath)){let g=js(q(y.responsePath,{maxBytes:o.maxItemBytes??H,inputKind:"durable Rust semantic mailbox response"}),{requestId:p,operationKey:l,sessionIdentity:d,deadlineAtMs:y.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:s.now()});if(!g.ok)throw new Error(g.error);return L()&&Le({type:"span",name:"rust.semantic.durable-session.request",durationMs:(s.monotonicNow??j)()-f,ok:!0,session:g.session,kind:r.kind}),g.response}let S=et(t);(!S||!Ze(S,s.now(),s.isProcessAlive,s.readProcessIdentity))&&Cr(t,e,n,u,s),s.sleep(wr)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function Cr(t,e,n,r,i){let s=et(t);if(s&&Ze(s,i.now(),i.isProcessAlive,i.readProcessIdentity))return;_s(ce(t,"server.json"),{force:!0}),i.spawnServer(e,t,n);let o=i.monotonicNow??j,a=Math.min(r,o()+Os);for(;o()<=a;){let c=et(t);if(c&&Ze(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(wr)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function et(t){try{let e=JSON.parse(q(ce(t,"server.json"),{maxBytes:an,inputKind:"durable Rust session state"}));if(typeof e.protocolVersion!="number"||e.sessionIdentity!==void 0&&(typeof e.sessionIdentity!="string"||e.sessionIdentity!==jt(t))||typeof e.pid!="number"||typeof e.heartbeatAtMs!="number"||e.busyUntilMs!==void 0&&typeof e.busyUntilMs!="number"||e.mailbox!==void 0&&!Ws(e.mailbox))return null;let n=e.processIdentity===void 0?null:we(e.processIdentity);return e.processIdentity!==void 0&&(!n||n.pid!==e.pid)?null:{protocolVersion:e.protocolVersion,...e.sessionIdentity===void 0?{}:{sessionIdentity:e.sessionIdentity},pid:e.pid,...n?{processIdentity:n}:{},heartbeatAtMs:e.heartbeatAtMs,...e.busyUntilMs===void 0?{}:{busyUntilMs:e.busyUntilMs},...e.mailbox===void 0?{}:{mailbox:e.mailbox}}}catch{return null}}function js(t,e){try{return vr(JSON.parse(t),e)}catch(n){return{ok:!1,code:"malformed-response",error:`helper wrote malformed JSON: ${n instanceof Error?n.message:String(n)}`}}}function Ws(t){if(!t||typeof t!="object")return!1;let e=t;return _(e.pending)&&_(e.inflight)&&_(e.responses)&&_(e.deadLetters)&&_(e.invalid)&&_(e.totalItems)&&typeof e.totalBytes=="number"&&Number.isFinite(e.totalBytes)&&e.totalBytes>=0&&(e.oldestPendingAt===void 0||Number.isFinite(Date.parse(e.oldestPendingAt)))}function Tr(){return Object.fromEntries(Object.entries(process.env).filter(([t])=>zs(t)).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>[t,e??null]))}function Fr(t){return t==="HOME"||t==="PATH"||t.startsWith("CARGO_")||t.startsWith("RA_")||t.startsWith("RUST")}function zs(t){return Fr(t)||t.startsWith("SCIP_RUST_")||t==="SCIP_QUERY_PROFILE"||t==="SCIP_QUERY_PROFILE_CACHE_STATE"||t==="SCIP_QUERY_PROFILE_COMMAND"||t==="SCIP_QUERY_PROFILE_OUT"||t==="SCIP_QUERY_PROFILE_RUN_ID"||t==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||t==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||t==="SCIP_QUERY_PROFILE_MIN_MS"}var Nr={canonicalProjectRoot(t){try{return Ns(t)}catch{return ce(t)}},projectFingerprint(t){return hr(t)},engineIdentity:Ut,fileFingerprint(t){return ft(t,{maxBytes:H,inputKind:"Rust semantic engine artifact"})},environment(){return Er(process.env)}},Ks={now:Date.now,monotonicNow:j,randomId:Fs,isProcessAlive:Ne,readProcessIdentity:Fe,spawnServer(t,e,n){if(!Pr(t))throw new Error(`Durable Rust semantic session helper was not found at ${t}. Run npm run build first.`);Es(process.execPath,[t,e,n],{detached:!0,stdio:"ignore"}).unref()},sleep(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}};function _r(t){return As("sha256").update(t).digest("hex")}import{randomUUID as Pl}from"crypto";import{readdirSync as Hs,rmSync as kl,writeFileSync as El}from"fs";import{join as $s}from"path";var Vs="rust-analyzer-owner-",Ys=".json",Js=16*1024;async function Lr(t,e){if(!t)return[];let n;try{n=Hs(t)}catch{return[]}let r=n.filter(o=>o.startsWith(Vs)&&o.endsWith(Ys)).map(o=>$s(t,o)),i=[],s=[];for(let o of r){let a=Gs(o);a?s.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${o} could not be validated.`})}return i.push(...await Promise.all(s.map(o=>Pn(o,e)))),i}function Gs(t){try{let e=q(t,{maxBytes:Js,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(e),r=we(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var Br=15e3,qr=8,Wr=5e3,to=64,no=96,Ht=class{constructor(e,n,r={}){this.projectRoot=e;this.status=n;this.opts=r;this.requester=r.requester??oo(e,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(e){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Ie(n),references:Me(e)};try{let r=this.requestSession(n.resolvedBinary,e,{includeReferences:!0});return{...he(r),resolvedBinary:n.resolvedBinary,references:K(e,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(e)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Me(e)}}}calleesForDefinitions(e){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Ie(n),callees:ve(e)};try{let r=this.requestSession(n.resolvedBinary,e,{includeReferences:!1,includeCallees:!0});return{...he(r),resolvedBinary:n.resolvedBinary,callees:Kt(e,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(e)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:ve(e)}}}referencesAndCalleesForDefinitions(e,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Ie(r),references:Me(e),callees:ve(n)};let i=[...e,...n];try{let s=this.requestSession(r.resolvedBinary,i,{includeReferences:e.length>0,includeCallees:n.length>0,referenceDefinitions:e,calleeDefinitions:n});return{...he(s),resolvedBinary:r.resolvedBinary,references:K(e,new Map(s.references),new Set(s.incompleteReferenceSymbolIds??[])),callees:Kt(n,new Map(s.callees??[]))}}catch(s){return this.fallbackReferencesAndCallees(r,e,n,s)}}signaturesForDefinitions(e){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Ie(n),signatures:jr(e)};try{let r=this.requestSession(n.resolvedBinary,e,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...he(r),resolvedBinary:n.resolvedBinary,signatures:fo(e,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(e)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:jr(e)}}}importDefinitionsForFile(e,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Ie(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,e,n);return{...he(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(s=>[s.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(e,n,r){let i=tt(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Br),s=nt(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),o=tt(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,qr),a=nt(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,f=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,l=De(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),p={projectRoot:this.projectRoot,rustAnalyzerBinary:e,definitions:[...n],...c?{referenceDefinitions:c}:{},...f?{calleeDefinitions:f}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:o,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},m=po(p);return w("rust.semantic.session.request",()=>this.requester.requestSemantic(p,J(m,$t(i,p.referenceRetryTimeoutMs),o)),()=>({definitions:n.length,operationDefinitions:m,referenceDefinitions:p.referenceDefinitions?.length,calleeDefinitions:p.calleeDefinitions?.length,signatureDefinitions:p.signatureDefinitions?.length,references:p.includeReferences!==!1,callees:p.includeCallees===!0,signatures:p.includeSignatures===!0,referenceRetryTimeoutMs:p.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(e,n,r,i){let s=n.length===0?{available:!0,resolvedBinary:e.resolvedBinary,references:Me(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),o=r.length===0?{available:!0,resolvedBinary:e.resolvedBinary,callees:ve(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(s&&o){let a={resolvedBinary:s.resolvedBinary??o.resolvedBinary??e.resolvedBinary,references:K(n,s.references),callees:Kt(r,o.callees)};return s.available&&o.available?{available:!0,...a}:{available:!1,reason:(s.available?void 0:s.reason)??(o.available?void 0:o.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:e.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Me(n),callees:ve(r)}}requestImportDefinitions(e,n,r){let i=tt(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Br),s=tt(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,qr),o=nt(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=nt(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Wr),c={projectRoot:this.projectRoot,rustAnalyzerBinary:e,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:o,settleDelayMs:a,concurrency:s};return w("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,J(r.length,i,s)),()=>({file:n,positions:r.length}))}};function he(t){return t.available?{available:!0}:{available:!1,reason:t.reason}}function Ie(t){return t.available?"rust-analyzer binary path is unavailable.":t.reason}function zr(t,e,n={}){return new Ht(t,e,n)}function De(t,e){let n=Hr(t);if(n!==null)return n;let r=e.includeReferences!==!1;return r&&e.includeCallees!==!0&&e.includeSignatures!==!0&&e.definitionCount<=to||r&&e.includeCallees===!0&&e.includeSignatures!==!0&&e.definitionCount<=no?0:Wr}function ro(t){let e=t?.trim().toLowerCase(),n=e==="0"||e==="false"||e==="off"||e==="worker",r=e==="1"||e==="true"||e==="on"||e==="durable",i=e===void 0||e==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function io(t){return ro(t).transport}function so(t,e){let n=null,r=!1,i=!1,s=!1,o=()=>n??=e(),a=()=>{i||(t.shutdown(),i=!0)},c=(u,l,p)=>{let m=uo(u);r=!0;try{a()}catch{}L()&&Le({type:"span",name:"rust.semantic.durable-session.request",durationMs:p,ok:!1,kind:l,session:"worker-fallback",reason:m})},f=(u,l,p)=>{if(s)throw new Error("Rust semantic failover session was already disposed.");if(r)return p(o());let m=performance.now();try{return l(t)}catch(d){c(d,u,performance.now()-m)}return p(o())};return{requestSemantic(u,l){return f("semantic",p=>p.requestSemantic(u,l),p=>p.requestSemantic(u,l))},requestImportDefinitions(u,l){return f("import-definitions",p=>p.requestImportDefinitions(u,l),p=>p.requestImportDefinitions(u,l))},shutdown(){if(s)return;s=!0;let u=[];try{a()}catch(l){u.push(l)}try{n?.shutdown()}catch(l){u.push(l)}if(u.length>0)throw u[0]}}}function oo(t,e,n={worker:()=>ao(),durable:()=>Ar(t,{serverPath:rt(mo()),semanticWorkerPath:rt(Kr())})}){return io(e)==="durable"?so(n.durable(),n.worker):n.worker()}function ao(t={}){let e=null,n=null,r=1,i=!1,s=null,o=null,a=l=>{l&&Wt(l,{recursive:!0,force:!0})},c=()=>{if(s)return;let l=e,p=n;e=null,n=null;let m=l?l.terminate():Promise.resolve(0);s=Promise.allSettled([m,Lr(p,{gracefulMs:1e3,forceMs:1e3})]).then(([d,y])=>{let g=(y.status==="fulfilled"?y.value:[{reaped:!1,detail:String(y.reason)}]).filter(I=>!I.reaped);if(d.status==="rejected"||g.length>0){o=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${p??"unknown"}.`);return}a(p)}).finally(()=>{s=null})},f=()=>{if(e)return e;if(s)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(o)throw o;let l=t.semanticWorkerPath?Xs(t.semanticWorkerPath):Kr();if(!Qs(rt(l)))throw new Error(`Rust semantic session worker was not found at ${rt(l)}. Run npm run build before using built semantic Rust queries.`);return n=Or(zt(Ur(),"scip-query-rust-session-")),e=new eo(l,t.shareEnvironment?{env:Zs}:void 0),e.unref(),e},u=()=>{let l=n??Or(zt(Ur(),"scip-query-rust-session-"));return n=l,zt(l,`${r++}.json`)};return{requestSemantic(l,p){if(i)throw new Error("Rust semantic session was already disposed.");let m=f(),d=u(),y=new SharedArrayBuffer(4),S=new Int32Array(y);if(m.postMessage({kind:"semantic",request:l,responsePath:d,sharedBuffer:y}),Atomics.wait(S,0,0,p)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(p/1e3).toFixed(0)}s`);try{let I=co(q(d,{maxBytes:H,inputKind:"Rust semantic worker response"}));if(!I.ok)throw new Error(I.error);return I.response}finally{Wt(d,{force:!0})}},requestImportDefinitions(l,p){if(i)throw new Error("Rust semantic session was already disposed.");let m=f(),d=u(),y=new SharedArrayBuffer(4),S=new Int32Array(y);if(m.postMessage({kind:"import-definitions",request:l,responsePath:d,sharedBuffer:y}),Atomics.wait(S,0,0,p)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(p/1e3).toFixed(0)}s`);try{let I=lo(q(d,{maxBytes:H,inputKind:"Rust import-definition worker response"}));if(!I.ok)throw new Error(I.error);return I.response}finally{Wt(d,{force:!0})}},shutdown(){if(i)return;if(i=!0,!e){a(n),n=null;return}let l=u(),p=new SharedArrayBuffer(4),m=new Int32Array(p);e.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:p}),Atomics.wait(m,0,0,5e3),c()}}}function co(t){let e=JSON.parse(t);if(!e||typeof e!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=e;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof e.error=="string"?e.error:"Rust semantic session worker failed."}}function lo(t){let e=JSON.parse(t);if(!e||typeof e!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=e;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof e.error=="string"?e.error:"Rust semantic session worker failed."}}function uo(t){let e=t instanceof Error?`${t.name} ${t.message}`.toLowerCase():String(t).toLowerCase();return e.includes("readiness")?"readiness":e.includes("timeout")||e.includes("timed out")?"timeout":e.includes("helper")?"helper":"request"}function Me(t){return new Map(t.map(e=>[e.symbolId,[]]))}function ve(t){return new Map(t.map(e=>[e.symbolId,[]]))}function jr(t){return new Map(t.map(e=>[e.symbolId,null]))}function Kt(t,e){return new Map(t.map(n=>[n.symbolId,e.get(n.symbolId)??[]]))}function fo(t,e){return new Map(t.map(n=>[n.symbolId,e.get(n.symbolId)??null]))}function po(t){let e=0;return t.includeReferences!==!1&&(e+=(t.referenceDefinitions??t.definitions).length),t.includeCallees===!0&&(e+=(t.calleeDefinitions??t.definitions).length),t.includeSignatures===!0&&(e+=(t.signatureDefinitions??t.definitions).length),Math.max(1,e)}function $t(t,e){return e&&e>0?Math.max(t,e):t}function Kr(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function mo(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function tt(t,e){return te(t)??e}function nt(t,e){return Hr(t)??e}function Hr(t){if(!t)return null;let e=Number(t);return Number.isInteger(e)&&e>=0?e:null}var Jt=15e3,Gt=8;function Jr(t,e={}){let n=e.status??Ge,r=Ro(t,n),i=bo(t,n),s=ho(t,n),o=e.referenceResolver||e.calleeResolver||e.signatureResolver||!So(e)?null:zr(t,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:s}),a=e.referenceResolver??o??r,c=e.calleeResolver??o??i,f=e.signatureResolver??o??s,u=e.importUsageResolver??dr(e.sourceImportUsageResolver??go(),e.importDefinitionResolver??o),l=e.calleeSymbolResolver,p=e.sourceZeroCalleeOracle,m=e.scipOccurrenceCalleeOracle,d=new Map,y=new Map,S=null,g=null,I=()=>(S??=n(t),S),k=()=>{let b=I();return b.dependencyAvailable?g??b:b},h=b=>{if(b.length===0)return new Map;let R=Ce(b);try{let M=a.referencesForDefinitions(R),T=I();return g=it(T,M),M.available?new Map(M.references):K(R,M.references)}catch(M){let T=I();return g=xe(T,M),G(R)}},v=b=>{if(b.length===0)return new Map;let R=Ce(b),M=R.filter($r);if(M.length===0)return Q(R);let T=new Map,W=Yr(M,m),N=[];for(let P of M)y.has(P.symbolId)?T.set(P.symbolId,y.get(P.symbolId)??[]):W.has(P.symbolId)?T.set(P.symbolId,W.get(P.symbolId)??[]):Vr(P,p)?T.set(P.symbolId,[]):N.push(P);if(N.length===0)return le(R,T,void 0);try{let P=c.calleesForDefinitions(N),U=I();g=it(U,P);let E=le(N,P.callees,l);for(let[fe,ct]of E)T.set(fe,ct);return le(R,T,void 0)}catch(P){let U=I();return g=xe(U,P),Q(R)}},C=(b,R)=>{let M=Ce(b),T=Ce(R),W=T.filter($r),N=new Map,P=Yr(W,m),U=[];for(let E of W)P.has(E.symbolId)?N.set(E.symbolId,P.get(E.symbolId)??[]):Vr(E,p)?N.set(E.symbolId,[]):U.push(E);if(M.length===0&&U.length===0)return{references:G(M),callees:le(T,N,void 0)};try{let E=o?o.referencesAndCalleesForDefinitions(M,U):Do(a,c,{referenceDefinitions:M,calleeDefinitions:U}),fe=I();g=it(fe,E);let ct=E.available?new Map(E.references):K(M,E.references);for(let[lt,ut]of E.callees)N.set(lt,ut);let on=le(T,N,l);for(let[lt,ut]of on)y.set(lt,ut);return{references:ct,callees:on}}catch(E){let fe=I();return g=xe(fe,E),{references:G(M),callees:Q(T)}}},D=b=>{if(b.length===0)return new Map;let R=Ce(b);try{let M=f.signaturesForDefinitions(R),T=I();return g=it(T,M),Gr(R,M.signatures)}catch(M){let T=I();return g=xe(T,M),st(R)}};return{language:"rust",availability:k,dispose:()=>{o?.dispose()},importUsage:b=>{let R=d.get(b);if(R)return R;try{let M=u.importUsage(b);return d.set(b,M),M}catch(M){let T=I();return g=xe(T,M),[]}},referencesFor:b=>h([b]).get(b.symbolId)??[],referencesForDefinitions:h,referencesAndCalleesForDefinitions:C,calleesFor:b=>v([b]).get(b.symbolId)??[],calleesForDefinitions:v,signatureFor:b=>D([b]).get(b.symbolId)??null}}function it(t,e){let n={dependencyAvailable:t.dependencyAvailable,resolvedBinary:e.resolvedBinary??t.resolvedBinary,...t.note?{note:t.note}:{}};return e.available?{available:!0,...n}:{available:!1,reason:e.reason,...n}}function xe(t,e){return{available:!1,dependencyAvailable:t.dependencyAvailable,resolvedBinary:t.resolvedBinary,...t.note?{note:t.note}:{},reason:e instanceof Error?e.message:String(e)}}function So(t){if(t.usePersistentSession!==void 0)return t.usePersistentSession;let e=process.env.SCIP_RUST_SEMANTIC_SESSION;return e!=="0"&&e!=="false"}function go(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Ce(t){return t.map(e=>{let n=e;return{...e,leaf:typeof n.leaf=="string"?n.leaf:V(e.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Dn(e.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function $r(t){return t.isFunctionLike}function Vr(t,e){if(!e)return!1;try{return e(t)}catch{return!1}}function Yr(t,e){if(!e||t.length===0)return new Map;try{return e(t)}catch{return new Map}}function Ro(t,e){return{referencesForDefinitions:n=>Io(t,e,n)}}function bo(t,e){return{calleesForDefinitions:n=>Mo(t,e,n)}}function ho(t,e){return{signaturesForDefinitions:n=>vo(t,e,n)}}function Io(t,e,n){let r=e(t);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Zt(r),references:G(n)};let i=Qt();if(!Yt(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:G(n)};let s=ue(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Jt),o=ot(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=ue(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Gt),c=ot(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(s,1e4)),f=De(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:t,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:s,...o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:c,settleDelayMs:f,concurrency:a},l=Vt(process.execPath,[i],{cwd:t,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:J(n.length,$t(s,u.referenceRetryTimeoutMs),a)}),p=en(l.stdout);if(p)return{...Xt(p),resolvedBinary:r.resolvedBinary,references:K(n,new Map(p.references),new Set(p.incompleteReferenceSymbolIds??[]))};let m=l.error instanceof Error?l.error.message:l.stderr.trim()||`Rust semantic worker exited with status ${l.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,references:G(n)}}function Mo(t,e,n){let r=e(t);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Zt(r),callees:Q(n)};let i=Qt();if(!Yt(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Q(n)};let s=ue(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Jt),o=ue(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Gt),a=ot(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(s,1e4)),c=De(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),f={projectRoot:t,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:s,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:o,includeReferences:!1,includeCallees:!0},u=Vt(process.execPath,[i],{cwd:t,input:JSON.stringify(f),encoding:"utf8",maxBuffer:50*1024*1024,timeout:J(n.length,s,o)}),l=en(u.stdout);if(l)return{...Xt(l),resolvedBinary:r.resolvedBinary,callees:le(n,new Map(l.callees??[]),void 0)};let p=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,callees:Q(n)}}function vo(t,e,n){let r=e(t);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Zt(r),signatures:st(n)};let i=Qt();if(!Yt(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:st(n)};let s=ue(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Jt),o=ue(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Gt),a=ot(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(s,1e4)),c=De(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),f={projectRoot:t,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:s,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:o,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Vt(process.execPath,[i],{cwd:t,input:JSON.stringify(f),encoding:"utf8",maxBuffer:50*1024*1024,timeout:J(n.length,s,o)}),l=en(u.stdout);if(l)return{...Xt(l),resolvedBinary:r.resolvedBinary,signatures:Gr(n,new Map(l.signatures??[]))};let p=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,signatures:st(n)}}function Do(t,e,n){let r=n.referenceDefinitions.length>0?t.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:G(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?e.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Q(n.calleeDefinitions)},s={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...s}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...s}}function G(t){return new Map(t.map(e=>[e.symbolId,[]]))}function Q(t){return new Map(t.map(e=>[e.symbolId,[]]))}function st(t){return new Map(t.map(e=>[e.symbolId,null]))}function le(t,e,n){let r=0,i=0;return w("rust.semantic.callees.complete-map",()=>{let s=new Map;for(let o of t){let a=e.get(o.symbolId)??[];a.length>0&&(r+=1),i+=a.length,s.set(o.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return s},()=>({definitions:t.length,rows:r,callees:i,resolveSymbols:!!n}))}function Gr(t,e){return new Map(t.map(n=>[n.symbolId,e.get(n.symbolId)??null]))}function Qt(){return yo(new URL("./rust-semantic-worker.js",import.meta.url))}function Xt(t){return t.available?{available:!0}:{available:!1,reason:t.reason}}function Zt(t){return t.available?"rust-analyzer binary path is unavailable.":t.reason}function en(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function ue(t,e){return te(t)??e}function ot(t,e){if(!t)return e;let n=Number(t);return Number.isInteger(n)&&n>=0?n:e}import{existsSync as xo}from"fs";import{deserializeSCIP as Co,SymbolRole as To}from"@c4312/scip";var tn=new WeakMap;function Xr(t,e){let n=e.filter(Po);if(n.length===0)return new Map;let r=!1,i=0,s=0;return w("rust.scip-occurrence.callees",()=>{let o=Eo(t);if(r=!!o,!o)return new Map;let a=new Map;for(let c of n){let f=wo(t,o,c);f!==null&&(a.set(c.symbolId,f),i+=1,s+=f.length)}return a},()=>({definitions:e.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:s}))}function Po(t){return!(!t.symbol.startsWith("rust-analyzer ")||!t.relativePath.endsWith(".rs")||!t.isFunctionLike||t.leaf==="main"||Se(t.symbol))}function wo(t,e,n){let r=Oe(t,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(f=>f.startLine!==n.startLine||f.endLine!==n.endLine?!1:f.name===n.leaf||n.leaf.endsWith(f.name)||f.name.endsWith(n.leaf));if(!i)return null;let s=r.callSites.filter(f=>f.line>=i.startLine&&f.line<=i.endLine);if(s.length===0)return null;let o=(e.occurrencesByFile.get(n.relativePath)??[]).filter(f=>f.line>=i.startLine&&f.line<=i.endLine&&f.callee.symbol!==n.symbol);if(o.some(f=>f.traitImplMember)||!ko(s,o))return null;let a=[],c=new Set;for(let f of o){let u=`${f.callee.symbol}\0${f.callee.file}\0${f.callee.line}`;c.has(u)||(c.add(u),a.push(f.callee))}return a}function ko(t,e){let n=Qr(t),r=Qr(e);if(n.size!==r.size)return!1;for(let[i,s]of n)if(r.get(i)!==s)return!1;return!0}function Qr(t){let e=new Map;for(let n of t){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;e.set(i,(e.get(i)??0)+1)}return e}function Eo(t){if(tn.has(t))return tn.get(t)??null;let e=Ao(t);return tn.set(t,e),e}function Ao(t){if(!t.generation.indexPath||!xo(t.generation.indexPath))return null;try{let e=ee(t).filter(s=>s.symbol.startsWith("rust-analyzer ")&&s.relativePath.endsWith(".rs")&&s.isFunctionLike),n=new Map(e.map(s=>[s.symbol,s])),r=Co(Ae(t.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Ee})),i=new Map;for(let s of r.documents??[]){let o=s.relativePath;if(!o||!o.endsWith(".rs")||t.isIgnored(o))continue;let a=[];for(let c of s.occurrences??[]){if(!c.symbol||(c.symbolRoles&To.Definition)!==0)continue;let f=n.get(c.symbol);if(!f)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:f.leaf,traitImplMember:Se(f.symbol),callee:{symbol:f.symbol,file:f.relativePath,line:f.startLine,callsiteLine:u}})}i.set(o,a)}return{occurrencesByFile:i}}catch{return null}}var at=class{sessions=new WeakMap;getOrCreate(e,n,r){let i=Fo(e,n),s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let o=s.get(i);if(o)return o.hits+=1,o.lastUsedAtMs=Date.now(),o.provider;let a=Date.now(),c=r();return s.set(i,{key:i,language:n,projectRoot:e.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(e){return[...this.sessions.get(e)?.values()??[]]}clear(e){let n=this.sessions.get(e);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(e)}};function Fo(t,e){return`${t.config.projectRoot}:${e}-workspace`}var Zr=new at;pn({name:"semantic-provider",groups:["semantic-provider"],clearAll:t=>Zr.clear(t)});function X(t,e){let n=O(e)??"typescript";return Zr.getOrCreate(t,n,()=>n==="rust"?Jr(t.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>pr(t,r)},calleeSymbolResolver:fr(t),sourceZeroCalleeOracle:r=>No(t,r),scipOccurrenceCalleeOracle:r=>Xr(t,r)}):cr(t,e))}function O(t){return t?bn(t)==="rust"?"rust":ie(t)?"typescript":null:"typescript"}function No(t,e){let n=Oe(t,e.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===e.startLine&&i.endLine===e.endLine&&i.name===e.leaf)??n.callables.find(i=>i.startLine===e.startLine&&i.endLine===e.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}import{resolve as jo}from"path";var _o=/^[A-Za-z_][A-Za-z0-9_]*$/,ei=/\bDefault::default\b/g,Lo=/^\.\.\s*Default::default\b/;function ti(t,e){let n=new Map,r=new Map;for(let i of e){let s=nn(t,i,r);s!==null&&n.set(i.symbolId,s)}return n}function nn(t,e,n=new Map){let r=Uo(e.symbol);if(!r)return null;let i=xn(t,[e.symbolId]);if(i.length===0)return null;let s=new RegExp(`(^|[^A-Za-z0-9_])${ye(r)}::default\\b`,"g"),o=new RegExp(`(^|[^A-Za-z0-9_])${ye(r)}\\s*$`),a=Oo(t,e.symbolId),c=[];for(let f of i){let u=Bo(t,f.relative_path,n);if(u===null)return null;let l=u.split(/\r?\n/),p=0,m=[],d=0;for(let y=f.chunk_start;y<=f.chunk_end&&y<l.length;y+=1){let g=l[y]??"",I=new Set;s.lastIndex=0;let k;for(;k=s.exec(g);)c.push({file:f.relative_path,line:y,column:k.index+k[1].length+r.length+2}),d+=1;for(let h=0;h<g.length;h+=1){let v=Lo.exec(g.slice(h));if(v){if(a&&m.includes(p)){let D=h+v[0].lastIndexOf("default");c.push({file:f.relative_path,line:y,column:D}),I.add(D),d+=1}h+=v[0].length-1;continue}let C=g[h];if(C==="{"){let D=o.test(g.slice(0,h));p+=1,D&&m.push(p);continue}if(C==="}")for(p=Math.max(0,p-1);m.length>0&&m[m.length-1]>p;)m.pop()}for(ei.lastIndex=0;k=ei.exec(g);){let h=k.index+9;if(!I.has(h))return null}}if(d===0)return null}return Qe(c)}function Oo(t,e){return t.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",e)?.present===1}function Uo(t){let e=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(t)?.[1]??null;return!e||!_o.test(e)?null:e}function Bo(t,e,n){if(n.has(e))return n.get(e)??null;let r=t.get("SELECT text FROM documents WHERE relative_path = ?",e),i=typeof r?.text=="string"?r.text:qo(t,e);return n.set(e,i),i}function qo(t,e){try{return un(t.config.projectRoot,e,{inputKind:"indexed Rust source file"})}catch(n){if(!de(n))throw n;return null}}function ni(t){let e=new Map;for(let n of t){let r=e.get(n.relativePath)??[];r.push(n),e.set(n.relativePath,r)}return e}var Wo="typescript-import-usage-v1",zo="typescript-signatures-v1",rn=dt("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),ri=me({kind:"semantic-import-usage",invalidation:$("semantic-import-usage"),serialize:t=>JSON.stringify(t),deserialize:pi}),ii=me({kind:"semantic-signatures",invalidation:$("semantic-signatures"),serialize:t=>JSON.stringify(t),deserialize:ra}),si=St({kind:"typescript-import-usage",invalidation:$("typescript-import-usage"),serialize:t=>JSON.stringify(t),deserialize:pi}),oi=St({kind:"typescript-signatures",invalidation:$("typescript-signatures"),serialize:t=>JSON.stringify(t),deserialize:ia}),Ko=256;function Yu(t,e={}){let n=e.coldFragmentLimit??Ko,r=Fn(t);return r===null||r.missing<=n?{ready:!0}:(e.serviceAvailable??lr)(t)?{ready:!0}:{ready:!1,reason:`TypeScript reference fragments are cold for ${r.missing} of ${r.files} files and no watch service is running; run \`scip-query health --full\` once or start the service with \`scip-query watch --daemon\`, then re-run this command.`}}var Ho=dt("typescript-reference-map",{clearGroups:["whole-project"]});function $o(t){return Ho.get(t,()=>{let e=Z(t);if(!e)return null;let n=ee(t).filter(i=>O(i.relativePath)==="typescript"),r=ht(t,n,i=>X(t,i));return r?{projectFingerprint:e,references:r.references,files:r.files,cacheHits:r.cacheHits,cacheMisses:r.cacheMisses,computedFiles:r.computedFiles}:null})}function Pe(t){let e=new Map,n=new Set;return{capability:(r,i)=>di(t,r,i),importUsage:r=>Yo(t,r),references:r=>ci(t,r),materializeReferences:(r,i)=>li(t,r,e,n,i),callerMap:r=>Jo(t,r,e,n),calleeMap:r=>Zo(t,r),signature:r=>ta(t,r)}}function Vo(t,e){if(e.size===0)return;let n=rn.get(t,()=>new Map);for(let[r,i]of e)n.set(r,[...i])}function Ju(t,e){if(!rn.has(t))return{hits:[],misses:[...e]};let n=rn.get(t,()=>new Map),r=[],i=[];for(let s of e)n.has(s.symbolId)?r.push({definition:s,callees:n.get(s.symbolId)??[]}):i.push(s);return{hits:r,misses:i}}function Gu(t,e){return Pe(t).importUsage(e)}function Yo(t,e){if(O(e)==="typescript"){let s="fallback",o=0,a=0,c=0,f=0;return w("typescript.import-usage.materialize",()=>{let u=Rt(t,e,Wo);if(u?.key){o=1;let p=si.read(t,e,u.key);if(p)return s="hit",a=1,p;c=1;let m=B(t,e);if(!m)return s="unavailable",[];let d=m.importUsage(e);return si.write(t,e,u.key,d),s="computed",d}f=1;let l=B(t,e);return l?(s="direct-fallback",l.importUsage(e)):(s="unavailable",[])},()=>({state:s,eligible:o,cacheHits:a,cacheMisses:c,fallbacks:f}))}let n=fi(t,"semantic-import-usage",e);if(n){let s=ri.read(t,e,n);if(s)return s}let r=B(t,e);if(!r)return[];let i=r.importUsage(e);return n&&ri.write(t,e,n,i),i}function Qu(t,e){return Pe(t).references(e)}function ci(t,e){let n=nn(t,e);if(n)return n;let r=yr(t,e);if(r)return r;let i=B(t,e.relativePath);return i?i.referencesFor(e):[]}function Xu(t,e){return Pe(t).callerMap(e)}function Zu(t,e){let n=new Map,r=[];for(let i of e){if(O(i.relativePath)==="typescript"){r.push(i);continue}sn(t,n,i,ci(t,i))}if(r.length>0){let s=ht(t,r,o=>X(t,o))?.references;if(!s){let o=B(t,r[0].relativePath);s=o?o.referencesForDefinitions?o.referencesForDefinitions(r,{exact:!0}):new Map(r.map(a=>[a.symbolId,o.referencesFor(a)])):new Map,o&&L()&&bt(t,r,s,a=>X(t,a))}for(let o of r)sn(t,n,o,s.get(o.symbolId)??[])}return n}function Jo(t,e,n=new Map,r=new Set){let i=new Map,s=li(t,e,n,r),o=0;return w("semantic.callers.from-references",()=>{for(let a of e)o+=sn(t,i,a,n.get(a.symbolId)??[])},()=>({definitions:e.length,materialized:s.definitions,inMemoryHits:s.inMemoryHits,incompleteInMemoryHits:s.incompleteInMemoryHits,resultRows:i.size,callerFiles:o})),i}function li(t,e,n,r,i={}){let s=Z(t),o=[],a=[],c=[],f=0,u=0,l=0,p=0,m=0,d=0,y=0,S=0,g=0,I=0,k=0,h=0,v=[],C=new Map,D=e.filter(R=>O(R.relativePath)==="typescript"&&!n.has(R.symbolId)&&!r.has(R.symbolId)),b=D.length>0?$o(t):null;if(b){g=D.length,I=b.cacheHits,k=b.cacheMisses,h=b.computedFiles;for(let R of D)n.set(R.symbolId,b.references.get(R.symbolId)??[])}if(w("semantic.references.cache-scan",()=>{for(let[R,M]of ni(e)){let T=[];for(let P of M)n.has(P.symbolId)?u+=1:r.has(P.symbolId)?S+=1:T.push(P);if(T.length===0){y+=1;continue}let W=Go(t,s,R);if(!W){for(let P of T)O(P.relativePath)||(f+=1),c.push(P);continue}d+=1;let N=mn(t,R,W);for(let P of T){let U=N.get(P.symbol)??null;if(U!==null){let E=Xo(U);if(E){l+=1,n.set(P.symbolId,E);continue}p+=1}a.push({definition:P,cacheFingerprint:W})}}},()=>({definitions:e.length,skippedUnsupportedLanguage:f,cacheHits:l,parseFailures:p,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:S,fullyInMemoryFiles:y,cacheReadFiles:d})),a.length>0||c.length>0){v=[...c,...a.map(R=>R.definition)],C=w("semantic.references.compute-misses",()=>{let R=Qo(t,v,i);return m=R.size,R},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:m}));for(let R of v)C.has(R.symbolId)?(n.set(R.symbolId,C.get(R.symbolId)??[]),r.delete(R.symbolId)):r.add(R.symbolId);for(let{definition:R,cacheFingerprint:M}of a)C.has(R.symbolId)&&di(t,"semantic-references",R.relativePath).available&&o.push({relativePath:R.relativePath,symbol:R.symbol,projectFingerprint:M,payload:JSON.stringify(C.get(R.symbolId)??[])})}return o.length>0&&w("semantic.references.cache-write",()=>yn(t,o),()=>({entries:o.length})),C.size>0&&bt(t,v,C,R=>X(t,R)),{definitions:e.length,inMemoryHits:u,incompleteInMemoryHits:S,cacheHits:l,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:f,parseFailures:p,computed:m,incomplete:r.size,cacheWrites:o.length,fragmentDefinitions:g,fragmentCacheHits:I,fragmentCacheMisses:k,fragmentComputedFiles:h}}function Go(t,e,n){if(!e)return null;let r=O(n);return r==="typescript"?e:r==="rust"?mt(JSON.stringify({kind:"semantic-references",language:r,engine:Bt(t.config.projectRoot),projectFingerprint:e})):null}function Qo(t,e,n={}){let r=L(),i=new Map,s=0,o=0,a=0,c=0,f=0,u=0,l=0,p=0,m=0;return w("semantic.references.provider-loop",()=>{let d=ti(t,e),y=mr(t,e),S=new Map,g=n.prefetchCallees?new Map:null,I=[];for(let h of e){let v,C=()=>(v??=B(t,h.relativePath),v);if(g){let M=C();if(M?.referencesAndCalleesForDefinitions){let T=g.get(M);T?T.push(h):g.set(M,[h]),m+=1}}let D=d.get(h.symbolId);if(D){a+=1,c+=D.length,Te(i,h.symbolId,D,r,M=>{l+=1,p+=M});continue}let b=y.get(h.symbolId);if(b){f+=1,u+=b.length,Te(i,h.symbolId,b,r,M=>{l+=1,p+=M});continue}let R=C();if(!R){r&&(o+=1);continue}if(r&&(s+=1),R.referencesForDefinitions){let M=S.get(R);M?M.push(h):S.set(R,[h])}else I.push({provider:R,definition:h})}let k=new Set;if(g)for(let[h,v]of g){if(!h.referencesAndCalleesForDefinitions)continue;let C=S.get(h)??[],D=h.referencesAndCalleesForDefinitions(C,v);k.add(h),Vo(t,D.callees);for(let b of C){if(!D.references.has(b.symbolId))continue;let R=D.references.get(b.symbolId)??[];Te(i,b.symbolId,R,r,M=>{l+=1,p+=M})}}for(let[h,v]of S){if(k.has(h))continue;let C=h.referencesForDefinitions(v);for(let D of v){if(!C.has(D.symbolId))continue;let b=C.get(D.symbolId)??[];Te(i,D.symbolId,b,r,R=>{l+=1,p+=R})}}for(let{provider:h,definition:v}of I){let C=h.referencesFor(v);Te(i,v.symbolId,C,r,D=>{l+=1,p+=D})}return i},()=>({definitions:e.length,providerHits:s,providerMisses:o,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:f,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:m,definitionsWithReferences:l,referenceCount:p,rows:i.size}))}function Te(t,e,n,r,i){t.set(e,n),r&&n.length>0&&i(n.length)}function sn(t,e,n,r){let i=0;for(let s of r){if(s.file===n.relativePath||t.isIgnored(s.file))continue;let o=e.get(n.symbolId);o||(o=new Set,e.set(n.symbolId,o));let a=o.size;o.add(s.file),o.size!==a&&(i+=1)}return i}function Xo(t){try{return JSON.parse(t)}catch{return null}}function ef(t,e){return Pe(t).calleeMap(e)}function tf(t){let e=ze();if(!e)return null;let n=Ve(t);if(n.length===0)return null;let r=new Map;return n.forEach((i,s)=>{for(let o of En(e,[i]))r.has(o)||r.set(o,s)}),i=>r.get(jo(t.config.projectRoot,i))??null}function nf(t,e){let n=new Map,r=new Map;for(let i of e){let s=B(t,i.relativePath);if(!s?.calleeCoverageForDefinitions)continue;let o=r.get(s);o?o.push(i):r.set(s,[i])}for(let[i,s]of r)for(let o of ui(s))for(let[a,c]of i.calleeCoverageForDefinitions(o))n.set(a,c);return n}function Zo(t,e){let n=L(),r=new Map,i=0,s=0,o=0,a=0;return w("semantic.callees.provider-loop",()=>{let c=new Map,f=[];for(let u of e){let l=B(t,u.relativePath);if(!l){n&&(s+=1);continue}n&&(i+=1);let p=u;if(l.calleesForDefinitions){let m=c.get(l);m?m.push(p):c.set(l,[p])}else f.push({provider:l,definition:p})}for(let[u,l]of c)for(let p of ui(l)){let m=u.calleesForDefinitions(p);for(let d of p){let y=m.get(d.symbolId)??[];ai(r,d.symbolId,y,n,S=>{o+=1,a+=S})}}for(let{provider:u,definition:l}of f){let p=u.calleesFor(l);ai(r,l.symbolId,p,n,m=>{o+=1,a+=m})}return r},()=>({definitions:e.length,providerHits:i,providerMisses:s,definitionsWithCallees:o,calleeCount:a,rows:r.size}))}var ea=256;function ui(t){let e=new Map;for(let i of t){let s=e.get(i.relativePath);s?s.push(i):e.set(i.relativePath,[i])}let n=[],r=[];for(let i of e.values())r.length>0&&r.length+i.length>ea&&(n.push(r),r=[]),r.push(...i);return r.length>0&&n.push(r),n}function ai(t,e,n,r,i){n.length>0&&(t.set(e,n),r&&i(n.length))}function rf(t,e){return Pe(t).signature(e)}function ta(t,e){if(O(e.relativePath)==="typescript"){let o="fallback",a=0,c=0,f=0,u=0;return w("typescript.signature.materialize",()=>{let l=Rt(t,e.relativePath,zo);if(l?.key){a=1;let m=oi.read(t,e.relativePath,l.key)??{};if(Object.prototype.hasOwnProperty.call(m,e.symbol))return o="hit",c=1,m[e.symbol]??null;f=1;let d=B(t,e.relativePath);if(!d)return o="unavailable",null;let y=d.signatureFor(e);return oi.write(t,e.relativePath,l.key,{...m,[e.symbol]:y}),o="computed",y}u=1;let p=B(t,e.relativePath);return p?(o="direct-fallback",p.signatureFor(e)):(o="unavailable",null)},()=>({state:o,eligible:a,cacheHits:c,cacheMisses:f,fallbacks:u}))}let n=fi(t,"semantic-signatures",e.relativePath),r=na(e);if(n){let o=ii.read(t,r,n);if(o)return o.signature}let i=B(t,e.relativePath);if(!i)return null;let s=i.signatureFor(e);return n&&ii.write(t,r,n,{signature:s}),s}function fi(t,e,n){let r=Z(t);if(!r)return null;let i=O(n);return i!=="rust"?null:mt(JSON.stringify({kind:e,language:i,engine:Bt(t.config.projectRoot),projectFingerprint:r}))}function na(t){return`${t.relativePath}\0${t.symbol}`}function pi(t){try{let e=JSON.parse(t);return Array.isArray(e)?e:null}catch{return null}}function ra(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function ia(t){try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))return null;for(let n of Object.values(e))if(n!==null&&typeof n!="string")return null;return e}catch{return null}}function di(t,e,n){let r=O(n);if(!r)return{slot:e,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:e,language:r,...X(t,n).availability()}}catch(i){return{slot:e,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function B(t,e){if(!O(e))return null;let n=X(t,e);return n.availability().available?n:null}export{ni as a,Bt as b,O as c,Yu as d,Pe as e,Ju as f,Gu as g,Qu as h,Xu as i,Zu as j,Qo as k,ef as l,tf as m,nf as n,rf as o};
3
- //# sourceMappingURL=chunk-YSYPDRD5.js.map
@@ -1,5 +0,0 @@
1
- import{a as te,b as N,e as V,f as j,g as E,h as re,i as se}from"./chunk-KMVGRIO2.js";import{b as _}from"./chunk-BOJ5SVE2.js";import{c as q}from"./chunk-2BMSSRBH.js";import{a as ie}from"./chunk-BJWFVAA5.js";import{f as ne}from"./chunk-U3SXIMII.js";import{a as D}from"./chunk-F5GSBHC6.js";import{d as I,e as K,j as $}from"./chunk-C7C6AKAT.js";import{a as B}from"./chunk-RBAD4GJ2.js";import{a as Y}from"./chunk-ZLMXIQLC.js";import{c as Q,e as ee,h as U,k as H}from"./chunk-ETC674NS.js";import{d as z,i as J,v as A,y}from"./chunk-KNLQGXVH.js";function ve(e,n,t={}){let{minSimilarity:i=.4,limit:r=20}=t,s=ze(e,n,{semantic:t.semantic!==!1});if(!s)return[];if(!$(s.symbol))return[];if(s.callees.size===0)return ae(e,n,{minSimilarity:i,limit:r,scanLimit:t.scanLimit,candidateMode:t.sourceCandidateMode??"full"});let a=Me(e,s,i,{scanLimit:t.scanLimit,semantic:t.semantic!==!1});return a.length>0?a.slice(0,r):ae(e,n,{minSimilarity:i,limit:r,scanLimit:t.scanLimit,candidateMode:t.sourceCandidateMode??"full"})}function Mn(e,n,t,i={}){let r=D(e,n),s=D(e,t);if(!r||!s)return null;let a=ve(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(m=>m.symbolB===s.symbol||m.symbolA===s.symbol);if(!a)return null;let l=r.endLine-r.startLine+1,c=s.endLine-s.startLine+1;return{symbolA:{symbol:r.symbol,shortName:I(r.symbol),file:r.relativePath,loc:l},symbolB:{symbol:s.symbol,shortName:I(s.symbol),file:s.relativePath,loc:c},similarity:a.similarity,similarityBasis:a.similarityBasis??"callees",sharedEvidence:a.sharedCallees,uniqueToA:a.uniqueToA,uniqueToB:a.uniqueToB,evidenceClass:a.evidenceClass,actionTier:a.actionTier,recommendation:a.recommendation,consolidationStrategy:we(a)}}function we(e){let n=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${n} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${n} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${n} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${n} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${n}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${n}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function Me(e,n,t,i){let r=G(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),s=je(n,r.corpus),a=Oe(s,r),l=Te(s,r),c=j(l),m=E(s.callees,l),g=[];for(let f of a){if(f.callees.size<3)continue;let o=E(f.callees,l),u=ue(s,f,l,{minSimilarity:t,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:m,magnitudeB:o});u&&g.push(u)}return g.sort((f,o)=>o.similarity-f.similarity),g}function Te(e,n){let t=new Map(n.docFreq);for(let i of e.callees)t.set(i,(t.get(i)??0)+1);return V(t,n.corpus.length+1)}function ue(e,n,t,i){let r=Re(e,n,t,i);if(!Ae(r,i))return null;let{similarity:s,significantShared:a,trivialShared:l}=r,c=a.length>0?a:l,m=Se(c,"callees");return{symbolA:e.symbol,shortNameA:I(e.symbol),fileA:e.file,symbolB:n.symbol,shortNameB:I(n.symbol),fileB:n.file,similarity:s,similarityBasis:"callees",sharedCallees:c.map(I),uniqueToA:[...N(e.callees,n.callees)].map(I),uniqueToB:[...N(n.callees,e.callees)].map(I),...m}}function Le(e,n,t,i){let r=i.magnitudeA??E(e.callees,t),s=i.magnitudeB??E(n.callees,t),a=0,l=0,c=0,m=i.medianIdf??j(t);for(let o of e.callees){if(!n.callees.has(o))continue;let u=t.get(o)??0;a+=u*u,c+=1,u>=m&&(l+=1)}if(c===0)return!1;let g=r*s;return(g>0?a/g:0)<i.minSimilarity?!1:l>=i.requireSignificantShared||c>=i.requireSharedCount}function Re(e,n,t,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?re(e.callees,n.callees,t,{medianIdf:i.medianIdf}):se(e.callees,n.callees,t,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function Ae(e,n){if(e.similarity<n.minSimilarity)return!1;let t=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=n.requireSignificantShared||t>=n.requireSharedCount}function Tn(e,n={}){let{minSimilarity:t=.5,limit:i=20,scope:r,minCallees:s=4,crossFileOnly:a=!1,scanLimit:l}=n,c=n.semantic!==!1,m=A(),g=0,f=0,o=0,u=0,d=0,p=0,S=0;return y("similar.all",()=>{let b=G(e).calleeIndex({minCallees:s,scope:r,scanLimit:l,semantic:c}),C=b.corpus;g=C.length;let v=n.focusFiles,k=[],P=0;return y("similar.all.pair-scan",()=>{for(let x=0;x<C.length;x+=1){let F=C[x],T=v?.has(F.file)??!1,w=b.weightedMagnitudes[x],M=new Set;for(let O of F.callees){let L=b.candidateIndexesByCallee.get(O);if(L)for(let R of L)R<=x||v&&!T&&!v.has(C[R].file)||M.add(R)}m&&(o+=M.size,M.size>0&&(f+=1));for(let O of M){let L=C[O];if(a&&F.file===L.file){m&&(d+=1);continue}if(me(F,L)){m&&(p+=1);continue}m&&(u+=1);let R=ue(F,L,b.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:w,magnitudeB:b.weightedMagnitudes[O]});R&&(Be(k,R,i,P),m&&(S+=1),P+=1)}}},()=>({corpusSize:g,candidateSets:f,candidatePairs:o,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:S,topResults:k.length})),y("similar.all.sort-project",()=>(k.sort((x,F)=>F.result.similarity-x.result.similarity||x.order-F.order),k.map(x=>x.result)),()=>({topResults:k.length}))},()=>({minSimilarity:t,limit:i,scope:r,minCallees:s,crossFileOnly:a,scanLimit:l,semantic:c,corpusSize:g,candidateSets:f,candidatePairs:o,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:S}))}function Ln(e,n={}){let{minSimilarity:t=.5,scope:i,minCallees:r=4,crossFileOnly:s=!1,scanLimit:a}=n,l=n.semantic!==!1,c=A(),m=0,g=0,f=0,o=0,u=0,d=0,p=0;return y("similar.all-count",()=>{let h=G(e).calleeIndex({minCallees:r,scope:i,scanLimit:a,semantic:l}),b=h.corpus;m=b.length;let C=n.focusFiles;return y("similar.all-count.pair-scan",()=>{for(let v=0;v<b.length;v+=1){let k=b[v],P=C?.has(k.file)??!1,x=h.weightedMagnitudes[v],F=new Set;for(let T of k.callees){let w=h.candidateIndexesByCallee.get(T);if(w)for(let M of w)M<=v||C&&!P&&!C.has(b[M].file)||F.add(M)}c&&(f+=F.size,F.size>0&&(g+=1));for(let T of F){let w=b[T];if(s&&k.file===w.file){c&&(u+=1);continue}if(me(k,w)){c&&(d+=1);continue}c&&(o+=1),Le(k,w,h.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:x,magnitudeB:h.weightedMagnitudes[T]})&&(p+=1)}}},()=>({corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:o,crossFileSkips:u,signatureSkips:d,insertedResults:p})),p},()=>({minSimilarity:t,scope:i,minCallees:r,crossFileOnly:s,scanLimit:a,semantic:l,corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:o,crossFileSkips:u,signatureSkips:d,insertedResults:p}))}function me(e,n){if(e.paramCount<0||n.paramCount<0)return!1;let t=Math.abs(e.paramCount-n.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,n.paramCount)*.5));return t>i}var de=Q({kind:"source-fingerprints",invalidation:ee("source-fingerprints"),serialize:cn,deserialize:ln});function Be(e,n,t,i){if(t<=0)return;if(e.length<t){e.push({result:n,order:i});return}let r=0;for(let a=1;a<e.length;a+=1){let l=e[a],c=e[r];(l.result.similarity<c.result.similarity||l.result.similarity===c.result.similarity&&l.order>c.order)&&(r=a)}let s=e[r];n.similarity<=s.result.similarity||(e[r]={result:n,order:i})}var Ee=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function ze(e,n,t){let i=D(e,n);if(!i||!$(i.symbol))return null;let r=new q(e),s=ne(e,i,{semantic:t.semantic,semanticEvidence:ie});return{symbol:i.symbol,file:i.relativePath,callees:pe(s.map(a=>a.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var De=z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),qe=z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function fe(e,n){let{minCallees:t,scope:i,excludeSymbol:r,scanLimit:s}=n,a=n.semantic!==!1,l=De.get(e,()=>new Map),c=`${t}|${i??""}|${s??""}|${a}`,m=!0,g=0,f=0;return y("similar.callee-fingerprints.resolve",()=>{let o=l.get(c);if(m=o!==void 0,o||(o=$e(e,{minCallees:t,scope:i,scanLimit:s,semantic:a}),l.set(c,o)),g=o.length,r===void 0)return o;let u=o.filter(d=>d.symbol!==r);return f=o.length-u.length,u},()=>({minCallees:t,scope:i,scanLimit:s,semantic:a,cacheHit:m,corpusSize:g,excludeSymbol:r!==void 0,excludedSymbols:f}))}function Ne(e,n){let{minCallees:t,scope:i,scanLimit:r}=n,s=n.semantic!==!1,a=qe.get(e,()=>new Map),l=`${t}|${i??""}|${r??""}|${s}`,c=!0,m=0,g=0,f=0;return y("similar.callee-index.resolve",()=>{let o=a.get(l);return c=o!==void 0,o||(o=Pe(fe(e,{minCallees:t,scope:i,scanLimit:r,semantic:s})),a.set(l,o)),m=o.corpus.length,g=o.docFreq.size,f=o.candidateIndexesByCallee.size,o},()=>({minCallees:t,scope:i,scanLimit:r,semantic:s,cacheHit:c,corpusSize:m,indexedCallees:g,candidateBuckets:f}))}function G(e){return{calleeCorpus:n=>fe(e,n),calleeIndex:n=>Ne(e,n),sourceCorpus:(n={})=>Fe(e,n),sourceIndex:(n={})=>ce(e,n),sourceCandidates:(n,t)=>(t.candidateMode??"full")==="target-pruned"?Qe(e,n,{minSimilarity:t.minSimilarity,scanLimit:t.scanLimit}):Ye(n,ce(e,{scanLimit:t.scanLimit}))}}function Pe(e){let n=A(),t=0,i=y("similar.callee-index.doc-frequency",()=>{let o=new Map;for(let u of e)for(let d of u.callees)o.set(d,(o.get(d)??0)+1);return t=o.size,o},()=>({corpusSize:e.length,uniqueCallees:t})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),s=y("similar.callee-index.idf-weights",()=>V(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),a=y("similar.callee-index.weighted-magnitudes",()=>e.map(o=>E(o.callees,s)),()=>({corpusSize:e.length})),l=0,c=0,m=0,g=y("similar.callee-index.candidate-buckets",()=>{let o=new Map;for(let u=0;u<e.length;u+=1){let d=e[u];for(let p of d.callees){if((i.get(p)??0)>r){n&&(c+=1);continue}let S=o.get(p);S||(S=[],o.set(p,S)),S.push(u),n&&(l+=1)}}return n&&(m=o.size),o},()=>({corpusSize:e.length,buckets:m,candidateRefs:l,ubiquitousSkips:c,ubiquityThreshold:r})),f=y("similar.callee-index.median-idf",()=>j(s),()=>({uniqueCallees:s.size}));return{corpus:e,candidateIndexesByCallee:g,docFreq:i,idfWeights:s,weightedMagnitudes:a,medianIdf:f,ubiquityThreshold:r}}function Oe(e,n){let t=new Map;for(let i of e.callees)for(let r of n.candidateIndexesByCallee.get(i)??[]){let s=n.corpus[r];s.symbol!==e.symbol&&t.set(s.symbol,s)}return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function $e(e,n){let{minCallees:t,scope:i,scanLimit:r,semantic:s}=n,a=A(),l=new q(e),c=0,m=y("similar.callee-fingerprints.candidates",()=>{let p=_(l.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=p.length,p},()=>({scope:i,scanLimit:r,candidateCount:c})),g=0,f=y("similar.callee-fingerprints.callee-map",()=>{let p=l.calleeMap(m,{semantic:s});if(a)for(let S of p.values())g+=S.length;return p},()=>({candidateCount:c,semantic:s,calleeEdges:g})),o=0,u=0,d=0;return y("similar.callee-fingerprints.shape",()=>{let p=m.map(b=>({symbol:b.symbol,file:b.relativePath,callees:pe((f.get(b.symbolId)??[]).filter(C=>C.kind!=="jsx-render").map(C=>C.symbol)),paramCount:l.callableSignature(b)?.paramCount??-1})),S=_e(p);a&&(d=S.filter((b,C)=>b.callees.size!==p[C].callees.size).length);let h=S.filter(b=>b.callees.size>=t);return o=h.length,a&&(u=h.reduce((b,C)=>b+C.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:o,retainedCalleeCount:u,minCallees:t,siblingSaturatedFingerprints:d}))}var ge=5;function _e(e){let n=new Map;for(let t of e){let i=n.get(t.file);i||(i=new Map,n.set(t.file,i));for(let r of t.callees)i.set(r,(i.get(r)??0)+1)}return e.map(t=>{let i=n.get(t.file);if(!i)return t;let r=[...t.callees].filter(a=>(i.get(a)??0)>=ge);if(r.length===0)return t;let s=new Set(t.callees);for(let a of r)s.delete(a);return{...t,callees:s}})}function je(e,n){let t=new Map;for(let s of n)if(!(s.file!==e.file||s.symbol===e.symbol))for(let a of s.callees)t.set(a,(t.get(a)??0)+1);let i=[...e.callees].filter(s=>(t.get(s)??0)+1>=ge);if(i.length===0)return e;let r=new Set(e.callees);for(let s of i)r.delete(s);return{...e,callees:r}}function pe(e){return new Set([...e].filter(n=>!Ge(n)))}function Ge(e){return Ee.some(n=>e.includes(n))}function ae(e,n,t){let i=Ve(e,n);if(!i||i.tokens.size<3)return[];let r=t.minSimilarity>=.5?t.minSimilarity:.3,s=[],a=t.candidateMode??"full",l=0,c=0,m=0,g=0;return y("similar.source-shape",()=>{let o=G(e).sourceCandidates(i,{minSimilarity:r,scanLimit:t.scanLimit,candidateMode:a});l=o.length;for(let u of o){if(u.symbol===i.symbol||u.tokens.size<3)continue;c+=1;let d=te(i.tokens,u.tokens);if(d.size<2){m+=1;continue}let p=new Set([...i.tokens,...u.tokens]),S=p.size>0?d.size/p.size:0;if(S<r){g+=1;continue}s.push({symbolA:i.symbol,shortNameA:I(i.symbol),fileA:i.file,symbolB:u.symbol,shortNameB:I(u.symbol),fileB:u.file,similarity:S,similarityBasis:"source-tokens",sharedCallees:[...d].sort(),uniqueToA:[...N(i.tokens,u.tokens)].sort(),uniqueToB:[...N(u.tokens,i.tokens)].sort(),...Se([...d],"source-tokens")})}return s.sort((u,d)=>d.similarity-u.similarity||u.shortNameB.localeCompare(d.shortNameB)),s.slice(0,t.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:a,candidates:l,comparedPairs:c,sharedSkips:m,similaritySkips:g,results:s.length}))}function Se(e,n){let t=e.flatMap(W),i=e.flatMap(S=>oe(S,n)),r=Z(t,be),s=Z(t,ye),a=Z(i,X),l=[...new Set(i.filter(le))],c=e.filter(S=>{let h=oe(S,n);return h.some(b=>X.has(b))&&h.some(le)}).length,m=[];r.length>0&&m.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),s.length>0&&m.push(`framework/generic scaffolding: ${s.slice(0,5).join(", ")}`),a.length>0&&m.push(`domain behavior verbs: ${a.slice(0,5).join(", ")}`),a.length>0&&l.length>0&&m.push(`domain-specific terms: ${l.slice(0,5).join(", ")}`);let g=n==="source-tokens"&&t.length>0&&t.every(S=>he.has(S));g&&m.push("shared source tokens are generic scaffolding");let f=a.length>0&&l.length>0,o=r.length+s.length>0,u=n==="callees"&&f&&e.length>=4&&l.length>=4&&c>=2,d=u?"domain-behavior":f?o?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":s.length>0||g?"framework-scaffolding":"structural-overlap";d==="structural-overlap"&&e.length>0&&m.push(`shared ${n} overlap has no recognized domain or scaffolding category`);let p=d==="domain-behavior"&&(e.length>=3||u)?"direct":"signal";return{evidenceClass:d,actionTier:p,evidenceClassReasons:m,recommendation:Ue(d,p)}}function Ue(e,n){return n==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function Z(e,n){return[...new Set(e.filter(t=>n.has(t)))]}function W(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>1)}function oe(e,n){if(n==="source-tokens")return W(e);let t=K(e);return W(t.length>0?t:He(e))}function He(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function le(e){return e.length>3&&!X.has(e)&&!be.has(e)&&!ye.has(e)&&!he.has(e)&&!Ke.has(e)}var X=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),be=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),ye=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),he=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Ke=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function Ve(e,n){let t=D(e,n);if(!t||!$(t.symbol))return null;let i=Ze(e,t);return i?{symbol:t.symbol,file:t.relativePath,tokens:i}:null}function Ze(e,n){let t=K(n.symbol),i=sn(e,n.relativePath,n.startLine,n.endLine,t),r=Ie(i,t);return r.size>0?r:null}var We=z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Xe=z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Ce(e){return`${e.scanLimit??""}`}function Fe(e,n={}){let t=We.get(e,()=>new Map),i=Ce(n),r=t.get(i);return r||(r=rn(e,n),t.set(i,r)),r}function ce(e,n={}){let t=Xe.get(e,()=>new Map),i=Ce(n),r=t.get(i);return r||(r=Je(Fe(e,n)),t.set(i,r)),r}function Je(e){let n=new Map;for(let r of e)for(let s of r.tokens)n.set(s,(n.get(s)??0)+1);let t=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let s of r.tokens){if((n.get(s)??0)>t)continue;let a=i.get(s);a||(a=[],i.set(s,a)),a.push(r)}return{corpus:e,candidateByToken:i,docFreq:n,ubiquityThreshold:t}}function Ye(e,n){let t=new Map;for(let i of e.tokens)for(let r of n.candidateByToken.get(i)??[])r.symbol!==e.symbol&&t.set(r.symbol,r);return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function Qe(e,n,t){let i=A(),r=new q(e),s=en(n.tokens.size,t.minSimilarity),a=0,l=0,c=0,m=y("similar.source-shape.target-files",()=>{let d=[...n.tokens],p=[];for(let S of Y(e,{includeIgnored:!1})){a+=1;let h=U(e,S);h&&(l+=1,nn(h,d,s)&&p.push(S))}return c=p.length,p},()=>({symbol:n.symbol,targetTokens:n.tokens.size,requiredSharedTokens:s,scannedFiles:a,readableFiles:l,candidateFiles:c})),g=0,f=y("similar.source-shape.target-definitions",()=>{let d=_(r.productionCallableDefinitions({files:m,sortByLocDesc:typeof t.scanLimit=="number"&&t.scanLimit>0}),t.scanLimit);return g=d.length,d},()=>({symbol:n.symbol,candidateFiles:c,scanLimit:t.scanLimit,definitionCount:g})),o=0;return y("similar.source-shape.target-fingerprints",()=>{let d=xe(e,f);return i&&(o=d.length),d},()=>({symbol:n.symbol,definitionCount:g,fingerprintCount:o})).filter(d=>d.symbol!==n.symbol)}function en(e,n){return Math.max(2,Math.ceil(e*n))}function nn(e,n,t){if(n.length<t)return!1;let i=e.toLowerCase(),r=0;for(let s of n)if(tn(i,s)&&(r+=1,r>=t))return!0;return!1}function tn(e,n){return n==="num"?/\b\d+\b/.test(e):e.includes(n)}function rn(e,n={}){let t=new q(e),{scanLimit:i}=n,r=_(t.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return xe(e,r)}function xe(e,n){let t=new Map;for(let r of n){let s=t.get(r.relativePath)??[];s.push(r),t.set(r.relativePath,s)}let i=new Map;for(let[r,s]of t){let a=U(e,r);if(!a)continue;let l=J(e,r,a),c=on(e,r,l),m=!1,g=null;for(let f of s){let o=an(f),u=c.get(o),d=u?new Set(u.tokens):null;d||(g??=H(e,r),d=Ie(ke(g,f.startLine,f.endLine,f.leaf),f.leaf),c.set(o,{key:o,symbol:f.symbol,startLine:f.startLine,endLine:f.endLine,leaf:f.leaf,tokens:[...d].sort()}),m=!0),d.size>0&&i.set(f.symbol,{symbol:f.symbol,file:f.relativePath,tokens:d})}m&&un(e,r,l,c)}return n.map(r=>i.get(r.symbol)).filter(r=>!!r)}function sn(e,n,t,i,r){let s=H(e,n);return s.length===0?"":ke(s,t,i,r)}function ke(e,n,t,i){if(t>=n&&t-n<=12)return e.slice(n,t+1).join(`
2
- `);let r=[new RegExp(`\\bdef\\s+${B(i)}\\b`),new RegExp(`\\bfun\\s+${B(i)}\\b`),new RegExp(`\\bfn\\s+${B(i)}\\b`),new RegExp(`\\bfunction\\s+${B(i)}\\b`),new RegExp(`\\b${B(i)}\\s*\\(`)],s=e.findIndex(a=>r.some(l=>l.test(a)));if(s>=0){let a=s;for(let l=s+1;l<e.length&&l<=s+8;l++){let c=e[l]??"";if(l>s&&dn(c)||(a=l,c.trim()===""&&l>s+1))break}return e.slice(s,a+1).join(`
3
- `)}return e.slice(n,Math.min(e.length,n+8)).join(`
4
- `)}function an(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function on(e,n,t){return de.read(e,n,t)??new Map}function ln(e){try{let n=JSON.parse(e);if(!Array.isArray(n.entries))return null;let t=new Map;for(let i of n.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;t.set(i.key,i)}return t}catch{return null}}function cn(e){let n={entries:[...e.values()].sort((t,i)=>t.key.localeCompare(i.key))};return JSON.stringify(n)}function un(e,n,t,i){de.write(e,n,t,new Map(i))}function Ie(e,n){if(!e)return new Set;let t=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=mn(n),s=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(a=>a.trim()).filter(a=>a.length>1).filter(a=>!t.has(a)).filter(a=>!i.has(a));return new Set(s)}function mn(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(n=>n.toLowerCase()).filter(n=>n.length>1))}function dn(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}export{ve as a,Mn as b,Te as c,ue as d,Tn as e,Ln as f,Be as g,fe as h,Ne as i,G as j,Pe as k,Oe as l,ge as m,_e as n,pe as o,Se as p};
5
- //# sourceMappingURL=chunk-ZFVPWH62.js.map
@@ -1,2 +0,0 @@
1
- import{a as p}from"./chunk-7KCZELVM.js";import{e as h,f as u}from"./chunk-AADQLOQ4.js";import{a as t}from"./chunk-WDSFQDPN.js";import{a as m}from"./chunk-2USA3S3P.js";import{c as i,g as d}from"./chunk-BL6DCHQP.js";function k(c,v,y={}){let l=m(c,v);if(!l)return null;let o=y.semantic!==!1,b=u(c,l,{semantic:o,semanticEvidence:t}).filter(e=>d(e.symbol)).slice(0,50),g=p(h(c,l,{limit:50,additive:!0,callableOnly:!0,semantic:o,semanticEvidence:t})),r=b.map(e=>({symbol:e.symbol,shortName:i(e.symbol),file:e.file,relationship:e.source!=="caller-map-inversion"?"reference-candidate":e.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="caller-map-inversion"&&e.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:e.callEvidence??e.source})),s=g.map(e=>({symbol:e.symbol,shortName:i(e.symbol),file:e.file,relationship:e.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="scip-chunk"?"candidate":"exact",evidenceSource:e.source,...e.kind==="jsx-render"?{interaction:"render"}:{}}));return{symbol:l.symbol,shortName:i(l.symbol),callers:r.map(({symbol:e,shortName:a,file:n})=>({symbol:e,shortName:a,file:n})),callees:s.map(({symbol:e,shortName:a,file:n})=>({symbol:e,shortName:a,file:n})),callerEvidence:r,calleeEvidence:s,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence"]}}}export{k as a};
2
- //# sourceMappingURL=chunk-ZGIHTH27.js.map
@@ -1,2 +0,0 @@
1
- import{Aa as k,Ca as b,Ea as j,f as T,va as x,x as v,ya as m,za as P}from"./chunk-JZ2A7LDM.js";import{createHash as A}from"crypto";import{isUtf8 as K}from"buffer";import{TextDecoder as _}from"util";var O=new _("utf-8",{fatal:!0});function H(e){return j(e.config.projectRoot)}function V(e,t){let i=T(t),n;try{n=m(e.config.projectRoot,i,{inputKind:"repository text file"})}catch(o){if(b(o)||o instanceof x)return null;throw o}let r=W(n);return r===null?null:w(i,n,r,E(e),L(e))}function X(e,t={}){let i=[],n=C(e,t,r=>i.push(r));return{files:i,candidateFiles:n.candidateFiles,scannedBytes:n.scannedBytes,skippedBinaryPaths:n.skippedBinaryPaths,skippedUnreadablePaths:n.skippedUnreadablePaths,skippedOversizedPaths:n.skippedOversizedPaths}}function C(e,t,i){let n=H(e).filter(s=>!t.scope||s.includes(t.scope)),r=E(e),o=L(e),u=[],S=[],B=[],f=0,d=0,h={aligned:0,stale:0,unavailable:0},l=t.literalBytes?Buffer.isBuffer(t.literalBytes)?[t.literalBytes]:[...t.literalBytes]:[],F=l.length>0?Buffer.allocUnsafe(1024*1024):void 0;for(let s of n){let c,p,g=[],y=o.has(s);try{if(l.length>0){let a=l.length===1?P(e.config.projectRoot,s,l[0],{inputKind:"repository text file",computeSha256:y,scratchBuffer:F}):k(e.config.projectRoot,s,l,{inputKind:"repository text file",computeSha256:y,scratchBuffer:F});if(!a.isUtf8Text){u.push(s);continue}f+=a.byteLength,d+=1,p=a.sha256;let z=R(s,p,r,o);if(h[z.state]+=1,g="matchedLiteralIndexes"in a?a.matchedLiteralIndexes:a.includesLiteral?[0]:[],g.length===0||!a.bytes)continue;c=a.bytes}else c=m(e.config.projectRoot,s,{inputKind:"repository text file"})}catch(a){if(a instanceof x){B.push(s);continue}if(b(a))continue;S.push(s);continue}if(l.length===0&&!I(c)){u.push(s);continue}if(l.length===0){f+=c.byteLength,d+=1,p=y?M(c):void 0;let a=R(s,p,r,o);h[a.state]+=1}if(t.includeBytes&&!t.includeBytes(s,c))continue;let U=O.decode(c);i(w(s,c,U,r,o,p),g)}return{candidateFiles:n.length,scannedTextFiles:d,semanticFiles:h,scannedBytes:f,skippedBinaryPaths:u,skippedUnreadablePaths:S,skippedOversizedPaths:B}}function w(e,t,i,n,r,o){let u=o??M(t);return{relativePath:e,text:i,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:u},semantic:R(e,u,n,r)}}}function R(e,t,i,n){if(!n.has(e))return{state:"unavailable",basis:"no-compiler-document"};let r=i.get(e);return!r||!t?{state:"unavailable",basis:"fingerprint-unavailable"}:{state:r===t?"aligned":"stale",basis:"indexed-input-fingerprint"}}function L(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function E(e){let t=new Map;if(!e.generation.metadataRaw)return t;let i=v(e.generation.metadataRaw);if(i.kind!=="legacy"&&i.kind!=="supported")return t;let n=i.metadata.fingerprint;if(!D(n)||!Array.isArray(n.files))return t;for(let r of n.files)!D(r)||typeof r.path!="string"||typeof r.hash!="string"||t.set(r.path,r.hash);return t}function W(e){return I(e)?O.decode(e):null}function I(e){return!e.includes(0)&&K(e)}function M(e){return A("sha256").update(e).digest("hex")}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}export{H as a,V as b,X as c,C as d};
2
- //# sourceMappingURL=chunk-ZGIQN2SX.js.map
@@ -1,12 +0,0 @@
1
- import{c as Re,f as ir,g as te,h as or,i as Y,j as ar,k as Ae,l as it,m as L,n as sr,p as cr,q as ne,r as Le,s as De,v as z,w as ie}from"./chunk-SYVJEEUJ.js";import{c as tr,d as rr,e as ve,f as Te,i as Pe,j as C,k as ke,m as yr,n as hr,o as Sr}from"./chunk-QBQE7ZJ5.js";import{h as M,y as oe}from"./chunk-KNLQGXVH.js";import{C as T,D as ee,E as R,F as xe,G as rt,H as v,I as P,J as _,Ja as at,N as er,O as we,P as nr,Q as nt,S as Ee,T as $,U as re,V as dr,W as lr,b as Qe,f as Ze,g as Yt,i as Kt,j as Xt,k as Ie,la as ur,o as Qt,oa as fr,pa as pr,q as et,qa as gr,ra as mr,u as N,ua as ot,v as tt,x as Zt}from"./chunk-JZ2A7LDM.js";import{spawn as ni}from"child_process";import{platform as br}from"os";import{performance as Ir}from"perf_hooks";var bs={probe:1e4,git:3e4,analysis:18e4,install:3e5,indexer:6e5},se=class extends Error{constructor(r,n,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=r;this.label=n;this.name="BoundedProcessError",this.timedOut=o.timedOut??!1,this.reaped=o.reaped??!1,this.stdout=o.stdout??"",this.stderr=o.stderr??"",this.stdoutTruncated=o.stdoutTruncated??!1,this.stderrTruncated=o.stderrTruncated??!1}kind;label;timedOut;reaped;stdout;stderr;stdoutTruncated;stderrTruncated};function ae(e,t){if(!Number.isFinite(e)||e<=0)throw new TypeError(`${t} must be a positive finite number.`)}function xr(e,t,r,n){let i=Math.max(0,n-r);i>0&&e.push(t.subarray(0,i))}function wr(e,t,r){let n=Buffer.concat([...e,t]);e.length=0,e.push(n.subarray(Math.max(0,n.length-r)))}function Is(e){ae(e.timeoutMs,"timeoutMs"),ae(e.maxStdoutBytes,"maxStdoutBytes"),ae(e.maxStderrBytes,"maxStderrBytes");let t=e.terminationGraceMs??1e3;ae(t,"terminationGraceMs");let r=e.terminationForceMs??t;return ae(r,"terminationForceMs"),new Promise((n,i)=>{let o=Ir.now(),a=br()!=="win32"&&process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1",s=br()!=="win32"&&!a,c;try{c=ni(e.command,[...e.args??[]],{cwd:e.cwd,env:e.env,detached:s?!0:e.detached,stdio:["pipe","pipe","pipe"]})}catch(S){let w=S instanceof Error?S.message:String(S);i(new se("spawn",e.label,`${e.label} could not start: ${w}`,{cause:S,reaped:!0}));return}let d=[],l=[],p=0,u=0,b=!1,g=!1,h=null,y=!1,k=c.pid===void 0?null:hr(c.pid,s),F=()=>{clearTimeout(Ht),e.signal?.removeEventListener("abort",Ye)},He=S=>{if(y||!h)return;y=!0,F();let w=Buffer.concat(d).toString("utf8"),Ke=Buffer.concat(l).toString("utf8"),Xe=S.reaped||!S.detail?"":` Process-tree cleanup failed: ${S.detail}`;i(new se(h.kind,e.label,`${h.message}${Xe}`,{timedOut:h.timedOut,reaped:S.reaped,stdout:w,stderr:Ke,stdoutTruncated:b,stderrTruncated:g}))},Z=S=>{if(!(h||y)){if(h=S,!k){He({reaped:c.pid===void 0,reason:c.pid===void 0?"terminated":"identity-unavailable"});return}Sr(k,{gracefulMs:t,forceMs:r}).then(He,w=>{He({reaped:!1,reason:"signal-failed",detail:w instanceof Error?w.message:String(w)})})}},Ht=setTimeout(()=>{Z({kind:"timeout",timedOut:!0,message:`${e.label} timed out after ${e.timeoutMs}ms.`})},e.timeoutMs);Ht.unref();let Ye=()=>{Z({kind:"aborted",timedOut:!1,message:`${e.label} was cancelled.`})};e.signal?.addEventListener("abort",Ye,{once:!0}),e.signal?.aborted&&Ye(),c.stdout.on("data",S=>{let w=Buffer.isBuffer(S)?S:Buffer.from(S);e.outputLimitBehavior==="truncate-tail"?wr(d,w,e.maxStdoutBytes):xr(d,w,p,e.maxStdoutBytes),p+=w.length,p>e.maxStdoutBytes&&(b=!0,e.outputLimitBehavior!=="truncate-tail"&&Z({kind:"stdout-limit",timedOut:!1,message:`${e.label} exceeded stdout limit (${e.maxStdoutBytes} bytes).`}))}),c.stderr.on("data",S=>{let w=Buffer.isBuffer(S)?S:Buffer.from(S);e.outputLimitBehavior==="truncate-tail"?wr(l,w,e.maxStderrBytes):xr(l,w,u,e.maxStderrBytes),u+=w.length,u>e.maxStderrBytes&&(g=!0,e.outputLimitBehavior!=="truncate-tail"&&Z({kind:"stderr-limit",timedOut:!1,message:`${e.label} exceeded stderr limit (${e.maxStderrBytes} bytes).`}))}),c.on("error",S=>{if(!y&&!h){if(c.pid===void 0){F(),y=!0,i(new se("spawn",e.label,`${e.label} could not start: ${S.message}`,{cause:S,reaped:!0}));return}Z({kind:"spawn",timedOut:!1,message:`${e.label} failed after start: ${S.message}`})}}),c.on("close",(S,w)=>{if(y||h)return;y=!0,F();let Ke=Buffer.concat(d).toString("utf8"),Xe=Buffer.concat(l).toString("utf8");n({status:S,signal:w,stdout:Ke,stderr:Xe,timedOut:!1,durationMs:Ir.now()-o,stdoutTruncated:b,stderrTruncated:g})}),e.input===void 0?c.stdin.end():c.stdin.end(e.input)})}import{execFileSync as Be}from"child_process";import{createRequire as wi}from"module";import{chmodSync as vi,existsSync as Dr}from"fs";import{platform as j,arch as Ge}from"os";import{dirname as Ri,join as kr}from"path";import{createHash as Er,randomUUID as ii}from"crypto";import{closeSync as Ce,createReadStream as oi,existsSync as ai,fsyncSync as si,mkdirSync as ci,openSync as ct,renameSync as di,unlinkSync as li,writeSync as ui}from"fs";import{homedir as fi}from"os";import{dirname as Tr,join as st}from"path";var pi=3e5,gi=256*1024*1024;function Pr(e,t=process.env){let r=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?st(t.XDG_CACHE_HOME,"scip-query"):st(fi(),".cache","scip-query"));return st(r,e)}var x=class extends Error{constructor(r,n,i={}){super(n,i.cause===void 0?void 0:{cause:i.cause});this.kind=r;this.name="VerifiedBinaryFetchError"}kind};async function Ar(e){let{cachePath:t,url:r,expectedSha256:n}=e,i=e.timeoutMs??pi,o=e.maxBytes??gi,a=e.lockWaitMs??i;mi(i,o,a);let s=yi(r,i,e.signal);try{let c=await vr(t,n,o,s.controller.signal);if(c)return{status:"cached",path:t,sha256:c};ci(Tr(t),{recursive:!0});let d=await or(`${t}.fetch.lock`,{waitMs:a,pollMs:25,signal:s.controller.signal});if(!d)throw new x("lock-timeout",`timed out waiting ${a}ms for verified binary cache ownership at ${t}`);try{let l=await vr(t,n,o,s.controller.signal);return l?{status:"cached",path:t,sha256:l}:await hi(e,s.controller,o)}finally{d.release()}}catch(c){throw s.controller.signal.aborted?K(s.controller.signal,r):c instanceof x?c:new x("stream",`failed to download ${r}: ${Lr(c)}`,{cause:c})}finally{clearTimeout(s.timeout),s.detachExternalAbort(),s.controller.signal.aborted||s.controller.abort()}}function mi(e,t,r){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(r)||r<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function yi(e,t,r){let n=new AbortController,i=()=>{n.abort(new x("aborted",`download of ${e} was aborted`,{cause:r?.reason}))};r?.addEventListener("abort",i,{once:!0}),r?.aborted&&i();let o=setTimeout(()=>{n.abort(new x("timeout",`download of ${e} timed out after ${t}ms`))},t);return o.unref(),{controller:n,timeout:o,detachExternalAbort:()=>r?.removeEventListener("abort",i)}}async function vr(e,t,r,n){if(!ai(e))return null;let i=Er("sha256"),o=0;try{for await(let s of oi(e,{signal:n})){let c=Buffer.isBuffer(s)?s:Buffer.from(s);if(o+=c.length,o>r)return null;i.update(c)}}catch{if(n.aborted)throw K(n,e);return null}let a=i.digest("hex");return a===t?a:null}async function hi(e,t,r){let n=e.fetchImpl??fetch,i;try{i=await Rr(n(e.url,{signal:t.signal}),t.signal)}catch(d){throw t.signal.aborted?K(t.signal,e.url):new x("stream",`failed to download ${e.url}: ${Lr(d)}`,{cause:d})}if(!i.ok){let d=new x("http",`failed to download ${e.url}: HTTP ${i.status}`);throw t.abort(d),d}let o=Si(i,r,e.url);if(!i.body)throw new x("stream",`downloaded ${e.url} response has no readable body`);let a=`${e.cachePath}.tmp-${process.pid}-${ii()}`,s,c=!1;try{s=ct(a,"wx",384),c=!0;let d=i.body.getReader(),l=Er("sha256"),p=0;for(;;){let{done:b,value:g}=await Rr(d.read(),t.signal);if(b)break;if(!(g instanceof Uint8Array))throw new x("stream",`downloaded ${e.url} produced a non-byte stream chunk`);if(p+=g.byteLength,p>r||o!==void 0&&p>o){let y=new x("length",`downloaded ${e.url} exceeded its ${o??r} byte limit`);throw t.abort(y),y}let h=Buffer.from(g.buffer,g.byteOffset,g.byteLength);l.update(h),nr(s,h,{writeFile:e.writeImpl??ui},"verified binary staging")}if(o!==void 0&&p!==o)throw new x("length",`downloaded ${e.url} length mismatch: declared ${o} bytes, received ${p}`);let u=l.digest("hex");if(u!==e.expectedSha256)throw new x("checksum",`downloaded ${e.url} checksum mismatch: expected ${e.expectedSha256}, got ${u}`);Ce(s),s=void 0;try{bi(a,e.cachePath,e.renameImpl??di,e.syncImpl??si)}catch(b){throw new x("install",`failed to install verified binary at ${e.cachePath}`,{cause:b})}return c=!1,{status:"downloaded",path:e.cachePath,sha256:u}}catch(d){throw t.signal.aborted?K(t.signal,e.url):d instanceof x?d:new x("install",`failed to stage verified binary at ${e.cachePath}`,{cause:d})}finally{if(s!==void 0)try{Ce(s)}catch{}if(c)try{li(a)}catch{}}}function Si(e,t,r){let n=e.headers?.get("content-length");if(n==null)return;if(!/^\d+$/.test(n))throw new x("length",`downloaded ${r} has an invalid Content-Length header`);let i=Number(n);if(!Number.isSafeInteger(i)||i<0)throw new x("length",`downloaded ${r} has an invalid Content-Length header`);if(i>t)throw new x("length",`downloaded ${r} declares ${i} bytes, above the ${t} byte limit`);return i}function bi(e,t,r,n){Ii(e,n),r(e,t),xi(Tr(t),n)}function Ii(e,t){let r=ct(e,"r");try{t(r)}finally{Ce(r)}}function xi(e,t){let r;try{r=ct(e,"r")}catch(n){if(nt(n,process.platform))return;throw n}try{t(r)}catch(n){if(!nt(n,process.platform))throw n}finally{Ce(r)}}function Rr(e,t){return t.aborted?Promise.reject(K(t,"operation")):new Promise((r,n)=>{let i=()=>{t.removeEventListener("abort",i),n(K(t,"operation"))};t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})})}function K(e,t){return e.reason instanceof Error?e.reason:new x("aborted",`verified binary operation for ${t} was aborted`)}function Lr(e){return e instanceof Error?e.message:String(e)}var E="v0.8.1",dt="https://github.com/sourcegraph/scip",Oe=`github.com/sourcegraph/scip/cmd/scip@${E}`,Cr=wi(import.meta.url),Ei={"scip-darwin-amd64.tar.gz":"39f18be957d350bcd9ed5cb12d7781b0e237a5cb2429a107feaf9ce2d1dcd5d5","scip-darwin-arm64.tar.gz":"5b3f4a2fb1dc10c599cb3422ed0406a739060e4ac0b1222c0f43630dd0dd8221","scip-linux-amd64.tar.gz":"16b79ed98f893abd530cfa63f333527f1351008b4a23e02b9e522e34d1da6596","scip-linux-arm64.tar.gz":"876dfb680119dd6e5713077c49b27701102d598bdeba94c809173276d399c7e2"},Or="SCIP_QUERY_SCIP_BIN";function _s(e=process.env){return e.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"}function Ti(e){let t=e.env[Or];if(t&&e.fileExists(t))return{source:"env",path:t};let r=e.resolveCached?.()??null;if(r)return{source:"cache",path:r};if(e.isOnPath("scip"))return{source:"path",path:"scip"};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function Pi(e){for(let t of e==="arm64"?["arm64","x64"]:[e])try{return Cr.resolve(`scip-query-scip-windows/scip-win32-${t}.exe`)}catch{}return null}function lt(e=process.env){return Ai(e)?.path??null}function Ai(e=process.env){let t=Ti({platform:j(),arch:Ge(),env:e,isOnPath:ke,fileExists:Dr,resolveSidecar:Pi,resolveCached:()=>Li(e)});return t?.source==="path"?{source:"path",path:yr("scip")??t.path}:t}function Br(e=process.env){return Pr(kr("scip",E,"scip"),e)}function Li(e){let t=Br(e);return Dr(t)?t:null}function Di(e){return e!==null&&e.includes(E.replace(/^v/,""))}function Ms(){return lt()!==null}function ki(){let e=lt();if(!e)return null;try{return Be(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}function Ci(e=j(),t=Ge()){let r=Gr(e,t);if(!r)return null;let n=Ei[r.filename];return n?{...r,sha256:n}:null}function Gr(e=j(),t=Ge()){let r,n,i;switch(e){case"darwin":r="darwin",i="tar.gz";break;case"linux":r="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":n="arm64";break;case"x64":n="amd64";break;default:return null}let o=`scip-${r}-${n}.${i}`;return{url:`${dt}/releases/download/${E}/${o}`,filename:o}}function Fs(){let e=Gr();if(console.log("\nThe `scip` CLI is required but not found on PATH.\n"),j()==="darwin"||j()==="linux")console.log(`Let scip-query install the reviewed release (${E}, digest-verified) into its cache:`),console.log(` scip-query setup --install-missing
2
- `),console.log("Or install it with Go:"),console.log(` go install ${Oe}
3
- `),console.log("Or download that exact release manually:");else if(j()==="win32"){let t=Oi();console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(` npm install -g ${t}`),console.log(`Or set ${Or} to a local scip.exe path.
4
- `),console.log("Upstream release page:")}else console.log("Download from:");console.log(e?` ${e.url}
5
- `:` ${dt}/releases/tag/${E}
6
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Oi(){let t=Cr("../../package.json").optionalDependencies?.["scip-query-scip-windows"];if(!t||!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(t))throw new Error("scip-query package metadata does not declare an exact Windows sidecar version.");return`scip-query-scip-windows@${t}`}var Bi={fetch:Ar,extract:(e,t)=>{Be("tar",["-xzf",e,"-C",t,"scip"],{stdio:"pipe",timeout:12e4,killSignal:"SIGKILL"})},markExecutable:e=>vi(e,493),probeVersion:e=>_i(e),env:process.env};async function Gi(e,t={}){let r={...Bi,...t},n=Ci();if(!n)return e(`No reviewed scip ${E} release archive is published for ${j()}/${Ge()}.`),null;let i=Br(r.env),o=Ri(i),a=kr(o,n.filename);e(`Downloading reviewed scip ${E} (${n.filename}, sha256 ${n.sha256.slice(0,12)}\u2026).`);try{let c=await r.fetch({cachePath:a,url:n.url,expectedSha256:n.sha256});r.extract(c.path,o),r.markExecutable(i)}catch(c){return e(`Could not install scip ${E}: ${c instanceof Error?c.message:String(c)}`),null}let s=r.probeVersion(i);return Di(s)?(e(`Installed reviewed scip ${E} at ${i}.`),i):(e(`Installed scip at ${i} did not report ${E} (reported: ${s??"unavailable"}).`),null)}function _i(e){try{return Be(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}async function Ns(e,t={}){if(j()!=="win32"&&await Gi(e,t)!==null)return!0;if(ke("go")){e(`Installing immutable ${Oe} via go install into the Go bin directory (GOBIN or GOPATH/bin); expected executable: scip.`);try{if(Be("go",["install",Oe],{stdio:"inherit",timeout:3e5,env:process.env}),ke("scip")){let r=lt(),n=ki();if(r&&n&&n.includes(E))return e(`Successfully installed ${Oe}; resolved executable: ${r}; reported version: ${n}.`),!0;e(`go install completed, but the resolved scip executable did not report ${E} (executable: ${r??"unresolved"}; version: ${n??"unavailable"}).`)}}catch(r){let n=r instanceof Error?r.message:String(r);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${dt}/releases/tag/${E}`),!1}var _r=class extends Error{constructor(t){super(t),this.name="ReindexLockUnavailableError"}};import{execFileSync as Mi}from"child_process";import{existsSync as Fi,readdirSync as Mr}from"fs";import{extname as Fr,join as Nr}from"path";var $r=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Ni=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Vs(e){let t=[],r=$i(e),n=zi(e);for(let i of Ni){if(ji(e,i.files)){t.push(i.language);continue}if(Wi(r,i.globs)){t.push(i.language);continue}Vi(n,i.extensions)&&t.push(i.language)}if(t.includes("typescript")&&ut(t,"javascript"),t.includes("cpp")&&t.includes("c")){let i=n.has(".c"),o=[".cc",".cpp",".cxx"].some(a=>n.has(a));i&&!o?ut(t,"cpp"):i||ut(t,"c")}return t}function $i(e){try{return Mr(e)}catch{return[]}}function ji(e,t){return t?.length?t.some(r=>Fi(Nr(e,r))):!1}function Wi(e,t){return t?.length?e.some(r=>t.some(n=>qi(r,n))):!1}function qi(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[r,n]=t.split("*");return e.startsWith(r??"")&&e.endsWith(n??"")}function zi(e){let t=Ji(e);if(t)return t;let r=new Set,n=[e];for(;n.length>0;){let i=n.pop();if(!i)continue;let o;try{o=Mr(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=Nr(i,a.name);if(a.isDirectory()){$r.has(a.name)||n.push(s);continue}let c=Fr(a.name).toLowerCase();c&&r.add(c)}}return r}function Ji(e){try{let t=dr(e,26214400,()=>Mi("git",["-C",e,"ls-files","-co","-v","-z","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:52428800,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})),r=new Set;for(let n of lr(t)){if(n.split("/").some(o=>$r.has(o)))continue;let i=Fr(n).toLowerCase();i&&r.add(i)}return r}catch{return null}}function Vi(e,t){return t?.length?t.some(r=>e.has(r)):!1}function ut(e,t){let r=e.indexOf(t);r!==-1&&e.splice(r,1)}import{closeSync as Wr,openSync as Qi,renameSync as Zi,rmSync as eo,writeSync as to}from"fs";import{create as qr,fromBinary as ro,toBinary as no}from"@bufbuild/protobuf";import{DocumentSchema as pt,IndexSchema as io,SymbolRole as mt}from"@c4312/scip";var A=class extends Error{},Ui=0,Hi=1,jr=2,Yi=5;function ft(e,t,r){let n=0,i=0;for(;t<r;){let o=e[t];if(t+=1,i<53)n+=(o&127)*2**i;else if((o&127)!==0)throw new A("varint exceeds the safe integer range");if((o&128)===0)return{value:n,pos:t};if(i+=7,i>63)throw new A("varint is longer than 64 bits")}throw new A("varint runs past the end of the buffer")}function*D(e,t=0,r=e.length){let n=t;for(;n<r;){let i=n,o=ft(e,n,r);n=o.pos;let a=Math.floor(o.value/8),s=o.value%8;if(a===0)throw new A("field number 0 is invalid");let c=n,d=0;if(s===Ui){let l=ft(e,n,r);d=l.value,n=l.pos}else if(s===jr){let l=ft(e,n,r);if(c=l.pos,n=l.pos+l.value,n>r)throw new A("length-delimited field runs past the end of the buffer")}else if(s===Hi)n+=8;else if(s===Yi)n+=4;else throw new A(`unsupported wire type ${s}`);if(n>r)throw new A("field value runs past the end of the buffer");yield{fieldNumber:a,wireType:s,fieldStart:i,valueStart:c,valueEnd:n,fieldEnd:n,varint:d}}}function ce(e){if(!Number.isSafeInteger(e)||e<0)throw new A(`cannot encode varint ${e}`);let t=[],r=e;do{let n=r%128;r=Math.floor(r/128),r>0&&(n|=128),t.push(n)}while(r>0);return Uint8Array.from(t)}function _e(e){return ce(e*8+jr)}var Ki=1,Xi=3;function de(e){let t=new TextDecoder,r;for(let n of D(e))if(!(n.fieldNumber!==Ki||n.wireType!==2))for(let i of D(e,n.valueStart,n.valueEnd)){if(i.fieldNumber!==Xi||i.wireType!==2)continue;let o=t.decode(e.subarray(i.valueStart,i.valueEnd));o&&(r=o)}return r}var gt=2,oo=3,ao=1,so=2,co=3,lo=1,uo=2,fo=3;function tc(e){let t;try{t=v(e,{inputKind:"SCIP sanitization input",maxBytes:R})}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}try{return po(t,e)}catch(r){if(r instanceof A)return{removedDefinitionOccurrences:0,touchedDocuments:0};throw r}}function po(e,t){let r=new TextDecoder,n=new Set;for(let a of D(e))if(a.wireType===2)if(a.fieldNumber===gt)for(let s of D(e,a.valueStart,a.valueEnd))s.wireType===2&&(s.fieldNumber===ao?Ze(r.decode(e.subarray(s.valueStart,s.valueEnd))):s.fieldNumber===co&&zr(e,s,r,n));else a.fieldNumber===oo&&zr(e,a,r,n);let i=0,o=[];for(let a of D(e)){if(a.wireType!==2||a.fieldNumber!==gt)continue;let s=go(e,a,r,n);s>0&&(i+=s,o.push(a))}return i===0?{removedDefinitionOccurrences:0,touchedDocuments:0}:(mo(e,t,o,n),{removedDefinitionOccurrences:i,touchedDocuments:o.length})}function zr(e,t,r,n){for(let i of D(e,t.valueStart,t.valueEnd)){if(i.wireType!==2||i.fieldNumber!==lo)continue;let o=r.decode(e.subarray(i.valueStart,i.valueEnd));o&&n.add(o)}}function go(e,t,r,n){let i=0;for(let o of D(e,t.valueStart,t.valueEnd)){if(o.wireType!==2||o.fieldNumber!==so)continue;let a="",s=0;for(let c of D(e,o.valueStart,o.valueEnd))c.fieldNumber===uo&&c.wireType===2?a=r.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===fo&&c.wireType===0&&(s=c.varint);(s&mt.Definition)!==0&&!n.has(a)&&(i+=1)}return i}function mo(e,t,r,n){let i=`${t}.sanitize-tmp`,o=Qi(i,"w",384);try{let a=0;for(let s of r){le(o,e.subarray(a,s.fieldStart));let c=ro(pt,e.subarray(s.valueStart,s.valueEnd));c.occurrences=c.occurrences.filter(l=>(l.symbolRoles&mt.Definition)===0||n.has(l.symbol));let d=no(pt,c);le(o,_e(gt)),le(o,ce(d.byteLength)),le(o,d),a=s.fieldEnd}le(o,e.subarray(a))}catch(a){throw Wr(o),eo(i,{force:!0}),a}Wr(o),Zi(i,t)}function le(e,t){let r=0;for(;r<t.byteLength;)r+=to(e,t,r,t.byteLength-r)}function Jr(e){let t=new Set;for(let o of e.documents){Ze(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let r=0,n=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&mt.Definition)===0||t.has(s.symbol)?!0:(r+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}n+=1,i.push(qr(pt,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:r===0?e:qr(io,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:r,touchedDocuments:n}}import{closeSync as fe,openSync as yt,readSync as yo,renameSync as ho,rmSync as Hr,statSync as So,writeFileSync as Yr,writeSync as Kr}from"fs";import{create as ht,fromBinary as bo,toBinary as Io}from"@bufbuild/protobuf";import{deserializeSCIP as Xr,serializeSCIP as Qr,DocumentSchema as xo,IndexSchema as wo,MetadataSchema as Vr,SymbolInformationSchema as vo}from"@c4312/scip";function Zr(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ro(e),r=Eo(e.flatMap(i=>i.documents??[])),n=tn(e.flatMap(i=>i.externalSymbols??[]));return ht(wo,{metadata:t,documents:r,externalSymbols:n})}function lc(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let r=e.map(i=>Xr(v(i,{inputKind:"SCIP merge input",maxBytes:R}))),n=Zr(r);return Yr(t,Qr(n)),{documentCount:n.documents.length,externalSymbolCount:n.externalSymbols.length,inputCount:e.length}}function uc(e,t){if(e.length===0)throw new Error("Cannot concatenate zero SCIP files");let r=0;for(let o of e)if(r+=So(o).size,r>R)throw new Error(`Concatenated SCIP output exceeds the ${R}-byte artifact limit. Reduce the indexed project scope or use compatible cached generations.`);let n=Buffer.allocUnsafe(1024*1024),i=yt(t,"w",384);try{for(let o of e){let a=yt(o,"r");try{let s=0;for(;(s=yo(a,n,0,n.byteLength,null))>0;){let c=0;for(;c<s;)c+=Kr(i,n,c,s-c)}}finally{fe(a)}}}catch(o){throw fe(i),Hr(t,{force:!0}),o}fe(i)}function fc(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let r=oe("reindex.publish.scip-output.deserialize",()=>e.map(o=>Xr(v(o,{inputKind:"SCIP merge input",maxBytes:R})))),n=oe("reindex.publish.scip-output.merge",()=>Zr(r)),i=oe("reindex.publish.scip-output.sanitize",()=>Jr(n));return oe("reindex.publish.scip-output.serialize",()=>Yr(t,Qr(i.index))),{documentCount:i.index.documents.length,externalSymbolCount:i.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:i.removedDefinitionOccurrences,touchedDocuments:i.touchedDocuments}}var Ur=1;function en(e,t,r){let n=v(e,{inputKind:"SCIP normalization input",maxBytes:R}),i=de(n),o=[];for(let c of D(n))c.fieldNumber===Ur&&c.wireType===2&&o.push(c);if(o.length===0)throw new Error("Cannot rebase a SCIP index without metadata");if((i??"")!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${i??""}`);let a=`${e}.rebase-tmp`,s=yt(a,"w",384);try{let c=0;for(let d of o){ue(s,n.subarray(c,d.fieldStart));let l=bo(Vr,n.subarray(d.valueStart,d.valueEnd));l.projectRoot=r;let p=Io(Vr,l);ue(s,_e(Ur)),ue(s,ce(p.byteLength)),ue(s,p),c=d.fieldEnd}ue(s,n.subarray(c))}catch(c){throw fe(s),Hr(a,{force:!0}),c}fe(s),ho(a,e)}function ue(e,t){let r=0;for(;r<t.byteLength;)r+=Kr(e,t,r,t.byteLength-r)}function Ro(e){let t=e[0]?.metadata;if(!t)return;let r=t.projectRoot;for(let n of e.slice(1)){let i=n.metadata?.projectRoot;if(r&&i&&i!==r)throw new Error(`Cannot merge SCIP indexes with different project roots: ${r} vs ${i}`)}return t}function Eo(e){let t=new Map;for(let r of e){let n=t.get(r.relativePath);if(!n){t.set(r.relativePath,r);continue}t.set(r.relativePath,ht(xo,{language:n.language||r.language,relativePath:n.relativePath||r.relativePath,occurrences:To([...n.occurrences,...r.occurrences]),symbols:tn([...n.symbols,...r.symbols]),text:Ao(n.text,r.text),positionEncoding:n.positionEncoding||r.positionEncoding}))}return[...t.values()]}function To(e){let t=new Set,r=[];for(let n of e){let i=JSON.stringify(n);t.has(i)||(t.add(i),r.push(n))}return r}function tn(e){let t=new Map;for(let r of e){let n=t.get(r.symbol);if(!n){t.set(r.symbol,r);continue}t.set(r.symbol,ht(vo,{symbol:n.symbol,documentation:Lo([...n.documentation,...r.documentation]),relationships:Po([...n.relationships,...r.relationships]),kind:n.kind||r.kind,displayName:n.displayName||r.displayName,enclosingSymbol:n.enclosingSymbol||r.enclosingSymbol,signatureDocumentation:n.signatureDocumentation??r.signatureDocumentation}))}return[...t.values()]}function Po(e){let t=new Set,r=[];for(let n of e){let i=[n.symbol,n.isReference?"1":"0",n.isImplementation?"1":"0",n.isTypeDefinition?"1":"0",n.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),r.push(n))}return r}function Ao(e,t){return e?t?e.length>=t.length?e:t:e:t}function Lo(e){return[...new Set(e)]}import{existsSync as cn,statSync as zo}from"fs";import{dirname as un,join as fn}from"path";import{appendFileSync as Do,existsSync as ko,mkdirSync as Co,renameSync as Oo,rmSync as Bo,statSync as Go,truncateSync as _o}from"fs";import{basename as Mo,dirname as Fo}from"path";var Me=".previous",No=".rotation.lock",$o=2e3,St=class extends Error{constructor(r,n){super(`Timed out after ${n}ms waiting for rotating JSONL lock: ${r}`);this.lockPath=r;this.timeoutMs=n;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},bt=class extends Error{constructor(r){super(`Rotating JSONL lock ownership changed before release: ${r}`);this.lockPath=r;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},rn=Object.freeze({monotonicNow:ve,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let r=Re(e,{kind:"rotating-jsonl",detail:{target:Mo(t)}});return r.kind==="acquired"?{kind:"acquired",lock:r.lock}:{kind:"contended"}},makeDirectory(e){Co(e,{recursive:!0})},exists:ko,readBytes(e){return v(e,{maxBytes:xe,inputKind:"rotating JSONL segment"})},size(e){return Go(e).size},truncate:_o,remove(e){Bo(e,{force:!0})},rename:Oo,append:Do});function nn(e,t,r){let n=r.runtime??rn,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
7
- `),a=Math.max(1,Math.floor(r.maxSegmentBytes),o.length);return an(e,r.lockTimeoutMs,n,()=>{n.makeDirectory(Fo(e));let s=jo(e,xe,n);r.onPhase?.("tail-repaired");let c=`${e}${r.previousSuffix??Me}`,d=!1,l=!1;return n.exists(e)&&n.size(e)+o.length>a&&(n.exists(c)&&(n.remove(c),l=!0),r.onPhase?.("previous-pruned"),n.rename(e,c),d=!0,r.onPhase?.("current-rotated")),n.append(e,o),r.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:a,repairedTailBytes:s,rotated:d,prunedPrevious:l}})}function on(e,t={}){let r=t.runtime??rn,n=Wo(t.maxSegmentBytes);return an(e,t.lockTimeoutMs,r,()=>{let i=[],o=0,a=`${e}${t.previousSuffix??Me}`;for(let s of[a,e]){if(!r.exists(s))continue;let c=qo(sn(s,n,r));i.push(...c.lines),o+=c.partialTailBytes}return{lines:i,ignoredPartialTailBytes:o}})}function an(e,t,r,n){let i=`${e}${No}`,o=Math.max(0,t??$o),a=r.monotonicNow()+o,s;for(;;){let u=r.tryAcquireLock(i,e);if(u.kind==="acquired"){s=u.lock;break}let b=a-r.monotonicNow();if(b<=0)throw new St(i,o);r.wait(Math.min(5,b))}let c=!1,d,l;try{l=n()}catch(u){c=!0,d=u}let p=!1;try{p=s.release()}catch(u){if(!c)throw u}if(c)throw d;if(!p)throw new bt(i);return l}function jo(e,t,r){if(!r.exists(e))return 0;let n=sn(e,t,r);if(n.length===0||n[n.length-1]===10)return 0;let i=n.lastIndexOf(10),o=i<0?0:i+1;return r.truncate(e,o),n.length-o}function Wo(e){let t=e??xe;if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`maxSegmentBytes must be a positive safe integer; received ${t}`);return t}function sn(e,t,r){let n=r.size(e);if(n>t)throw new rt("rotating JSONL segment",e,"too-large",n,t);let i=r.readBytes(e),o=r.size(e);if(o!==n||i.byteLength!==n)throw new rt("rotating JSONL segment",e,"changed-during-read",o,t);return i}function qo(e){let t=e.lastIndexOf(10),r=t<0?0:t+1;return{lines:e.subarray(0,r).toString("utf8").split(`
8
- `).filter(i=>i.length>0),partialTailBytes:e.length-r}}var Jo="reindex-activity.jsonl",Fe=Me,Vo=1024*1024,Uo=1440*60*1e3,dn=e=>_(e,"reindex activity segment");function xt(e){return fn(un(e),Jo)}function pn(e){if(e.reused)return 0;let r=(e.shards?.some(n=>!n.reused&&n.strategy==="incremental")??!1?0:It(e.indexPath))+It(e.dbPath);for(let n of e.shards??[]){if(n.reused)continue;let i=n.producedOutputBytes??n.outputBytes;i!==null&&(r+=i)}return r}function Ho(e){let t=pn(e),r=e.writeTelemetry;return r?Math.max(0,t-r.reflinkedBytes)+r.fallbackCopiedBytes+(r.incrementalWrittenBytes??0):t}function Tc(e,t){let r=t.lastRefresh;if(!r)return{state:"failed",reason:"reindex result has no refresh metadata"};let n=pn(t);return gn(xt(e),{version:1,event:"run",recordedAt:r.completedAt,trigger:r.trigger,result:r.result,durationMs:r.durationMs,estimatedLogicalOutputBytes:n,estimatedWriteBytes:Ho(t),reflinkedBytes:t.writeTelemetry?.reflinkedBytes??0,fallbackCopiedBytes:t.writeTelemetry?.fallbackCopiedBytes??0,incrementalWrittenBytes:t.writeTelemetry?.incrementalWrittenBytes??0,byLanguage:na(t)})}function Pc(e,t){return gn(xt(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function Yo(e,t,r=Vo,n){nn(e,t,{maxSegmentBytes:r,previousSuffix:Fe,...n?{runtime:n}:{}})}function Ko(e,t=new Date,r=Uo,n=dn){let i=t.getTime(),o=i-r,a={confidence:"complete",recordsRead:0,invalidRecords:0,skippedRecords:0,readErrors:0,ignoredPartialTailBytes:0,windowStartedAt:new Date(o).toISOString(),windowEndedAt:t.toISOString(),runs:0,rebuilt:0,fullRebuilds:0,reused:0,failed:0,suppressed:0,estimatedLogicalOutputBytes:0,estimatedWriteBytes:0,reflinkedBytes:0,fallbackCopiedBytes:0,languageAttribution:"complete",attributedRuns:0,unattributedRuns:0,invalidLanguageDetails:0,byLanguage:{},byTrigger:{},automatic:{runs:0,rebuilt:0,fullRebuilds:0,estimatedWriteBytes:0}},s=a.automatic,c=xt(e),d=[];if(n===dn){if(!cn(c)&&!cn(`${c}${Fe}`))return a;try{let l=on(c,{previousSuffix:Fe});d=l.lines,a.ignoredPartialTailBytes=l.ignoredPartialTailBytes}catch{a.readErrors+=1,a.confidence="unavailable"}}else{let l=0;for(let p of[`${c}${Fe}`,c])try{d.push(...da(n(p))),l+=1}catch{a.readErrors+=1}l===0?a.confidence="unavailable":a.readErrors>0&&(a.confidence="partial")}for(let l of d){a.recordsRead+=1;let p=Xo(l);if(!p){a.invalidRecords+=1,a.confidence!=="unavailable"&&(a.confidence="partial");continue}let{record:u}=p,b=Date.parse(u.recordedAt);if(b<o||b>i){a.skippedRecords+=1;continue}if(a.invalidLanguageDetails=(a.invalidLanguageDetails??0)+p.invalidLanguageDetails,a.byTrigger[u.trigger.kind]=(a.byTrigger[u.trigger.kind]??0)+1,u.event==="suppressed"){a.suppressed+=1;continue}a.runs+=1,a[u.result]+=1,a.estimatedLogicalOutputBytes+=u.estimatedLogicalOutputBytes;let g=Qo(u);a.estimatedWriteBytes=(a.estimatedWriteBytes??0)+g,a.reflinkedBytes=(a.reflinkedBytes??0)+(u.reflinkedBytes??0),a.fallbackCopiedBytes=(a.fallbackCopiedBytes??0)+(u.fallbackCopiedBytes??0),u.result!=="failed"&&(p.hasLanguageDetails?a.attributedRuns=(a.attributedRuns??0)+1:a.unattributedRuns=(a.unattributedRuns??0)+1);for(let[y,k]of mn(u.byLanguage)){let F=(a.byLanguage??={})[y]??=sa();F.runs+=1,F[k.result]+=1,F.producedOutputBytes+=k.producedOutputBytes,F.durationMs+=k.durationMs}let h=ta(u);h&&a.oldestRebuildAt===void 0&&(a.oldestRebuildAt=u.recordedAt),h&&(a.fullRebuilds=(a.fullRebuilds??0)+1),g>0&&a.oldestWriteAt===void 0&&(a.oldestWriteAt=u.recordedAt),Zo(u.trigger)&&(s.runs+=1,u.result==="rebuilt"&&(s.rebuilt+=1),h&&(s.fullRebuilds+=1,s.oldestRebuildAt??=u.recordedAt),s.estimatedWriteBytes+=g,g>0&&(s.oldestWriteAt??=u.recordedAt))}return a.ignoredPartialTailBytes>0&&a.confidence!=="unavailable"&&(a.confidence="partial"),a.languageAttribution=ca(a),a}function gn(e,t){try{return Yo(e,t),{state:"recorded"}}catch(r){return{state:"failed",reason:r instanceof Error?r.message:String(r)}}}function Xo(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=t;if(r.version!==1||!Qt(r.recordedAt)||!r.trigger||!ra(r.trigger.kind))return null;if(r.event==="suppressed")return r.reason==="completed-index-is-fresh"?{record:r,hasLanguageDetails:!1,invalidLanguageDetails:0}:null;if(r.event!=="run"||r.result!=="rebuilt"&&r.result!=="reused"&&r.result!=="failed"||!N(r.durationMs)||!N(r.estimatedLogicalOutputBytes)||r.estimatedWriteBytes!==void 0&&!N(r.estimatedWriteBytes)||r.reflinkedBytes!==void 0&&!N(r.reflinkedBytes)||r.fallbackCopiedBytes!==void 0&&!N(r.fallbackCopiedBytes)||r.incrementalWrittenBytes!==void 0&&!N(r.incrementalWrittenBytes))return null;let n=r,{byLanguage:i,...o}=n,a=ia(i);return{record:{...o,...a.byLanguage?{byLanguage:a.byLanguage}:{}},hasLanguageDetails:a.hasLanguageDetails,invalidLanguageDetails:a.invalidLanguageDetails}}catch{return null}}function Qo(e){return e.reflinkedBytes===void 0?e.estimatedWriteBytes??e.estimatedLogicalOutputBytes:Math.max(0,e.estimatedLogicalOutputBytes-e.reflinkedBytes)+(e.fallbackCopiedBytes??0)+(e.incrementalWrittenBytes??0)}function Ac(e,t,r=new Date){return t.enabled?ea(Ko(e,r,t.windowMs),t,r.getTime()):{state:"allowed",rebuilt:0,estimatedWriteBytes:0}}function Zo(e){return e.kind.startsWith("watch-")}function ea(e,t,r){let n=e.automatic??{fullRebuilds:e.fullRebuilds??e.rebuilt,estimatedWriteBytes:e.estimatedWriteBytes??e.estimatedLogicalOutputBytes,oldestRebuildAt:e.oldestRebuildAt,oldestWriteAt:e.oldestWriteAt},i=n.estimatedWriteBytes,o=n.fullRebuilds,a={rebuilt:o,estimatedWriteBytes:i};return t.enabled?e.confidence!==void 0&&e.confidence!=="complete"?{state:"paused",reason:"activity-evidence",until:r+t.windowMs,...a,detail:`reindex activity evidence is ${e.confidence}`}:o>=t.maxRebuilds?{state:"paused",reason:"rebuild-count",until:ln(n.oldestRebuildAt,t.windowMs,r),...a,detail:`${o}/${t.maxRebuilds} expensive full rebuild slots consumed by automatic refreshes`}:i>=t.maxEstimatedWriteBytes?{state:"paused",reason:"estimated-write-bytes",until:ln(n.oldestWriteAt,t.windowMs,r),...a,detail:`${i}/${t.maxEstimatedWriteBytes} estimated write bytes consumed by automatic refreshes`}:{state:"allowed",...a}:{state:"allowed",...a}}function ta(e){if(e.result!=="rebuilt")return!1;let t=mn(e.byLanguage);return t.length===0?!0:t.some(([,r])=>r.result==="rebuilt"&&r.strategy!=="incremental"&&r.strategy!=="reused")}function ln(e,t,r){let n=e?Date.parse(e):Number.NaN;return Number.isFinite(n)&&n+t>r?n+t:r+t}function ra(e){return e==="manual-cli"||e==="setup"||e==="watch-source"||e==="watch-startup"||e==="watch-demand"||e==="watch-git-head"||e==="watch-git-index"||e==="watch-git-state"||e==="unknown"}function It(e){try{return zo(e).size}catch{return 0}}function na(e){let t={};for(let r of e.languages){let n=(e.shards??[]).filter(d=>d.language===r),i=n.find(d=>d.id===r),o=e.reused||(i?i.reused:n.length>0&&n.every(d=>d.reused)),a=It(fn(un(e.dbPath),"language-indexes",`${r}.scip`)),s=a>0?a:i?.outputBytes??a,c=o?0:i?.durationMs??n.filter(d=>!d.reused).reduce((d,l)=>d+l.durationMs,0);t[r]={result:o?"reused":"rebuilt",strategy:o?"reused":i?.strategy??"full",...i?.strategy==="full"&&(i.fallbackReason??i.missReason)?{fallbackReason:i.fallbackReason??i.missReason}:{},outputBytes:s,producedOutputBytes:o?0:i?.producedOutputBytes??s,durationMs:c}}return t}function ia(e){if(e===void 0)return{hasLanguageDetails:!1,invalidLanguageDetails:0};if(!e||typeof e!="object"||Array.isArray(e))return{hasLanguageDetails:!1,invalidLanguageDetails:1};let t={},r=0;for(let[i,o]of Object.entries(e)){if(!aa(i)||!oa(o)){r+=1;continue}t[i]=o}let n=Object.keys(t).length>0;return{...n?{byLanguage:t}:{},hasLanguageDetails:n,invalidLanguageDetails:r}}function oa(e){if(!e||typeof e!="object")return!1;let t=e;return(t.result==="rebuilt"||t.result==="reused")&&(t.strategy===void 0||t.strategy==="reused"||t.strategy==="incremental"||t.strategy==="full")&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")&&et(t.outputBytes)&&et(t.producedOutputBytes)&&N(t.durationMs)&&(t.result!=="reused"||t.producedOutputBytes===0&&t.durationMs===0)&&t.producedOutputBytes<=t.outputBytes}function aa(e){return tt.includes(e)}function mn(e){return e?tt.flatMap(t=>{let r=e[t];return r?[[t,r]]:[]}):[]}function sa(){return{runs:0,rebuilt:0,reused:0,producedOutputBytes:0,durationMs:0}}function ca(e){let t=e.invalidLanguageDetails??0,r=e.attributedRuns??0;return(e.unattributedRuns??0)===0&&t===0?"complete":r===0?"unavailable":"partial"}function da(e){return e.endsWith(`
9
- `)||(e=e.slice(0,Math.max(0,e.lastIndexOf(`
10
- `)+1))),e.split(`
11
- `).filter(t=>t.length>0)}import la from"better-sqlite3";var ua=25,fa=new Set(["typescript","javascript"]);function Oc(e,t,r){let n=null;try{n=new la(e,{readonly:!0,fileMustExist:!0});let i=new Set(n.prepare("SELECT relative_path FROM documents").pluck().all().map(Qe)),o=pa(t,r),a=new Set([...o.values()].flatMap(l=>[...l])),s=[...a].filter(l=>!i.has(l)).sort();if(s.length===0)return{state:"complete",expectedDocumentCount:a.size,actualDocumentCount:i.size};let c=new Set(s),d=r.filter(l=>[...o.get(l)??[]].some(p=>c.has(p)));return{state:"incomplete",expectedDocumentCount:a.size,actualDocumentCount:i.size,missingDocumentCount:s.length,missingPaths:s.slice(0,ua),affectedLanguages:d}}catch(i){return{state:"unavailable",reason:i instanceof Error?i.message:String(i)}}finally{n?.close()}}function pa(e,t){let r=new Map,n=t.filter(i=>fa.has(i));for(let i of n)r.set(i,new Set);for(let i of e.files){let o=Qe(i.path);for(let a of n)Yt(o,[a])==="source"&&r.get(a).add(o)}return r}import{existsSync as hn,readdirSync as Sn,rmSync as bn}from"fs";import{join as X}from"path";import{create as xn,fromBinary as wn,toBinary as qc}from"@bufbuild/protobuf";import{deserializeSCIP as wt,DocumentSchema as vn,IndexSchema as Rn,serializeSCIP as En}from"@c4312/scip";import{existsSync as ga,mkdirSync as ma,renameSync as ya,writeFileSync as ha}from"fs";import{join as Sa}from"path";function yn(e){ma(e.blobDir,{recursive:!0});let t=Sa(e.blobDir,`${e.blobHash}.scipdoc`);if(ga(t)){let n=v(t,{maxBytes:ee,inputKind:e.inputKind});if(n.byteLength!==e.bytes.byteLength||M(n)!==e.blobHash)throw new Error(`existing ${e.inputKind} is corrupt: ${e.relativePath}`);return}let r=`${t}.${process.pid}.${Date.now()}.tmp`;ha(r,e.bytes),ya(r,t)}var vt=1,pe="typescript-scip-fragments";function Uc(e){let t=new Set,r=[];for(let o of e){let a=Ne(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=wn(vn,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);r.push(s)}let n=En(xn(Rn,{documents:r,externalSymbols:[]})),i=wt(n);if(i.documents.length!==r.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return n}function ba(e){let t=X(e,pe);return{rootDir:t,blobDir:X(t,"blobs"),generationDir:X(t,"generations")}}function Tn(e){let t=Ia(e);return xa(t.baseIndex,t.completeDocuments,"assembled")}function Ia(e){let t=wt(e.baseIndexBytes);Ea(t.metadata,Ta(e)),Ra(t.externalSymbols);let r=new Map;for(let s of e.fragments){let c=Ne(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);r.set(c,s)}if(r.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let n=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=Ne(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);n.add(c);let d=r.get(c);if(!d){i.push(s);continue}if(r.delete(c),d.bytes===null){a.push(c);continue}let l=In(c,d.bytes);i.push(l),o.push(l)}for(let s of[...r.keys()].sort()){let c=r.get(s);if(c.bytes===null)continue;if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let d=In(s,c.bytes);i.push(d),o.push(d)}return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function In(e,t){let r=wn(vn,t);if(r.relativePath!==e)throw new Error(`TypeScript fragment path mismatch: expected ${e}, got ${r.relativePath}`);return r}function xa(e,t,r){let n=En(xn(Rn,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=wt(n);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${r} TypeScript SCIP index failed structural verification`);return n}function Hc(e,t){let r=ba(e);if(!hn(r.generationDir))return;let n=new Set(t.map(a=>va(a))),i=Sn(r.generationDir).filter(a=>a.endsWith(".json")),o=new Set;for(let a of i.filter(s=>n.has(s))){let s=wa(P(X(r.generationDir,a),{maxBytes:T,inputKind:"TypeScript fragment manifest"}));for(let c of s.documents)o.add(`${c.blobHash}.scipdoc`)}for(let a of i)n.has(a)||bn(X(r.generationDir,a),{force:!0});if(hn(r.blobDir))for(let a of Sn(r.blobDir))o.has(a)||bn(X(r.blobDir,a),{force:!0})}function wa(e){let t=JSON.parse(e);if(t.version!==vt||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let r=new Set;for(let n of t.documents){if(!n||typeof n.relativePath!="string"||typeof n.blobHash!="string"||!/^[a-f0-9]{64}$/.test(n.blobHash)||typeof n.byteLength!="number"||!Number.isInteger(n.byteLength)||n.byteLength<0||typeof n.documentIdentity!="string"||!n.documentIdentity)throw new Error("invalid TypeScript fragment record");if(Ne(n.relativePath),r.has(n.relativePath))throw new Error("duplicate TypeScript fragment record");r.add(n.relativePath)}return t}function va(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${M(e)}.json`}function Ra(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ea(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let r=e,n=r.toolInfo??r.tool_info;if(!n||typeof n!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=n;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Ta(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Ne(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}import{existsSync as $e,readdirSync as Rt,rmSync as Pn}from"fs";import{join as O}from"path";var je=1,ge="typescript-scip-overlays",An="typescript-project-v3:";function nd(e){let t=Dn(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t?.producerIdentity!==void 0&&t.producerIdentity!==e.producerIdentity)throw new Error("TypeScript overlay producer identity changed");let r=e.allowLegacyProjectIdentityMigration===!0&&t!==null&&!t.projectIdentity.startsWith(An)&&e.projectIdentity.startsWith(An);if(t&&t.projectIdentity!==e.projectIdentity&&!e.allowProjectIdentityChange&&!r)throw new Error("TypeScript overlay project identity changed");let n=new Map((t?.overlays??[]).map(a=>[a.relativePath,a])),i=new Set;for(let a of e.fragments){let s=Pt(a.relativePath);if(i.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);i.add(s),n.set(s,Pa(e.cacheDir,a))}if(i.size===0)throw new Error("TypeScript overlay generation requires affected documents");let o={version:je,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((a,s)=>a.relativePath.localeCompare(s.relativePath))};return Aa(e.cacheDir,o),o}function id(e){let t=Dn(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let r=t.overlays.map(n=>{if(n.blobHash===null)return{relativePath:n.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=v(O(me(e.cacheDir),"blobs",`${n.blobHash}.scipdoc`),{maxBytes:ee,inputKind:"TypeScript overlay blob"});if(i.byteLength!==n.byteLength||M(i)!==n.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${n.relativePath}`);return{relativePath:n.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Tn({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:r})}function od(e,t){let r=me(e),n=O(r,"generations");if(!$e(n))return;let i=new Set(t.map(Tt)),o=new Set;for(let s of Rt(n).filter(c=>i.has(c))){let c=Et(P(O(n,s),{maxBytes:T,inputKind:"TypeScript overlay manifest"}));for(let d of c.overlays)d.blobHash&&o.add(`${d.blobHash}.scipdoc`)}for(let s of Rt(n))i.has(s)||Pn(O(n,s),{force:!0});let a=O(r,"blobs");if($e(a))for(let s of Rt(a))o.has(s)||Pn(O(a,s),{force:!0})}function Dn(e,t){let r=O(me(e),"generations",Tt(t));if(!$e(r))return null;let n=Et(P(r,{maxBytes:T,inputKind:"TypeScript overlay manifest"}));if(n.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return n}function Pa(e,t){let r=Pt(t.relativePath);if(t.bytes===null)return{relativePath:r,blobHash:null,byteLength:0};let n=Buffer.from(t.bytes),i=M(n);return yn({blobDir:O(me(e),"blobs"),blobHash:i,bytes:n,relativePath:r,inputKind:"TypeScript overlay blob"}),{relativePath:r,blobHash:i,byteLength:n.byteLength}}function Aa(e,t){let r=O(me(e),"generations",Tt(t.generationIdentity));if($e(r)){let n=Et(P(r,{maxBytes:T,inputKind:"TypeScript overlay manifest"}));if(Ln(n)!==Ln(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}Pe(r,t,{spacing:2,trailingNewline:!0})}function Et(e){let t=JSON.parse(e);if(t.version!==je||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let r=new Set;for(let n of t.overlays){if(!n||typeof n.relativePath!="string"||n.blobHash!==null&&(typeof n.blobHash!="string"||!/^[a-f0-9]{64}$/.test(n.blobHash))||!Number.isInteger(n.byteLength)||n.byteLength<0||n.blobHash===null&&n.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Pt(n.relativePath),r.has(n.relativePath))throw new Error("duplicate TypeScript overlay record");r.add(n.relativePath)}return t}function me(e){return O(e,ge)}function Tt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${M(e)}.json`}function Ln(e){return M(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Pt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}import{createHash as Ot}from"crypto";import{closeSync as La,existsSync as I,mkdirSync as Da,openSync as ka,readSync as Ca,readdirSync as Bt,renameSync as kt,rmSync as ye,statSync as J}from"fs";import{basename as Gt,dirname as B,join as m,relative as kn}from"path";var Oa=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function On(e){let t=L(e.outputDb),r=Fa(e);e.onStage?.("after-recovery-retained");let n=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=Na(e,r),o=Mt({generationRoot:t,databasePath:e.tempOutputDb,indexPath:I(n)?n:void 0,verifiedIndexArtifact:i,metadataPath:I(e.tempMetaPath)?e.tempMetaPath:void 0}),a=(e.now??(()=>new Date))().toISOString(),s={version:Y,currentGeneration:o.identity,artifactSet:"immutable-v1",...r?{previousGeneration:r}:{},...e.publication?{publication:e.publication}:{},publishedAt:a},c=C(m(t,"state.json"),s,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||Dt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Dt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Dt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let d=o.identity,l={...s,stableMirrors:_t(e.outputDb,e.outputScip)};C(m(t,"state.json"),l,{spacing:2,trailingNewline:!0});let p=Bn(e.outputDb,{now:e.now}),u=re(o.directorySync,c.directorySync);return{currentGeneration:d,...r?{previousGeneration:r}:{},retention:p,achievedDurability:u==="synced"?"directory-durable":"file-flushed",directorySync:u}}function Ba(e,t,r,n=()=>new Date){if(!I(e))return null;let i=ne(e),o=m(L(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Le(e,i.currentGeneration))return i;let a=L(e),s=!i&&I(o)?ja(r,e,t):void 0;if(s&&!De(a,s))return null;let c=Mt({generationRoot:a,databasePath:e,indexPath:I(t)?t:void 0,metadataPath:I(r)?r:void 0,forcedIdentity:i?.currentGeneration??s}),d={version:Y,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:_t(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??n().toISOString()};return C(m(a,"state.json"),d,{spacing:2,trailingNewline:!0}),d}function hd(e,t,r=()=>new Date){if(!I(e)||!I(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let n=ne(e),i=L(e),o=Mt({generationRoot:i,databasePath:e,indexPath:I(m(B(e),"index.scip"))?m(B(e),"index.scip"):void 0,metadataPath:t}),a=n&&n.currentGeneration!==o.identity?_n(e,n.currentGeneration):void 0,s={version:Y,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:_t(e,m(B(e),"index.scip")),...a?{previousGeneration:a}:{},...n?.publication?{publication:n.publication}:{},publishedAt:r().toISOString()};return C(m(L(e),"state.json"),s,{spacing:2,trailingNewline:!0}),Bn(e,{now:r}),s}function Bn(e,t={}){let r=Ga(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=te(sr(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:r,at:i,reason:"another process owns local generation retention"};try{let a=ne(e),s=_a(e),c=cr(e,s.map(y=>y.identity),{isProcessAlive:t.isProcessAlive??rr,readProcessIdentity:t.readProcessIdentity??tr}),d=new Set(c.protectedGenerations);a?.currentGeneration&&d.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&d.add(a.previousGeneration.generationIdentity);let l=s.length,p=s.reduce((y,k)=>y+k.logicalBytes,0),u=0,b=0;for(let y of s){if(l<=r.maxGenerations&&p<=r.maxLogicalBytes)break;d.has(y.identity)||(t.onBeforeRemove?.(y.identity),ye(y.path,{recursive:!0,force:!0}),l-=1,p-=y.logicalBytes,u+=1,b+=y.logicalBytes)}let g=l>r.maxGenerations||p>r.maxLogicalBytes,h={state:g?"protected":u>0?"collected":"within-bounds",generationCount:l,logicalBytes:p,protectedGenerations:d.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:u,removedLogicalBytes:b,limits:r,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return Cn(e,h),h}catch(a){let s={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:r,at:i,reason:a instanceof Error?a.message:String(a)};try{Cn(e,s)}catch{}return s}finally{o.release()}}function Ga(e={}){let t={...Oa,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function _a(e){let t=L(e);return I(t)?Bt(t,{withFileTypes:!0}).filter(r=>r.isDirectory()&&/^[a-f0-9]{64}$/.test(r.name)).map(r=>{let n=m(t,r.name),i=De(t,r.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):Gn(n);return{identity:r.name,path:n,logicalBytes:o,modifiedAtMs:J(n).mtimeMs}}).sort((r,n)=>r.modifiedAtMs-n.modifiedAtMs||r.identity.localeCompare(n.identity)):[]}function Gn(e){let t=0;for(let r of Bt(e,{withFileTypes:!0})){let n=m(e,r.name);r.isDirectory()?t+=Gn(n):r.isFile()&&(t+=J(n).size)}return t}function Cn(e,t){Pe(m(L(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function qe(e,t=m(B(e),"meta.json")){let r=m(L(e),"state.json");if(!I(r))return{state:"legacy",statePath:r};let n=ne(e);if(!n)return{state:"invalid",statePath:r,reason:"generation state is malformed"};try{let i=Le(e,n.currentGeneration),o=i!==null,a=i?Ma(e,t,i,n):!1,s=n.previousGeneration?I(m(B(e),n.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:r,currentMatches:a,recoveryExists:s,generation:n,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:r,currentMatches:a,recoveryExists:s,generation:n}}catch(i){return{state:"drifted",statePath:r,currentMatches:!1,recoveryExists:!1,generation:n,reason:i instanceof Error?i.message:String(i)}}}function Ma(e,t,r,n){if(n.stableMirrors&&(n.stableMirrors.databaseFileIdentity!==ie(e)||n.stableMirrors.indexFileIdentity!==void 0&&n.stableMirrors.indexFileIdentity!==ie(m(B(e),"index.scip")))||!Ct(e,r.database))return!1;let i=m(B(e),"index.scip");if(r.index&&!Ct(i,r.index))return!1;if(!r.metadata)return!I(t);if(!I(t))return!1;let o=m(L(e),r.identity,r.metadata.file);return I(o)&&z(_(t,"reindex metadata"))===z(_(o,"immutable reindex metadata"))}function Ct(e,t){return I(e)&&J(e).isFile()&&J(e).size===t.size}function Fa(e){let t=Ba(e.outputDb,e.outputScip,e.metaPath);return t?_n(e.outputDb,t.currentGeneration):void 0}function Na(e,t){if(!e.preserveOutputScip)return;if(!t)throw new Error("deferred SCIP publication requires an accepted immutable generation");let r=qe(e.outputDb,e.metaPath);if(r.state!=="current"||r.generation.currentGeneration!==t.generationIdentity){let i=r.state==="current"?"generation identity changed":"reason"in r?r.reason:`generation state is ${r.state}`;throw new Error(`deferred SCIP publication requires a verified accepted companion: ${i}`)}let n=Le(e.outputDb,t.generationIdentity);if(!n?.index||!Ct(e.outputScip,n.index))throw new Error("deferred SCIP publication requires the verified accepted index artifact");return n.index}function _t(e,t){return{databaseFileIdentity:ie(e),...I(t)?{indexFileIdentity:ie(t)}:{}}}function _n(e,t){let r=m(L(e),t),n=m(r,Gt(e)),i=m(r,"meta.json");return{generationIdentity:t,databasePath:kn(B(e),n),...I(i)?{metadataPath:kn(B(e),i)}:{}}}function $a(e){if(I(e))for(let t of Bt(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&ye(m(e,t.name),{recursive:!0,force:!0})}function ja(e,t,r=m(B(t),"index.scip")){let n=Ot("sha256").update("sqlite-generation-artifacts-v1\0");return n.update(We(t)),I(r)&&n.update(`\0${We(r)}`),I(e)&&n.update(`\0${z(_(e,"reindex metadata"))}`),n.digest("hex")}function Mt(e){let t=At(e.databasePath),r=e.indexPath?e.verifiedIndexArtifact?qa(e.indexPath,e.verifiedIndexArtifact):At(e.indexPath):void 0,n=e.metadataPath?At(e.metadataPath):void 0,i=e.forcedIdentity??Wa(t,r,e.metadataPath),o=m(e.generationRoot,i),a=m(o,it);if(I(a)){let d=De(e.generationRoot,i);if(d&&Mn(o,d.database,t)&&Ja(o,d.index,r)&&Va(o,d.metadata,e.metadataPath))return{identity:i,directorySync:$(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[Ee(e.generationRoot)];$a(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;ye(c,{recursive:!0,force:!0}),Da(c,{recursive:!0});try{s.push(Lt(e.databasePath,m(c,t.file))),r&&e.indexPath&&s.push(Lt(e.indexPath,m(c,r.file))),n&&e.metadataPath&&s.push(Lt(e.metadataPath,m(c,n.file)));let d=C(m(c,it),{version:ar,identity:i,database:t,...r?{index:r}:{},...n?{metadata:n}:{}},{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&s.push(d.directorySync),s.push($(c)),kt(c,o),s.push($(e.generationRoot))}finally{ye(c,{recursive:!0,force:!0})}return{identity:i,directorySync:re(...s)}}function Wa(e,t,r){let n=Ot("sha256").update("sqlite-generation-artifacts-v1\0");return n.update(e.sha256),t&&n.update(`\0${t.sha256}`),r&&n.update(`\0${z(_(r,"reindex metadata"))}`),n.digest("hex")}function At(e){return{file:Gt(e),size:J(e).size,sha256:We(e)}}function qa(e,t){if(t.file!==Gt(e)||J(e).size!==t.size)throw new Error(`verified SQLite generation artifact changed before publication: ${e}`);return t}function We(e){let t=Ot("sha256"),r=ka(e,"r"),n=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=za(r,n);if(i===0)break;t.update(n.subarray(0,i))}}finally{La(r)}return t.digest("hex")}function za(e,t){let r=0;for(;r<t.length;){let n=Ca(e,t,r,t.length-r,null);if(r+=n,n===0)break}return r}function Lt(e,t){return Te(e,t,{mode:292})}function Mn(e,t,r){let n=m(e,t.file);return t.file===r.file&&t.size===r.size&&t.sha256===r.sha256&&I(n)&&J(n).size===t.size&&We(n)===t.sha256}function Ja(e,t,r){return!t||!r?t===r:Mn(e,t,r)}function Va(e,t,r){if(!t||!r)return t===void 0&&r===void 0;let n=m(e,t.file);return I(n)&&z(_(n,"stored reindex metadata"))===z(_(r,"candidate reindex metadata"))}function Dt(e,t){ye(`${t}.tmp-replace`,{force:!0}),kt(e,`${t}.tmp-replace`),kt(`${t}.tmp-replace`,t)}import{createHash as Vn,randomUUID as Za}from"crypto";import{existsSync as q,lstatSync as $t,mkdirSync as Q,mkdtempSync as Un,readdirSync as Hn,realpathSync as Yn,renameSync as U,rmSync as W,statSync as Ue}from"fs";import{dirname as jt,join as f,resolve as V}from"path";import{setTimeout as es}from"timers/promises";import{pathToFileURL as jn}from"url";import ts from"better-sqlite3";import{lstatSync as Ua,readdirSync as Ha}from"fs";import{join as Ya,relative as Ka,resolve as Ft,sep as Xa}from"path";var he=1,Nt="language-indexes",Fn=["index.db","index.scip","meta.json"],Nn=[Nt,pe,ge];function ze(e){let t=[];for(let r of Fn)Qa(e,r),t.push(r);for(let r of Nn)$n(e,r,t);return{version:he,files:t.sort()}}function Je(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(n=>!n||n==="."||n===".."))throw new Error(`invalid index artifact path: ${e}`);let r=t[0];if(!Fn.includes(e)&&!Nn.includes(r))throw new Error(`index artifact path is not shareable: ${e}`);return e}function G(e,t){let r=Je(t),n=Ft(e),i=Ft(n,...r.split("/"));if(i!==n&&!i.startsWith(`${n}${Xa}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function $n(e,t,r){let n=Ya(e,t),i;try{i=Ha(n,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?$n(e,a,r):o.isFile()&&r.push(Je(a))}}function Qa(e,t){let r=G(e,t),n;try{n=Ua(r)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!n.isFile()||n.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(Ka(Ft(e),r).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}var Wt=1,Wn="SCIP_QUERY_SHARED_CACHE",rs=2,Ve=JSON.stringify({cliVersion:ur,artifactCatalogVersion:he,postIndexAugmentationSchemaVersion:rs,sqliteGenerationStoreVersion:Y,typescriptFragmentStoreVersion:vt,typescriptOverlayStoreVersion:je}),qt="manifest.json",Kn="shared-cache.json";var zt=[Nt,pe,ge];function ns(e,t){if(!e.clean||!e.treeOid)return;let r=ri(JSON.stringify({version:Wt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:Xt(t),producerIdentity:Ve}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ve,generationId:r,repositoryCacheDir:gr(e.repositoryId)}}function Hd(e,t,r){if(!gs(r))return!1;let n=ns(e,r);if(!n)return!1;try{let i=ds(t);if(!i||i.repositoryId!==e.repositoryId||i.worktreeId!==e.worktreeId)return!1;let o=JSON.parse(P(f(n.repositoryCacheDir,"worktrees",`${i.worktreeId}.json`),{inputKind:"worktree cache lease",maxBytes:T}));return o.version!==1||o.repositoryId!==i.repositoryId||o.worktreeId!==i.worktreeId||V(o.projectRoot)!==V(e.projectRoot)||o.treeOid!==e.treeOid||V(o.localCacheDir)!==V(t)||o.ownershipChecksum!==Jt(o)||o.baseGenerationId!==n.generationId||o.activeGenerationId!==n.generationId?!1:H(n,!1)!==null}catch{return!1}}function Yd(e,t,r){if(process.env[Wn]==="0")return`${Wn}=0`;if(!mr(r))return"explicit cache or database override";if(ot(jt(t))!==ot(pr(e))||t!==f(jt(t),"index.db"))return"index database is outside the managed worktree cache"}function H(e,t=!0){let r=Vt(e),n;try{n=Xn(P(f(r,qt),{inputKind:"shared-generation manifest",maxBytes:T}))}catch{return null}if(n.generationId!==e.generationId||n.repositoryId!==e.repositoryId||n.treeOid!==e.treeOid||n.producerIdentity!==e.producerIdentity||!Ie(n.fingerprint,e.fingerprint)||!ss(r))return null;if(!t)return n;try{for(let i of n.artifacts){let o=G(r,i.path),a=Ue(o);if(!a.isFile()||a.size!==i.size||we(o,{inputKind:"shared-generation artifact",maxBytes:R})!==i.sha256)return null}}catch{return null}return n}function Kd(e,t,r,n){if(!e.treeOid)return null;let i=at(t,r),o=f(fr(),"repositories",e.repositoryId),a;try{let d=$t(o);if(!d.isDirectory()||d.isSymbolicLink())return null;a=Yn(o)}catch{return null}let s=f(a,"generations"),c=[];try{for(let d of Hn(s)){if(!/^[a-f0-9]{64}$/.test(d))continue;let l=f(s,d),p;try{p=$t(l)}catch{continue}if(!(!p.isDirectory()||p.isSymbolicLink()))try{let u=Xn(P(f(l,qt),{inputKind:"shared-generation baseline manifest",maxBytes:T}));u.generationId===d&&u.repositoryId===e.repositoryId&&u.producerIdentity===Ve&&cs(u.fingerprint,i)&&c.push(u)}catch{continue}}}catch{return null}c.sort((d,l)=>{let p=d.treeOid===e.treeOid?0:1,u=l.treeOid===e.treeOid?0:1;if(p!==u)return p-u;if(n){let g=Jn(d.fingerprint,n)-Jn(l.fingerprint,n);if(g!==0)return g}return Date.parse(l.createdAt)-Date.parse(d.createdAt)||d.generationId.localeCompare(l.generationId)});for(let d of c){let l={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:d.treeOid,fingerprint:d.fingerprint,producerIdentity:d.producerIdentity,generationId:d.generationId,repositoryCacheDir:a},p=H(l);if(p)return{snapshot:l,manifest:p}}return null}function Xd(e){let t=te(f(e.snapshot.repositoryCacheDir,"locks",`${e.snapshot.generationId}.publish.lock`));if(!t)throw new Error(`shared generation publication is already in progress for ${e.snapshot.generationId}`);try{return is(e)}finally{t.release()}}function is(e){let t=H(e.snapshot);if(t)return qn(e.snapshot,t);if(!ti(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let r=zn(e.sourceCacheDir);if(!r)throw new Error("source index artifacts are incomplete");let n=ze(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations"),o=[Ee(i)],a=Un(f(i,`.tmp-${process.pid}-`));try{let s=[];for(let g of n.files){let h=G(e.sourceCacheDir,g),y=G(a,g);o.push(be(h,y,292)),e.onPublicationStage?.("after-artifact-flushed",g);let k=Ue(y).size;s.push({path:g,size:k,sha256:we(y,{inputKind:"staged shared-generation artifact",maxBytes:R})})}let c=de(v(f(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:R}));if(!c)throw new Error("shared SCIP generation has no project root metadata");let d=Ut(e.sourceProjectRoot);if(c!==d)throw new Error("shared SCIP generation root does not match its source worktree");if(zn(e.sourceCacheDir)!==r||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Wt,artifactCatalogVersion:he,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((g,h)=>g.path.localeCompare(h.path))},p=C(f(a,qt),l,{spacing:2,trailingNewline:!0});p.directorySync!=="not-requested"&&o.push(p.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push($(a)),e.onPublicationStage?.("after-staging-directory-synced");let u=Vt(e.snapshot);try{if(q(u)&&!H(e.snapshot)){let g=`${u}.corrupt-${process.pid}-${Date.now()}`;U(u,g),W(g,{recursive:!0,force:!0})}U(a,u)}catch(g){let h=H(e.snapshot);if(h)return qn(e.snapshot,h);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push($(i)),e.onPublicationStage?.("after-generations-directory-synced");let b=re(...o);return{kind:"published",manifest:l,achievedDurability:b==="synced"?"directory-durable":"file-flushed",directorySync:b}}finally{W(a,{recursive:!0,force:!0})}}function qn(e,t){let r=$(f(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:r==="synced"?"directory-durable":"file-flushed",directorySync:r}}function Qd(e){let t=Vt(e.snapshot);Q(e.targetCacheDir,{recursive:!0});let r=te(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:e.lockWaitMs??3e4});if(!r)throw new Error("timed out waiting for another cache hydration");let n,i,o=!1;try{n=Un(f(e.targetCacheDir,".shared-hydrate-")),ps(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let d=G(t,c.path),l=G(n,c.path);if(be(d,l),Ue(l).size!==c.size||we(l,{inputKind:"hydrated shared-generation artifact",maxBytes:R})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Ut(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&en(G(n,c.path),e.manifest.scipProjectRoot,a);if(!ti(n,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=ls(e.targetCacheDir,n),o=!0,us(n,e.targetCacheDir,i),On({tempOutputScip:f(n,"index.scip"),tempOutputDb:f(n,"index.db"),tempMetaPath:f(n,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let s=qe(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);e.persistLease!==!1&&os(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&fs(e.targetCacheDir,i),a}finally{n&&W(n,{recursive:!0,force:!0}),r.release()}}async function Zd(e,t={}){let r=t.timeoutMs??3e4,n=t.pollMs??100,i=t.now??ve,o=i()+r,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`),c=d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;let l=d.pid;return typeof l=="number"&&Number.isSafeInteger(l)&&l>0?{pid:l}:null};for(;i()<=o;){if(H(e))return{kind:"generation-ready"};let d=Re(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(d.kind==="acquired")return{kind:"owner",release:()=>d.lock.release()};let l=o-i();if(l<=0)break;await es(Math.min(n,l))}return H(e)?{kind:"generation-ready"}:{kind:"timeout"}}function os(e,t,r,n=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:r,lastSeenAt:(n??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Jt(i)};return Zn(e.repositoryCacheDir,o,!0),o}function el(e,t,r=void 0){let n={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,lastAction:"overlay",lastReason:`private cache forked from shared baseline ${e.generationId}`,lastSeenAt:(r??(()=>new Date))().toISOString()},i={...n,ownershipChecksum:Jt(n)};return Zn(e.repositoryCacheDir,i,!0),i}function Jt(e){return ri(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:V(e.projectRoot),localCacheDir:V(e.localCacheDir)}))}function Xn(e){let t=JSON.parse(e);if(t.version!==Wt||t.artifactCatalogVersion!==he||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Ve||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let r=new Set;for(let n of t.artifacts){if(!n||typeof n.path!="string"||typeof n.size!="number"||n.size<0||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new Error("invalid shared generation artifact");if(Je(n.path),r.has(n.path))throw new Error(`duplicate shared generation artifact: ${n.path}`);r.add(n.path)}for(let n of["index.db","index.scip","meta.json"])if(!r.has(n))throw new Error(`shared generation is missing ${n}`);return t}function be(e,t,r=384){return Te(e,t,{mode:r})}function as(e,t,r){Q(e,{recursive:!0}),C(f(e,Kn),{version:1,repositoryId:t,worktreeId:r},{spacing:2,trailingNewline:!0})}function zn(e){try{let t=ze(e),r=Vn("sha256");for(let n of t.files){let i=G(e,n),o=Ue(i).size;r.update(n).update("\0").update(String(o)).update("\0"),er(i,{inputKind:"source-generation artifact",maxBytes:R},a=>r.update(a)),r.update("\0")}return r.digest("hex")}catch{return null}}function Qn(e){try{let t=Zt(P(f(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:T}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function ss(e){return Qn(e)?.scipCompanion!=="deferred"}function cs(e,t){let r=at(e.languages,e);return JSON.stringify(r)===JSON.stringify(t)}function Jn(e,t){let r=new Map(e.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),n=new Map(t.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),i=0;for(let[o,a]of r)n.get(o)!==a&&(i+=1);for(let o of n.keys())r.has(o)||(i+=1);return i}function Vt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function ds(e){let t=JSON.parse(P(f(e,Kn),{inputKind:"worktree cache pointer",maxBytes:T}));return t.version!==1||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(t.worktreeId)?null:{version:t.version,repositoryId:t.repositoryId,worktreeId:t.worktreeId}}function Zn(e,t,r){let n=ir(e,{waitMs:5e3});if(!n)throw new Error("repository cache cleanup is busy");try{if(r){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!q(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");Q(i,{recursive:!0}),C(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),as(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{n.release()}}function ls(e,t){let r=f(t,".rollback"),n=new Map,i=new Map;Q(r,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),d=q(c);n.set(s,d),d&&be(c,f(r,"stable",s))}for(let s of zt){let c=f(e,s),d=q(c);if(d){let l=$t(c);if(!l.isDirectory()||l.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,d)}let o=f(e,Ae),a=q(o);return a&&ei(o,f(r,"sqlite-generations")),{root:r,stableFiles:n,managedDirectories:i,generationStoreExisted:a}}function us(e,t,r){for(let n of zt){let i=f(t,n);if(r.managedDirectories.get(n)){let a=f(r.root,"managed",n);Q(jt(a),{recursive:!0}),U(i,a)}let o=f(e,n);q(o)&&U(o,i)}}function fs(e,t){for(let i of zt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?q(a)&&(W(o,{recursive:!0,force:!0}),U(a,o)):W(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){W(a,{force:!0});continue}let s=`${a}.shared-restore-${Za()}`;be(f(t.root,"stable",i),s),W(a,{force:!0}),U(s,a)}let r=f(e,Ae);W(r,{recursive:!0,force:!0});let n=f(t.root,"sqlite-generations");t.generationStoreExisted&&q(n)&&U(n,r)}function ei(e,t){Q(t,{recursive:!0});for(let r of Hn(e,{withFileTypes:!0})){let n=f(e,r.name),i=f(t,r.name);if(r.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${n}`);r.isDirectory()?ei(n,i):r.isFile()&&be(n,i)}}function ps(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||!Ie(e.fingerprint,t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function ti(e,t,r,n=!0,i=!0){try{let o=Qn(e);if(!o||o.scipCompanion==="deferred"||!Ie(Kt(o.fingerprint),r)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...r.languages].sort()))return Se("source validation rejected metadata"),!1;let a=ze(e),s=qe(f(e,"index.db"),f(e,"meta.json"));if(n?s.state!=="current":s.state==="invalid"||s.state==="drifted")return Se(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new ts(f(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let d=Ut(t),p=(i?a.files.filter(u=>u.endsWith(".scip")):["index.scip"]).every(u=>{let b=de(v(G(e,u),{inputKind:"shared SCIP validation artifact",maxBytes:R}));return b!==d&&Se(`source validation rejected SCIP root for ${u}: ${String(b)}`),b===d});return p||Se("source validation rejected SCIP project roots"),p}catch(o){return Se(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Se(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Ut(e){try{return jn(Yn(e)).href}catch{return jn(V(e)).href}}function gs(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===3&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(r=>r!==null&&typeof r=="object"&&typeof r.path=="string"&&typeof r.size=="number"&&typeof r.hash=="string"&&(r.semanticHash===void 0||typeof r.semanticHash=="string"))}function ri(e){return Vn("sha256").update(e).digest("hex")}export{bs as a,se as b,Is as c,E as d,_s as e,lt as f,Ai as g,Di as h,Ms as i,ki as j,Fs as k,Gi as l,Ns as m,_r as n,Me as o,nn as p,Vs as q,D as r,ce as s,_e as t,tc as u,Zr as v,lc as w,uc as x,fc as y,Jo as z,Tc as A,Pc as B,Ac as C,Oc as D,Uc as E,Hc as F,nd as G,id as H,od as I,On as J,Ba as K,hd as L,qe as M,ns as N,Hd as O,Yd as P,H as Q,Kd as R,Xd as S,Qd as T,Zd as U,os as V,el as W};
12
- //# sourceMappingURL=chunk-ZHG4WAHR.js.map