scip-query 0.19.5 → 0.19.8

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 (421) hide show
  1. package/CHANGELOG.md +85 -1
  2. package/README.md +259 -53
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/chunk-2465DLHK.js +3 -0
  5. package/dist/{chunk-7GXM52MI.js → chunk-24GTWJ3N.js} +2 -2
  6. package/dist/{chunk-NH5ALKPW.js → chunk-2SNGN6U4.js} +2 -2
  7. package/dist/{chunk-3SVWW4PN.js → chunk-2U3OLUNJ.js} +2 -2
  8. package/dist/{chunk-XLTP42QA.js → chunk-33KUO7CG.js} +2 -2
  9. package/dist/{chunk-54HA4ZXH.js → chunk-33XTHFKR.js} +2 -2
  10. package/dist/{chunk-ZGZUZ7XE.js → chunk-3EDFLQ6A.js} +2 -2
  11. package/dist/chunk-3ZSJ3PWF.js +16 -0
  12. package/dist/{chunk-F6O7AAC3.js → chunk-43KC6EQZ.js} +2 -2
  13. package/dist/{chunk-I5RJM53C.js → chunk-464PLI5O.js} +2 -2
  14. package/dist/chunk-46XGSFNI.js +2 -0
  15. package/dist/{chunk-M7AIS73L.js → chunk-47BU5Z4T.js} +2 -2
  16. package/dist/chunk-4BV4QAZJ.js +5 -0
  17. package/dist/chunk-4YTUWQ6M.js +18 -0
  18. package/dist/{chunk-RV2FQIX3.js → chunk-5ML2BNRH.js} +2 -2
  19. package/dist/{chunk-6NSFJYRC.js → chunk-5YLUDDAF.js} +2 -2
  20. package/dist/chunk-67QRR5YC.js +6 -0
  21. package/dist/{chunk-GPBBJ5Y4.js → chunk-6GXYN7YA.js} +3 -3
  22. package/dist/{chunk-4333ETTV.js → chunk-6M7RONVB.js} +2 -2
  23. package/dist/chunk-6YTSKJJ3.js +2 -0
  24. package/dist/{chunk-QDV6RDCP.js → chunk-7FT5Y65S.js} +2 -2
  25. package/dist/{chunk-XTX6QHOF.js → chunk-7KYNAMMH.js} +2 -2
  26. package/dist/{chunk-DZ74OMG6.js → chunk-7LSVMFX7.js} +2 -2
  27. package/dist/{chunk-VTKGCT3V.js → chunk-7QHY3H7P.js} +2 -2
  28. package/dist/{chunk-MITTUCEH.js → chunk-7RAG65VK.js} +2 -2
  29. package/dist/{chunk-25LPM4DG.js → chunk-7SWJEWJF.js} +2 -2
  30. package/dist/{chunk-52ZYCAEO.js → chunk-7VCOXZH3.js} +2 -2
  31. package/dist/chunk-A2TNXAXO.js +8 -0
  32. package/dist/{chunk-IUFDSKGG.js → chunk-A3QXWFBK.js} +2 -2
  33. package/dist/{chunk-4T3LTWUS.js → chunk-AA4UWRNL.js} +2 -2
  34. package/dist/{chunk-4SALD7RU.js → chunk-ACAM6O5R.js} +2 -2
  35. package/dist/chunk-APMMR5Y2.js +2 -0
  36. package/dist/chunk-AQOFWNQJ.js +1 -0
  37. package/dist/chunk-AZFUMCQB.js +2 -0
  38. package/dist/{chunk-M7MTH5NR.js → chunk-BDOIKGDI.js} +2 -2
  39. package/dist/{chunk-BTEE5NZQ.js → chunk-BNXICU42.js} +2 -2
  40. package/dist/chunk-C5Q44Q5D.js +3 -0
  41. package/dist/{chunk-EOOJGLDU.js → chunk-CTF2GDEX.js} +2 -2
  42. package/dist/chunk-DHEQMPLW.js +2 -0
  43. package/dist/{chunk-IZKFSVBV.js → chunk-DQBCO2UY.js} +2 -2
  44. package/dist/{chunk-7B3UPBVA.js → chunk-DQGSM7RZ.js} +2 -2
  45. package/dist/chunk-E2LAW7SL.js +30 -0
  46. package/dist/chunk-E3HYEQO7.js +2 -0
  47. package/dist/chunk-E4NFOAD4.js +6 -0
  48. package/dist/chunk-E5HNT4X2.js +3 -0
  49. package/dist/{chunk-J77UIT3I.js → chunk-ELLMY7XJ.js} +2 -2
  50. package/dist/chunk-FD3HFKXR.js +5 -0
  51. package/dist/{chunk-SOAT6NLA.js → chunk-FIJCV235.js} +2 -2
  52. package/dist/{chunk-H7UKLTWJ.js → chunk-FJ5UDTQF.js} +2 -2
  53. package/dist/{chunk-HEXVUYFQ.js → chunk-GHKEJTCE.js} +2 -2
  54. package/dist/{chunk-LBMJEAEW.js → chunk-GLZTVKAB.js} +3 -3
  55. package/dist/{chunk-FWUUZTIO.js → chunk-GNC4JVAN.js} +2 -2
  56. package/dist/chunk-HIB452NU.js +949 -0
  57. package/dist/{chunk-NRCXJDHL.js → chunk-HZYDQPNY.js} +2 -2
  58. package/dist/chunk-IF6FP6B2.js +66 -0
  59. package/dist/{chunk-4RSI5EMG.js → chunk-JAY7YWS3.js} +2 -2
  60. package/dist/{chunk-STOL2BTL.js → chunk-JHF3E4YM.js} +2 -2
  61. package/dist/chunk-JORHF5AL.js +108 -0
  62. package/dist/{chunk-A2EZV2UM.js → chunk-K2WO7XY7.js} +2 -2
  63. package/dist/chunk-KFZNKUNT.js +2 -0
  64. package/dist/{chunk-YVVCVR2L.js → chunk-KJ2IIBZN.js} +2 -2
  65. package/dist/{chunk-QGXBRIM5.js → chunk-KKME5ZAI.js} +2 -2
  66. package/dist/chunk-KSGTULOS.js +9 -0
  67. package/dist/{chunk-UOAV44HR.js → chunk-KXDJAG4N.js} +3 -3
  68. package/dist/{chunk-UKZBVX4U.js → chunk-L4S2A7BV.js} +2 -2
  69. package/dist/chunk-LP3ARJKF.js +8 -0
  70. package/dist/chunk-LSOR3LQG.js +3 -0
  71. package/dist/{chunk-Q4IIEGXJ.js → chunk-MLFZP76A.js} +2 -2
  72. package/dist/{chunk-WQTAC523.js → chunk-MNSTUIDD.js} +2 -2
  73. package/dist/{chunk-VXQNNXJE.js → chunk-MSBDMFER.js} +2 -2
  74. package/dist/{chunk-X6D5IC6I.js → chunk-MZZBAITE.js} +5 -5
  75. package/dist/{chunk-I5AWSI2G.js → chunk-NE3TZUCI.js} +2 -2
  76. package/dist/{chunk-6E7UTQY7.js → chunk-NTUMF2X3.js} +2 -2
  77. package/dist/{chunk-S44IULR6.js → chunk-O23I56NA.js} +2 -2
  78. package/dist/{chunk-CFMXJPHH.js → chunk-O3O4XXO6.js} +2 -2
  79. package/dist/{chunk-IG7N5ZIK.js → chunk-OUBAF226.js} +2 -2
  80. package/dist/chunk-P3UO3EH3.js +2 -0
  81. package/dist/{chunk-YNRNA5LK.js → chunk-QGGLL3UH.js} +2 -2
  82. package/dist/chunk-QIQ63BHW.js +16 -0
  83. package/dist/{chunk-VGRICIQI.js → chunk-QJIVBYEK.js} +2 -2
  84. package/dist/chunk-QOXBSI6G.js +20 -0
  85. package/dist/chunk-QXK6UUSM.js +2 -0
  86. package/dist/{chunk-XYADIZHU.js → chunk-RA3AYNWP.js} +2 -2
  87. package/dist/chunk-RJMDJR3A.js +2 -0
  88. package/dist/{chunk-NSS46APD.js → chunk-RLH5VUMG.js} +2 -2
  89. package/dist/{chunk-GBQ5NYPR.js → chunk-S4S2WOIX.js} +6 -6
  90. package/dist/{chunk-YIJ7ZAA4.js → chunk-SERUIGV5.js} +2 -2
  91. package/dist/{chunk-FECYOO5O.js → chunk-SMQWE25B.js} +2 -2
  92. package/dist/{chunk-R4FQGQ4X.js → chunk-TAVELHYR.js} +2 -2
  93. package/dist/{chunk-U6WNH5GC.js → chunk-TWMJ3Y3G.js} +2 -2
  94. package/dist/chunk-VAXNI5NE.js +146 -0
  95. package/dist/chunk-VVY2G5ET.js +2 -0
  96. package/dist/{chunk-WER3B7MI.js → chunk-W3DBTGL4.js} +2 -2
  97. package/dist/{chunk-CNKAGUPL.js → chunk-WANA4KAQ.js} +2 -2
  98. package/dist/chunk-WJL2L6MV.js +60 -0
  99. package/dist/chunk-WUW7YUAH.js +11 -0
  100. package/dist/{chunk-QVWS2VWZ.js → chunk-WWKWUPSU.js} +2 -2
  101. package/dist/{chunk-ABMYA4TN.js → chunk-WY45BHKQ.js} +2 -2
  102. package/dist/chunk-X4FR5BZF.js +9 -0
  103. package/dist/chunk-X6RKPDY7.js +2 -0
  104. package/dist/{chunk-ZXJYMGD3.js → chunk-YLFORA5G.js} +2 -2
  105. package/dist/{chunk-KP6XRY5Z.js → chunk-YTVWB7YJ.js} +2 -2
  106. package/dist/{chunk-4XTA5OMB.js → chunk-ZCEJ63SP.js} +2 -2
  107. package/dist/{chunk-HKEHS2AS.js → chunk-ZJ5CBXK3.js} +2 -2
  108. package/dist/chunk-ZL2OGDCD.js +2 -0
  109. package/dist/cli.js +8 -3
  110. package/dist/command-descriptors-ZW5J4ZEM.js +631 -0
  111. package/dist/{config-types-D20KuvvZ.d.ts → config-types-B6MEoRNy.d.ts} +8 -0
  112. package/dist/{db-G_II8yXU.d.ts → db-DYLKr9Wn.d.ts} +18 -1
  113. package/dist/direct-navigation-42YHQPOI.js +3 -0
  114. package/dist/{health-oblXYgkF.d.ts → health-DgxIDXJC.d.ts} +1 -1
  115. package/dist/index.d.ts +2 -2
  116. package/dist/index.js +1 -1
  117. package/dist/postinstall.js +1 -1
  118. package/dist/queries/affected.d.ts +2 -2
  119. package/dist/queries/affected.js +1 -1
  120. package/dist/queries/architecture.d.ts +2 -2
  121. package/dist/queries/architecture.js +1 -1
  122. package/dist/queries/bottlenecks.d.ts +2 -2
  123. package/dist/queries/bottlenecks.js +1 -1
  124. package/dist/queries/by-kind.d.ts +2 -2
  125. package/dist/queries/by-kind.js +1 -1
  126. package/dist/queries/call-graph.d.ts +2 -2
  127. package/dist/queries/call-graph.js +1 -1
  128. package/dist/queries/change-surface.d.ts +2 -2
  129. package/dist/queries/change-surface.js +1 -1
  130. package/dist/queries/cleanup-plan.d.ts +2 -2
  131. package/dist/queries/cleanup-plan.js +1 -1
  132. package/dist/queries/co-change.d.ts +2 -2
  133. package/dist/queries/co-change.js +1 -1
  134. package/dist/queries/code.d.ts +2 -2
  135. package/dist/queries/code.js +1 -1
  136. package/dist/queries/complexity-hotspots.d.ts +2 -2
  137. package/dist/queries/complexity-hotspots.js +1 -1
  138. package/dist/queries/complexity.d.ts +2 -2
  139. package/dist/queries/complexity.js +1 -1
  140. package/dist/queries/convergence.d.ts +2 -2
  141. package/dist/queries/convergence.js +1 -1
  142. package/dist/queries/coupling.d.ts +2 -2
  143. package/dist/queries/coupling.js +1 -1
  144. package/dist/queries/cycles.d.ts +2 -2
  145. package/dist/queries/cycles.js +1 -1
  146. package/dist/queries/dataflow.d.ts +2 -2
  147. package/dist/queries/dataflow.js +1 -1
  148. package/dist/queries/dead.d.ts +2 -2
  149. package/dist/queries/dead.js +1 -1
  150. package/dist/queries/decorative-checkers.d.ts +3 -3
  151. package/dist/queries/decorative-checkers.js +1 -1
  152. package/dist/queries/deep-chains.d.ts +2 -2
  153. package/dist/queries/deep-chains.js +1 -1
  154. package/dist/queries/deps.d.ts +2 -2
  155. package/dist/queries/deps.js +1 -1
  156. package/dist/queries/diff-gate.d.ts +30 -2
  157. package/dist/queries/diff-gate.js +1 -1
  158. package/dist/queries/diff-impact.d.ts +2 -2
  159. package/dist/queries/diff-impact.js +1 -1
  160. package/dist/queries/doc-drift.d.ts +2 -2
  161. package/dist/queries/doc-drift.js +1 -1
  162. package/dist/queries/drift.d.ts +2 -2
  163. package/dist/queries/drift.js +1 -1
  164. package/dist/queries/duplicate-bodies.d.ts +2 -2
  165. package/dist/queries/duplicate-bodies.js +1 -1
  166. package/dist/queries/extract-candidates.d.ts +2 -2
  167. package/dist/queries/extract-candidates.js +1 -1
  168. package/dist/queries/fan.d.ts +2 -2
  169. package/dist/queries/fan.js +1 -1
  170. package/dist/queries/files.d.ts +2 -2
  171. package/dist/queries/health.d.ts +3 -3
  172. package/dist/queries/health.js +1 -1
  173. package/dist/queries/hierarchy.d.ts +2 -2
  174. package/dist/queries/hierarchy.js +1 -1
  175. package/dist/queries/hotspots.d.ts +2 -2
  176. package/dist/queries/hotspots.js +1 -1
  177. package/dist/queries/imports.d.ts +2 -2
  178. package/dist/queries/imports.js +1 -1
  179. package/dist/queries/incomplete-migration.d.ts +2 -2
  180. package/dist/queries/incomplete-migration.js +1 -1
  181. package/dist/queries/index.d.ts +17 -3
  182. package/dist/queries/index.js +1 -1
  183. package/dist/queries/isolated.d.ts +2 -2
  184. package/dist/queries/isolated.js +1 -1
  185. package/dist/queries/locality-candidates.d.ts +2 -2
  186. package/dist/queries/locality-candidates.js +1 -1
  187. package/dist/queries/members.d.ts +2 -2
  188. package/dist/queries/members.js +1 -1
  189. package/dist/queries/methods.d.ts +2 -2
  190. package/dist/queries/methods.js +1 -1
  191. package/dist/queries/not-implemented.d.ts +3 -3
  192. package/dist/queries/not-implemented.js +1 -1
  193. package/dist/queries/outline.d.ts +2 -2
  194. package/dist/queries/outline.js +1 -1
  195. package/dist/queries/passthrough-candidates.d.ts +2 -2
  196. package/dist/queries/passthrough-candidates.js +1 -1
  197. package/dist/queries/plan-context.d.ts +2 -2
  198. package/dist/queries/plan-context.js +1 -1
  199. package/dist/queries/react-component-duplicates.d.ts +2 -2
  200. package/dist/queries/react-component-duplicates.js +1 -1
  201. package/dist/queries/react-hook-candidates.d.ts +2 -2
  202. package/dist/queries/react-hook-candidates.js +1 -1
  203. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  204. package/dist/queries/react-large-component-pressure.js +1 -1
  205. package/dist/queries/recent-duplicates.d.ts +2 -2
  206. package/dist/queries/recent-duplicates.js +1 -1
  207. package/dist/queries/redundant-reexports.d.ts +2 -2
  208. package/dist/queries/redundant-reexports.js +1 -1
  209. package/dist/queries/refs.d.ts +2 -2
  210. package/dist/queries/refs.js +1 -1
  211. package/dist/queries/self-audit.d.ts +2 -2
  212. package/dist/queries/self-audit.js +1 -1
  213. package/dist/queries/similar-chains.d.ts +2 -2
  214. package/dist/queries/similar-chains.js +1 -1
  215. package/dist/queries/similar-files.d.ts +2 -2
  216. package/dist/queries/similar-files.js +1 -1
  217. package/dist/queries/similar-signatures.d.ts +2 -2
  218. package/dist/queries/similar-signatures.js +1 -1
  219. package/dist/queries/similar.d.ts +2 -2
  220. package/dist/queries/similar.js +1 -1
  221. package/dist/queries/slice.d.ts +2 -2
  222. package/dist/queries/slice.js +1 -1
  223. package/dist/queries/stale-abstractions.d.ts +2 -2
  224. package/dist/queries/stale-abstractions.js +1 -1
  225. package/dist/queries/stats.d.ts +2 -2
  226. package/dist/queries/stats.js +1 -1
  227. package/dist/queries/surface.d.ts +2 -2
  228. package/dist/queries/surface.js +1 -1
  229. package/dist/queries/symbols.d.ts +2 -2
  230. package/dist/queries/symbols.js +1 -1
  231. package/dist/queries/system.d.ts +2 -2
  232. package/dist/queries/system.js +1 -1
  233. package/dist/queries/test-quality.d.ts +2 -2
  234. package/dist/queries/test-quality.js +1 -1
  235. package/dist/queries/trace.d.ts +2 -2
  236. package/dist/queries/trace.js +1 -1
  237. package/dist/queries/twin-ab.d.ts +3 -3
  238. package/dist/queries/twin-ab.js +1 -1
  239. package/dist/queries/twin-drift.d.ts +2 -2
  240. package/dist/queries/twin-drift.js +1 -1
  241. package/dist/queries/unused-imports.d.ts +2 -2
  242. package/dist/queries/unused-imports.js +1 -1
  243. package/dist/queries/unused-params.d.ts +2 -2
  244. package/dist/queries/unused-params.js +1 -1
  245. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  246. package/dist/queries/vue-component-duplicates.js +1 -1
  247. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  248. package/dist/queries/vue-composable-candidates.js +1 -1
  249. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  250. package/dist/queries/vue-large-view-pressure.js +1 -1
  251. package/dist/queries/wrapper-candidates.d.ts +2 -2
  252. package/dist/queries/wrapper-candidates.js +1 -1
  253. package/dist/reindex-worker.js +26 -26
  254. package/dist/reindex.d.ts +14 -4
  255. package/dist/reindex.js +34 -38
  256. package/dist/runtime.d.ts +167 -18
  257. package/dist/runtime.js +3 -2
  258. package/dist/rust-semantic-session-server.js +1 -1
  259. package/dist/rust-semantic-session-worker.js +1 -1
  260. package/dist/rust-semantic-worker.js +1 -1
  261. package/dist/{scip-cli-kRpaexVJ.d.ts → scip-cli-Cc6c00-a.d.ts} +6 -2
  262. package/dist/watch-server.js +5 -5
  263. package/docs/AGENT_GUIDE.md +20 -4
  264. package/docs/AI_FAILURE_MODES.md +17 -17
  265. package/docs/API_EVOLUTION.md +71 -0
  266. package/docs/CLI_JSON_OUTPUT.md +168 -0
  267. package/docs/COMMAND_REFERENCE.md +10 -6
  268. package/docs/COMMITTED_RECORD_COMPATIBILITY.md +117 -0
  269. package/docs/CONFIGURATION_WRITE_SAFETY.md +130 -0
  270. package/docs/DETECTOR_GUIDE.md +46 -46
  271. package/docs/DURABILITY.md +103 -0
  272. package/docs/INDEX_GENERATIONS.md +121 -0
  273. package/docs/LOCK_PROTOCOL.md +133 -0
  274. package/docs/MAILBOX_LIFECYCLE.md +197 -0
  275. package/docs/REINDEX_METADATA_COMPATIBILITY.md +84 -0
  276. package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
  277. package/docs/SECURITY_MODEL.md +129 -0
  278. package/docs/TELEMETRY_RETENTION.md +77 -0
  279. package/docs/TIME_SEMANTICS.md +77 -0
  280. package/docs/WATCH_REFRESH_REQUESTS.md +110 -0
  281. package/docs/WINDOWS_SIDECAR_RELEASE.md +298 -0
  282. package/docs/analyzer-validation-ledger.md +24 -23
  283. package/docs/schemas/cli-json-envelope.schema.json +53 -0
  284. package/docs/schemas/cli-output-page.schema.json +104 -0
  285. package/docs/schemas/npm-release-state.schema.json +146 -0
  286. package/docs/schemas/outcome-event-record.schema.json +39 -0
  287. package/docs/schemas/project-config.schema.json +247 -0
  288. package/docs/schemas/suppression-record.schema.json +31 -0
  289. package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
  290. package/package.json +21 -10
  291. package/scripts/build-scip-windows.mjs +180 -61
  292. package/scripts/scip-windows-provenance.mjs +364 -0
  293. package/scripts/verify-scip-windows.mjs +29 -0
  294. package/skills/_shared/SKILL.md +90 -229
  295. package/skills/_shared/agents/openai.yaml +1 -1
  296. package/skills/_shared/references/agent-contract-catalog.md +105 -0
  297. package/skills/_shared/references/command-catalog.md +118 -0
  298. package/skills/_shared/references/detector-precision-and-diffgate.md +59 -0
  299. package/skills/_shared/references/evidence-and-dead-code.md +25 -0
  300. package/skills/scip-audit/SKILL.md +77 -0
  301. package/skills/scip-audit/agents/openai.yaml +4 -0
  302. package/skills/scip-audit/references/claims.md +98 -0
  303. package/skills/scip-audit/references/cleanup.md +101 -0
  304. package/skills/scip-audit/references/directory.md +222 -0
  305. package/skills/scip-audit/references/frontend.md +130 -0
  306. package/skills/scip-audit/references/integrity.md +154 -0
  307. package/skills/scip-audit/references/maintainability.md +162 -0
  308. package/skills/scip-audit/references/twin-drift.md +104 -0
  309. package/skills/scip-diagnose/SKILL.md +52 -0
  310. package/skills/scip-diagnose/agents/openai.yaml +4 -0
  311. package/skills/scip-diagnose/references/debug.md +117 -0
  312. package/skills/{scip-probe-reachability/SKILL.md → scip-diagnose/references/probe-reachability.md} +11 -27
  313. package/skills/scip-diagnose/references/root-cause.md +145 -0
  314. package/skills/scip-diagnose/references/triage.md +119 -0
  315. package/skills/scip-explore/SKILL.md +54 -85
  316. package/skills/scip-explore/agents/openai.yaml +2 -2
  317. package/skills/scip-explore/references/diagrams.md +40 -0
  318. package/skills/scip-explore/references/language-playbook.md +49 -0
  319. package/skills/scip-improve/SKILL.md +56 -0
  320. package/skills/scip-improve/agents/openai.yaml +4 -0
  321. package/skills/scip-improve/references/cleanup-batches.md +53 -0
  322. package/skills/scip-improve/references/directory-moves.md +53 -0
  323. package/skills/scip-improve/references/doc-reconcile.md +30 -0
  324. package/skills/scip-improve/references/frontend-extraction.md +39 -0
  325. package/skills/scip-improve/references/maintainability-mechanism.md +43 -0
  326. package/skills/scip-improve/references/twin-drift.md +35 -0
  327. package/skills/scip-plan/SKILL.md +68 -0
  328. package/skills/scip-plan/agents/openai.yaml +4 -0
  329. package/skills/scip-plan/references/api-impact.md +19 -0
  330. package/skills/scip-plan/references/conductor.md +41 -0
  331. package/skills/scip-plan/references/high-assurance.md +43 -0
  332. package/skills/scip-plan/references/hyper-optimization.md +50 -0
  333. package/skills/scip-plan/references/tla-model.md +88 -0
  334. package/skills/scip-query/SKILL.md +53 -98
  335. package/skills/scip-query/agents/openai.yaml +2 -2
  336. package/skills/scip-setup/SKILL.md +69 -181
  337. package/skills/scip-setup/agents/openai.yaml +3 -3
  338. package/skills/scip-setup/references/bootstrap-workflow.md +120 -0
  339. package/skills/scip-setup/references/language-verification.md +61 -0
  340. package/skills/scip-setup/references/lifecycle-commands.md +119 -0
  341. package/skills/scip-setup/references/per-repo-triage.md +24 -0
  342. package/skills/scip-verify/SKILL.md +126 -84
  343. package/skills/scip-verify/agents/openai.yaml +2 -2
  344. package/skills/scip-verify/references/calibrate-detectors.md +170 -0
  345. package/dist/chunk-2CTX5CMX.js +0 -4
  346. package/dist/chunk-2Y373BDD.js +0 -2
  347. package/dist/chunk-2YU7I3QO.js +0 -2
  348. package/dist/chunk-3MJ5YA4Y.js +0 -16
  349. package/dist/chunk-64RFXJT5.js +0 -16
  350. package/dist/chunk-7UY7SD7D.js +0 -927
  351. package/dist/chunk-B5NLK2B3.js +0 -6
  352. package/dist/chunk-C2QSK7E7.js +0 -2
  353. package/dist/chunk-C7NIYIQ4.js +0 -67
  354. package/dist/chunk-D4U5Q3FT.js +0 -7
  355. package/dist/chunk-DGAGY7RJ.js +0 -60
  356. package/dist/chunk-DLWR3NUU.js +0 -5
  357. package/dist/chunk-K2ERX4UT.js +0 -3
  358. package/dist/chunk-KHE7J5ZN.js +0 -3
  359. package/dist/chunk-L7SPDE73.js +0 -84
  360. package/dist/chunk-LHMNRHGV.js +0 -3
  361. package/dist/chunk-LM72NQ7T.js +0 -3
  362. package/dist/chunk-MSWVMDAH.js +0 -122
  363. package/dist/chunk-NH7WNNQC.js +0 -20
  364. package/dist/chunk-NPKYOIFM.js +0 -18
  365. package/dist/chunk-NZL2DBT7.js +0 -2
  366. package/dist/chunk-OMPZHGHO.js +0 -2
  367. package/dist/chunk-P2PC2WGR.js +0 -2
  368. package/dist/chunk-Q3AFUTGB.js +0 -8
  369. package/dist/chunk-QRGV2F7L.js +0 -2
  370. package/dist/chunk-TW4OG5FC.js +0 -4
  371. package/dist/chunk-U7DSEKOM.js +0 -30
  372. package/dist/chunk-V27BEQJN.js +0 -7
  373. package/dist/chunk-XAGAZSFE.js +0 -6
  374. package/dist/chunk-XBN5VO53.js +0 -2
  375. package/dist/chunk-YGAGTIDK.js +0 -11
  376. package/dist/command-descriptors-N2TL4XM2.js +0 -613
  377. package/dist/direct-navigation-DUCZCTOE.js +0 -3
  378. package/skills/scip-api-impact/SKILL.md +0 -140
  379. package/skills/scip-api-impact/agents/openai.yaml +0 -4
  380. package/skills/scip-calibrate/SKILL.md +0 -131
  381. package/skills/scip-calibrate/agents/openai.yaml +0 -4
  382. package/skills/scip-claim-audit/SKILL.md +0 -107
  383. package/skills/scip-claim-audit/agents/openai.yaml +0 -4
  384. package/skills/scip-cleanup-audit/SKILL.md +0 -130
  385. package/skills/scip-cleanup-audit/agents/openai.yaml +0 -4
  386. package/skills/scip-cleanup-improve/SKILL.md +0 -85
  387. package/skills/scip-cleanup-improve/agents/openai.yaml +0 -4
  388. package/skills/scip-concrete-plan/HIGH_ASSURANCE.md +0 -317
  389. package/skills/scip-concrete-plan/SKILL.md +0 -105
  390. package/skills/scip-concrete-plan/agents/openai.yaml +0 -4
  391. package/skills/scip-conductor/SKILL.md +0 -133
  392. package/skills/scip-conductor/agents/openai.yaml +0 -4
  393. package/skills/scip-debug/SKILL.md +0 -130
  394. package/skills/scip-debug/agents/openai.yaml +0 -4
  395. package/skills/scip-diagram/SKILL.md +0 -110
  396. package/skills/scip-diagram/agents/openai.yaml +0 -4
  397. package/skills/scip-directory-architecture/SKILL.md +0 -266
  398. package/skills/scip-directory-architecture/agents/openai.yaml +0 -4
  399. package/skills/scip-doc-reconcile/SKILL.md +0 -89
  400. package/skills/scip-doc-reconcile/agents/openai.yaml +0 -4
  401. package/skills/scip-hyper-optimization/SKILL.md +0 -156
  402. package/skills/scip-hyper-optimization/agents/openai.yaml +0 -4
  403. package/skills/scip-integrity-audit/SKILL.md +0 -152
  404. package/skills/scip-integrity-audit/agents/openai.yaml +0 -4
  405. package/skills/scip-language-playbook/SKILL.md +0 -106
  406. package/skills/scip-language-playbook/agents/openai.yaml +0 -4
  407. package/skills/scip-maintainability/SKILL.md +0 -158
  408. package/skills/scip-maintainability/agents/openai.yaml +0 -4
  409. package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
  410. package/skills/scip-react-maintainability/SKILL.md +0 -101
  411. package/skills/scip-react-maintainability/agents/openai.yaml +0 -4
  412. package/skills/scip-root-cause/SKILL.md +0 -151
  413. package/skills/scip-root-cause/agents/openai.yaml +0 -4
  414. package/skills/scip-tla-model-system/SKILL.md +0 -148
  415. package/skills/scip-tla-model-system/agents/openai.yaml +0 -4
  416. package/skills/scip-triage-issue/SKILL.md +0 -133
  417. package/skills/scip-triage-issue/agents/openai.yaml +0 -4
  418. package/skills/scip-twin-drift/SKILL.md +0 -109
  419. package/skills/scip-twin-drift/agents/openai.yaml +0 -4
  420. package/skills/scip-vue-maintainability/SKILL.md +0 -107
  421. package/skills/scip-vue-maintainability/agents/openai.yaml +0 -4
package/dist/reindex.js CHANGED
@@ -1,8 +1,6 @@
1
- import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i as Nn,j as $n,k as Gn}from"./chunk-V27BEQJN.js";import{a as Ln}from"./chunk-DGAGY7RJ.js";import{A as _n,a as Y,b as ne,c as re,d as ct,e as ut,f as dt,h as T,i as R,j as En,k as Tn,l as Ee,m as Dn,n as Te,o as Fn,p as On,q as jn,r as lt,t as pt,y as An}from"./chunk-2CTX5CMX.js";import{a as st,b as kn,d as De,g as Cn}from"./chunk-LM72NQ7T.js";import{a as ke}from"./chunk-7B3UPBVA.js";import"./chunk-X6D5IC6I.js";import{J as Pn,K as wn,d as Z}from"./chunk-YGAGTIDK.js";import{s as ee,t as te}from"./chunk-L7SPDE73.js";import{a as we}from"./chunk-64MNV6AB.js";import{execFileSync as Td}from"child_process";import{createHash as Dd}from"crypto";import{closeSync as Fd,copyFileSync as rt,existsSync as O,mkdirSync as nt,mkdtempSync as Od,openSync as jd,readdirSync as Ao,readFileSync as it,renameSync as _o,rmSync as M,statSync as Cd,writeFileSync as Ad}from"fs";import{basename as tt,dirname as h,extname as _d,join as x,resolve as Eo}from"path";import{platform as Ld}from"os";import{randomUUID as Vn}from"crypto";import{closeSync as Bn,mkdirSync as zo,openSync as Un,readFileSync as Wn,unlinkSync as Hn,writeFileSync as Jn}from"fs";import{dirname as Yo,join as Xo}from"path";function qn(e,t={}){return ie(Xo(e,"gc.lock"),t)}function ie(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;zo(Yo(e),{recursive:!0});do{let a=Vn();try{let s=Un(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};Jn(s,`${JSON.stringify(c)}
2
- `)}finally{Bn(s)}return{release:()=>Yn(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=zn(e);if(c&&(c.pid===void 0||!T(c.pid))){Qo(e,c);continue}if(Date.now()>=o)return null;Ko(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function zn(e){try{let t=Wn(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function Qo(e,t){let n=`${e}.reclaim`,r=Vn(),i;try{i=Un(n,"wx")}catch{return!1}try{Jn(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
3
- `)}finally{Bn(i)}try{let o=zn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Hn(e),!0)}catch{return!1}finally{Yn(n,r)}}function Yn(e,t){try{let n=JSON.parse(Wn(e,"utf8"));n.pid===process.pid&&n.token===t&&Hn(e)}catch{}}function Ko(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Zo from"better-sqlite3";import{execFileSync as ea}from"child_process";import{existsSync as ta,readdirSync as na,readFileSync as ra}from"fs";import{extname as Fe,join as Xn}from"path";function H(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Qn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Qn(e){let t=new Set((e.extensions??Pn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ta(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ln(e.projectRoot),r=ia(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Zo(e.dbPath);try{let o=aa(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
4
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=ra(Xn(e.projectRoot,l),"utf-8"),g=a.run(sa(l),l,m);p+=Number(g.changes)}return p})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function ia(e,t){let n=oa(e,t);if(n)return n;let r=[],i=o=>{let a=o?Xn(e,o):e,s;try{s=na(a,{withFileTypes:!0})}catch{return}for(let c of s){if(wn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Fe(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function oa(e,t){try{return ea("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(r=>r&&t.has(Fe(r).toLowerCase())).sort()}catch{return null}}function aa(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function sa(e){return Fe(e).toLowerCase()===".vue"?"vue":Fe(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as ua}from"crypto";import{appendFileSync as da,existsSync as tr,mkdirSync as la,readFileSync as _l,renameSync as pa,rmSync as yt,statSync as ga}from"fs";import{dirname as nr,join as Zn}from"path";function ht(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Oe(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=ht(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),Kn(r,i,a)):a.size>0?Kn(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ca(r,t,i),reasons:[]}}function Kn(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ca(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var fa="<global-symbols>";function ma(e){let t=[];for(let n of e.all(`
1
+ import{a as te}from"./chunk-QOXBSI6G.js";import{a as vr,b as wr,c as kr,d as Tr,f as Lt,g as Nt,h as $t,l as Gt,m as le,n as Vt,o as Er,p as Fr,q as Dr,s as Bt,t as Ar,u as _r,v as jr,w as Or}from"./chunk-KSGTULOS.js";import{a as Pr}from"./chunk-WJL2L6MV.js";import"./chunk-AQOFWNQJ.js";import{A as Ot,B as Sr,C as br,D as Ct,F as Mt,K as xr,M as Ir,a as oe,b as ar,c as Ve,d as wt,e as G,f as Be,g as kt,h as Tt,j as ee,k as Se,l as ae,m as xe,n as se,o as Ft,p as Dt,q as gr,r as fr,s as At,v as de,w as O,x as _t,y as yr,z as jt}from"./chunk-FD3HFKXR.js";import{a as Et,b as pr,d as ce,e as mr,f as Ie,g as ue,h as S,m as hr,o as He,r as Rr}from"./chunk-LSOR3LQG.js";import{a as qe}from"./chunk-DQGSM7RZ.js";import"./chunk-MZZBAITE.js";import{F as dr,G as lr}from"./chunk-WUW7YUAH.js";import{A as be,B as Re,G as sr,J as cr,M as We,N as ur,a as nr,b as rr,c as $e,d as ye,e as z,f as Pt,g as ir,h as vt}from"./chunk-JORHF5AL.js";import{a as Ue}from"./chunk-64MNV6AB.js";import{e as he,f as tr,k as D,l as $,m as A,p as T,q as v,r as E,u as or,v as Ge}from"./chunk-VVY2G5ET.js";import{execFileSync as Dl}from"child_process";import{createHash as Al}from"crypto";import{copyFileSync as Rt,existsSync as M,mkdirSync as St,mkdtempSync as _l,readdirSync as Aa,renameSync as _a,rmSync as fe,statSync as jl}from"fs";import{basename as yt,dirname as y,extname as Ol,join as F,resolve as Pa}from"path";import{platform as Cl}from"os";import{join as Ja}from"path";var Ya=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.pid;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{pid:t}:null};function Cr(e,t={}){return Pe(Ja(e,"gc.lock"),t)}function Pe(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??S,o=i()+n;do{let a=Ka(e);if(a)return Xa(a);let s=o-i();if(s<=0)return null;Qa(Math.min(r,s))}while(i()<=o);return null}function Ka(e){let t=le(e,{kind:"generic",parseLegacy:Ya});return t.kind==="acquired"?t.lock:null}function Xa(e){return{release:()=>{e.release()}}}function Qa(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Za from"better-sqlite3";import{execFileSync as es}from"child_process";import{existsSync as ts,readdirSync as ns}from"fs";import{extname as ze,join as rs}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Mr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Mr(e){let t=new Set((e.extensions??dr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ts(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Pr(e.projectRoot),r=is(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Za(e.dbPath);try{let o=as(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let l=0;for(let p of d){if(o.has(p))continue;let f=cr(e.projectRoot,p,{inputKind:"auxiliary source file"}),g=a.run(ss(p),p,f);l+=Number(g.changes)}return l})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function is(e,t){let n=os(e,t);if(n)return n;let r=[],i=o=>{let a=o?rs(e,o):e,s;try{s=ns(a,{withFileTypes:!0})}catch{return}for(let c of s){if(lr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(ze(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function os(e,t){try{return es("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
3
+ `).filter(r=>r&&t.has(ze(r).toLowerCase())).sort()}catch{return null}}function as(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function ss(e){return ze(e).toLowerCase()===".vue"?"vue":ze(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as us}from"crypto";import{existsSync as ds}from"fs";import{dirname as ls,join as Nr}from"path";function Ut(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Je(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=Ut(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),Lr(r,i,a)):a.size>0?Lr(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:cs(r,t,i),reasons:[]}}function Lr(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function cs(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var ps="<global-symbols>";function gs(e){let t=[];for(let n of e.all(`
6
4
  SELECT relative_path, language, position_encoding, text
7
5
  FROM documents
8
6
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -29,7 +27,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
29
27
  FROM defn_enclosing_ranges r
30
28
  JOIN documents d ON d.id = r.document_id
31
29
  JOIN global_symbols g ON g.id = r.symbol_id
32
- `))t.push({relativePath:n.relative_path,kind:"definition",values:St(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
30
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:Wt(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
33
31
  SELECT d.relative_path,
34
32
  c.chunk_index,
35
33
  m.role,
@@ -44,7 +42,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
44
42
  JOIN chunks c ON c.id = m.chunk_id
45
43
  JOIN documents d ON d.id = c.document_id
46
44
  JOIN global_symbols g ON g.id = m.symbol_id
47
- `))t.push({relativePath:n.relative_path,kind:"mention",values:St(n,[n.chunk_index,n.role])});for(let n of e.all(`
45
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:Wt(n,[n.chunk_index,n.role])});for(let n of e.all(`
48
46
  SELECT g.symbol,
49
47
  g.display_name,
50
48
  g.kind,
@@ -58,10 +56,9 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
58
56
  ) AND NOT EXISTS (
59
57
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
60
58
  )
61
- `))t.push({relativePath:fa,kind:"global-symbol",values:St(n)});return ha(t)}function ha(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[a])=>o.localeCompare(a))){let o=ua("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
62
- `);n.set(r,o.digest("hex"))}return n}function ya(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function bt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Rt(e,t=Ia){let n=t.now();if(!t.databaseExists(e.previousDbPath))return je(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return je(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),a=Ee(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!ht(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=Oe(a,c?t.dependencyGraph(r):new Map,o),d=ya(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:a,plan:u,comparison:d,evaluation:bt(u,d,o.length)}}catch(o){return je(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{er(r),er(i)}}function rr(e,t,n,r=Date.now()){return je(e,t,r,r,n)}function Sa(e){let t=nr(e);return{latestPath:Zn(t,"affected-shadow-latest.json"),historyPath:Zn(t,"affected-shadow.jsonl")}}function ir(e,t,n=Pa){let r=Sa(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ba=8*1024*1024,Ra=".previous";function xa(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function va(e,t,n=ba){let r=`${JSON.stringify(xa(t))}
63
- `,i=Math.max(1,Math.floor(n)),o=`${e}${Ra}`;if(la(nr(e),{recursive:!0}),tr(e)){let a=ga(e).size;a>i?(yt(e,{force:!0}),yt(o,{force:!0})):a+Buffer.byteLength(r)>i&&(yt(o,{force:!0}),pa(e,o))}da(e,r)}function St(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Ia={now:()=>Date.now(),databaseExists:e=>tr(e),openDatabase:(e,t,n)=>new W({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>we(e),dependencyGraph:e=>ke(e),factDigests:e=>ma(e)},Pa={appendHistory:va,writeLatest:(e,t)=>R(e,t,{spacing:2,trailingNewline:!0})};function je(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function er(e){try{e?.close()}catch{}}import{execFileSync as wa}from"child_process";import{existsSync as ka,readdirSync as ar}from"fs";import{extname as sr,join as cr}from"path";var ur=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Ea=[{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 xt(e){let t=[],n=Ta(e),r=ja(e);for(let i of Ea){if(Da(e,i.files)){t.push(i.language);continue}if(Fa(n,i.globs)){t.push(i.language);continue}Aa(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&or(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&or(t,"c"),t}function Ta(e){try{return ar(e)}catch{return[]}}function Da(e,t){return t?.length?t.some(n=>ka(cr(e,n))):!1}function Fa(e,t){return t?.length?e.some(n=>t.some(r=>Oa(n,r))):!1}function Oa(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function ja(e){let t=Ca(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ar(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=cr(i,a.name);if(a.isDirectory()){ur.has(a.name)||r.push(s);continue}let c=sr(a.name).toLowerCase();c&&n.add(c)}}return n}function Ca(e){try{let t=wa("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
64
- `)){if(!r||r.split("/").some(o=>ur.has(o)))continue;let i=sr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Aa(e,t){return t?.length?t.some(n=>e.has(n)):!1}function or(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as dr,readdirSync as _a}from"fs";import{isAbsolute as La,join as vt,resolve as Ma}from"path";var pr={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Y.language,indexerBinary:Y.indexerBinary,checkCommand:`${Y.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Y.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Y.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",La(r)?r:Ma(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",lr(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",lr(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=vt(e,"vendor","bin","scip-php"),r=vt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",dr(r)?r:dr(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Ce(e){return pr[e]}function lr(e,t){let n;try{n=_a(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return vt(e,i);return null}import{readFileSync as Pt,writeFileSync as wt}from"fs";import{create as oe}from"@bufbuild/protobuf";import{deserializeSCIP as kt,serializeSCIP as Et,DocumentSchema as Ha,IndexSchema as mr,MetadataSchema as Ja,SymbolInformationSchema as qa}from"@c4312/scip";import{readFileSync as Na,writeFileSync as $a}from"fs";import{create as gr}from"@bufbuild/protobuf";import{deserializeSCIP as Ga,DocumentSchema as Va,IndexSchema as Ba,serializeSCIP as Ua,SymbolRole as Wa}from"@c4312/scip";function fr(e){let t;try{t=Ga(Na(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=It(t);return n.removedDefinitionOccurrences>0&&$a(e,Buffer.from(Ua(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function It(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Wa.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(gr(Va,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:gr(Ba,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function Tt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ya(e),n=Xa(e.flatMap(i=>i.documents??[])),r=Sr(e.flatMap(i=>i.externalSymbols??[]));return oe(mr,{metadata:t,documents:n,externalSymbols:r})}function Dt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>kt(Pt(i))),r=Tt(n);return wt(t,Buffer.from(Et(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function hr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>kt(Pt(i))),r=It(Tt(n));return wt(t,Buffer.from(Et(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function za(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return oe(mr,{metadata:oe(Ja,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function yr(e,t,n){let r=kt(Pt(e)),i=za(r,t,n);wt(e,Buffer.from(Et(i)))}function Ya(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Xa(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,oe(Ha,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Qa([...r.occurrences,...n.occurrences]),symbols:Sr([...r.symbols,...n.symbols]),text:Za(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Qa(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function Sr(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,oe(qa,{symbol:r.symbol,documentation:es([...r.documentation,...n.documentation]),relationships:Ka([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Ka(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Za(e,t){return e?t?e.length>=t.length?e:t:e:t}function es(e){return[...new Set(e)]}import{createHash as ts}from"crypto";import{copyFileSync as ns,existsSync as br,rmSync as Rr}from"fs";import{resolve as rs}from"path";import Ir from"better-sqlite3";var is={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},os={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Pr(e){let t=Date.now(),n=as(e.affectedFiles);if(ss(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Rr(e.candidateDbPath,{force:!0}),!br(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!br(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");xr(e.previousDbPath,"previous SQLite generation",!1),xr(e.miniDbPath,"incremental SQLite mini database"),ns(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Ir(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Ft(r,"main","candidate SQLite generation"),Ft(r,"incremental","incremental SQLite mini database"),cs(r,n),us(r,n.length);let i=Ot(r,"main",!0),o=N(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ds(r),ls(r),ps(r),e.onStage?.("after-delete"),gs(r),e.onStage?.("after-symbol-reconciliation"),fs(r),e.onStage?.("after-insert"),ms(r),hs(r,n.length,o),e.onStage?.("before-commit")}).immediate(),wr(r,"main","candidate SQLite generation");let c=[...ys(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Rr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function as(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function ss(e,t,n){let r=[e,t,n].map(i=>rs(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function xr(e,t,n=!0){let r=new Ir(e,{readonly:!0,fileMustExist:!0});try{Ft(r,"main",t),n&&wr(r,"main",t)}finally{r.close()}}function Ft(e,t,n){for(let[r,i]of Object.entries(is)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(os)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}vr(e,t,"documents",["relative_path"],n),vr(e,t,"global_symbols",["symbol"],n)}function vr(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function wr(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function cs(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function us(e,t){let n=N(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=N(e,`SELECT COUNT(*) AS value
59
+ `))t.push({relativePath:ps,kind:"global-symbol",values:Wt(n)});return fs(t)}function fs(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[a])=>o.localeCompare(a))){let o=us("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
60
+ `);n.set(r,o.digest("hex"))}return n}function ms(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function qt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Ht(e,t=xs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,d)=>{let l=r();return Br(e.refreshResult,u,n?l:i(),Math.max(0,l-o),d)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),d=$e(e.previousSnapshot,e.currentSnapshot),l=new Set(u),p=d.changes.length>0&&!Ut(d).fullProject&&d.changes.every(b=>l.has(b.path)),f=Je(d,p?t.dependencyGraph(s):new Map,u),g=ms(t.factDigests(s),t.factDigests(c)),m=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?m:i()).toISOString(),durationMs:Math.max(0,m-o),manifest:d,plan:f,comparison:g,evaluation:qt(f,g,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{$r(s),$r(c)}}function Gr(e,t,n,r=Date.now()){return Br(e,t,r,0,n)}function hs(e){let t=ls(e);return{latestPath:Nr(t,"affected-shadow-latest.json"),historyPath:Nr(t,"affected-shadow.jsonl")}}function Vr(e,t,n=Is){let r=hs(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ys=8*1024*1024,Ss=Fr;function bs(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function Rs(e,t,n=ys){Dr(e,bs(t),{maxSegmentBytes:n,previousSuffix:Ss})}function Wt(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var xs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:S,databaseExists:e=>ds(e),openDatabase:(e,t,n)=>new te({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ue(e),dependencyGraph:e=>qe(e),factDigests:e=>gs(e)},Is={appendHistory:Rs,writeLatest:(e,t)=>de(e,t,{spacing:2,trailingNewline:!0})};function Br(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function $r(e){try{e?.close()}catch{}}import{execFileSync as Ps}from"child_process";import{existsSync as vs,readdirSync as Wr}from"fs";import{extname as qr,join as Hr}from"path";var zr=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),ws=[{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 zt(e){let t=[],n=ks(e),r=Ds(e);for(let i of ws){if(Ts(e,i.files)){t.push(i.language);continue}if(Es(n,i.globs)){t.push(i.language);continue}_s(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Ur(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Ur(t,"c"),t}function ks(e){try{return Wr(e)}catch{return[]}}function Ts(e,t){return t?.length?t.some(n=>vs(Hr(e,n))):!1}function Es(e,t){return t?.length?e.some(n=>t.some(r=>Fs(n,r))):!1}function Fs(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function Ds(e){let t=As(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=Wr(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=Hr(i,a.name);if(a.isDirectory()){zr.has(a.name)||r.push(s);continue}let c=qr(a.name).toLowerCase();c&&n.add(c)}}return n}function As(e){try{let t=Ps("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}),n=new Set;for(let r of t.split(`
61
+ `)){if(!r||r.split("/").some(o=>zr.has(o)))continue;let i=qr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function _s(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Ur(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as js}from"fs";import{isAbsolute as Jr,join as Os,resolve as Cs}from"path";var Ye="@sourcegraph/scip-typescript@0.4.0",Yr="scip-python-plus@0.7.5",Kr="github.com/sourcegraph/scip-go@v0.2.7",Xr="scip-dotnet@0.2.14",Ms="scip_dart@1.6.2",Zr={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",identity:Ye,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Ye]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",identity:Ye,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Ye]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:ae.language,indexerBinary:ae.indexerBinary,checkCommand:`${ae.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:ae.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[],installUrl:ae.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",identity:Yr,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Yr]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",Jr(r)?r:Cs(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",identity:Kr,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Kr]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Qr(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",identity:Xr,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Qr(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",identity:Xr,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",identity:Ms,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>Jr(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Ke(e){return Zr[e]}function Qr(e,t){let n;try{n=js(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Os(e,i);return null}import{writeFileSync as Yt}from"fs";import{create as ve}from"@bufbuild/protobuf";import{deserializeSCIP as Kt,serializeSCIP as Xt,DocumentSchema as Us,IndexSchema as ni,MetadataSchema as Ws,SymbolInformationSchema as qs}from"@c4312/scip";import{writeFileSync as Ls}from"fs";import{create as ei}from"@bufbuild/protobuf";import{deserializeSCIP as Ns,DocumentSchema as $s,IndexSchema as Gs,serializeSCIP as Vs,SymbolRole as Bs}from"@c4312/scip";function ti(e){let t;try{t=Ns(T(e,{inputKind:"SCIP sanitization input",maxBytes:A}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Jt(t);return n.removedDefinitionOccurrences>0&&Ls(e,Buffer.from(Vs(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Jt(e){let t=new Set;for(let o of e.documents){tr(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Bs.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ei($s,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ei(Gs,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function Qt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=zs(e),n=Js(e.flatMap(i=>i.documents??[])),r=oi(e.flatMap(i=>i.externalSymbols??[]));return ve(ni,{metadata:t,documents:n,externalSymbols:r})}function Zt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Kt(T(i,{inputKind:"SCIP merge input",maxBytes:A}))),r=Qt(n);return Yt(t,Buffer.from(Xt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ri(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Kt(T(i,{inputKind:"SCIP merge input",maxBytes:A}))),r=Jt(Qt(n));return Yt(t,Buffer.from(Xt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Hs(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return ve(ni,{metadata:ve(Ws,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function ii(e,t,n){let r=Kt(T(e,{inputKind:"SCIP normalization input",maxBytes:A})),i=Hs(r,t,n);Yt(e,Buffer.from(Xt(i)))}function zs(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Js(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,ve(Us,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Ys([...r.occurrences,...n.occurrences]),symbols:oi([...r.symbols,...n.symbols]),text:Xs(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ys(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function oi(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,ve(qs,{symbol:r.symbol,documentation:Qs([...r.documentation,...n.documentation]),relationships:Ks([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Ks(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Xs(e,t){return e?t?e.length>=t.length?e:t:e:t}function Qs(e){return[...new Set(e)]}import{createHash as Zs}from"crypto";import{copyFileSync as ec,existsSync as ai,rmSync as si}from"fs";import{resolve as tc}from"path";import di from"better-sqlite3";var nc={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},rc={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function li(e){let t=S(),n=ic(e.affectedFiles);if(oc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),si(e.candidateDbPath,{force:!0}),!ai(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!ai(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ci(e.previousDbPath,"previous SQLite generation",!1),ci(e.miniDbPath,"incremental SQLite mini database"),ec(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new di(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),en(r,"main","candidate SQLite generation"),en(r,"incremental","incremental SQLite mini database"),ac(r,n),sc(r,n.length);let i=tn(r,"main",!0),o=Y(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{cc(r),uc(r),dc(r),e.onStage?.("after-delete"),lc(r),e.onStage?.("after-symbol-reconciliation"),pc(r),e.onStage?.("after-insert"),gc(r),fc(r,n.length,o),e.onStage?.("before-commit")}).immediate(),pi(r,"main","candidate SQLite generation");let c=[...mc(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:S()-t}}catch(i){try{r?.close()}finally{si(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function ic(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function oc(e,t,n){let r=[e,t,n].map(i=>tc(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ci(e,t,n=!0){let r=new di(e,{readonly:!0,fileMustExist:!0});try{en(r,"main",t),n&&pi(r,"main",t)}finally{r.close()}}function en(e,t,n){for(let[r,i]of Object.entries(nc)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(rc)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}ui(e,t,"documents",["relative_path"],n),ui(e,t,"global_symbols",["symbol"],n)}function ui(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function pi(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function ac(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function sc(e,t){let n=Y(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Y(e,`SELECT COUNT(*) AS value
65
62
  FROM main.documents d
66
63
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
67
64
  FROM temp.incremental_affected_paths p
@@ -71,7 +68,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
71
68
  FROM incremental.documents d
72
69
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
73
70
  WHERE p.relative_path IS NULL
74
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function ds(e){e.exec(`
71
+ LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function cc(e){e.exec(`
75
72
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
76
73
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
77
74
  SELECT g.symbol
@@ -98,7 +95,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
98
95
  FROM incremental.mentions m
99
96
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
100
97
  WHERE m.role = 1;
101
- `)}function ls(e){let t=e.prepare(`WITH changed_symbols AS (
98
+ `)}function uc(e){let t=e.prepare(`WITH changed_symbols AS (
102
99
  SELECT symbol FROM temp.incremental_old_defined_symbols
103
100
  UNION
104
101
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -121,7 +118,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
121
118
  SELECT u.symbol
122
119
  FROM unaffected_definitions u
123
120
  JOIN changed_symbols c ON c.symbol = u.symbol
124
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function ps(e){e.exec(`
121
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function dc(e){e.exec(`
125
122
  DELETE FROM main.mentions
126
123
  WHERE chunk_id IN (
127
124
  SELECT c.id
@@ -143,7 +140,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
143
140
  );
144
141
  DELETE FROM main.documents
145
142
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
146
- `)}function gs(e){e.exec(`
143
+ `)}function lc(e){e.exec(`
147
144
  UPDATE main.global_symbols
148
145
  SET display_name = NULL,
149
146
  kind = NULL,
@@ -185,7 +182,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
185
182
  WHERE source.symbol = main.global_symbols.symbol
186
183
  )
187
184
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
188
- `)}function fs(e){let t=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
185
+ `)}function pc(e){let t=Y(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Y(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Y(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
189
186
  SELECT id + ?, language, relative_path, position_encoding, text
190
187
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
191
188
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -200,15 +197,15 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
200
197
  r.start_line, r.start_char, r.end_line, r.end_char
201
198
  FROM incremental.defn_enclosing_ranges r
202
199
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
203
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ms(e){e.exec(`
200
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function gc(e){e.exec(`
204
201
  DELETE FROM main.global_symbols
205
202
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
206
203
  AND NOT EXISTS (
207
204
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
208
205
  );
209
- `)}function hs(e,t,n){let r=N(e,"SELECT COUNT(*) AS value FROM main.documents"),i=N(e,`SELECT COUNT(*) AS value
206
+ `)}function fc(e,t,n){let r=Y(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Y(e,`SELECT COUNT(*) AS value
210
207
  FROM main.documents d
211
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ys(e){let t=Ot(e,"main",!0),n=Ot(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function Ot(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
208
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function mc(e){let t=tn(e,"main",!0),n=tn(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function tn(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
212
209
  FROM ${t}.documents d
213
210
  ${r}
214
211
  ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
@@ -230,13 +227,12 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
230
227
  JOIN ${t}.documents d ON d.id = c.document_id
231
228
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
232
229
  ${r}
233
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let l of p){let m=JSON.stringify([d,l]),g=c.get(l.relative_path)??[];g.push(m),c.set(l.relative_path,g)}let u=new Map;for(let[d,p]of[...c].sort(([l],[m])=>l.localeCompare(m))){let l=ts("sha256");for(let m of p.sort())l.update(m).update(`
234
- `);u.set(d,l.digest("hex"))}return u}function N(e,t){return e.prepare(t).get().value}import{readFileSync as Ss,writeFileSync as bs}from"fs";function $(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Er(e){let t=e.readFingerprint(),n=Rs(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return xs(e.cachePath,e.readFingerprint(),r),r}function Rs(e,t){try{let n=JSON.parse(Ss(e,"utf-8"));return kr(n.fingerprint)===kr(t)?{result:n.result}:null}catch{return null}}function xs(e,t,n){bs(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
235
- `)}function kr(e){return JSON.stringify(e)}import{createHash as vs}from"crypto";import{existsSync as jt,readFileSync as Is,readdirSync as Ps}from"fs";import{dirname as Ct,join as Ae,relative as ws,resolve as At,sep as Tr}from"path";function Dr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Cr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Fr(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],a=r.get(i);if(!o||o.parseFailed){for(let s of e)s!==i&&a.add(s);continue}for(let s of o.dependencyNames){let c=n.get(s);c&&c!==i&&a.add(c)}for(let s of[...o.pathsTargets,...o.referencesPaths]){let c=Cr(s,e);c&&c!==i&&a.add(c)}}return ks(e,r)}function Or(e,t,n){let r={};for(let i of e){let o=new Map;for(let a of t.files[i]??[])o.set(a.path,a);for(let a of n[i]??[])for(let s of t.files[a]??[])o.set(s.path,s);for(let a of t.shared)o.set(a.path,a);r[i]={files:[...o.values()].sort((a,s)=>a.path.localeCompare(s.path))}}return r}function _t(e){if(e===".")return"root";let t=vs("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function jr(e,t){let n=At(e),r={};for(let i of t)r[i]=Es(n,i);return r}function Cr(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function ks(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let a=o.pop();if(!(a===r||i.has(a))){i.add(a);for(let s of t.get(a)??[])s!==r&&!i.has(s)&&o.push(s)}}n[r]=[...i].sort((a,s)=>a.localeCompare(s))}return n}function Es(e,t){let n=t==="."?e:Ae(e,t),r=Ts(n),i=Ds(n),o=i?Fs(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function Ts(e){let t=Ae(e,"package.json");if(!jt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Lt(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let a=n.value[o];if(a&&typeof a=="object"&&!Array.isArray(a))for(let s of Object.keys(a))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function Ds(e){let t=Ae(e,"tsconfig.json");if(jt(t))return t;let n;try{n=Ps(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Ae(e,n[0]):void 0}function Fs(e,t){let n=Lt(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Os(n.value,e,t),i=Ar(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Os(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ct(t),o=new Set;for(let a of r){if(!a||typeof a!="object")continue;let s=a.path;if(typeof s!="string"||s.trim()==="")continue;let c=_r(s,i,n);c&&o.add(c)}return[...o]}function Ar(e,t,n,r){let i=js(t);if(i)return{pathsTargets:Cs(i,Ct(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=As(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Lt(o);return a.ok?Ar(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function js(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Cs(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let a=_r(o,t,n);a&&r.add(a)}return[...r]}function As(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=At(Ct(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Tr).includes("node_modules")&&Z(n,i)&&jt(i))return i}function _r(e,t,n){let r=e.replace(/\/?\*+$/,""),i=At(t,r===""?".":r);if(!Z(n,i))return;let a=ws(n,i).split(Tr).join("/");return a===""?".":a}function _s(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
236
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Lt(e){try{let t=Is(e,"utf-8"),n=JSON.parse(_s(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as Ii,randomUUID as Qt}from"crypto";import{closeSync as Pi,constants as gc,copyFileSync as bi,existsSync as U,lstatSync as fc,mkdirSync as A,mkdtempSync as wi,openSync as ki,readdirSync as mc,readFileSync as F,realpathSync as hc,renameSync as z,rmSync as B,statSync as yc,unlinkSync as Yt,writeFileSync as Ei}from"fs";import{dirname as Ti,join as f,resolve as me}from"path";import{setTimeout as Sc}from"timers/promises";import{pathToFileURL as Ri}from"url";import{deserializeSCIP as Di}from"@c4312/scip";import bc from"better-sqlite3";import{createRequire as Ls}from"module";var Ms=Ls(import.meta.url),Lr=Ns().version;function Ns(){for(let e of["../package.json","../../package.json"])try{return Ms(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Zs,readdirSync as ec}from"fs";import{join as tc,relative as nc,resolve as Ht,sep as rc}from"path";import{createHash as $s}from"crypto";import{existsSync as Nt,mkdirSync as Gs,readFileSync as _e,readdirSync as Ip,renameSync as Vs,rmSync as Pp,writeFileSync as Bs}from"fs";import{join as X}from"path";import{create as Nr,fromBinary as $r,toBinary as Us}from"@bufbuild/protobuf";import{deserializeSCIP as Le,DocumentSchema as $t,IndexSchema as Gr,serializeSCIP as Vr}from"@c4312/scip";var Me=1,ae="typescript-scip-fragments";function Br(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=J(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=$r($t,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Vr(Nr(Gr,{documents:n,externalSymbols:[]})),i=Le(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ne(e){let t=X(e,ae);return{rootDir:t,blobDir:X(t,"blobs"),generationDir:X(t,"generations")}}function Ws(e){let t=Le(e.indexBytes);ei(t.metadata,ti(e)),Zr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=J(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Us($t,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?q(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:q(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Yr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Xr(e,r);return Qr(e.cacheDir,i),i}function Ur(e){let t=Ne(e.cacheDir);if(!Nt(Gt(t,e.generationIdentity)))return Ws(e);let n=Hr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Wr(e){let t=Hr({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=J(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Yr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Xr(e,[...n.values()]);return Qr(e.cacheDir,i),i}function Hr(e){let t=Ne(e.cacheDir),n=Gt(t,e.generationIdentity),r;try{r=Kr(_e(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=X(t.blobDir,`${o.blobHash}.scipdoc`),s=_e(a);if(s.byteLength!==o.byteLength||q(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Jr(e){let t=zr(e);return Mt(t.baseIndex,t.completeDocuments,"assembled")}function qr(e){let t=zr(e);return Hs(t.deletedAffectedPaths),{completeIndexBytes:Mt(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Mt(t.baseIndex,t.affectedDocuments,"affected")}}function zr(e){let t=Le(e.baseIndexBytes);ei(t.metadata,ti(e)),Zr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=J(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=J(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=$r($t,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function Mt(e,t,n){let r=Vr(Nr(Gr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Le(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Hs(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Yr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=J(t.relativePath),i=Buffer.from(t.bytes),o=q(i),a=Ne(e);Gs(a.blobDir,{recursive:!0});let s=X(a.blobDir,`${o}.scipdoc`);if(Nt(s)){let c=_e(s);if(c.byteLength!==i.byteLength||q(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Bs(c,i),Vs(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Xr(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Me,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Qr(e,t){let n=Ne(e),r=Gt(n,t.generationIdentity);if(Nt(r)){let i=Kr(_e(r,"utf8"));if(Mr(i)!==Mr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}R(r,t,{spacing:2,trailingNewline:!0})}function Mr(e){return q(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Kr(e){let t=JSON.parse(e);if(t.version!==Me||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(J(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Gt(e,t){return X(e.generationDir,Js(t))}function Js(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${q(e)}.json`}function Zr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function ei(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function ti(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function J(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function q(e){return $s("sha256").update(e).digest("hex")}import{createHash as qs}from"crypto";import{existsSync as se,mkdirSync as zs,readFileSync as ue,readdirSync as Vt,renameSync as Ys,rmSync as ni,writeFileSync as Xs}from"fs";import{join as D}from"path";var $e=1,ii=64*1024*1024,de="typescript-scip-overlays";function oi(e){let t=ci(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Wt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Qs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:$e,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Ks(e.cacheDir,i),i}function ai(e){let t=ci(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=ue(D(le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ce(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Jr({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function si(e,t){let n=le(e),r=D(n,"generations");if(!se(r))return;let i=new Set(t.map(Ut)),o=new Set;for(let s of Vt(r).filter(c=>i.has(c))){let c=Bt(ue(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Vt(r))i.has(s)||ni(D(r,s),{force:!0});let a=D(n,"blobs");if(se(a))for(let s of Vt(a))o.has(s)||ni(D(a,s),{force:!0})}function ci(e,t){let n=D(le(e),"generations",Ut(t));if(!se(n))return null;let r=Bt(ue(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Qs(e,t){let n=Wt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ce(r),o=D(le(e),"blobs");zs(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(se(a)){let s=ue(a);if(s.byteLength!==r.byteLength||ce(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Xs(s,r),Ys(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Ks(e,t){let n=D(le(e),"generations",Ut(t.generationIdentity));if(se(n)){let r=Bt(ue(n,"utf8"));if(ri(r)!==ri(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}R(n,t,{spacing:2,trailingNewline:!0})}function Bt(e){let t=JSON.parse(e);if(t.version!==$e||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Wt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function le(e){return D(e,de)}function Ut(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ce(e)}.json`}function ri(e){return ce(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Wt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function ce(e){return qs("sha256").update(e).digest("hex")}var pe=1,Jt="language-indexes",ui=["index.db","index.scip","meta.json"],di=[Jt,ae,de];function Ge(e){let t=[];for(let n of ui)ic(e,n),t.push(n);for(let n of di)li(e,n,t);return{version:pe,files:t.sort()}}function Ve(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!ui.includes(e)&&!di.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Ve(t),r=Ht(e),i=Ht(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${rc}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function li(e,t,n){let r=tc(e,t),i;try{i=ec(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?li(e,a,n):o.isFile()&&n.push(Ve(a))}}function ic(e,t){let n=j(e,t),r;try{r=Zs(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(nc(Ht(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as oc}from"crypto";import{copyFileSync as pi,existsSync as G,linkSync as ac,mkdirSync as gi,readFileSync as hi,readdirSync as fi,renameSync as zt,rmSync as Ue,statSync as sc}from"fs";import{basename as Be,dirname as ge,join as k,relative as mi}from"path";var Q=1,We=".scipquery-generations";function He(e){let t=Je(e.outputDb),n=cc(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||qt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),qt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),qt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=qe(e.metaPath,e.outputDb),i={version:Q,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return R(k(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function yi(e){try{let t=JSON.parse(hi(k(Je(e),"state.json"),"utf8"));return t.version!==Q||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!lc(t.previousGeneration)||!pc(t.publication)?null:t}catch{return null}}function Si(e,t,n=()=>new Date){if(!G(e)||!G(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=yi(e),i={version:Q,currentGeneration:qe(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return R(k(Je(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function V(e,t=k(ge(e),"meta.json")){let n=k(Je(e),"state.json");if(!G(n))return{state:"legacy",statePath:n};let r=yi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=qe(t,e),o=r.currentGeneration===i,a=r.previousGeneration?G(k(ge(e),r.previousGeneration.databasePath)):!0;return!o||!a?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:a,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Je(e){return k(ge(e),We)}function cc(e,t){if(!G(e.outputDb))return;let n=qe(e.metaPath,e.outputDb),r=k(t,n),i=k(r,Be(e.outputDb)),o=G(e.metaPath)?k(r,Be(e.metaPath)):void 0;if(!G(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;Ue(a,{recursive:!0,force:!0}),gi(a,{recursive:!0});let s=k(a,Be(e.outputDb));try{ac(e.outputDb,s)}catch{pi(e.outputDb,s)}o&&pi(e.metaPath,k(a,Be(e.metaPath))),gi(t,{recursive:!0}),zt(a,r)}return uc(t,n),{generationIdentity:n,databasePath:mi(ge(e.outputDb),i),...o?{metadataPath:mi(ge(e.outputDb),o)}:{}}}function uc(e,t){for(let n of fi(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Ue(k(e,n.name),{recursive:!0,force:!0});for(let n of fi(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Ue(k(e,n.name),{recursive:!0,force:!0})}function qe(e,t){let n=oc("sha256").update(`sqlite-generation-v${Q}\0`);G(e)&&n.update(dc(hi(e,"utf8")));let r=sc(t);return n.update(`\0${r.size}`),n.digest("hex")}function dc(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function qt(e,t){Ue(`${t}.tmp-replace`,{force:!0}),zt(e,`${t}.tmp-replace`),zt(`${t}.tmp-replace`,t)}function lc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function pc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Kt=1,xi="SCIP_QUERY_SHARED_CACHE",Xt=JSON.stringify({cliVersion:Lr,artifactCatalogVersion:pe,sqliteGenerationStoreVersion:Q,typescriptFragmentStoreVersion:Me,typescriptOverlayStoreVersion:$e}),Fi="manifest.json",Rc="shared-cache.json",Zt=[Jt,ae,de];function ze(e,t){if(!e.clean||!e.treeOid)return;let n=ye(JSON.stringify({version:Kt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Xt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Xt,generationId:n,repositoryCacheDir:$n(e.repositoryId)}}function Oi(e,t,n){if(process.env[xi]==="0")return`${xi}=0`;if(!Gn(n))return"explicit cache or database override";if(me(t)!==me(f(Nn(e),"index.db")))return"index database is outside the managed worktree cache"}function C(e,t=!0){let n=tn(e),r;try{r=vc(F(f(n,Fi),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=j(n,i.path),a=yc(o);if(!a.isFile()||a.size!==i.size||ye(F(o))!==i.sha256)return null}}catch{return null}return r}function ji(e){let t=C(e.snapshot);if(t)return t;if(!Li(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=vi(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Ge(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");A(i,{recursive:!0});let o=wi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);he(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:ye(g)})}let s=Di(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=nn(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(vi(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Kt,artifactCatalogVersion:pe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,l)=>p.path.localeCompare(l.path))};R(f(o,Fi),u,{spacing:2,trailingNewline:!0});let d=tn(e.snapshot);try{if(U(d)&&!C(e.snapshot)){let p=`${d}.corrupt-${process.pid}-${Date.now()}`;z(d,p),B(p,{recursive:!0,force:!0})}z(o,d)}catch(p){let l=C(e.snapshot);if(l)return l;throw p}return u}finally{B(o,{recursive:!0,force:!0})}}function en(e){let t=tn(e.snapshot);A(e.targetCacheDir,{recursive:!0});let n=ie(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=wi(f(e.targetCacheDir,".shared-hydrate-")),Fc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);he(u,d);let p=F(d);if(p.byteLength!==c.size||ye(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=nn(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&yr(j(r,c.path),e.manifest.scipProjectRoot,a);if(!Li(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Ec(e.targetCacheDir,r),o=!0,Tc(r,e.targetCacheDir,i),He({tempOutputScip:f(r,"index.scip"),tempOutputDb:f(r,"index.db"),tempMetaPath:f(r,"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=V(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}`);Ye(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Dc(e.targetCacheDir,i),a}finally{r&&B(r,{recursive:!0,force:!0}),n.release()}}async function Ci(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`);for(A(a,{recursive:!0});i()<=o;){if(C(e))return{kind:"generation-ready"};let c=Qt();try{let u=ki(s,"wx");try{Ei(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
237
- `)}finally{Pi(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&Yt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Ai(s);if(d&&(d.pid===void 0||!T(d.pid))){wc(s,d);continue}await Sc(r)}}return C(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Ye(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:xc(i)};return kc(e.repositoryCacheDir,o,!0),o}function xc(e){return ye(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:me(e.projectRoot),localCacheDir:me(e.localCacheDir)}))}function vc(e){let t=JSON.parse(e);if(t.version!==Kt||t.artifactCatalogVersion!==pe||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!==Xt||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Ve(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function he(e,t){A(Ti(t),{recursive:!0});try{bi(e,t,gc.COPYFILE_FICLONE)}catch{bi(e,t)}}function Ic(e,t,n){A(e,{recursive:!0}),R(f(e,Rc),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function vi(e){try{let t=Ge(e),n=Ii("sha256");for(let r of t.files){let i=F(j(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function Pc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function tn(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Ai(e){try{let t=F(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function wc(e,t){let n=`${e}.reclaim`,r=Qt(),i;try{i=ki(n,"wx")}catch{return!1}try{Ei(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
238
- `)}finally{Pi(i)}try{let o=Ai(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Yt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&Yt(n)}catch{}}}function kc(e,t,n){let r=qn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!U(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");A(i,{recursive:!0}),R(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Ic(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Ec(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;A(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=U(c);r.set(s,u),u&&he(c,f(n,"stable",s))}for(let s of Zt){let c=f(e,s),u=U(c);if(u){let d=fc(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=f(e,We),a=U(o);return a&&_i(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Tc(e,t,n){for(let r of Zt){let i=f(t,r);if(n.managedDirectories.get(r)){let a=f(n.root,"managed",r);A(Ti(a),{recursive:!0}),z(i,a)}let o=f(e,r);U(o)&&z(o,i)}}function Dc(e,t){for(let i of Zt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?U(a)&&(B(o,{recursive:!0,force:!0}),z(a,o)):B(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){B(a,{force:!0});continue}let s=`${a}.shared-restore-${Qt()}`;he(f(t.root,"stable",i),s),B(a,{force:!0}),z(s,a)}let n=f(e,We);B(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&U(r)&&z(r,n)}function _i(e,t){A(t,{recursive:!0});for(let n of mc(e,{withFileTypes:!0})){let r=f(e,n.name),i=f(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?_i(r,i):n.isFile()&&he(r,i)}}function Fc(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Li(e,t,n,r=!0,i=!0){try{let o=Pc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return fe("source validation rejected metadata"),!1;let a=Ge(e),s=V(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return fe(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new bc(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 u=nn(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=Di(F(j(e,l))).metadata?.projectRoot;return m!==u&&fe(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||fe("source validation rejected SCIP project roots"),p}catch(o){return fe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function fe(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function nn(e){try{return Ri(hc(e)).href}catch{return Ri(me(e)).href}}function ye(e){return Ii("sha256").update(e).digest("hex")}import{existsSync as Oc,readFileSync as jc,readdirSync as Cc,statSync as Ac}from"fs";import v from"path";var _c=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Se(e,t=[]){let n=v.resolve(e),r=t.flatMap(c=>Mc(n,c));if(r.length>0)return Mi(n,Ni(r));let i=Lc(n),o=Ni(i),a=$c(n,o)?[n,...o]:o,s=a.length>0?a:[n];return Mi(n,s)}function Mi(e,t){return[...new Set(t.map(n=>Vc(e,n)))].sort((n,r)=>n.localeCompare(r))}function Lc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Cc(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=v.join(r,o.name);if(o.isDirectory()){!_c.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Nc(a)&&t.push(v.dirname(a))}}return t}function Mc(e,t){let n=t.trim();if(!n)return[];let r=v.resolve(e,n);if(!Z(e,r))return[];try{let i=Ac(r);if(i.isDirectory())return[r];if(i.isFile()&&$i(v.basename(r)))return[v.dirname(r)]}catch{return[]}return[]}function Nc(e){if(!$i(v.basename(e)))return!1;let t=Gi(e);return t?v.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function $i(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Ni(e){let t=[...new Set(e.map(n=>v.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Bc(n,r)))}function $c(e,t){if(t.length===0||t.some(r=>v.resolve(r)===e))return!1;let n=v.join(e,"tsconfig.json");return Oc(n)&&Gc(n)}function Gc(e){let n=Gi(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!v.extname(r))):!1}function Gi(e){try{let t=JSON.parse(jc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Vc(e,t){let n=v.relative(e,t);return n?n.split(v.sep).join("/"):"."}function Bc(e,t){let n=v.relative(e,t);return!!n&&!n.startsWith("..")&&!v.isAbsolute(n)}import{createHash as uu}from"crypto";import{existsSync as on,readFileSync as Zi,statSync as du,writeFileSync as an}from"fs";import{join as lu}from"path";import{readFileSync as Vi}from"fs";import{createRequire as Uc}from"module";import{dirname as Wc,isAbsolute as yg,relative as Sg,resolve as bg,sep as Rg}from"path";var Bi=Uc(import.meta.url),Hc=1,Ui="0.4.0";function rn(){let e=Jc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Jc(){try{let e=Bi.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Vi(e,"utf8"));if(t.version!==Ui)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Ui}`};let n=Wc(e),r=Bi.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Vi(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:qc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function qc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Hc}`}import{createHash as zc}from"crypto";import{readFileSync as Yc}from"fs";import{dirname as Xc,join as Xe}from"path";var Qe=2,Qc="typescript-index";function Wi(e){let t=Xe(e,Qc);return{rootDir:t,requestDir:Xe(t,"requests"),responseDir:Xe(t,"responses")}}function Hi(e){try{let t=JSON.parse(Yc(Xe(Xc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:zc("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Kc}from"crypto";import{existsSync as Zc,mkdirSync as Ji,readFileSync as eu,rmSync as qi}from"fs";import{resolve as zi}from"path";var tu=12e4,nu=5,Ke=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Cn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??su(),this.runtime=n.runtime??cu}request(t){let n=jn(this.cacheDir),r=Wi(this.cacheDir),i=lt(n.statePath);if(!Yi(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=zi(r.requestDir,`${o}.json`),s=zi(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Ji(r.requestDir,{recursive:!0}),Ji(r.responseDir,{recursive:!0}),R(a,{protocolVersion:Qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Zc(s))return ru(eu(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=lt(n.statePath);if(!Yi(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(nu)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{qi(a,{force:!0}),qi(s,{force:!0})}}};function Yi(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=On,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Qe&&n.isProcessAlive(e.pid)&&(r||i)}function ru(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==Qe||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let a=iu(o.response,r),s=[...new Set(i)].sort(),c=a.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return a}function iu(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(ou)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:au(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function ou(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function au(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function su(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:tu}var cu={now:Date.now,randomId:Kc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function pu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Ee(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!pt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Oe(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=gu([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Xi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Xi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Ki(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Ki(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Qi(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Qi(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function gu(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function eo(e){let t=Date.now();try{if(!on(e.previousDbPath)||!on(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=rn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new W({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=we(o,{includeIgnored:!1}).filter(pt).sort(),s=ke(o)}finally{o.close()}let c=performance.now()-n,u=pu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Se(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:on(lu(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Hi(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Ke({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=du(e.previousShardPath).size>=ii;n=performance.now();let S=g?null:Zi(e.previousShardPath),b=g?{completeIndexBytes:null,affectedIndexBytes:Br(l.fragments)}:qr({packageVersion:r.packageVersion,baseIndexBytes:S,fragments:l.fragments}),P=performance.now()-n;n=performance.now(),g?oi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):(Ur({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:S,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Wr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:l.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),b.completeIndexBytes&&an(e.candidateShardPath,b.completeIndexBytes),an(e.candidateAffectedScipPath,b.affectedIndexBytes);let I=performance.now()-n,w={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:l.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(l.fragments.map(Pe=>[Pe.relativePath,Pe.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:l.durationMs,assemblyMs:P,fragmentStoreMs:y,writeMs:I}};return e.onStatus(`Incremental TypeScript index emitted ${w.affectedFiles.length} affected document(s) in ${(w.durationMs/1e3).toFixed(3)}s (${w.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${P.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${I.toFixed(0)}ms).`),w}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function to(e){let t=rn();if(!t.available)throw new Error(t.reason);let n=ai({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Zi(e.baseShardPath),packageVersion:t.packageVersion});an(e.candidateShardPath,n)}function Xi(e,t,n){let r=e.files.filter(i=>En(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return sn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Qi(e,t){return sn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Ki(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=An({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,sn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function sn(e){return uu("sha256").update(e).digest("hex")}import{execFile as fu}from"child_process";import{existsSync as Ze,renameSync as un,rmSync as dn,statSync as mu}from"fs";import{cpus as hu}from"os";import{join as no}from"path";function yu(e,t,n){if(!e.defaultOutputPath)return;let r=no(t,e.defaultOutputPath);n!==r&&Ze(r)&&un(r,n)}function Su(e,t,n){if(!e.defaultOutputPath)return null;let r=no(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return dn(i,{force:!0}),Ze(r)?(un(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function bu(e){e&&(dn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ze(e.backupPath)&&un(e.backupPath,e.defaultOutputPath))}function Ru(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function ro(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Ru(o.length,r),c=await vu(o,s,u=>cn(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(l=>l.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await cn(p,t,n)))}a.push(...c.map(d=>u.get(d.id)??d))}else a.push(...c);for(let u of i)a.push(await cn(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function cn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),dn(e.scipPath,{force:!0});let r=Su(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let s=kn(e.binary,e.args);await xu(s.binary,s.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),yu(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
239
- `)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{bu(r)}if(!Ze(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let a;try{a=mu(e.scipPath).size}catch{a=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:a}}function xu(e,t,n){return new Promise((r,i)=>{fu(e,[...t],n,o=>{o?i(o):r()})})}async function vu(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),a=Array.from({length:o},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(a),r}import{execFileSync as Iu}from"child_process";import{platform as Pu}from"os";function ln(e,t){let n=e.installMethods,r=ne(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(st(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Iu(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Pu()==="win32"});let o=re(e);if(o){let a=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${a}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let a=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import od from"better-sqlite3";import{existsSync as ad}from"fs";import{dirname as sd,join as cd,resolve as ud}from"path";import{readFileSync as ku,rmSync as Eu,statSync as Tu,mkdtempSync as Du}from"fs";import{tmpdir as Fu}from"os";import{join as pn}from"path";import{Worker as Ou}from"worker_threads";function wu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function K(){return{skippedReferences:0,skippedReferenceReasons:wu(),skippedReferenceSamples:[]}}function et(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}function io(e){return e.length>=8&&ao(e.length)>1}function oo(e){let t=ao(e.vueFiles.length),n=Cu(e.vueFiles),r=_u(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Du(pn(Fu(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=ju(),u=Date.now();try{for(let l=0;l<r.length;l++)new Ou(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:pn(o,`${l}.json`),sharedBuffer:a}});for(;Atomics.load(s,0)<r.length;){if(Date.now()-u>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(s,0,Atomics.load(s,0),100)}let d=r.map((l,m)=>{let g=JSON.parse(ku(pn(o,`${m}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(l=>l.occurrences),...K()};for(let l of d)et(p,l);return p}finally{Eu(o,{recursive:!0,force:!0})}}function ao(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function ju(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Cu(e){let t=Au(),n=[];for(let r of e){let i=so(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Au(){return Number.POSITIVE_INFINITY}function _u(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Lu(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Lu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,so(e.fileName)-e.startOffset)}function so(e){try{return Tu(e).size}catch{return 1}}import{createRequire as Mu}from"module";import{existsSync as Nu,readFileSync as fn}from"fs";import{dirname as co,extname as $u,join as uo,relative as Gu,resolve as Vu}from"path";import{pathToFileURL as Bu}from"url";function Uu(e){e.transaction(()=>{e.prepare(`
230
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let f=JSON.stringify([d,p]),g=c.get(p.relative_path)??[];g.push(f),c.set(p.relative_path,g)}let u=new Map;for(let[d,l]of[...c].sort(([p],[f])=>p.localeCompare(f))){let p=Zs("sha256");for(let f of l.sort())p.update(f).update(`
231
+ `);u.set(d,p.digest("hex"))}return u}function Y(e,t){return e.prepare(t).get().value}import{writeFileSync as hc}from"fs";function V(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function fi(e){let t=e.readFingerprint(),n=hi(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return yi(e.cachePath,e.readFingerprint(),r),r}async function mi(e){let t=e.readFingerprint(),n=hi(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return yi(e.cachePath,e.readFingerprint(),r),r}function hi(e,t){try{let n=JSON.parse(v(e,{maxBytes:D,inputKind:"post-index augmentation cache"}));return gi(n.fingerprint)===gi(t)?{result:n.result}:null}catch{return null}}function yi(e,t,n){hc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
232
+ `)}function gi(e){return JSON.stringify(e)}import{createHash as yc}from"crypto";import{existsSync as nn,readdirSync as Sc}from"fs";import{dirname as rn,join as Xe,relative as bc,resolve as on,sep as Si}from"path";function bi(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Pi(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Ri(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],a=r.get(i);if(!o||o.parseFailed){for(let s of e)s!==i&&a.add(s);continue}for(let s of o.dependencyNames){let c=n.get(s);c&&c!==i&&a.add(c)}for(let s of[...o.pathsTargets,...o.referencesPaths]){let c=Pi(s,e);c&&c!==i&&a.add(c)}}return Rc(e,r)}function xi(e,t,n){let r={};for(let i of e){let o=new Map;for(let a of t.files[i]??[])o.set(a.path,a);for(let a of n[i]??[])for(let s of t.files[a]??[])o.set(s.path,s);for(let a of t.shared)o.set(a.path,a);r[i]={files:[...o.values()].sort((a,s)=>a.path.localeCompare(s.path))}}return r}function an(e){if(e===".")return"root";let t=yc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ii(e,t){let n=on(e),r={};for(let i of t)r[i]=xc(n,i);return r}function Pi(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function Rc(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let a=o.pop();if(!(a===r||i.has(a))){i.add(a);for(let s of t.get(a)??[])s!==r&&!i.has(s)&&o.push(s)}}n[r]=[...i].sort((a,s)=>a.localeCompare(s))}return n}function xc(e,t){let n=t==="."?e:Xe(e,t),r=Ic(n),i=Pc(n),o=i?vc(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function Ic(e){let t=Xe(e,"package.json");if(!nn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=sn(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let a=n.value[o];if(a&&typeof a=="object"&&!Array.isArray(a))for(let s of Object.keys(a))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function Pc(e){let t=Xe(e,"tsconfig.json");if(nn(t))return t;let n;try{n=Sc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Xe(e,n[0]):void 0}function vc(e,t){let n=sn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=wc(n.value,e,t),i=vi(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function wc(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=rn(t),o=new Set;for(let a of r){if(!a||typeof a!="object")continue;let s=a.path;if(typeof s!="string"||s.trim()==="")continue;let c=wi(s,i,n);c&&o.add(c)}return[...o]}function vi(e,t,n,r){let i=kc(t);if(i)return{pathsTargets:Tc(i,rn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Ec(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=sn(o);return a.ok?vi(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function kc(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Tc(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let a=wi(o,t,n);a&&r.add(a)}return[...r]}function Ec(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=on(rn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Si).includes("node_modules")&&he(n,i)&&nn(i))return i}function wi(e,t,n){let r=e.replace(/\/?\*+$/,""),i=on(t,r===""?".":r);if(!he(n,i))return;let a=bc(n,i).split(Si).join("/");return a===""?".":a}function Fc(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
233
+ `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function sn(e){try{let t=v(e,{maxBytes:D,inputKind:"TypeScript project manifest"}),n=JSON.parse(Fc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as mo,randomUUID as du}from"crypto";import{constants as lu,copyFileSync as lo,existsSync as Q,lstatSync as pu,mkdirSync as Z,mkdtempSync as ho,readdirSync as gu,realpathSync as fu,renameSync as ie,rmSync as X,statSync as ut}from"fs";import{dirname as ct,join as h,resolve as kn}from"path";import{setTimeout as mu}from"timers/promises";import{pathToFileURL as po}from"url";import{deserializeSCIP as yo}from"@c4312/scip";import hu from"better-sqlite3";import{lstatSync as Wc,readdirSync as qc}from"fs";import{join as Hc,relative as zc,resolve as hn,sep as Jc}from"path";import{createHash as Dc}from"crypto";import{existsSync as un,mkdirSync as Ac,readdirSync as kg,renameSync as _c,rmSync as Tg,writeFileSync as jc}from"fs";import{join as pe}from"path";import{create as Ti,fromBinary as Ei,toBinary as Oc}from"@bufbuild/protobuf";import{deserializeSCIP as Qe,DocumentSchema as dn,IndexSchema as Fi,serializeSCIP as Di}from"@c4312/scip";var Ze=1,we="typescript-scip-fragments";function Ai(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=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=Ei(dn,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Di(Ti(Fi,{documents:n,externalSymbols:[]})),i=Qe(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function et(e){let t=pe(e,we);return{rootDir:t,blobDir:pe(t,"blobs"),generationDir:pe(t,"generations")}}function Cc(e){let t=Qe(e.indexBytes);Ui(t.metadata,Wi(e)),Bi(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=ne(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Oc(dn,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?re(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:re(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Ni(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=$i(e,r);return Gi(e.cacheDir,i),i}function _i(e){let t=et(e.cacheDir);if(!un(ln(t,e.generationIdentity)))return Cc(e);let n=Oi({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function ji(e){let t=Oi({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=ne(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Ni(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=$i(e,[...n.values()]);return Gi(e.cacheDir,i),i}function Oi(e){let t=et(e.cacheDir),n=ln(t,e.generationIdentity),r;try{r=Vi(v(n,{maxBytes:D,inputKind:"TypeScript fragment manifest"}))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=pe(t.blobDir,`${o.blobHash}.scipdoc`),s=T(a,{maxBytes:$,inputKind:"TypeScript fragment blob"});if(s.byteLength!==o.byteLength||re(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Ci(e){let t=Li(e);return cn(t.baseIndex,t.completeDocuments,"assembled")}function Mi(e){let t=Li(e);return Mc(t.deletedAffectedPaths),{completeIndexBytes:cn(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:cn(t.baseIndex,t.affectedDocuments,"affected")}}function Li(e){let t=Qe(e.baseIndexBytes);Ui(t.metadata,Wi(e)),Bi(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=ne(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=ne(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Ei(dn,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function cn(e,t,n){let r=Di(Ti(Fi,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Qe(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Mc(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Ni(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=ne(t.relativePath),i=Buffer.from(t.bytes),o=re(i),a=et(e);Ac(a.blobDir,{recursive:!0});let s=pe(a.blobDir,`${o}.scipdoc`);if(un(s)){let c=T(s,{maxBytes:$,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||re(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;jc(c,i),_c(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function $i(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Ze,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Gi(e,t){let n=et(e),r=ln(n,t.generationIdentity);if(un(r)){let i=Vi(v(r,{maxBytes:D,inputKind:"TypeScript fragment manifest"}));if(ki(i)!==ki(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}de(r,t,{spacing:2,trailingNewline:!0})}function ki(e){return re(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Vi(e){let t=JSON.parse(e);if(t.version!==Ze||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(ne(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function ln(e,t){return pe(e.generationDir,Lc(t))}function Lc(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${re(e)}.json`}function Bi(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ui(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Wi(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}function re(e){return Dc("sha256").update(e).digest("hex")}import{createHash as Nc}from"crypto";import{existsSync as ke,mkdirSync as $c,readdirSync as pn,renameSync as Gc,rmSync as qi,writeFileSync as Vc}from"fs";import{join as C}from"path";var tt=1,zi=64*1024*1024,Ee="typescript-scip-overlays";function Ji(e){let t=Xi(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=mn(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Bc(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:tt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Uc(e.cacheDir,i),i}function Yi(e){let t=Xi(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=T(C(Fe(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:$,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||Te(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Ci({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Ki(e,t){let n=Fe(e),r=C(n,"generations");if(!ke(r))return;let i=new Set(t.map(fn)),o=new Set;for(let s of pn(r).filter(c=>i.has(c))){let c=gn(v(C(r,s),{maxBytes:D,inputKind:"TypeScript overlay manifest"}));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of pn(r))i.has(s)||qi(C(r,s),{force:!0});let a=C(n,"blobs");if(ke(a))for(let s of pn(a))o.has(s)||qi(C(a,s),{force:!0})}function Xi(e,t){let n=C(Fe(e),"generations",fn(t));if(!ke(n))return null;let r=gn(v(n,{maxBytes:D,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Bc(e,t){let n=mn(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Te(r),o=C(Fe(e),"blobs");$c(o,{recursive:!0});let a=C(o,`${i}.scipdoc`);if(ke(a)){let s=T(a,{maxBytes:$,inputKind:"TypeScript overlay blob"});if(s.byteLength!==r.byteLength||Te(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Vc(s,r),Gc(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Uc(e,t){let n=C(Fe(e),"generations",fn(t.generationIdentity));if(ke(n)){let r=gn(v(n,{maxBytes:D,inputKind:"TypeScript overlay manifest"}));if(Hi(r)!==Hi(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}de(n,t,{spacing:2,trailingNewline:!0})}function gn(e){let t=JSON.parse(e);if(t.version!==tt||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(mn(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Fe(e){return C(e,Ee)}function fn(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Te(e)}.json`}function Hi(e){return Te(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function mn(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Te(e){return Nc("sha256").update(e).digest("hex")}var De=1,yn="language-indexes",Qi=["index.db","index.scip","meta.json"],Zi=[yn,we,Ee];function nt(e){let t=[];for(let n of Qi)Yc(e,n),t.push(n);for(let n of Zi)eo(e,n,t);return{version:De,files:t.sort()}}function rt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!Qi.includes(e)&&!Zi.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function L(e,t){let n=rt(t),r=hn(e),i=hn(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Jc}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function eo(e,t,n){let r=Hc(e,t),i;try{i=qc(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?eo(e,a,n):o.isFile()&&n.push(rt(a))}}function Yc(e,t){let n=L(e,t),r;try{r=Wc(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(zc(hn(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as In}from"crypto";import{closeSync as io,chmodSync as Kc,copyFileSync as Xc,constants as Qc,existsSync as I,fsyncSync as Zc,mkdirSync as to,openSync as oo,readSync as eu,readdirSync as tu,renameSync as xn,rmSync as it,statSync as ot}from"fs";import{basename as ao,dirname as N,join as R,relative as no}from"path";function st(e){let t=G(e.outputDb),n=ru(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=wn({generationRoot:t,databasePath:e.tempOutputDb,indexPath:I(r)?r:void 0,metadataPath:I(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:oe,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o};O(R(t,"state.json"),a,{spacing:2,trailingNewline:!0}),e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||Rn(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Rn(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Rn(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let s=i.identity,c={...a,stableMirrors:vn(e.outputDb,e.outputScip)};return O(R(t,"state.json"),c,{spacing:2,trailingNewline:!0}),{currentGeneration:s,...n?{previousGeneration:n}:{}}}function Pn(e,t,n,r=()=>new Date){if(!I(e))return null;let i=Be(e),o=R(G(e),"state.json");if(i?.artifactSet==="immutable-v1"&&kt(e,i.currentGeneration))return i;let a=G(e),s=!i&&I(o)?ou(n,e,t):void 0;if(s&&!Tt(a,s))return null;let c=wn({generationRoot:a,databasePath:e,indexPath:I(t)?t:void 0,metadataPath:I(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),u={version:oe,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:vn(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return O(R(a,"state.json"),u,{spacing:2,trailingNewline:!0}),u}function so(e,t,n=()=>new Date){if(!I(e)||!I(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=Be(e),i=G(e),o=wn({generationRoot:i,databasePath:e,indexPath:I(R(N(e),"index.scip"))?R(N(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?co(e,r.currentGeneration):void 0,s={version:oe,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:vn(e,R(N(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return O(R(G(e),"state.json"),s,{spacing:2,trailingNewline:!0}),s}function K(e,t=R(N(e),"meta.json")){let n=R(G(e),"state.json");if(!I(n))return{state:"legacy",statePath:n};let r=Be(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=kt(e,r.currentGeneration),o=i!==null,a=i?nu(e,t,i,r):!1,s=r.previousGeneration?I(R(N(e),r.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:n,currentMatches:a,recoveryExists:s,generation:r,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:a,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function nu(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==Se(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==Se(R(N(e),"index.scip")))||!ro(e,n.database))return!1;let i=R(N(e),"index.scip");if(n.index&&!ro(i,n.index))return!1;if(!n.metadata)return!I(t);if(!I(t))return!1;let o=R(G(e),n.identity,n.metadata.file);return I(o)&&ee(E(t,"reindex metadata"))===ee(E(o,"immutable reindex metadata"))}function ro(e,t){return I(e)&&ot(e).isFile()&&ot(e).size===t.size}function ru(e){let t=Pn(e.outputDb,e.outputScip,e.metaPath);return t?co(e.outputDb,t.currentGeneration):void 0}function vn(e,t){return{databaseFileIdentity:Se(e),...I(t)?{indexFileIdentity:Se(t)}:{}}}function co(e,t){let n=R(G(e),t),r=R(n,ao(e)),i=R(n,"meta.json");return{generationIdentity:t,databasePath:no(N(e),r),...I(i)?{metadataPath:no(N(e),i)}:{}}}function iu(e){if(I(e))for(let t of tu(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&it(R(e,t.name),{recursive:!0,force:!0})}function ou(e,t,n=R(N(t),"index.scip")){let r=In("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(at(t)),I(n)&&r.update(`\0${at(n)}`),I(e)&&r.update(`\0${ee(E(e,"reindex metadata"))}`),r.digest("hex")}function wn(e){let t=Sn(e.databasePath),n=e.indexPath?Sn(e.indexPath):void 0,r=e.metadataPath?Sn(e.metadataPath):void 0,i=e.forcedIdentity??au(t,n,e.metadataPath),o=R(e.generationRoot,i),a=R(o,wt);if(I(a)){let c=Tt(e.generationRoot,i);if(c&&uo(o,c.database,t)&&cu(o,c.index,n)&&uu(o,c.metadata,e.metadataPath))return{identity:i};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}to(e.generationRoot,{recursive:!0}),iu(e.generationRoot);let s=`${o}.${process.pid}.${Date.now()}.tmp`;it(s,{recursive:!0,force:!0}),to(s,{recursive:!0});try{bn(e.databasePath,R(s,t.file)),n&&e.indexPath&&bn(e.indexPath,R(s,n.file)),r&&e.metadataPath&&bn(e.metadataPath,R(s,r.file)),O(R(s,wt),{version:ar,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0}),xn(s,o),hr(e.generationRoot)}finally{it(s,{recursive:!0,force:!0})}return{identity:i}}function au(e,t,n){let r=In("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ee(E(n,"reindex metadata"))}`),r.digest("hex")}function Sn(e){return{file:ao(e),size:ot(e).size,sha256:at(e)}}function at(e){let t=In("sha256"),n=oo(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=su(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{io(n)}return t.digest("hex")}function su(e,t){let n=0;for(;n<t.length;){let r=eu(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function bn(e,t){Xc(e,t,Qc.COPYFILE_FICLONE);let n=oo(t,"r");try{Zc(n)}finally{io(n)}Kc(t,292)}function uo(e,t,n){let r=R(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&I(r)&&ot(r).size===t.size&&at(r)===t.sha256}function cu(e,t,n){return!t||!n?t===n:uo(e,t,n)}function uu(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=R(e,t.file);return I(r)&&ee(E(r,"stored reindex metadata"))===ee(E(n,"candidate reindex metadata"))}function Rn(e,t){it(`${t}.tmp-replace`,{force:!0}),xn(e,`${t}.tmp-replace`),xn(`${t}.tmp-replace`,t)}var En=1,go="SCIP_QUERY_SHARED_CACHE",Tn=JSON.stringify({cliVersion:vr,artifactCatalogVersion:De,sqliteGenerationStoreVersion:oe,typescriptFragmentStoreVersion:Ze,typescriptOverlayStoreVersion:tt}),So="manifest.json",yu="shared-cache.json",Fn=[yn,we,Ee];function dt(e,t){if(!e.clean||!e.treeOid)return;let n=vo(JSON.stringify({version:En,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Tn}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Tn,generationId:n,repositoryCacheDir:kr(e.repositoryId)}}function bo(e,t,n){if(process.env[go]==="0")return`${go}=0`;if(!Tr(n))return"explicit cache or database override";if(Nt(ct(t))!==Nt(wr(e))||t!==h(ct(t),"index.db"))return"index database is outside the managed worktree cache"}function B(e,t=!0){let n=An(e),r;try{r=bu(v(h(n,So),{inputKind:"shared-generation manifest",maxBytes:D}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=L(n,i.path),a=ut(o);if(!a.isFile()||a.size!==i.size||Ge(o,{inputKind:"shared-generation artifact",maxBytes:A})!==i.sha256)return null}}catch{return null}return r}function Ro(e){let t=B(e.snapshot);if(t)return t;if(!Po(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=fo(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=nt(e.sourceCacheDir),i=h(e.snapshot.repositoryCacheDir,"generations");Z(i,{recursive:!0});let o=ho(h(i,`.tmp-${process.pid}-`));try{let a=[];for(let l of r.files){let p=L(e.sourceCacheDir,l),f=L(o,l);_e(p,f);let g=ut(f).size;a.push({path:l,size:g,sha256:Ge(f,{inputKind:"staged shared-generation artifact",maxBytes:A})})}let s=yo(T(h(o,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:A})).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=_n(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(fo(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:En,artifactCatalogVersion:De,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((l,p)=>l.path.localeCompare(p.path))};O(h(o,So),u,{spacing:2,trailingNewline:!0});let d=An(e.snapshot);try{if(Q(d)&&!B(e.snapshot)){let l=`${d}.corrupt-${process.pid}-${Date.now()}`;ie(d,l),X(l,{recursive:!0,force:!0})}ie(o,d)}catch(l){let p=B(e.snapshot);if(p)return p;throw l}return u}finally{X(o,{recursive:!0,force:!0})}}function Dn(e){let t=An(e.snapshot);Z(e.targetCacheDir,{recursive:!0});let n=Pe(h(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=ho(h(e.targetCacheDir,".shared-hydrate-")),ku(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=L(t,c.path),d=L(r,c.path);if(_e(u,d),ut(d).size!==c.size||Ge(d,{inputKind:"hydrated shared-generation artifact",maxBytes:A})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=_n(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&ii(L(r,c.path),e.manifest.scipProjectRoot,a);if(!Po(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Pu(e.targetCacheDir,r),o=!0,vu(r,e.targetCacheDir,i),st({tempOutputScip:h(r,"index.scip"),tempOutputDb:h(r,"index.db"),tempMetaPath:h(r,"meta.json"),outputScip:h(e.targetCacheDir,"index.scip"),outputDb:h(e.targetCacheDir,"index.db"),metaPath:h(e.targetCacheDir,"meta.json"),now:e.now});let s=K(h(e.targetCacheDir,"index.db"),h(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);lt(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&wu(e.targetCacheDir,i),a}finally{r&&X(r,{recursive:!0,force:!0}),n.release()}}async function xo(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??S,o=i()+n,a=h(e.repositoryCacheDir,"locks"),s=h(a,`${e.generationId}.lock`),c=u=>{if(!u||typeof u!="object"||Array.isArray(u))return null;let d=u.pid;return typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pid:d}:null};for(;i()<=o;){if(B(e))return{kind:"generation-ready"};let u=le(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(u.kind==="acquired")return{kind:"owner",release:()=>u.lock.release()};let d=o-i();if(d<=0)break;await mu(Math.min(r,d))}return B(e)?{kind:"generation-ready"}:{kind:"timeout"}}function lt(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Su(i)};return Iu(e.repositoryCacheDir,o,!0),o}function Su(e){return vo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:kn(e.projectRoot),localCacheDir:kn(e.localCacheDir)}))}function bu(e){let t=JSON.parse(e);if(t.version!==En||t.artifactCatalogVersion!==De||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!==Tn||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(rt(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function _e(e,t){Z(ct(t),{recursive:!0});try{lo(e,t,lu.COPYFILE_FICLONE)}catch{lo(e,t)}}function Ru(e,t,n){Z(e,{recursive:!0}),O(h(e,yu),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function fo(e){try{let t=nt(e),n=mo("sha256");for(let r of t.files){let i=L(e,r),o=ut(i).size;n.update(r).update("\0").update(String(o)).update("\0"),or(i,{inputKind:"source-generation artifact",maxBytes:A},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function xu(e){try{let t=z(v(h(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:D}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function An(e){return h(e.repositoryCacheDir,"generations",e.generationId)}function Iu(e,t,n){let r=Cr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!Q(h(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=h(e,"worktrees");Z(i,{recursive:!0}),O(h(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Ru(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Pu(e,t){let n=h(t,".rollback"),r=new Map,i=new Map;Z(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=h(e,s),u=Q(c);r.set(s,u),u&&_e(c,h(n,"stable",s))}for(let s of Fn){let c=h(e,s),u=Q(c);if(u){let d=pu(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=h(e,Ve),a=Q(o);return a&&Io(o,h(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function vu(e,t,n){for(let r of Fn){let i=h(t,r);if(n.managedDirectories.get(r)){let a=h(n.root,"managed",r);Z(ct(a),{recursive:!0}),ie(i,a)}let o=h(e,r);Q(o)&&ie(o,i)}}function wu(e,t){for(let i of Fn){let o=h(e,i),a=h(t.root,"managed",i);t.managedDirectories.get(i)?Q(a)&&(X(o,{recursive:!0,force:!0}),ie(a,o)):X(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=h(e,i);if(!o){X(a,{force:!0});continue}let s=`${a}.shared-restore-${du()}`;_e(h(t.root,"stable",i),s),X(a,{force:!0}),ie(s,a)}let n=h(e,Ve);X(n,{recursive:!0,force:!0});let r=h(t.root,"sqlite-generations");t.generationStoreExisted&&Q(r)&&ie(r,n)}function Io(e,t){Z(t,{recursive:!0});for(let n of gu(e,{withFileTypes:!0})){let r=h(e,n.name),i=h(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?Io(r,i):n.isFile()&&_e(r,i)}}function ku(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Po(e,t,n,r=!0,i=!0){try{let o=xu(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return Ae("source validation rejected metadata"),!1;let a=nt(e),s=K(h(e,"index.db"),h(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return Ae(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new hu(h(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=_n(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let f=yo(T(L(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:A})).metadata?.projectRoot;return f!==u&&Ae(`source validation rejected SCIP root for ${p}: ${String(f)}`),f===u});return l||Ae("source validation rejected SCIP project roots"),l}catch(o){return Ae(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Ae(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function _n(e){try{return po(fu(e)).href}catch{return po(kn(e)).href}}function vo(e){return mo("sha256").update(e).digest("hex")}import{existsSync as Tu,readdirSync as Eu,statSync as Fu}from"fs";import _ from"path";var Du=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function je(e,t=[]){let n=_.resolve(e),r=t.flatMap(c=>_u(n,c));if(r.length>0)return wo(n,ko(r));let i=Au(n),o=ko(i),a=Ou(n,o)?[n,...o]:o,s=a.length>0?a:[n];return wo(n,s)}function wo(e,t){return[...new Set(t.map(n=>Mu(e,n)))].sort((n,r)=>n.localeCompare(r))}function Au(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Eu(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=_.join(r,o.name);if(o.isDirectory()){!Du.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&ju(a)&&t.push(_.dirname(a))}}return t}function _u(e,t){let n=t.trim();if(!n)return[];let r=_.resolve(e,n);if(!he(e,r))return[];try{let i=Fu(r);if(i.isDirectory())return[r];if(i.isFile()&&To(_.basename(r)))return[_.dirname(r)]}catch{return[]}return[]}function ju(e){if(!To(_.basename(e)))return!1;let t=Eo(e);return t?_.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function To(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function ko(e){let t=[...new Set(e.map(n=>_.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Lu(n,r)))}function Ou(e,t){if(t.length===0||t.some(r=>_.resolve(r)===e))return!1;let n=_.join(e,"tsconfig.json");return Tu(n)&&Cu(n)}function Cu(e){let n=Eo(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!_.extname(r))):!1}function Eo(e){try{let t=JSON.parse(E(e,"TypeScript project config"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mu(e,t){let n=_.relative(e,t);return n?n.split(_.sep).join("/"):"."}function Lu(e,t){let n=_.relative(e,t);return!!n&&!n.startsWith("..")&&!_.isAbsolute(n)}import{createHash as nd}from"crypto";import{existsSync as On,statSync as rd,writeFileSync as Cn}from"fs";import{join as id}from"path";import{createRequire as Nu}from"module";import{dirname as $u,isAbsolute as Ff,relative as Df,resolve as Af,sep as _f}from"path";var Fo=Nu(import.meta.url),Gu=1,Do="0.4.0";function jn(){let e=Vu();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Vu(){try{let e=Fo.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(E(e,"scip-typescript package manifest"));if(t.version!==Do)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Do}`};let n=$u(e),r=Fo.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(E(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Bu(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Bu(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Gu}`}import{createHash as Uu}from"crypto";import{dirname as Wu,join as Ao}from"path";var pt=3;var qu="typescript-index";function _o(e){let t=Ao(e,qu),n=yr(t);return{...n,requestDir:n.legacyRequestDir}}function jo(e){try{let t=ir(z(E(Ao(Wu(e),"meta.json"),"reindex metadata")));return t?Uu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Hu}from"crypto";import{existsSync as zu}from"fs";var Ju=12e4,Yu=5,gt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=Rr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??ed(),this.runtime=n.runtime??td,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=br(this.cacheDir),r=_o(this.cacheDir),i=Ct(n.statePath);if(!Oo(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??S)()+this.timeoutMs,c=jt("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),u=Ot(c),d=Sr(r,{mailboxVersion:_t,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:pt,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??S)()<=s;){if(zu(d.responsePath))return Ku(v(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Ct(n.statePath);if(!Oo(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Yu)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function Oo(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===pt&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Ie(e.processIdentity,r))}function Ku(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==pt||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0)throw new Error(typeof a.error=="string"?a.error:"TypeScript index service request failed.");let s=Xu(a.response,i),c=[...new Set(o)].sort(),u=s.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(u)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return s}function Xu(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Qu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Zu(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Qu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Zu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function ed(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Ju}var td={now:Date.now,monotonicNow:S,randomId:Hu,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ce,readProcessIdentity:ue};function od(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=$e(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!Mt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Je(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=ad([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Co(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Co(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Lo(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Lo(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Mo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Mo(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function ad(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function No(e){let t=S();try{if(!On(e.previousDbPath)||!On(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=jn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new te({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Ue(o,{includeIgnored:!1}).filter(Mt).sort(),s=qe(o)}finally{o.close()}let c=performance.now()-n,u=od({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?je(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:On(id(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=jo(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new gt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),f=performance.now()-n,g=rd(e.previousShardPath).size>=zi;n=performance.now();let m=g?null:T(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:A}),b=g?{completeIndexBytes:null,affectedIndexBytes:Ai(p.fragments)}:Mi({packageVersion:r.packageVersion,baseIndexBytes:m,fragments:p.fragments}),w=performance.now()-n;n=performance.now(),g?Ji({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(_i({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:m,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),ji({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:p.fragments,documentIdentities:u.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),b.completeIndexBytes&&Cn(e.candidateShardPath,b.completeIndexBytes),Cn(e.candidateAffectedScipPath,b.affectedIndexBytes);let P=performance.now()-n,k={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:S()-t,cold:p.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(p.fragments.map(H=>[H.relativePath,H.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:p.durationMs,assemblyMs:w,fragmentStoreMs:x,writeMs:P}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${w.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${P.toFixed(0)}ms).`),k}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function $o(e){let t=jn();if(!t.available)throw new Error(t.reason);let n=Yi({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:T(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:A}),packageVersion:t.packageVersion});Cn(e.candidateShardPath,n)}function Co(e,t,n){let r=e.files.filter(i=>nr(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Mn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Mo(e,t){return Mn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Lo(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=xr({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,Mn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function Mn(e){return nd("sha256").update(e).digest("hex")}import{existsSync as ft,renameSync as Nn,rmSync as $n,statSync as sd}from"fs";import{cpus as cd}from"os";import{join as Vo}from"path";function ud(e,t,n){if(!e.defaultOutputPath)return;let r=Vo(t,e.defaultOutputPath);n!==r&&ft(r)&&Nn(r,n)}function dd(e,t,n){if(!e.defaultOutputPath)return null;let r=Vo(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return $n(i,{force:!0}),ft(r)?(Nn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function ld(e){e&&($n(e.defaultOutputPath,{force:!0}),e.backupPath&&ft(e.backupPath)&&Nn(e.backupPath,e.defaultOutputPath))}function pd(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,cd().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bo(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=pd(o.length,r),c=await md(o,s,u=>Ln(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(l=>l.result.skipped&&l.retryable)){let l=o.find(p=>p.id===d.result.id);l&&(n(`Retrying ${l.label} indexer serially after parallel failure...`),u.set(l.id,(await Ln(l,t,n)).result))}a.push(...c.map(({result:d})=>u.get(d.id)??d))}else a.push(...c.map(({result:u})=>u));for(let u of i)a.push((await Ln(u,t,n)).result);return a.sort((u,d)=>e.findIndex(l=>l.id===u.id)-e.findIndex(l=>l.id===d.id))}async function Ln(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),$n(e.scipPath,{force:!0});let r=dd(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=S();try{e.trustedProjectTool&&fr(t,e.trustedProjectTool);let s=pr(e.binary,e.args),c=await Or({command:s.binary,args:s.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:gd(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let u=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${u?`:
234
+ ${u}`:""}`)}ud(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
235
+ `)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:S()-o,command:i,skipped:{language:e.language,reason:d}},retryable:fd(s)}}finally{ld(r)}if(!ft(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:S()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let a;try{a=sd(e.scipPath).size}catch{a=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:S()-o,command:i,outputBytes:a},retryable:!1}}function gd(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):_r.indexer}function fd(e){return e instanceof jr?e.kind==="spawn"&&Go(e.cause):Go(e)}function Go(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}async function md(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),a=Array.from({length:o},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(a),r}import{execFileSync as Wo}from"child_process";import{homedir as Uo,platform as hd}from"os";import{delimiter as yd,join as mt}from"path";function Vn(e,t){let n=e.installMethods,r=xe(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Et(i.prerequisite))continue;let o=Sd(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Wo(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:hd()==="win32"});let a=se(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${i.identity} via ${i.label}${s}; resolved executable: ${a}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Sd(e){if(e.binary==="npm")return Gn("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Gn("go",["env","GOBIN"]);if(t)return t;let n=Gn("go",["env","GOPATH"]);if(n)return mt(n.split(yd)[0],"bin")}return e.binary==="dotnet"?mt(process.env.DOTNET_CLI_HOME??Uo(),".dotnet","tools"):e.binary==="dart"?mt(process.env.PUB_CACHE??mt(Uo(),".pub-cache"),"bin"):e.destination}function Gn(e,t){try{return Wo(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import ga from"better-sqlite3";import{existsSync as fa}from"fs";import{dirname as ma,join as ha,resolve as ya}from"path";import{randomUUID as Rd}from"crypto";import{mkdtempSync as xd,rmSync as Id,statSync as Ho}from"fs";import{tmpdir as Pd}from"os";import{join as zo}from"path";import{Worker as vd}from"worker_threads";function bd(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function ge(){return{skippedReferences:0,skippedReferenceReasons:bd(),skippedReferenceSamples:[]}}function ht(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var wd=3e5,Jo=64*1024*1024,kd={createResultDirectory:()=>xd(zo(Pd(),"scip-query-vue-workers-")),spawn:(e,t)=>new vd(e,{workerData:t}),resultSize:e=>Ho(e).size,readResult:e=>v(e,{maxBytes:Jo,inputKind:"Vue worker result"}),removeResultDirectory:e=>Id(e,{recursive:!0,force:!0})};function Yo(e){return e.length>=8&&Xo(e.length)>1}async function Ko(e,t=kd){let n=Xo(e.vueFiles.length),r=$d(e.vueFiles),i=Vd(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??Ld(),s=e.maxResultBytes??Nd();qo("timeoutMs",a),qo("maxResultBytes",s);let c=Rd(),u=t.createResultDirectory(),d=[],l,p,f;try{for(let m=0;m<i.length;m++){let b=m,w=i[m]??[],x=w.map(H=>H.taskId),P=zo(u,`${b}.json`),k=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:w,resultPath:P,runId:c,workerId:b,taskIds:x});d.push({workerId:b,taskIds:x,resultPath:P,handle:k,completion:Td(k,b)})}await Ed(d,a);let g=d.sort((m,b)=>m.workerId-b.workerId).map(m=>Dd(m,c,s,t));f={occurrences:g.flatMap(m=>m.occurrences),...ge()};for(let m of g)ht(f,m)}catch(g){l=g}finally{let g=await Fd(d);if(g.length===0)try{t.removeResultDirectory(u)}catch(m){g.push(m)}if(g.length>0){let m=l===void 0?g:[l,...g];p=new AggregateError(m,`Vue worker cleanup failed: ${Md(m[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function Td(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function Ed(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Fd(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Dd(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(a){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:a})}if(!Oe(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!Cd(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!Ad(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Ad(e){if(!Oe(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(_d)||!U(e.skippedReferences)||!Oe(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!U(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(jd)}function _d(e){return Oe(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&U(e.symbolId)}function jd(e){return Oe(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.token=="string"&&Od(e.reason)}function Od(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function U(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Oe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cd(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function qo(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Md(e){return e instanceof Error?e.message:String(e)}function Xo(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function Ld(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:wd}function Nd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Jo}function $d(e){let t=Gd(),n=[];for(let r of e){let i=Qo(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({taskId:`${n.length}:${r}:${a}`,fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Gd(){return Number.POSITIVE_INFINITY}function Vd(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Bd(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Bd(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Qo(e.fileName)-e.startOffset)}function Qo(e){try{return Ho(e).size}catch{return 1}}import{createRequire as Ud}from"module";import{existsSync as Wd}from"fs";import{dirname as Zo,extname as qd,join as ea,relative as Hd,resolve as zd}from"path";import{pathToFileURL as Jd}from"url";function Yd(e){e.transaction(()=>{e.prepare(`
240
236
  DELETE FROM mentions
241
237
  WHERE chunk_id IN (
242
238
  SELECT c.id
@@ -251,12 +247,12 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
251
247
  FROM documents
252
248
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
253
249
  )
254
- `).run()})()}function lo(e,t){return e.prepare(`
250
+ `).run()})()}function Un(e,t){return e.prepare(`
255
251
  SELECT relative_path AS relativePath
256
252
  FROM documents
257
253
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
258
254
  ORDER BY relative_path
259
- `).all().map(r=>Vu(t,r.relativePath))}function po(e,t){let{vueCore:n,ts:r,volarTs:i}=Wu(e),{parsed:o,vueOptions:a}=Hu(n,r,t),s=co(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=Ju(n,r,c),d=qu(s,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),l=r.createLanguageService(p);return{ts:r,language:u,languageService:l,fileNames:o.fileNames,configDir:s}}function Wu(e){let t=Mu(Bu(uo(e,"package.json")).href);return{vueCore:gn(t,"@vue/language-core",e),ts:gn(t,"typescript",e),volarTs:gn(t,"@volar/typescript",e)}}function Hu(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,co(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ju(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Nu(o))return;let a=fn(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Zu(o))});return r.current=i,i}function qu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function gn(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function go(e,t,n){let r=zu(e);return i=>{if(!i.name)return null;let o=_(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let u=c.starts.find(p=>p.line===s.line&&p.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:Yu(c.starts,s.line,2,i.name)}}function zu(e){let t=e.prepare(`
255
+ `).all().map(r=>zd(t,r.relativePath))}function ta(e,t){let{vueCore:n,ts:r,volarTs:i}=Kd(e),{parsed:o,vueOptions:a}=Xd(n,r,t),s=Zo(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Qd(n,r,c),d=Zd(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,u,f=>f,d),p=r.createLanguageService(l);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function Kd(e){let t=Ud(Jd(ea(e,"package.json")).href);return{vueCore:Bn(t,"@vue/language-core",e),ts:Bn(t,"typescript",e),volarTs:Bn(t,"@volar/typescript",e)}}function Xd(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,Zo(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Qd(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Wd(o))return;let a=v(o,{maxBytes:$,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??ol(o))});return r.current=i,i}function Zd(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Bn(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function na(e,t,n){let r=el(e);return i=>{if(!i.name)return null;let o=W(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let u=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:tl(c.starts,s.line,2,i.name)}}function el(e){let t=e.prepare(`
260
256
  SELECT
261
257
  d.relative_path AS relativePath,
262
258
  der.start_line AS startLine,
@@ -267,22 +263,22 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
267
263
  JOIN documents d ON d.id = der.document_id
268
264
  JOIN global_symbols gs ON gs.id = der.symbol_id
269
265
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
270
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Yu(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function fo(e,t,n){let r=nd(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
266
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function tl(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function Wn(e,t,n){let r=cl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
271
267
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
272
268
  VALUES (?, ?, ?, ?)
273
- `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=_(t,u),p=Io(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let l=rd(i,r,t,u);l&&(a++,s.set(u,l))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function mo(e,t,n,r,i){return e.transaction(()=>(Uu(e),Xu(e,t,n,r),Qu(e,i)))()}function Xu(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
269
+ `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=W(t,u),l=la(r.name,r.version,d);o.run(l,"default",7,`Vue component|${d}`);let p=ul(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function ra(e,t,n,r,i){return e.transaction(()=>(Yd(e),nl(e,t,n,r),rl(e,i)))()}function nl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
274
270
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
275
271
  VALUES (?, ?, ?, ?, X'00')
276
272
  `),a=e.prepare(`
277
273
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
278
274
  VALUES (?, ?, 1)
279
- `);for(let s of n){let c=r.get(s);if(!c)continue;let u=_(t,s),d=i.get(u);if(!d)continue;let p=o.run(d.id,-1,0,0);a.run(Number(p.lastInsertRowid),c)}}function ho(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(mn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function yo(e){let t=new Set,n=[];for(let r of e){let i=So(r);t.has(i)||(t.add(i),n.push(r))}return n}function So(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Qu(e,t){let n=td(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
275
+ `);for(let s of n){let c=r.get(s);if(!c)continue;let u=W(t,s),d=i.get(u);if(!d)continue;let l=o.run(d.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function ia(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(qn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function oa(e){let t=new Set,n=[];for(let r of e){let i=aa(r);t.has(i)||(t.add(i),n.push(r))}return n}function aa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function rl(e,t){let n=sl(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
280
276
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
281
277
  VALUES (?, ?, ?, ?, X'00')
282
278
  `),i=e.prepare(`
283
279
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
284
280
  VALUES (?, ?, 0)
285
- `),o=new Set,a=0,s=0;for(let c of t){let u=So(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,s++,c.sourceLine,c.sourceLine),l=i.run(Number(p.lastInsertRowid),c.symbolId);a+=Number(l.changes)}return a}function*bo(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Ro(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function mn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ku(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function xo(e,t){return _(e,t).startsWith("node_modules/")}function _(e,t){return Gu(e,t).replaceAll("\\","/")}function Zu(e){switch($u(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function vo(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=fn(t,"utf-8"),r={text:n,lineStarts:ed(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ku}}function ed(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function td(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function nd(e){try{let t=JSON.parse(fn(uo(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function rd(e,t,n,r){let i=_(n,r),o=Io(t.name,t.version,i);return e.get(o)?.id??null}function Io(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function wo(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>ld({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function dd(e){return $(H(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),$(wo({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function ld(e){let t=ud(e.projectRoot,e.tsconfig);if(!ad(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new od(e.dbPath);try{let r=lo(n,e.projectRoot),i=cd(sd(e.dbPath),"augment-vue-meta.json");return Er({cachePath:i,readFingerprint:()=>fd(n,e.projectRoot,e.tsconfig),compute:()=>pd({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function pd(e){let t=fo(e.db,e.projectRoot,e.vueFiles),n=gd(e,t),r=yo(n.occurrences),i=mo(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Id(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:vd(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function gd(e,t){if(io(e.vueFiles))return oo({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=md({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return hd({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function fd(e,t,n){let r=e.prepare(`
281
+ `),o=new Set,a=0,s=0;for(let c of t){let u=aa(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let l=r.run(d,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*sa(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function ca(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function qn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function il(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function ua(e,t){return W(e,t).startsWith("node_modules/")}function W(e,t){return Hd(e,t).replaceAll("\\","/")}function ol(e){switch(qd(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function da(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=v(t,{maxBytes:$,inputKind:"Vue source file"}),r={text:n,lineStarts:al(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:il}}function al(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function sl(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function cl(e){try{let t=JSON.parse(v(ea(e,"package.json"),{maxBytes:D,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function ul(e,t,n,r){let i=W(n,r),o=la(t.name,t.version,i);return e.get(o)?.id??null}function la(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Sa(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>gl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function ll(e){return V(J(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),V(Sa({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function pl(e){return V(J(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),fl(e)}function gl(e){let t=ya(e.projectRoot,e.tsconfig);if(!fa(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ga(e.dbPath);try{let r=Un(n,e.projectRoot),i=ha(ma(e.dbPath),"augment-vue-meta.json");return fi({cachePath:i,readFingerprint:()=>xa(n,e.projectRoot,e.tsconfig),compute:()=>ml({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}async function fl(e){let t=ya(e.projectRoot,e.tsconfig);if(!fa(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ga(e.dbPath);try{let r=Un(n,e.projectRoot),i=ha(ma(e.dbPath),"augment-vue-meta.json");return await mi({cachePath:i,readFingerprint:()=>xa(n,e.projectRoot,e.tsconfig),compute:()=>hl({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function ml(e){let t=Wn(e.db,e.projectRoot,e.vueFiles),n=Ra(e,t);return ba(e,t,n)}async function hl(e){let t=Wn(e.db,e.projectRoot,e.vueFiles),n=Yo(e.vueFiles)?await Ko({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Ra(e,t);return ba(e,t,n)}function ba(e,t,n){let r=oa(n.occurrences),i=ra(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:wl(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:vl(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Ra(e,t){let n=yl({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Sl({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function xa(e,t,n){let r=e.prepare(`
286
282
  SELECT
287
283
  (SELECT COUNT(*) FROM documents) AS documents,
288
284
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -291,13 +287,13 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i
291
287
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
292
288
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
293
289
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
294
- `).get();return{version:3,tsconfig:n,files:Te(t),db:r}}function md(e){let t=vo();return{projectRoot:e.projectRoot,context:po(e.projectRoot,e.configPath),symbolLookup:go(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function hd(e){let t=[],n=K(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=yd(e,i);t.push(...o.occurrences),et(n,o)}return{occurrences:t,...n}}function yd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Po(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Po(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=_(e.projectRoot,t.fileName),s=[...bo(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:wd(s),processedStarts:new Set};return Sd({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Sd(e){let t=[],n=K();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||bd(e.sourceInfo.text,r.start))continue;let i=Ro(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!xo(e.projectRoot,d.fileName));if(!a){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=_(e.projectRoot,a.fileName),c=Rd(e.sourceFile,r.text,s);if(c){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ho(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ko(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Pd(t,e,r,i,s,u)}return{occurrences:t,...n}}function bd(e,t){let n=e.lastIndexOf(`
295
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Rd(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Po(e,t,n){let r=K();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:_(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function hn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function yn(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function xd(e,t){let n=yn(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=yn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function vd(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...yn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Id(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return xd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Pd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of kd(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(ko(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ko(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function wd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function kd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=Ed(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function Ed(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=mn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function pm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Nd(e),a=Date.now();nt(h(o.outputScip),{recursive:!0}),nt(h(o.outputDb),{recursive:!0});let s=e.languages??xt(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=ee("reindex.fingerprint",()=>Fn(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!Oi(t,o.outputDb)&&Eo(o.outputScip)===Eo(x(h(o.outputDb),"index.scip"))){let g=De(t);if(u=g?ze(g,c):void 0,u){let S=C(u);if(S){if(!Md(o,c))try{en({snapshot:u,manifest:S,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(b){r(`Shared generation attach failed; continuing locally: ${Re(b)}`)}}else{let b=await Ci(u);if(b.kind==="owner")d=b.release;else if(b.kind==="generation-ready"){let P=C(u);if(P)try{en({snapshot:u,manifest:P,targetCacheDir:h(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(y){r(`Shared generation attach failed after waiting; continuing locally: ${Re(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ie(x(h(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${h(o.outputDb)}.`);let l;try{l=await te("reindex.lock",()=>ll(x(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length})}catch(g){throw p.release(),d?.(),g}let m=null;try{let g=Bd(h(o.outputDb));g.removed>0&&r(`Removed ${g.removed} abandoned reindex workspace(s)`);for(let w of g.errors)r(`Could not remove abandoned reindex workspace: ${w}`);let S=null,b=ee("reindex.reuse-check",()=>(S=$d({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),S),()=>({languages:s.length,reused:S!==null}));if(b)return To({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),mt(o.outputDb,b),b;await te("reindex.scip-cli-ready",()=>rl(i,r));let P=Vd(o);m=P.runDir;let y,I=await te("reindex.fresh",async()=>(y=await Ud({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:P,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),y),()=>({languages:s.length,reused:y?.reused,skipped:y?.skipped.length}));return To({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),mt(o.outputDb,I),I}catch(g){let S=at({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)});throw Ho(o.metaPath,S),Mn(o.outputDb,S),g}finally{m&&M(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function To(e){if(e.snapshot){if(C(e.snapshot)){Ye(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=De(e.projectRoot),n=t?ze(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}ji({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=De(e.projectRoot);return(r?ze(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Ye(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Re(t)}`)}}}function Md(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!Wo(e.metaPath,t))return!1;let n=V(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Re(e){return e instanceof Error?e.message:String(e)}function Nd(e){let t=e.outputScip??x(e.projectRoot,"index.scip"),n=e.outputDb??x(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:x(h(n),"meta.json")}}function $d(e){let t=V(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!Wo(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;$(H(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=at({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Ho(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:Gd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Gd(e,t,n,r){let i=Bo(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:be(i[o]),outputBytes:xe(Rn(e.outputDb,o)),durationMs:0}))}function Vd(e){let t=Od(x(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:x(t,tt(e.outputScip)),tempOutputDb:x(t,tt(e.outputDb)),tempMetaPath:x(t,tt(e.metaPath))}}function Bd(e){let t=[],n;try{n=Ao(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Re(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{M(x(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Re(o)}`)}return{removed:r,errors:t}}async function Ud(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await te("reindex.language-indexers",async()=>(n=await Hd(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Wd({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=ee("reindex.publish",()=>el(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(S=>S.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=ee("reindex.publish",()=>Zd(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),l=p.durationMs;return e.onStatus(`Done in ${(l/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:l,reused:!1,skipped:o,lastRefresh:p,shards:c}}function Wd(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!O(e.run.paths.outputScip)||!O(e.run.paths.outputDb))return!1;let t=V(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Hd(e,t){let n=Xd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[E,In]of n)In.reused&&(r.push({language:E,scipPath:In.scipPath}),i.add(E));for(let E of i)e.onStatus(`Reusing cached ${E} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=V(e.paths.outputDb,e.paths.metaPath),s=Ie(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?eo({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:ve(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:ve(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:bn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Jd(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:S}=il({languages:e.languages.filter(E=>!i.has(E)&&!p.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=l?m.filter(E=>E.language!=="typescript"||l.missedProjectIds.has(E.id)):m,P=await ro(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){zd(e.paths.outputDb,P);let E=S.typescript??e.tempPaths.tempOutputScip;y=Yd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let I=[...P,...y],{indexedOutputs:w}=al(I,g),Pe=d?[{language:"typescript",scipPath:d.scipPath}]:[],vn=[...r,...Pe,...w];sl(vn,g,e.languages,e.opts.allowPartial,e.onStatus);let Jo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:xe(d.scipPath)??void 0}]:[],qo=Qd(n,[...P,...Jo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:vn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Kd(n,e.languages),shards:qo,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Jd(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Se(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=jr(e.projectRoot,r),o=Dr(n.fingerprint.files,r),a=Fr(r,i),s=Or(r,o,a),c=Ie(e.paths.metaPath),d=qd(c,s,g=>O(ot(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),l=new Set(p),m=new Set(r.filter(g=>!l.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:p,missedProjectIds:m}}function qd(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.typescriptProjectShards?.[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(L(a)!==L(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function zd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=ot(e,r);nt(h(i),{recursive:!0}),rt(n.scipPath,i)}}function Yd(e){return e.reusedProjects.map((t,n)=>{let r=ot(e.outputDb,t),i=ve(e.tempOutputScip,"typescript-project-cached",n);return rt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:xe(i)??void 0}})}function Xd(e){let t=Ie(e.paths.metaPath),n=Bo(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Rn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!O(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(L(s)!==L(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Qd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:be(o.fingerprint),outputBytes:xe(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?be(s.fingerprint):o?be(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:be(o.fingerprint),outputBytes:xe(ot(n.outputDb,i)),durationMs:0});return r}function be(e){return Dd("sha256").update(L(e)).digest("hex").slice(0,16)}function xe(e){try{return Cd(e).size}catch{return null}}function Kd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Zd(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Do(e.paths.outputDb,n),u=Fo(n,e.tempPaths.tempOutputScip,e.onStatus));let d=cl({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),to({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(I=>I.language==="typescript"?{language:I.language,scipPath:s.candidateScipPath}:I);return Do(e.paths.outputDb,y),u=Fo(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if($(H(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let y=null,I=null;try{y=new W({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),I=new W({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let w=_n(y,e.fingerprint,s.referenceFragmentsByFile,I);e.onStatus(`Cached exact TypeScript reference fragments for ${w} affected document(s).`)}catch(w){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${w instanceof Error?w.message:String(w)}.`)}finally{y?.close(),I?.close()}}let p=bn(e.paths.metaPath),l=d.mode==="incremental"&&s?dl(s,d.changedDocumentPaths):Rt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=at({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",S={...o};g&&delete S.typescript;let{metadata:b,pruneProjects:P}=Mo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:S,typescriptProjectShardContext:a,lastRefresh:m});return b.scipCompanion=g?"deferred":"current",No(e.paths.outputDb,P),xn(e.tempPaths.tempMetaPath,b),He({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),si(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Lo(e.paths.outputDb,l,e.onStatus),m}function el(e,t,n,r,i,o){let a=bn(e.paths.metaPath),s=null;try{rt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=rr("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}$(H(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=Rt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=at({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Mo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return No(e.paths.outputDb,d),xn(e.paths.metaPath,u),Si(e.paths.outputDb,e.paths.metaPath),Lo(e.paths.outputDb,s,e.onStatus),c}function bn(e){return Tn(Ie(e)?.fingerprint)}function Lo(e,t,n){try{ir(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Mo(e){let t=tl({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function tl(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=Ie(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function No(e,t){let n=Uo(e);if(t===null){M(n,{recursive:!0,force:!0});return}let r;try{r=Ao(n)}catch{return}for(let i of nl(r,t))M(x(n,i),{force:!0})}function nl(e,t){let n=new Set(t.map(r=>`${_t(r)}.scip`));return e.filter(r=>!n.has(r))}function Do(e,t){for(let n of t){let r=Rn(e,n.language);nt(h(r),{recursive:!0}),n.scipPath!==r&&rt(n.scipPath,r)}}async function rl(e,t){if(!gt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
296
- Install from: https://github.com/sourcegraph/scip/releases`);if(Ld()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!ft(t))throw new Error(`The scip CLI is required but could not be installed.
297
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function il(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?ve(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=ol({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?$o(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function ol(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Sn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Se(e.projectRoot,e.typescriptProjects);return t.length===0?[Sn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Sn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:ve(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Sn(e){let t=Ce(e.language),n=ne(t),r=ut(t,e.projectRoot);if(!r&&!ct(t)){if(e.skipAutoInstall){let s=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!ln(t,e.onStatus)){let s=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}}let i=r??re(t);if(!i){let s=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}let{binary:o,args:a}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:a,env:dt(t,e.env,i)}}}function al(e,t){let n=new Map;for(let i of e)if(i.skipped)$o(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Dt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&_o(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function $o(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function sl(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
290
+ `).get();return{version:3,tsconfig:n,files:We(t),db:r}}function yl(e){let t=da();return{projectRoot:e.projectRoot,context:ta(e.projectRoot,e.configPath),symbolLookup:na(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Sl(e){let t=[],n=ge(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=bl(e,i);t.push(...o.occurrences),ht(n,o)}return{occurrences:t,...n}}function bl(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return pa(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return pa(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=W(e.projectRoot,t.fileName),s=[...sa(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:Tl(s),processedStarts:new Set};return Rl({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Rl(e){let t=[],n=ge();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||xl(e.sourceInfo.text,r.start))continue;let i=ca(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!ua(e.projectRoot,d.fileName));if(!a){Hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=W(e.projectRoot,a.fileName),c=Il(e.sourceFile,r.text,s);if(c){Hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ia(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){Hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Ia(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),kl(t,e,r,i,s,u)}return{occurrences:t,...n}}function xl(e,t){let n=e.lastIndexOf(`
291
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Il(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function pa(e,t,n){let r=ge();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:W(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Hn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function zn(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function Pl(e,t){let n=zn(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=zn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function vl(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...zn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function wl(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Pl(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function kl(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of El(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(Ia(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function Ia(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function Tl(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function El(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=Fl(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function Fl(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=qn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Bh(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Ll(e),a=Date.now(),s=S();St(y(o.outputScip),{recursive:!0}),St(y(o.outputDb),{recursive:!0});let c=e.languages??zt(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${c.join(", ")}`);let u=be("reindex.fingerprint",()=>ur(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,l;if(e.skipIfUnchanged!==!1&&!bo(t,o.outputDb)&&Pa(o.outputScip)===Pa(F(y(o.outputDb),"index.scip"))){let m=He(t);if(d=m?dt(m,u):void 0,d){let b=B(d);if(b){if(!Ml(o,u))try{Dn({snapshot:d,manifest:b,targetCacheDir:y(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(w){r(`Shared generation attach failed; continuing locally: ${me(w)}`)}}else{let w=await xo(d);if(w.kind==="owner")l=w.release;else if(w.kind==="generation-ready"){let x=B(d);if(x)try{Dn({snapshot:d,manifest:x,targetCacheDir:y(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(P){r(`Shared generation attach failed after waiting; continuing locally: ${me(P)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=Pe(F(y(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw l?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${y(o.outputDb)}.`);let f;try{f=await Re("reindex.lock",()=>dp(F(y(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(m){throw p.release(),l?.(),m}let g=null;try{Pn(o.outputDb,o.outputScip,o.metaPath);let m=Vl(y(o.outputDb));m.removed>0&&r(`Removed ${m.removed} abandoned reindex workspace(s)`);for(let H of m.errors)r(`Could not remove abandoned reindex workspace: ${H}`);let b=null,w=be("reindex.reuse-check",()=>(b=Nl({opts:e,paths:o,languages:c,fingerprint:u,start:a,monotonicStart:s,onStatus:r}),b),()=>({languages:c.length,reused:b!==null}));if(w)return va({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r}),Bt(o.outputDb,w),Lt(t,y(o.outputDb)),w;await Re("reindex.scip-cli-ready",()=>np(i,r));let x=Gl(o);g=x.runDir;let P,k=await Re("reindex.fresh",async()=>(P=await Bl({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:x,fingerprint:u,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));return va({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r}),Bt(o.outputDb,k),Lt(t,y(o.outputDb)),k}catch(m){let b=It({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:m instanceof Error?m.message:String(m)});throw qa(o.metaPath,b),Ar(o.outputDb,b),m}finally{g&&fe(g,{recursive:!0,force:!0}),f(),p.release(),l?.()}}function va(e){if(e.snapshot){if(B(e.snapshot)){lt(e.snapshot,y(e.paths.outputDb),"local-fresh");return}try{let t=He(e.projectRoot),n=t?dt(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}Ro({snapshot:e.snapshot,sourceCacheDir:y(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=He(e.projectRoot);return(r?dt(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),lt(e.snapshot,y(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${me(t)}`)}}}function Ml(e,t){if(!M(e.outputScip)||!M(e.outputDb)||!Wa(e.metaPath,t))return!1;let n=K(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function me(e){return e instanceof Error?e.message:String(e)}function Ll(e){let t=e.outputScip??F(e.projectRoot,"index.scip"),n=e.outputDb??F(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:F(y(n),"meta.json")}}function Nl(e){let t=K(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!M(e.paths.outputScip)||!M(e.paths.outputDb)||!Wa(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;V(J(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=S()-e.monotonicStart,r=It({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return qa(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:$l(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function $l(e,t,n,r){let i=Ba(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Ce(i[o]),outputBytes:Me(Xn(e.outputDb,o)),durationMs:0}))}function Gl(e){let t=_l(F(y(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:F(t,yt(e.outputScip)),tempOutputDb:F(t,yt(e.outputDb)),tempMetaPath:F(t,yt(e.metaPath))}}function Vl(e){let t=[],n;try{n=Aa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[me(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{fe(F(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${me(o)}`)}return{removed:r,errors:t}}async function Bl(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Re("reindex.language-indexers",async()=>(n=await Wl(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ul({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=be("reindex.publish",()=>Zl(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let l=be("reindex.publish",()=>Ql(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=l.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c}}function Ul(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!M(e.run.paths.outputScip)||!M(e.run.paths.outputDb))return!1;let t=K(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Wl(e,t){let n=Yl({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[j,er]of n)er.reused&&(r.push({language:j,scipPath:er.scipPath}),i.add(j));for(let j of i)e.onStatus(`Reusing cached ${j} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=K(e.paths.outputDb,e.paths.metaPath),s=Ne(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?No({projectRoot:e.projectRoot,cacheDir:y(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:Kn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,l=new Set(d?["typescript"]:[]),p=d?void 0:ql(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:m}=rp({languages:e.languages.filter(j=>!i.has(j)&&!l.has(j)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:p?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=p?f.filter(j=>j.language!=="typescript"||p.missedProjectIds.has(j.id)):f,w=await Bo(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(p){zl(e.paths.outputDb,w);let j=m.typescript??e.tempPaths.tempOutputScip;x=Jl({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:j,reusedProjects:p.reusedProjects})}let P=[...w,...x],{indexedOutputs:k}=op(P,g),H=d?[{language:"typescript",scipPath:d.scipPath}]:[],Zn=[...r,...H,...k];ap(Zn,g,e.languages,e.opts.allowPartial,e.onStatus);let Ha=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Me(d.scipPath)??void 0}]:[],za=Kl(n,[...w,...Ha],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:Zn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Xl(n,e.languages),shards:za,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function ql(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=je(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ii(e.projectRoot,r),o=bi(n.fingerprint.files,r),a=Ri(r,i),s=xi(r,o,a),c=Ne(e.paths.metaPath),d=Hl(c,s,g=>M(xt(e.paths.outputDb,g))),l=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),f=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:l,missedProjectIds:f}}function Hl(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===ye&&vt(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(q(a)!==q(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function zl(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=xt(e,r);St(y(i),{recursive:!0}),Rt(n.scipPath,i)}}function Jl(e){return e.reusedProjects.map((t,n)=>{let r=xt(e.outputDb,t),i=Le(e.tempOutputScip,"typescript-project-cached",n);return Rt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Me(i)??void 0}})}function Yl(e){let t=Ne(e.paths.metaPath),n=Ba(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Xn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==ye){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!vt(t).languageShardReuse||!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!M(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(q(s)!==q(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Kl(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Ce(o.fingerprint),outputBytes:Me(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?Ce(s.fingerprint):o?Ce(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:Ce(o.fingerprint),outputBytes:Me(xt(n.outputDb,i)),durationMs:0});return r}function Ce(e){return Al("sha256").update(q(e)).digest("hex").slice(0,16)}function Me(e){try{return jl(e).size}catch{return null}}function Xl(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Ql(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(wa(e.paths.outputDb,n),u=ka(n,e.tempPaths.tempOutputScip,e.onStatus));let d=sp({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),$o({cacheDir:y(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let x=n.map(P=>P.language==="typescript"?{language:P.language,scipPath:s.candidateScipPath}:P);return wa(e.paths.outputDb,x),u=ka(x,e.tempPaths.tempOutputScip,e.onStatus),u}});if(V(J(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let x=null,P=null;try{x=new te({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),P=new te({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Ir(x,e.fingerprint,s.referenceFragmentsByFile,P);e.onStatus(`Cached exact TypeScript reference fragments for ${k} affected document(s).`)}catch(k){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${k instanceof Error?k.message:String(k)}.`)}finally{x?.close(),P?.close()}}let l=Kn(e.paths.metaPath),p=d.mode==="incremental"&&s?up(s,d.changedDocumentPaths):Ht({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:l,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=It({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(x=>x.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",m={...o};g&&delete m.typescript;let{metadata:b,pruneProjects:w}=Oa({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:m,typescriptProjectShardContext:a,lastRefresh:f});return b.scipCompanion=g?"deferred":"current",Ca(e.paths.outputDb,w),Qn(e.tempPaths.tempMetaPath,b),st({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),Ki(y(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),ja(e.paths.outputDb,p,e.onStatus),f}function Zl(e,t,n,r,i,o){let a=Kn(e.paths.metaPath),s=null;try{Rt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(l){s=Gr("reused","oracle-error",`Could not snapshot the prior database: ${l instanceof Error?l.message:String(l)}`)}V(J(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=Ht({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=It({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(l=>l.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Oa({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Ca(e.paths.outputDb,d),Qn(e.paths.metaPath,u),so(e.paths.outputDb,e.paths.metaPath),ja(e.paths.outputDb,s,e.onStatus),c}function Kn(e){return rr(Ne(e)?.fingerprint)}function ja(e,t,n){try{Vr(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Oa(e){let t=ep({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:ye,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function ep(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=Ne(e.metaPath),n=t?.version===ye?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Ca(e,t){let n=Ua(e);if(t===null){fe(n,{recursive:!0,force:!0});return}let r;try{r=Aa(n)}catch{return}for(let i of tp(r,t))fe(F(n,i),{force:!0})}function tp(e,t){let n=new Set(t.map(r=>`${an(r)}.scip`));return e.filter(r=>!n.has(r))}function wa(e,t){for(let n of t){let r=Xn(e,n.language);St(y(r),{recursive:!0}),n.scipPath!==r&&Rt(n.scipPath,r)}}async function np(e,t){if(!$t()){if(Cl()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
292
+ To install the reviewed version, run: scip-query reindex --install-missing
293
+ Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Gt(t))throw new Error(`The scip CLI is required but could not be installed.
294
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function rp(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Le(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=ip({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ma(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function ip(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Jn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??je(e.projectRoot,e.typescriptProjects);return t.length===0?[Jn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Jn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Le(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Jn(e){let t=Ke(e.language),n=xe(t),r=Dt(t,e.projectRoot),i=e.trustProjectTools&&r?gr(t,e.projectRoot):null,o=se(t);if(!i&&!o&&r){let u=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(!i&&!o&&!Ft(t)){if(e.skipAutoInstall){let u=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Vn(t,e.onStatus)){let u=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}}let a=i?.canonicalPath??se(t);if(!a){let u=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}let{binary:s,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:a,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});if(i&&!i.executable){let u=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:a,binary:s,args:c,env:At(t,e.env,a),...i?{trustedProjectTool:i}:{}}}}function op(e,t){let n=new Map;for(let i of e)if(i.skipped)Ma(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Zt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&_a(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Ma(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function ap(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
298
295
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
299
296
  `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
300
297
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
301
- `))}function Fo(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=hr(e.map(o=>o.scipPath),t);return Vo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&_o(e[0].scipPath,t);return!1}function cl(e){let t;if(ul(e)){let i=x(e.run.tempPaths.runDir,"typescript-affected.db");try{Go(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Oo(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Pr({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),M(i,{force:!0}),M(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Oo(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function ul(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!O(e.run.paths.outputDb)||!O(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function dl(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:bt(e.plan,o,e.projectFileCount)}}function Oo(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!O(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Go(e,r);let o=gt();if(!o)throw new Error("scip CLI is not available");Td(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Go(e,t){let n=fr(e);Vo(n,t)}function Vo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function ve(e,t,n){let r=_d(e)||".scip",i=tt(e,r);return x(h(e),`${i}.${n+1}.${t}${r}`)}async function ll(e,t){for(let n=0;n<2;n++){let r=pl(e,t);if(r)return r;let i=gl(e);if(i&&fl(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await hl(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${h(e)}; refusing to steal an active lock.`);M(e,{force:!0});continue}if(i&&!T(i.pid)){M(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${h(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function pl(e,t){let n;try{n=jd(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return Ad(n,JSON.stringify(r)+`
302
- `),()=>{try{Fd(n)}finally{M(e,{force:!0})}}}function gl(e){try{let t=JSON.parse(it(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:h(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function fl(e,t){return e?.kind==="manual-cli"&&ml(t?.trigger)}function ml(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function hl(e){return jo(e,"SIGTERM"),await Co(e,2e3)?!0:(jo(e,"SIGKILL"),Co(e,1e3))}function jo(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Co(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await yl(50)}return!T(e)}function yl(e){return new Promise(t=>setTimeout(t,e))}function Bo(e,t,n){return Object.fromEntries(t.map(r=>{let i=Ce(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Dn(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Sl(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&bl(n),...o,clojureConfigPath:a,files:Te(e,{language:r,markerFiles:i})}]}))}function Sl(e){return e?.trim()||void 0}function bl(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Rn(e,t){return x(h(e),"language-indexes",`${t}.scip`)}function Uo(e){return x(h(e),"language-indexes","typescript-projects")}function ot(e,t){return x(Uo(e),`${_t(t)}.scip`)}function Ie(e){try{return JSON.parse(it(e,"utf-8"))}catch{return null}}function Wo(e,t){try{let n=JSON.parse(it(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&L(n.fingerprint)===L(t)&&L([...n.indexedLanguages??[]].sort())===L(t.languages)}catch{return!1}}function xn(e,t){R(e,t,{spacing:2,trailingNewline:!0})}function Ho(e,t){try{let n=JSON.parse(it(e,"utf-8"));if(n.version!==2&&n.version!==3)return;xn(e,{...n,lastRefresh:t})}catch{}}function at(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{pr as INDEXER_CONFIGS,Qn as augmentAuxiliaryDocuments,dd as augmentVueResolvedReferences,H as auxiliaryDocumentsAugmentationStage,ne as describeIndexerBinary,xt as detectLanguages,Ce as getIndexerConfig,dt as getIndexerExecutionEnv,st as isBinaryAvailable,ct as isIndexerInstalled,Dt as mergeScipFiles,Tt as mergeScipIndexes,pm as reindex,re as resolveIndexerBinary,ut as resolveProjectLocalIndexerBinary,$ as runPostIndexAugmentation,ln as tryInstallIndexer,ft as tryInstallScipCli,wo as vueResolvedReferencesAugmentationStage};
298
+ `))}function ka(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ri(e.map(o=>o.scipPath),t);return Na(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&_a(e[0].scipPath,t);return!1}function sp(e){let t;if(cp(e)){let i=F(e.run.tempPaths.runDir,"typescript-affected.db");try{La(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Ta(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=li({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),fe(i,{force:!0}),fe(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Ta(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function cp(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!M(e.run.paths.outputDb)||!M(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function up(e,t){let n=S(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:S()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:qt(e.plan,o,e.projectFileCount)}}function Ta(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!M(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||La(e,r);let o=$t();if(!o)throw new Error("scip CLI is not available");Dl(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function La(e,t){let n=ti(e);Na(n,t)}function Na(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Le(e,t,n){let r=Ol(e)||".scip",i=yt(e,r);return F(y(e),`${i}.${n+1}.${t}${r}`)}async function dp(e,t){for(let n=0;n<2;n++){let r=lp(e,t);if(r)return r;let i=pp(e);if(i&&Va(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await fp(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${me(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${y(e)}; refusing to steal an active lock.`);let a=Vt(e,{parseLegacy:bt});if(!Er(e,a,{parseLegacy:bt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${y(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${y(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${y(e)}.`)}function lp(e,t){let n=ue(process.pid),r=le(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:bt});if(r.kind==="acquired"&&r.reclaimed){let i=$a(r.reclaimed,e);i&&Va(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${y(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function pp(e){return $a(Vt(e,{parseLegacy:bt}),e)}var bt=e=>{let t=Ga(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function $a(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:y(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ga(e.parsed,t)}function Ga(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=mr(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:y(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function Va(e,t){return e?.kind==="manual-cli"&&gp(t?.trigger)}function gp(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function fp(e){return!ce(e.pid)||(Yn(e),Ea(e,"SIGTERM"),await Fa(e,2e3))?!0:(Yn(e),Ea(e,"SIGKILL"),Fa(e,1e3))}function Ea(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ce(e.pid))return;Yn(e)}try{process.kill(e.pid,t)}catch{}}async function Fa(e,t){let n=S()+t;for(;S()<n;){if(Da(e))return!0;await mp(50)}return Da(e)}function Yn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=ue(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Ie(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Da(e){if(!ce(e.pid))return!0;if(!e.processIdentity)return!1;let t=ue(e.pid);return t!==null&&!Ie(e.processIdentity,t)}function mp(e){return new Promise(t=>setTimeout(t,e))}function Ba(e,t,n){return Object.fromEntries(t.map(r=>{let i=Ke(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:sr(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?hp(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&yp(n),...o,clojureConfigPath:a,files:We(e,{language:r,markerFiles:i})}]}))}function hp(e){return e?.trim()||void 0}function yp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Xn(e,t){return F(y(e),"language-indexes",`${t}.scip`)}function Ua(e){return F(y(e),"language-indexes","typescript-projects")}function xt(e,t){return F(Ua(e),`${an(t)}.scip`)}function Ne(e){try{return Pt(z(E(e,"reindex metadata")))}catch{return null}}function Wa(e,t){try{let n=z(E(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&q(r.fingerprint)===q(t)&&q([...r.indexedLanguages??[]].sort())===q(t.languages)}catch{return!1}}function Qn(e,t){O(e,t,{spacing:2,trailingNewline:!0})}function qa(e,t){try{let n=Pt(z(E(e,"reindex metadata")));if(!n)return;Qn(e,{...n,lastRefresh:t})}catch{}}function It(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:S()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function q(e){return JSON.stringify(e)}export{Zr as INDEXER_CONFIGS,Mr as augmentAuxiliaryDocuments,ll as augmentVueResolvedReferences,pl as augmentVueResolvedReferencesAsync,J as auxiliaryDocumentsAugmentationStage,xe as describeIndexerBinary,zt as detectLanguages,Ke as getIndexerConfig,At as getIndexerExecutionEnv,Et as isBinaryAvailable,Ft as isIndexerInstalled,Zt as mergeScipFiles,Qt as mergeScipIndexes,Bh as reindex,se as resolveIndexerBinary,Dt as resolveProjectLocalIndexerBinary,V as runPostIndexAugmentation,Vn as tryInstallIndexer,Gt as tryInstallScipCli,Sa as vueResolvedReferencesAugmentationStage};
303
299
  //# sourceMappingURL=reindex.js.map