@terra-symposium/hygiene 0.0.0-stage → 2.4.5

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 (349) hide show
  1. package/README.md +70 -2
  2. package/dist/accessibility.d.ts +39 -0
  3. package/dist/accessibility.d.ts.map +1 -0
  4. package/dist/accessibility.js +524 -0
  5. package/dist/accessibility.js.map +1 -0
  6. package/dist/app/workspace-test-runner.d.ts +6 -0
  7. package/dist/app/workspace-test-runner.d.ts.map +1 -0
  8. package/dist/app/workspace-test-runner.js +39 -0
  9. package/dist/app/workspace-test-runner.js.map +1 -0
  10. package/dist/capabilities/core/analysis.d.ts +22 -0
  11. package/dist/capabilities/core/analysis.d.ts.map +1 -0
  12. package/dist/capabilities/core/analysis.js +44 -0
  13. package/dist/capabilities/core/analysis.js.map +1 -0
  14. package/dist/capabilities/core/cli.d.ts +19 -0
  15. package/dist/capabilities/core/cli.d.ts.map +1 -0
  16. package/dist/capabilities/core/cli.js +58 -0
  17. package/dist/capabilities/core/cli.js.map +1 -0
  18. package/dist/capabilities/core/config.d.ts +49 -0
  19. package/dist/capabilities/core/config.d.ts.map +1 -0
  20. package/dist/capabilities/core/config.js +88 -0
  21. package/dist/capabilities/core/config.js.map +1 -0
  22. package/dist/capabilities/core/index.d.ts +11 -0
  23. package/dist/capabilities/core/index.d.ts.map +1 -0
  24. package/dist/capabilities/core/index.js +11 -0
  25. package/dist/capabilities/core/index.js.map +1 -0
  26. package/dist/capabilities/core/lib/files.d.ts +55 -0
  27. package/dist/capabilities/core/lib/files.d.ts.map +1 -0
  28. package/dist/capabilities/core/lib/files.js +287 -0
  29. package/dist/capabilities/core/lib/files.js.map +1 -0
  30. package/dist/capabilities/core/lib/progress.d.ts +25 -0
  31. package/dist/capabilities/core/lib/progress.d.ts.map +1 -0
  32. package/dist/capabilities/core/lib/progress.js +40 -0
  33. package/dist/capabilities/core/lib/progress.js.map +1 -0
  34. package/dist/capabilities/core/lib/source-kind.d.ts +14 -0
  35. package/dist/capabilities/core/lib/source-kind.d.ts.map +1 -0
  36. package/dist/capabilities/core/lib/source-kind.js +29 -0
  37. package/dist/capabilities/core/lib/source-kind.js.map +1 -0
  38. package/dist/capabilities/core/types.d.ts +156 -0
  39. package/dist/capabilities/core/types.d.ts.map +1 -0
  40. package/dist/capabilities/core/types.js +35 -0
  41. package/dist/capabilities/core/types.js.map +1 -0
  42. package/dist/capabilities/documentation/cli.d.ts +3 -0
  43. package/dist/capabilities/documentation/cli.d.ts.map +1 -0
  44. package/dist/capabilities/documentation/cli.js +14 -0
  45. package/dist/capabilities/documentation/cli.js.map +1 -0
  46. package/dist/capabilities/documentation/index.d.ts +5 -0
  47. package/dist/capabilities/documentation/index.d.ts.map +1 -0
  48. package/dist/capabilities/documentation/index.js +5 -0
  49. package/dist/capabilities/documentation/index.js.map +1 -0
  50. package/dist/capabilities/documentation/lib/documentation.d.ts +108 -0
  51. package/dist/capabilities/documentation/lib/documentation.d.ts.map +1 -0
  52. package/dist/capabilities/documentation/lib/documentation.js +1007 -0
  53. package/dist/capabilities/documentation/lib/documentation.js.map +1 -0
  54. package/dist/capabilities/formatting/cli.d.ts +3 -0
  55. package/dist/capabilities/formatting/cli.d.ts.map +1 -0
  56. package/dist/capabilities/formatting/cli.js +15 -0
  57. package/dist/capabilities/formatting/cli.js.map +1 -0
  58. package/dist/capabilities/formatting/index.d.ts +8 -0
  59. package/dist/capabilities/formatting/index.d.ts.map +1 -0
  60. package/dist/capabilities/formatting/index.js +8 -0
  61. package/dist/capabilities/formatting/index.js.map +1 -0
  62. package/dist/capabilities/formatting/lib/collapse.d.ts +13 -0
  63. package/dist/capabilities/formatting/lib/collapse.d.ts.map +1 -0
  64. package/dist/capabilities/formatting/lib/collapse.js +179 -0
  65. package/dist/capabilities/formatting/lib/collapse.js.map +1 -0
  66. package/dist/capabilities/formatting/lib/inline-if.d.ts +13 -0
  67. package/dist/capabilities/formatting/lib/inline-if.d.ts.map +1 -0
  68. package/dist/capabilities/formatting/lib/inline-if.js +49 -0
  69. package/dist/capabilities/formatting/lib/inline-if.js.map +1 -0
  70. package/dist/capabilities/formatting/lib/run-formatting.d.ts +14 -0
  71. package/dist/capabilities/formatting/lib/run-formatting.d.ts.map +1 -0
  72. package/dist/capabilities/formatting/lib/run-formatting.js +134 -0
  73. package/dist/capabilities/formatting/lib/run-formatting.js.map +1 -0
  74. package/dist/capabilities/imports/cli.d.ts +3 -0
  75. package/dist/capabilities/imports/cli.d.ts.map +1 -0
  76. package/dist/capabilities/imports/cli.js +9 -0
  77. package/dist/capabilities/imports/cli.js.map +1 -0
  78. package/dist/capabilities/imports/index.d.ts +6 -0
  79. package/dist/capabilities/imports/index.d.ts.map +1 -0
  80. package/dist/capabilities/imports/index.js +6 -0
  81. package/dist/capabilities/imports/index.js.map +1 -0
  82. package/dist/capabilities/imports/lib/imports.d.ts +19 -0
  83. package/dist/capabilities/imports/lib/imports.d.ts.map +1 -0
  84. package/dist/capabilities/imports/lib/imports.js +88 -0
  85. package/dist/capabilities/imports/lib/imports.js.map +1 -0
  86. package/dist/capabilities/languages/cli.d.ts +3 -0
  87. package/dist/capabilities/languages/cli.d.ts.map +1 -0
  88. package/dist/capabilities/languages/cli.js +9 -0
  89. package/dist/capabilities/languages/cli.js.map +1 -0
  90. package/dist/capabilities/languages/index.d.ts +6 -0
  91. package/dist/capabilities/languages/index.d.ts.map +1 -0
  92. package/dist/capabilities/languages/index.js +6 -0
  93. package/dist/capabilities/languages/index.js.map +1 -0
  94. package/dist/capabilities/languages/lib/language-profiles.d.ts +110 -0
  95. package/dist/capabilities/languages/lib/language-profiles.d.ts.map +1 -0
  96. package/dist/capabilities/languages/lib/language-profiles.js +509 -0
  97. package/dist/capabilities/languages/lib/language-profiles.js.map +1 -0
  98. package/dist/capabilities/languages/lib/run-language-checks.d.ts +12 -0
  99. package/dist/capabilities/languages/lib/run-language-checks.d.ts.map +1 -0
  100. package/dist/capabilities/languages/lib/run-language-checks.js +109 -0
  101. package/dist/capabilities/languages/lib/run-language-checks.js.map +1 -0
  102. package/dist/capabilities/naming/cli.d.ts +3 -0
  103. package/dist/capabilities/naming/cli.d.ts.map +1 -0
  104. package/dist/capabilities/naming/cli.js +15 -0
  105. package/dist/capabilities/naming/cli.js.map +1 -0
  106. package/dist/capabilities/naming/index.d.ts +5 -0
  107. package/dist/capabilities/naming/index.d.ts.map +1 -0
  108. package/dist/capabilities/naming/index.js +5 -0
  109. package/dist/capabilities/naming/index.js.map +1 -0
  110. package/dist/capabilities/naming/lib/naming.d.ts +169 -0
  111. package/dist/capabilities/naming/lib/naming.d.ts.map +1 -0
  112. package/dist/capabilities/naming/lib/naming.js +908 -0
  113. package/dist/capabilities/naming/lib/naming.js.map +1 -0
  114. package/dist/capabilities/patterns/cli.d.ts +3 -0
  115. package/dist/capabilities/patterns/cli.d.ts.map +1 -0
  116. package/dist/capabilities/patterns/cli.js +30 -0
  117. package/dist/capabilities/patterns/cli.js.map +1 -0
  118. package/dist/capabilities/patterns/index.d.ts +5 -0
  119. package/dist/capabilities/patterns/index.d.ts.map +1 -0
  120. package/dist/capabilities/patterns/index.js +5 -0
  121. package/dist/capabilities/patterns/index.js.map +1 -0
  122. package/dist/capabilities/patterns/lib/patterns.d.ts +102 -0
  123. package/dist/capabilities/patterns/lib/patterns.d.ts.map +1 -0
  124. package/dist/capabilities/patterns/lib/patterns.js +1584 -0
  125. package/dist/capabilities/patterns/lib/patterns.js.map +1 -0
  126. package/dist/capabilities/refactoring/cli.d.ts +3 -0
  127. package/dist/capabilities/refactoring/cli.d.ts.map +1 -0
  128. package/dist/capabilities/refactoring/cli.js +15 -0
  129. package/dist/capabilities/refactoring/cli.js.map +1 -0
  130. package/dist/capabilities/refactoring/index.d.ts +6 -0
  131. package/dist/capabilities/refactoring/index.d.ts.map +1 -0
  132. package/dist/capabilities/refactoring/index.js +6 -0
  133. package/dist/capabilities/refactoring/index.js.map +1 -0
  134. package/dist/capabilities/refactoring/lib/object-forwarding.d.ts +42 -0
  135. package/dist/capabilities/refactoring/lib/object-forwarding.d.ts.map +1 -0
  136. package/dist/capabilities/refactoring/lib/object-forwarding.js +166 -0
  137. package/dist/capabilities/refactoring/lib/object-forwarding.js.map +1 -0
  138. package/dist/capabilities/refactoring/lib/single-use.d.ts +61 -0
  139. package/dist/capabilities/refactoring/lib/single-use.d.ts.map +1 -0
  140. package/dist/capabilities/refactoring/lib/single-use.js +1791 -0
  141. package/dist/capabilities/refactoring/lib/single-use.js.map +1 -0
  142. package/dist/capabilities/reports/cli.d.ts +3 -0
  143. package/dist/capabilities/reports/cli.d.ts.map +1 -0
  144. package/dist/capabilities/reports/cli.js +34 -0
  145. package/dist/capabilities/reports/cli.js.map +1 -0
  146. package/dist/capabilities/reports/index.d.ts +10 -0
  147. package/dist/capabilities/reports/index.d.ts.map +1 -0
  148. package/dist/capabilities/reports/index.js +10 -0
  149. package/dist/capabilities/reports/index.js.map +1 -0
  150. package/dist/capabilities/reports/lib/github-report.d.ts +94 -0
  151. package/dist/capabilities/reports/lib/github-report.d.ts.map +1 -0
  152. package/dist/capabilities/reports/lib/github-report.js +499 -0
  153. package/dist/capabilities/reports/lib/github-report.js.map +1 -0
  154. package/dist/capabilities/reports/lib/history-report.d.ts +58 -0
  155. package/dist/capabilities/reports/lib/history-report.d.ts.map +1 -0
  156. package/dist/capabilities/reports/lib/history-report.js +300 -0
  157. package/dist/capabilities/reports/lib/history-report.js.map +1 -0
  158. package/dist/capabilities/reports/lib/node-reporter.d.ts +79 -0
  159. package/dist/capabilities/reports/lib/node-reporter.d.ts.map +1 -0
  160. package/dist/capabilities/reports/lib/node-reporter.js +244 -0
  161. package/dist/capabilities/reports/lib/node-reporter.js.map +1 -0
  162. package/dist/capabilities/reports/lib/playwright-reporter.d.ts +100 -0
  163. package/dist/capabilities/reports/lib/playwright-reporter.d.ts.map +1 -0
  164. package/dist/capabilities/reports/lib/playwright-reporter.js +122 -0
  165. package/dist/capabilities/reports/lib/playwright-reporter.js.map +1 -0
  166. package/dist/capabilities/security/cli.d.ts +3 -0
  167. package/dist/capabilities/security/cli.d.ts.map +1 -0
  168. package/dist/capabilities/security/cli.js +9 -0
  169. package/dist/capabilities/security/cli.js.map +1 -0
  170. package/dist/capabilities/security/index.d.ts +5 -0
  171. package/dist/capabilities/security/index.d.ts.map +1 -0
  172. package/dist/capabilities/security/index.js +5 -0
  173. package/dist/capabilities/security/index.js.map +1 -0
  174. package/dist/capabilities/security/lib/security.d.ts +19 -0
  175. package/dist/capabilities/security/lib/security.d.ts.map +1 -0
  176. package/dist/capabilities/security/lib/security.js +115 -0
  177. package/dist/capabilities/security/lib/security.js.map +1 -0
  178. package/dist/capabilities/ui/cli.d.ts +3 -0
  179. package/dist/capabilities/ui/cli.d.ts.map +1 -0
  180. package/dist/capabilities/ui/cli.js +22 -0
  181. package/dist/capabilities/ui/cli.js.map +1 -0
  182. package/dist/capabilities/ui/index.d.ts +8 -0
  183. package/dist/capabilities/ui/index.d.ts.map +1 -0
  184. package/dist/capabilities/ui/index.js +8 -0
  185. package/dist/capabilities/ui/index.js.map +1 -0
  186. package/dist/capabilities/ui/lib/accessibility.d.ts +37 -0
  187. package/dist/capabilities/ui/lib/accessibility.d.ts.map +1 -0
  188. package/dist/capabilities/ui/lib/accessibility.js +676 -0
  189. package/dist/capabilities/ui/lib/accessibility.js.map +1 -0
  190. package/dist/capabilities/ui/lib/display-name.d.ts +42 -0
  191. package/dist/capabilities/ui/lib/display-name.d.ts.map +1 -0
  192. package/dist/capabilities/ui/lib/display-name.js +277 -0
  193. package/dist/capabilities/ui/lib/display-name.js.map +1 -0
  194. package/dist/capabilities/ui/lib/error-boundaries.d.ts +30 -0
  195. package/dist/capabilities/ui/lib/error-boundaries.d.ts.map +1 -0
  196. package/dist/capabilities/ui/lib/error-boundaries.js +401 -0
  197. package/dist/capabilities/ui/lib/error-boundaries.js.map +1 -0
  198. package/dist/capabilities/ui/lib/ui-recommendations.d.ts +45 -0
  199. package/dist/capabilities/ui/lib/ui-recommendations.d.ts.map +1 -0
  200. package/dist/capabilities/ui/lib/ui-recommendations.js +183 -0
  201. package/dist/capabilities/ui/lib/ui-recommendations.js.map +1 -0
  202. package/dist/display-name.d.ts +44 -0
  203. package/dist/display-name.d.ts.map +1 -0
  204. package/dist/display-name.js +256 -0
  205. package/dist/display-name.js.map +1 -0
  206. package/dist/index.d.ts +5 -0
  207. package/dist/index.d.ts.map +1 -0
  208. package/dist/index.js +5 -0
  209. package/dist/index.js.map +1 -0
  210. package/dist/lib/accessibility.d.ts +5 -0
  211. package/dist/lib/accessibility.d.ts.map +1 -0
  212. package/dist/lib/accessibility.js +5 -0
  213. package/dist/lib/accessibility.js.map +1 -0
  214. package/dist/lib/collapse.d.ts +5 -0
  215. package/dist/lib/collapse.d.ts.map +1 -0
  216. package/dist/lib/collapse.js +5 -0
  217. package/dist/lib/collapse.js.map +1 -0
  218. package/dist/lib/dev.d.ts +3 -0
  219. package/dist/lib/dev.d.ts.map +1 -0
  220. package/dist/lib/dev.js +126 -0
  221. package/dist/lib/dev.js.map +1 -0
  222. package/dist/lib/display-name.d.ts +5 -0
  223. package/dist/lib/display-name.d.ts.map +1 -0
  224. package/dist/lib/display-name.js +5 -0
  225. package/dist/lib/display-name.js.map +1 -0
  226. package/dist/lib/documentation.d.ts +5 -0
  227. package/dist/lib/documentation.d.ts.map +1 -0
  228. package/dist/lib/documentation.js +5 -0
  229. package/dist/lib/documentation.js.map +1 -0
  230. package/dist/lib/error-boundaries-astro.d.ts +6 -0
  231. package/dist/lib/error-boundaries-astro.d.ts.map +1 -0
  232. package/dist/lib/error-boundaries-astro.js +6 -0
  233. package/dist/lib/error-boundaries-astro.js.map +1 -0
  234. package/dist/lib/error-boundaries-react.d.ts +6 -0
  235. package/dist/lib/error-boundaries-react.d.ts.map +1 -0
  236. package/dist/lib/error-boundaries-react.js +6 -0
  237. package/dist/lib/error-boundaries-react.js.map +1 -0
  238. package/dist/lib/error-boundaries.d.ts +5 -0
  239. package/dist/lib/error-boundaries.d.ts.map +1 -0
  240. package/dist/lib/error-boundaries.js +5 -0
  241. package/dist/lib/error-boundaries.js.map +1 -0
  242. package/dist/lib/eslint-api.d.ts +13 -0
  243. package/dist/lib/eslint-api.d.ts.map +1 -0
  244. package/dist/lib/eslint-api.js +24 -0
  245. package/dist/lib/eslint-api.js.map +1 -0
  246. package/dist/lib/files.d.ts +5 -0
  247. package/dist/lib/files.d.ts.map +1 -0
  248. package/dist/lib/files.js +5 -0
  249. package/dist/lib/files.js.map +1 -0
  250. package/dist/lib/formatting.d.ts +5 -0
  251. package/dist/lib/formatting.d.ts.map +1 -0
  252. package/dist/lib/formatting.js +5 -0
  253. package/dist/lib/formatting.js.map +1 -0
  254. package/dist/lib/github-report.d.ts +5 -0
  255. package/dist/lib/github-report.d.ts.map +1 -0
  256. package/dist/lib/github-report.js +5 -0
  257. package/dist/lib/github-report.js.map +1 -0
  258. package/dist/lib/history-report.d.ts +5 -0
  259. package/dist/lib/history-report.d.ts.map +1 -0
  260. package/dist/lib/history-report.js +5 -0
  261. package/dist/lib/history-report.js.map +1 -0
  262. package/dist/lib/imports.d.ts +5 -0
  263. package/dist/lib/imports.d.ts.map +1 -0
  264. package/dist/lib/imports.js +5 -0
  265. package/dist/lib/imports.js.map +1 -0
  266. package/dist/lib/index.d.ts +20 -0
  267. package/dist/lib/index.d.ts.map +1 -0
  268. package/dist/lib/index.js +20 -0
  269. package/dist/lib/index.js.map +1 -0
  270. package/dist/lib/inline-if.d.ts +5 -0
  271. package/dist/lib/inline-if.d.ts.map +1 -0
  272. package/dist/lib/inline-if.js +5 -0
  273. package/dist/lib/inline-if.js.map +1 -0
  274. package/dist/lib/language-checks.d.ts +5 -0
  275. package/dist/lib/language-checks.d.ts.map +1 -0
  276. package/dist/lib/language-checks.js +5 -0
  277. package/dist/lib/language-checks.js.map +1 -0
  278. package/dist/lib/language-profiles.d.ts +5 -0
  279. package/dist/lib/language-profiles.d.ts.map +1 -0
  280. package/dist/lib/language-profiles.js +5 -0
  281. package/dist/lib/language-profiles.js.map +1 -0
  282. package/dist/lib/naming.d.ts +5 -0
  283. package/dist/lib/naming.d.ts.map +1 -0
  284. package/dist/lib/naming.js +5 -0
  285. package/dist/lib/naming.js.map +1 -0
  286. package/dist/lib/node-reporter.d.ts +6 -0
  287. package/dist/lib/node-reporter.d.ts.map +1 -0
  288. package/dist/lib/node-reporter.js +6 -0
  289. package/dist/lib/node-reporter.js.map +1 -0
  290. package/dist/lib/object-forwarding.d.ts +5 -0
  291. package/dist/lib/object-forwarding.d.ts.map +1 -0
  292. package/dist/lib/object-forwarding.js +5 -0
  293. package/dist/lib/object-forwarding.js.map +1 -0
  294. package/dist/lib/patterns.d.ts +5 -0
  295. package/dist/lib/patterns.d.ts.map +1 -0
  296. package/dist/lib/patterns.js +5 -0
  297. package/dist/lib/patterns.js.map +1 -0
  298. package/dist/lib/playwright-reporter.d.ts +6 -0
  299. package/dist/lib/playwright-reporter.d.ts.map +1 -0
  300. package/dist/lib/playwright-reporter.js +6 -0
  301. package/dist/lib/playwright-reporter.js.map +1 -0
  302. package/dist/lib/port.d.ts +21 -0
  303. package/dist/lib/port.d.ts.map +1 -0
  304. package/dist/lib/port.js +81 -0
  305. package/dist/lib/port.js.map +1 -0
  306. package/dist/lib/progress.d.ts +5 -0
  307. package/dist/lib/progress.d.ts.map +1 -0
  308. package/dist/lib/progress.js +5 -0
  309. package/dist/lib/progress.js.map +1 -0
  310. package/dist/lib/reports.d.ts +5 -0
  311. package/dist/lib/reports.d.ts.map +1 -0
  312. package/dist/lib/reports.js +5 -0
  313. package/dist/lib/reports.js.map +1 -0
  314. package/dist/lib/runner.d.ts +150 -0
  315. package/dist/lib/runner.d.ts.map +1 -0
  316. package/dist/lib/runner.js +4522 -0
  317. package/dist/lib/runner.js.map +1 -0
  318. package/dist/lib/security.d.ts +5 -0
  319. package/dist/lib/security.d.ts.map +1 -0
  320. package/dist/lib/security.js +5 -0
  321. package/dist/lib/security.js.map +1 -0
  322. package/dist/lib/single-use.d.ts +6 -0
  323. package/dist/lib/single-use.d.ts.map +1 -0
  324. package/dist/lib/single-use.js +5 -0
  325. package/dist/lib/single-use.js.map +1 -0
  326. package/dist/lib/source-kind.d.ts +5 -0
  327. package/dist/lib/source-kind.d.ts.map +1 -0
  328. package/dist/lib/source-kind.js +5 -0
  329. package/dist/lib/source-kind.js.map +1 -0
  330. package/dist/lib/spinner-worker.d.ts +6 -0
  331. package/dist/lib/spinner-worker.d.ts.map +1 -0
  332. package/dist/lib/spinner-worker.js +33 -0
  333. package/dist/lib/spinner-worker.js.map +1 -0
  334. package/dist/lib/ui-quality.d.ts +5 -0
  335. package/dist/lib/ui-quality.d.ts.map +1 -0
  336. package/dist/lib/ui-quality.js +5 -0
  337. package/dist/lib/ui-quality.js.map +1 -0
  338. package/dist/lib/ui-recommendations.d.ts +5 -0
  339. package/dist/lib/ui-recommendations.d.ts.map +1 -0
  340. package/dist/lib/ui-recommendations.js +5 -0
  341. package/dist/lib/ui-recommendations.js.map +1 -0
  342. package/dist/spinner-worker.d.ts +6 -0
  343. package/dist/spinner-worker.d.ts.map +1 -0
  344. package/dist/spinner-worker.js +39 -0
  345. package/dist/spinner-worker.js.map +1 -0
  346. package/package.json +160 -5
  347. package/quality-configs/checkstyle.xml +29 -0
  348. package/quality-configs/pmd-rules.xml +11 -0
  349. package/quality.schema.json +392 -0
@@ -0,0 +1,1791 @@
1
+ /**
2
+ * packages/hygiene/src/lib/single-use.ts
3
+ * AST inventory and safe autofix for single-consumer declarations (types, and helpers).
4
+ */
5
+ /*//////////////////////////////////////////////////
6
+ IMPORTS
7
+ //////////////////////////////////////////////////*/
8
+ // API
9
+ import ts from 'typescript';
10
+ import { basename, dirname, join, normalize, relative, resolve, sep } from 'node:path';
11
+ import { hasGeneratedSourceHeader, qualityProgress, srcFiles } from '@terra-symposium/hygiene/core';
12
+ import { readFileSync, statSync, writeFileSync } from 'node:fs';
13
+ const S_U_REGEX = /^\s*$/u;
14
+ const S_S_W_CM_JT_SX_B_REGEX = /^\/\*\*\s*(?:\*\s*)?[\w./-]+\.[cm]?[jt]sx?\b/;
15
+ const PLAYWRIGHT_QUERY_METHODS = new Set([
16
+ 'first',
17
+ 'frameLocator',
18
+ 'getByAltText',
19
+ 'getByDisplayValue',
20
+ 'getByLabel',
21
+ 'getByPlaceholder',
22
+ 'getByRole',
23
+ 'getByTestId',
24
+ 'getByText',
25
+ 'getByTitle',
26
+ 'last',
27
+ 'locator',
28
+ 'nth',
29
+ 'filter',
30
+ ]);
31
+ const REPEATED_CALLBACK_METHODS = new Set(['every', 'filter', 'find', 'findIndex', 'findLast', 'findLastIndex', 'flatMap', 'forEach', 'map', 'reduce', 'reduceRight', 'some', 'sort']);
32
+ /*//////////////////////////////////////////////////
33
+ REGEX
34
+ //////////////////////////////////////////////////*/
35
+ const S_REGEX = /^\s*$/;
36
+ const C_M_JS_JSX_TS_TSX_REGEX = /\.(?:c|m)?(?:js|jsx|ts|tsx)$/;
37
+ /*//////////////////////////////////////////////////
38
+ HELPERS
39
+ //////////////////////////////////////////////////*/
40
+ /** Reports progress at the start, end, and roughly twenty evenly spaced points of an analysis pass.
41
+ *
42
+ * @param label Name of the analysis phase shown to the user.
43
+ * @param idx Number of completed items in the current phase.
44
+ * @param total Total items scheduled for the current phase.
45
+ */
46
+ const reportProgress = (label, idx, total) => {
47
+ if (idx === 0 || idx === total || idx % Math.max(1, Math.ceil(total / 20)) === 0)
48
+ qualityProgress(label, idx, total);
49
+ };
50
+ /**
51
+ * Detects authored TSDoc that the single-use fixer must preserve for agent review.
52
+ *
53
+ * @param candidate Declaration whose leading comments are inspected.
54
+ *
55
+ * @return Whether the candidate has authored TSDoc rather than a generated path comment.
56
+ */
57
+ const hasMeaningfulLeadingTSDoc = (candidate) => (ts.getLeadingCommentRanges(candidate.source.text, candidate.statement.getFullStart()) ?? []).some(range => {
58
+ const comment = candidate.source.text.slice(range.pos, range.end);
59
+ return comment.startsWith('/**') && !S_S_W_CM_JT_SX_B_REGEX.test(comment);
60
+ });
61
+ const SINGLE_USE_IGNORE_PREFIX_REGEX = /^\/\/\s*hygiene-ignore\s+single-use\b/;
62
+ const SINGLE_USE_IGNORE_DOC_GAP_REGEX = /^[ \t]*\r?\n[ \t]*\/\*\*[\s\S]*?\*\/[ \t]*\r?\n[ \t]*$/;
63
+ const rejectedInlineCandidates = new Map();
64
+ const astroConsumerCache = new WeakMap();
65
+ const repeatedCallbackOwnerCache = new WeakMap();
66
+ const dynamicScopeCache = new WeakMap();
67
+ /**
68
+ * Resolves alias symbols before candidate/reference identity comparisons.
69
+ *
70
+ * @param c Type checker that can follow symbol aliases.
71
+ * @param s Symbol to canonicalize, when one was found.
72
+ *
73
+ * @return Target symbol for aliases, the original symbol, or `undefined`.
74
+ */
75
+ const canonical = (c, s) => (s && s.flags & ts.SymbolFlags.Alias ? c.getAliasedSymbol(s) : s);
76
+ /**
77
+ * Checks whether a syntax node is part of an import declaration.
78
+ *
79
+ * @param n Node whose containing source is inspected.
80
+ *
81
+ * @return Whether the node appears within an import statement.
82
+ */
83
+ const isImportNode = (n) => {
84
+ const src = n.getSourceFile();
85
+ if (src.statements.some(s => ts.isImportDeclaration(s) && n.getStart(src) >= s.getStart(src) && n.getEnd() <= s.getEnd()))
86
+ return true;
87
+ for (let parent = n.parent; parent && !ts.isSourceFile(parent); parent = parent.parent)
88
+ if (ts.isImportDeclaration(parent))
89
+ return true;
90
+ return false;
91
+ };
92
+ /**
93
+ * Resolves reasoned single-use exceptions beside one declaration.
94
+ *
95
+ * @param cfg Quality configuration defining the in-scope source roots.
96
+ * @param srcs TypeScript source files from the current analysis program.
97
+ * @param candidates Eligible declarations which may receive a directive.
98
+ *
99
+ * @return Every marker and the declaration it protects, when present.
100
+ */
101
+ function singleUseIgnoreDirectives(cfg, srcs, candidates) {
102
+ const directives = [];
103
+ const byCandidate = new Map();
104
+ for (const src of srcs) {
105
+ if (src.isDeclarationFile || !inSingleUseScope(cfg, src.fileName))
106
+ continue;
107
+ const comments = new Map();
108
+ const nodes = [src];
109
+ while (nodes.length) {
110
+ const node = nodes.pop();
111
+ for (const range of [...(ts.getLeadingCommentRanges(src.text, node.getFullStart()) ?? []), ...(ts.getTrailingCommentRanges(src.text, node.getEnd()) ?? [])])
112
+ if (range.kind === ts.SyntaxKind.SingleLineCommentTrivia)
113
+ comments.set(range.pos, range);
114
+ node.forEachChild(child => {
115
+ nodes.push(child);
116
+ });
117
+ }
118
+ for (const range of [...comments.values()].sort((left, right) => left.pos - right.pos)) {
119
+ if (!SINGLE_USE_IGNORE_PREFIX_REGEX.test(src.text.slice(range.pos, range.end)))
120
+ continue;
121
+ const start = range.pos;
122
+ const line = src.getLineAndCharacterOfPosition(start).line + 1;
123
+ const attached = candidates.find(candidate => {
124
+ if (candidate.source !== src)
125
+ return false;
126
+ return ((range.end <= candidate.statement.getStart(src) &&
127
+ ((src.getLineAndCharacterOfPosition(candidate.statement.getStart(src)).line + 1 === line + 1 && S_REGEX.test(src.text.slice(range.end, candidate.statement.getStart(src)))) ||
128
+ SINGLE_USE_IGNORE_DOC_GAP_REGEX.test(src.text.slice(range.end, candidate.statement.getStart(src))))) ||
129
+ (src.getLineAndCharacterOfPosition(candidate.statement.getEnd()).line + 1 === line &&
130
+ candidate.statement.getEnd() <= start &&
131
+ S_REGEX.test(src.text.slice(candidate.statement.getEnd(), start))));
132
+ });
133
+ const candidateKey = attached ? `${attached.file}:${attached.name.getStart(attached.source)}` : undefined;
134
+ const directive = { source: src, line, reason: /^\/\/\s*hygiene-ignore\s+single-use\s+--\s*(\S.*)$/.exec(src.text.slice(range.pos, range.end))?.[1]?.trim(), candidateKey };
135
+ directives.push(directive);
136
+ if (candidateKey && !byCandidate.has(candidateKey))
137
+ byCandidate.set(candidateKey, directive);
138
+ }
139
+ }
140
+ return { directives, byCandidate };
141
+ }
142
+ /**
143
+ * Reports an invalid, detached, duplicate, or stale single-use exception.
144
+ *
145
+ * @param cfg Quality configuration defining repository-relative paths.
146
+ * @param directive Inline single-use marker to report.
147
+ *
148
+ * @return A blocking finding that requires the marker to be corrected or removed.
149
+ */
150
+ function singleUseDirectiveFinding(cfg, directive) {
151
+ return {
152
+ file: relative(cfg.root, directive.source.fileName),
153
+ line: directive.line,
154
+ name: 'single-use-ignore',
155
+ decision: 'REVIEW',
156
+ autofixable: false,
157
+ reason: !directive.reason
158
+ ? 'single-use ignore markers require a concrete reason after --'
159
+ : !directive.candidateKey
160
+ ? 'single-use ignore marker must be immediately before or after one declaration'
161
+ : 'single-use ignore marker is stale or duplicated; its declaration has no matching single-use finding',
162
+ agentAction: 'Attach the marker to one declaration with a concrete reason, or remove it when the declaration no longer has one in-scope consumer.',
163
+ };
164
+ }
165
+ /**
166
+ * Creates the TypeScript program used to identify declarations and their consumers.
167
+ *
168
+ * @param cfg Quality configuration defining the source files to include.
169
+ *
170
+ * @return TypeScript program configured for repository JavaScript and TypeScript sources.
171
+ */
172
+ function programFor(cfg) {
173
+ return ts.createProgram({
174
+ rootNames: srcFiles(cfg).filter(f => C_M_JS_JSX_TS_TSX_REGEX.test(f)),
175
+ options: {
176
+ allowJs: true,
177
+ baseUrl: cfg.root,
178
+ checkJs: false,
179
+ jsx: ts.JsxEmit.Preserve,
180
+ module: ts.ModuleKind.ESNext,
181
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
182
+ paths: Object.fromEntries(Object.entries(cfg.aliases ?? {}).map(([p, t]) => [p.endsWith('*') ? p : `${p}*`, [t.endsWith('*') ? t : `${t}*`]])),
183
+ skipLibCheck: true,
184
+ target: ts.ScriptTarget.ESNext,
185
+ },
186
+ });
187
+ }
188
+ /**
189
+ * Creates the shared TypeScript program used to validate a complete dead-code edit batch.
190
+ *
191
+ * @param cfg Quality configuration defining the source roots and compiler settings.
192
+ *
193
+ * @return TypeScript program used to inspect and validate the configured source files.
194
+ */
195
+ export function deadCodeTypeProgram(cfg) {
196
+ return programFor(cfg);
197
+ }
198
+ /**
199
+ * Checks the single-use-specific scope without changing other quality checks.
200
+ *
201
+ * @param cfg Quality configuration containing source roots.
202
+ * @param file Absolute source path being considered.
203
+ *
204
+ * @return `true` when the file is in scope for the single-use rule.
205
+ */
206
+ function inSingleUseScope(cfg, file) {
207
+ if (file.split(sep).some(part => part === 'node_modules' || part === '.pnpm'))
208
+ return false;
209
+ return [...cfg.sourceRoots, ...(cfg.includeRoots ?? [])].some(r => file === r || file.startsWith(`${r}${sep}`));
210
+ }
211
+ /**
212
+ * Collects eligible declarations and all non-import references to their symbols.
213
+ *
214
+ * @param cfg Quality configuration defining which source roots are in scope.
215
+ * @param program TypeScript program containing the source files to inspect.
216
+ * @param checker TypeScript type checker used to canonicalize aliases and references.
217
+ *
218
+ * @return Candidate declarations and references grouped by canonical symbol.
219
+ */
220
+ function collect(cfg, program, checker) {
221
+ const candidates = [];
222
+ const declarationByLocation = new Map();
223
+ const refs = new Map();
224
+ const scopedSrcs = program.getSourceFiles().filter(src => {
225
+ if (src.isDeclarationFile || !C_M_JS_JSX_TS_TSX_REGEX.test(src.fileName) || !inSingleUseScope(cfg, src.fileName))
226
+ return false;
227
+ return !(cfg.singleUse?.skippedDirectories ?? []).some(skipped => {
228
+ const normalized = normalize(skipped.replaceAll('\\', '/'));
229
+ if (!normalized || normalized === '.')
230
+ return false;
231
+ if (!normalized.includes(sep))
232
+ return basename(src.fileName) === normalized || src.fileName.split(sep).includes(normalized);
233
+ const skippedPath = resolve(cfg.root, normalized);
234
+ return src.fileName === skippedPath || src.fileName.startsWith(`${skippedPath}${sep}`);
235
+ });
236
+ });
237
+ reportProgress('Single-use declaration scan:', 0, scopedSrcs.length);
238
+ for (const [sourceIndex, source] of scopedSrcs.entries()) {
239
+ reportProgress('Single-use declaration scan:', sourceIndex + 1, scopedSrcs.length);
240
+ const visitCandidates = (node) => {
241
+ const statement = node;
242
+ if ((ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some(m => m.kind === ts.SyntaxKind.DeclareKeyword)) ||
243
+ !(ts.isTypeAliasDeclaration(statement) ||
244
+ ts.isInterfaceDeclaration(statement) ||
245
+ (ts.isFunctionDeclaration(statement) && Boolean(statement.body)) ||
246
+ (ts.isVariableStatement(statement) && statement.declarationList.declarations.length === 1 && ts.isIdentifier(statement.declarationList.declarations[0]?.name)))) {
247
+ ts.forEachChild(node, visitCandidates);
248
+ return;
249
+ }
250
+ const name = ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isFunctionDeclaration(statement)
251
+ ? statement.name
252
+ : ts.isVariableStatement(statement)
253
+ ? statement.declarationList.declarations[0]?.name
254
+ : undefined;
255
+ if (!name || !ts.isIdentifier(name)) {
256
+ ts.forEachChild(node, visitCandidates);
257
+ return;
258
+ }
259
+ const symbol = canonical(checker, checker.getSymbolAtLocation(name));
260
+ if (!symbol) {
261
+ ts.forEachChild(node, visitCandidates);
262
+ return;
263
+ }
264
+ const candidate = {
265
+ file: source.fileName,
266
+ source,
267
+ statement,
268
+ name,
269
+ symbol,
270
+ kind: ts.isTypeAliasDeclaration(statement) ? 'type' : ts.isInterfaceDeclaration(statement) ? 'interface' : ts.isFunctionDeclaration(statement) ? 'function' : 'variable',
271
+ };
272
+ candidates.push(candidate);
273
+ declarationByLocation.set(`${source.fileName}:${name.getStart(source)}`, candidate);
274
+ ts.forEachChild(node, visitCandidates);
275
+ };
276
+ visitCandidates(source);
277
+ }
278
+ const candidateSymbols = new Set(candidates.map(c => c.symbol));
279
+ const refSrcs = program.getSourceFiles().filter(src => !src.isDeclarationFile && inSingleUseScope(cfg, src.fileName) && C_M_JS_JSX_TS_TSX_REGEX.test(src.fileName));
280
+ const requiredExports = new Map();
281
+ for (const src of refSrcs) {
282
+ const visitRequires = (node) => {
283
+ if (ts.isVariableDeclaration(node) &&
284
+ ts.isObjectBindingPattern(node.name) &&
285
+ node.initializer &&
286
+ ts.isCallExpression(node.initializer) &&
287
+ ts.isIdentifier(node.initializer.expression) &&
288
+ node.initializer.expression.text === 'require' &&
289
+ node.initializer.arguments.length === 1 &&
290
+ ts.isStringLiteral(node.initializer.arguments[0])) {
291
+ const moduleSrc = program.getSourceFile(ts.resolveModuleName(node.initializer.arguments[0].text, src.fileName, program.getCompilerOptions(), ts.sys).resolvedModule?.resolvedFileName ?? '');
292
+ const moduleSymbol = moduleSrc && checker.getSymbolAtLocation(moduleSrc);
293
+ if (moduleSymbol) {
294
+ for (const el of node.name.elements) {
295
+ if (!ts.isIdentifier(el.name) || el.dotDotDotToken)
296
+ continue;
297
+ const localSymbol = canonical(checker, checker.getSymbolAtLocation(el.name));
298
+ const exportSymbol = canonical(checker, checker
299
+ .getExportsOfModule(moduleSymbol)
300
+ .find(i => i.name === (el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : ts.isIdentifier(el.name) ? el.name.text : '')));
301
+ if (localSymbol && exportSymbol && candidateSymbols.has(exportSymbol))
302
+ requiredExports.set(localSymbol, exportSymbol);
303
+ }
304
+ }
305
+ }
306
+ ts.forEachChild(node, visitRequires);
307
+ };
308
+ visitRequires(src);
309
+ }
310
+ reportProgress('Single-use reference scan:', 0, refSrcs.length);
311
+ for (const [sourceIndex, src] of refSrcs.entries()) {
312
+ reportProgress('Single-use reference scan:', sourceIndex + 1, refSrcs.length);
313
+ const visit = (node) => {
314
+ if (ts.isIdentifier(node)) {
315
+ if (ts.isBindingElement(node.parent)) {
316
+ ts.forEachChild(node, visit);
317
+ return;
318
+ }
319
+ let importUse = false;
320
+ for (let parent = node.parent; parent && !ts.isSourceFile(parent); parent = parent.parent) {
321
+ if (ts.isImportDeclaration(parent)) {
322
+ importUse = true;
323
+ break;
324
+ }
325
+ }
326
+ const symbol = canonical(checker, (ts.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : undefined) ??
327
+ checker.getSymbolAtLocation(node) ??
328
+ (ts.isTypeQueryNode(node.parent) ? checker.getSymbolAtLocation(node.parent) : undefined));
329
+ const candidateSymbol = symbol && (candidateSymbols.has(symbol) ? symbol : requiredExports.get(symbol));
330
+ if (!importUse && candidateSymbol) {
331
+ if (!declarationByLocation.has(`${src.fileName}:${node.getStart(src)}`))
332
+ refs.set(candidateSymbol, [...(refs.get(candidateSymbol) ?? []), { file: src.fileName, source: src, node }]);
333
+ }
334
+ }
335
+ ts.forEachChild(node, visit);
336
+ };
337
+ visit(src);
338
+ }
339
+ return { candidates, references: refs };
340
+ }
341
+ /**
342
+ * Finds type-position references to a candidate declaration across the configured source scope.
343
+ *
344
+ * @param candidate Declaration whose references are being filtered.
345
+ * @param refs Resolved references grouped by declaration symbol.
346
+ *
347
+ * @return Type references excluding the declaration and import syntax itself.
348
+ */
349
+ function typeRefs(candidate, refs) {
350
+ return (refs.get(candidate.symbol) ?? []).filter(ref => {
351
+ const tgt = refTgt(ref.node);
352
+ return !isExportSpecifierRef(ref) && (ts.isTypeReferenceNode(tgt) || ts.isExpressionWithTypeArguments(tgt));
353
+ });
354
+ }
355
+ /**
356
+ * Collects Astro frontmatter and markup consumers once for an analysis run.
357
+ *
358
+ * @param cfg Quality configuration defining the files to inspect.
359
+ * @param program TypeScript program used to map declarations and imports.
360
+ *
361
+ * @return Source-and-name keys for declarations referenced from Astro files.
362
+ */
363
+ function astroConsumersFor(cfg, program) {
364
+ const astroFiles = srcFiles({ ...cfg, extensions: [...new Set([...cfg.extensions, '.astro'])] }).filter(path => path.endsWith('.astro'));
365
+ const signature = astroFiles
366
+ .map(f => {
367
+ const stats = statSync(f);
368
+ return `${f}:${stats.mtimeMs}:${stats.size}`;
369
+ })
370
+ .join('\n');
371
+ let cached = astroConsumerCache.get(cfg);
372
+ if (!cached || cached.signature !== signature) {
373
+ const consumers = new Set();
374
+ for (const f of astroFiles) {
375
+ const raw = readFileSync(f, 'utf8');
376
+ const match = /^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(raw);
377
+ if (!match)
378
+ continue;
379
+ const src = ts.createSourceFile(f, match[1], ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
380
+ for (const statement of src.statements) {
381
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
382
+ continue;
383
+ const bindings = statement.importClause?.namedBindings;
384
+ if (!bindings || !ts.isNamedImports(bindings))
385
+ continue;
386
+ const resolved = ts.resolveModuleName(statement.moduleSpecifier.text, f, program.getCompilerOptions(), ts.sys).resolvedModule?.resolvedFileName;
387
+ if (!resolved)
388
+ continue;
389
+ for (const imported of bindings.elements) {
390
+ if (!raw.slice(match[0].length).includes(imported.name.text)) {
391
+ let used = false;
392
+ const inspect = (node) => {
393
+ if (node === statement || used)
394
+ return;
395
+ if (ts.isIdentifier(node) && node.text === imported.name.text && !isImportNode(node))
396
+ used = true;
397
+ ts.forEachChild(node, inspect);
398
+ };
399
+ for (const bodyStatement of src.statements)
400
+ inspect(bodyStatement);
401
+ if (!used)
402
+ continue;
403
+ }
404
+ consumers.add(`${resolved}\u0000${(imported.propertyName ?? imported.name).text}`);
405
+ }
406
+ }
407
+ }
408
+ cached = { signature, consumers };
409
+ astroConsumerCache.set(cfg, cached);
410
+ }
411
+ return cached.consumers;
412
+ }
413
+ /**
414
+ * Keeps exported bindings that are imported from Astro frontmatter outside the TypeScript program.
415
+ *
416
+ * @param candidate Candidate declaration whose Astro use should be checked.
417
+ * @param consumers Source-and-name keys collected from Astro frontmatter and markup.
418
+ *
419
+ * @return Whether an Astro file references this declaration.
420
+ */
421
+ function hasAstroConsumer(candidate, consumers) {
422
+ return consumers.has(`${candidate.file}\u0000${candidate.name.text}`);
423
+ }
424
+ /**
425
+ * Keeps explicitly configured module contracts out of single-consumer cleanup.
426
+ *
427
+ * @param cfg Quality configuration containing explicit framework export contracts.
428
+ * @param candidate Candidate declaration to match against the configured contract.
429
+ * @param checker TypeScript checker used to confirm the binding is exported.
430
+ *
431
+ * @return Whether this named export is protected by configuration.
432
+ */
433
+ function isCfgdPublicContract(cfg, candidate, checker) {
434
+ if (!cfg.frameworkEntryExports?.[relative(cfg.root, candidate.file).split(sep).join('/')]?.includes(candidate.name.text))
435
+ return false;
436
+ const moduleSymbol = checker.getSymbolAtLocation(candidate.source);
437
+ const exported = moduleSymbol && checker.getExportsOfModule(moduleSymbol).find(symbol => symbol.name === candidate.name.text);
438
+ return Boolean(exported && canonical(checker, exported) === candidate.symbol);
439
+ }
440
+ /**
441
+ * Keeps module-exported declarations intact because consumers may exist outside the scanned source roots.
442
+ *
443
+ * @param candidate Declaration whose source module is inspected.
444
+ * @param checker TypeScript checker used to resolve the source module's exports.
445
+ *
446
+ * @return Whether the declaration is reachable through any module export.
447
+ */
448
+ function isModuleExport(candidate, checker) {
449
+ const moduleSymbol = checker.getSymbolAtLocation(candidate.source);
450
+ return Boolean(moduleSymbol && checker.getExportsOfModule(moduleSymbol).some(exported => canonical(checker, exported) === candidate.symbol));
451
+ }
452
+ /**
453
+ * Keeps declarations exported by a package entrypoint out of local single-use advice.
454
+ *
455
+ * @param cfg Quality configuration defining the repository package root.
456
+ * @param candidate Candidate declaration to match against the package entry points.
457
+ * @param checker TypeScript checker used to resolve module exports.
458
+ * @param program Program used to inspect package entry modules.
459
+ *
460
+ * @return Whether the declaration is reachable from a package entry point.
461
+ */
462
+ function isPackageEntryExport(cfg, candidate, checker, program) {
463
+ const moduleSymbol = checker.getSymbolAtLocation(candidate.source);
464
+ const exported = moduleSymbol && checker.getExportsOfModule(moduleSymbol).find(symbol => symbol.name === candidate.name.text);
465
+ if (!exported || canonical(checker, exported) !== candidate.symbol)
466
+ return false;
467
+ for (let dir = dirname(candidate.file); dir.startsWith(cfg.root); dir = dirname(dir)) {
468
+ const manifestPath = join(dir, 'package.json');
469
+ if (!statSync(manifestPath, { throwIfNoEntry: false })?.isFile())
470
+ continue;
471
+ try {
472
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
473
+ const tgts = [];
474
+ const pending = [manifest.exports];
475
+ while (pending.length) {
476
+ const value = pending.pop();
477
+ if (typeof value === 'string')
478
+ tgts.push(value);
479
+ else if (Array.isArray(value))
480
+ pending.push(...value);
481
+ else if (value && typeof value === 'object')
482
+ pending.push(...Object.values(value));
483
+ }
484
+ if (tgts.length === 0)
485
+ tgts.push(...[manifest.main, manifest.module, manifest.types, manifest.typings].filter((v) => Boolean(v)));
486
+ for (const tgt of tgts) {
487
+ const norm = tgt.replace(/^\.\//, '').replace(/\.(?:m|c)?(?:js|jsx|ts|tsx|d\.ts)$/, '');
488
+ if (norm === relative(dir, candidate.file).split(sep).join('/').replace(C_M_JS_JSX_TS_TSX_REGEX, ''))
489
+ return true;
490
+ const tsconfigPath = [join(dir, 'tsconfig.json'), join(dir, 'config/tsconfig.json'), join(cfg.configRoot ?? join(cfg.root, 'config'), 'tsconfig.json')].find(path => statSync(path, { throwIfNoEntry: false })?.isFile());
491
+ if (!tsconfigPath)
492
+ continue;
493
+ const parsed = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
494
+ if (parsed.error)
495
+ continue;
496
+ const { rootDir, outDir } = ts.parseJsonConfigFileContent(parsed.config, ts.sys, dirname(tsconfigPath)).options;
497
+ if (!rootDir || !outDir)
498
+ continue;
499
+ if (norm ===
500
+ relative(dir, join(outDir, `${relative(rootDir, candidate.file).replace(C_M_JS_JSX_TS_TSX_REGEX, '')}.js`))
501
+ .split(sep)
502
+ .join('/')
503
+ .replace(C_M_JS_JSX_TS_TSX_REGEX, ''))
504
+ return true;
505
+ const entryOutput = relative(outDir, resolve(dir, norm)).split(sep).join('/');
506
+ if (entryOutput === '..' || entryOutput.startsWith('../'))
507
+ continue;
508
+ const entrySrc = program.getSourceFiles().find(src => {
509
+ const entryPath = relative(rootDir, src.fileName).replace(C_M_JS_JSX_TS_TSX_REGEX, '').split(sep).join('/');
510
+ return entryPath === entryOutput || entryPath === `${entryOutput === '.' ? '' : entryOutput}/index`;
511
+ });
512
+ const entrySymbol = entrySrc && checker.getSymbolAtLocation(entrySrc);
513
+ if (entrySymbol && checker.getExportsOfModule(entrySymbol).some(entryExport => canonical(checker, entryExport) === candidate.symbol))
514
+ return true;
515
+ }
516
+ return false;
517
+ }
518
+ catch {
519
+ return false;
520
+ }
521
+ }
522
+ return false;
523
+ }
524
+ /**
525
+ * Preserves a React identity hook or interval handle whose one use is required by lifecycle semantics.
526
+ *
527
+ * @param candidate Candidate value declaration whose lifecycle behavior is checked.
528
+ * @param use The candidate's single reference.
529
+ *
530
+ * @return Whether retaining the binding protects hook or interval lifecycle semantics.
531
+ */
532
+ function isRequiredLifecycleVal(candidate, use) {
533
+ if (candidate.kind !== 'variable' || !ts.isVariableStatement(candidate.statement))
534
+ return false;
535
+ const init = candidate.statement.declarationList.declarations[0]?.initializer;
536
+ if (!init || !ts.isCallExpression(init))
537
+ return false;
538
+ if (ts.isIdentifier(init.expression) && init.expression.text === 'useId')
539
+ return true;
540
+ if (!(ts.isPropertyAccessExpression(init.expression) && ts.isIdentifier(init.expression.expression) && init.expression.expression.text === 'window' && init.expression.name.text === 'setInterval') ||
541
+ !ts.isCallExpression(use.node.parent))
542
+ return false;
543
+ return (ts.isPropertyAccessExpression(use.node.parent.expression) &&
544
+ ts.isIdentifier(use.node.parent.expression.expression) &&
545
+ use.node.parent.expression.expression.text === 'window' &&
546
+ use.node.parent.expression.name.text === 'clearInterval');
547
+ }
548
+ /**
549
+ * Keeps imported type names in scope when an inline would discard their annotation.
550
+ *
551
+ * @param candidate Variable candidate whose explicit annotation might be discarded.
552
+ * @param checker TypeScript checker used to identify whether annotation names are imported.
553
+ *
554
+ * @return Whether inlining would remove a required imported type annotation.
555
+ */
556
+ function hasImportedTypeAnnotation(candidate, checker) {
557
+ if (candidate.kind !== 'variable' || !ts.isVariableStatement(candidate.statement))
558
+ return false;
559
+ return candidate.statement.declarationList.declarations.some(d => {
560
+ if (!d.type)
561
+ return false;
562
+ let imported = false;
563
+ const inspect = (node) => {
564
+ const symbol = ts.isIdentifier(node) ? checker.getSymbolAtLocation(node) : undefined;
565
+ if (symbol?.flags && symbol.flags & ts.SymbolFlags.Alias)
566
+ imported = true;
567
+ ts.forEachChild(node, inspect);
568
+ };
569
+ inspect(d.type);
570
+ return imported;
571
+ });
572
+ }
573
+ /**
574
+ * Detects explicit annotations that can change overload or generic call resolution.
575
+ *
576
+ * @param candidate Variable candidate whose annotation may affect its consumer.
577
+ * @param checker TypeScript checker used to inspect call signatures.
578
+ * @param ref Sole consumer that would receive the initializer.
579
+ *
580
+ * @return Whether replacing the annotated reference could select a different signature.
581
+ */
582
+ function hasCallSensitiveTypeAnnotation(candidate, checker, ref) {
583
+ if (candidate.kind !== 'variable' || !ts.isVariableDeclaration(candidate.name.parent) || !candidate.name.parent.type)
584
+ return false;
585
+ let value = ref.node;
586
+ while (ts.isParenthesizedExpression(value.parent) ||
587
+ ts.isAsExpression(value.parent) ||
588
+ ts.isTypeAssertionExpression(value.parent) ||
589
+ ts.isNonNullExpression(value.parent) ||
590
+ ts.isSatisfiesExpression(value.parent)) {
591
+ value = value.parent;
592
+ }
593
+ const parent = value.parent;
594
+ const call = (ts.isCallExpression(parent) && parent.arguments.includes(value)) || (ts.isNewExpression(parent) && parent.arguments?.includes(value)) ? parent : undefined;
595
+ if (!call)
596
+ return false;
597
+ const signatures = checker.getSignaturesOfType(checker.getTypeAtLocation(call.expression), ts.SignatureKind.Call);
598
+ return signatures.length > 1 || signatures.some(signature => Boolean(signature.typeParameters?.length));
599
+ }
600
+ /**
601
+ * Checks whether a cross-file type body depends on names unavailable to the consumer.
602
+ *
603
+ * @param candidate Type declaration proposed for inlining.
604
+ * @param ref Its consumer reference.
605
+ * @param checker Type checker used to resolve names in the declaration body.
606
+ *
607
+ * @return `true` when copied type syntax remains resolvable in the consumer file.
608
+ */
609
+ function crossFileTypeSafe(candidate, ref, checker) {
610
+ if (candidate.file === ref.file)
611
+ return true;
612
+ let s = true;
613
+ const visit = (node) => {
614
+ if (ts.isTypeReferenceNode(node)) {
615
+ const declaration = checker.getSymbolAtLocation(node.typeName)?.declarations?.[0];
616
+ if (declaration && !ts.isTypeParameterDeclaration(declaration) && declaration.getSourceFile().fileName !== ref.file && declaration.getSourceFile().isDeclarationFile === false)
617
+ s = false;
618
+ }
619
+ ts.forEachChild(node, visit);
620
+ };
621
+ if (ts.isTypeAliasDeclaration(candidate.statement))
622
+ visit(candidate.statement.type);
623
+ if (ts.isInterfaceDeclaration(candidate.statement)) {
624
+ for (const mem of candidate.statement.members)
625
+ visit(mem);
626
+ for (const clause of candidate.statement.heritageClauses ?? [])
627
+ visit(clause);
628
+ }
629
+ return s;
630
+ }
631
+ /**
632
+ * Rejects type aliases whose expansion would introduce explicit `any` at their use site.
633
+ *
634
+ * @param candidate Type alias or interface proposed for inlining.
635
+ *
636
+ * @return `true` when the declaration body contains an explicit `any` type node.
637
+ */
638
+ function containsExplicitAny(candidate) {
639
+ let found = false;
640
+ const visit = (node) => {
641
+ if (node.kind === ts.SyntaxKind.AnyKeyword)
642
+ found = true;
643
+ ts.forEachChild(node, visit);
644
+ };
645
+ if (ts.isTypeAliasDeclaration(candidate.statement))
646
+ visit(candidate.statement.type);
647
+ if (ts.isInterfaceDeclaration(candidate.statement))
648
+ visit(candidate.statement);
649
+ return found;
650
+ }
651
+ /**
652
+ * Rejects initializers whose await would be moved into an unrelated callback.
653
+ *
654
+ * @param candidate Candidate declaration whose initializer is inspected.
655
+ *
656
+ * @return Whether the initializer contains an await expression.
657
+ */
658
+ function containsAwait(candidate) {
659
+ if (!ts.isVariableStatement(candidate.statement))
660
+ return false;
661
+ let found = false;
662
+ const visit = (node) => {
663
+ if (ts.isAwaitExpression(node))
664
+ found = true;
665
+ ts.forEachChild(node, visit);
666
+ };
667
+ const init = candidate.statement.declarationList.declarations[0]?.initializer;
668
+ if (init)
669
+ visit(init);
670
+ return found;
671
+ }
672
+ /**
673
+ * Determines whether an expression contains only literal values and static arrays or objects.
674
+ *
675
+ * @param expr Expression proposed for inlining.
676
+ *
677
+ * @return Whether evaluation avoids variable reads, spreads, computed keys, and executable properties.
678
+ */
679
+ function isStaticLiteralExpr(expr) {
680
+ const node = ts.isParenthesizedExpression(expr) || ts.isAsExpression(expr) || ts.isTypeAssertionExpression(expr) || ts.isNonNullExpression(expr) ? expr.expression : expr;
681
+ if (ts.isStringLiteral(node) ||
682
+ ts.isNumericLiteral(node) ||
683
+ ts.isBigIntLiteral(node) ||
684
+ ts.isNoSubstitutionTemplateLiteral(node) ||
685
+ ts.isRegularExpressionLiteral(node) ||
686
+ node.kind === ts.SyntaxKind.TrueKeyword ||
687
+ node.kind === ts.SyntaxKind.FalseKeyword ||
688
+ node.kind === ts.SyntaxKind.NullKeyword)
689
+ return true;
690
+ if (ts.isPrefixUnaryExpression(node))
691
+ return (node.operator === ts.SyntaxKind.PlusToken || node.operator === ts.SyntaxKind.MinusToken) && (ts.isNumericLiteral(node.operand) || ts.isBigIntLiteral(node.operand));
692
+ if (ts.isArrayLiteralExpression(node))
693
+ return node.elements.every(el => !ts.isSpreadElement(el) && isStaticLiteralExpr(el));
694
+ if (ts.isObjectLiteralExpression(node))
695
+ return node.properties.every(prop => ts.isPropertyAssignment(prop) && !ts.isComputedPropertyName(prop.name) && isStaticLiteralExpr(prop.initializer));
696
+ return false;
697
+ }
698
+ /**
699
+ * Checks whether a type is declared by Playwright as a lazy page or locator query receiver.
700
+ *
701
+ * @param type Type of the receiver for a query call.
702
+ * @param checker Type checker for the current source program.
703
+ *
704
+ * @return Whether every receiver type is a Playwright `Page`, `Locator`, or `FrameLocator`.
705
+ */
706
+ function isPlaywrightQueryReceiver(type, checker) {
707
+ const types = checker.getApparentType(type);
708
+ return (types.isUnionOrIntersection() ? types.types : [types]).every(member => {
709
+ const symbol = member.aliasSymbol ?? member.getSymbol();
710
+ return (Boolean(symbol && ['Page', 'Locator', 'FrameLocator'].includes(symbol.name)) &&
711
+ (symbol?.declarations ?? []).some(declaration => {
712
+ return /\/node_modules\/(?:playwright-core|playwright|@playwright\/test)\//u.test(declaration.getSourceFile().fileName.replaceAll('\\', '/'));
713
+ }));
714
+ });
715
+ }
716
+ /**
717
+ * Recognizes a lazy Playwright locator query whose call and arguments have no execution effects.
718
+ *
719
+ * @param init Variable initializer proposed for inlining.
720
+ * @param checker Type checker used to confirm the receiver belongs to Playwright.
721
+ *
722
+ * @return Whether a static Playwright query can be recreated without moving application work.
723
+ */
724
+ function isStaticPlaywrightLocator(init, checker) {
725
+ if (!ts.isCallExpression(init) || init.questionDotToken || !ts.isPropertyAccessExpression(init.expression))
726
+ return false;
727
+ const call = init.expression;
728
+ if (call.questionDotToken || !PLAYWRIGHT_QUERY_METHODS.has(call.name.text))
729
+ return false;
730
+ const receiver = call.expression;
731
+ if (!isPlaywrightQueryReceiver(checker.getTypeAtLocation(receiver), checker))
732
+ return false;
733
+ if (ts.isIdentifier(receiver)) {
734
+ const symbol = checker.getSymbolAtLocation(receiver);
735
+ if (!symbol)
736
+ return false;
737
+ let reassigned = false;
738
+ const visit = (node) => {
739
+ if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === symbol) {
740
+ const parent = node.parent;
741
+ if ((ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
742
+ ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(parent.operator)))
743
+ reassigned = true;
744
+ }
745
+ if (!reassigned)
746
+ ts.forEachChild(node, visit);
747
+ };
748
+ visit(init.getSourceFile());
749
+ if (reassigned)
750
+ return false;
751
+ }
752
+ else if (!ts.isCallExpression(receiver) || !isStaticPlaywrightLocator(receiver, checker))
753
+ return false;
754
+ return init.arguments.every(isStaticLiteralExpr);
755
+ }
756
+ // hygiene-ignore single-use -- Keep the documented isModuleCallArgument declaration so its parameter and return contract remains attached.
757
+ /**
758
+ * Checks whether a declaration and its reference share a single module-level call boundary.
759
+ *
760
+ * @param candidate Const declaration proposed for inlining.
761
+ * @param ref Sole reference that would receive the initializer.
762
+ *
763
+ * @return Whether the initializer and its call execute once at module evaluation.
764
+ */
765
+ function isModuleCallArg(candidate, ref) {
766
+ const call = ref.node.parent;
767
+ return (candidate.statement.parent === candidate.source &&
768
+ ts.isCallExpression(call) &&
769
+ call.arguments.some(arg => arg === ref.node) &&
770
+ ts.isExpressionStatement(call.parent) &&
771
+ call.parent.parent === candidate.source);
772
+ }
773
+ /**
774
+ * Recognizes inert configuration data containing literals and binding reads only.
775
+ *
776
+ * @param expr Expression proposed for a directly adjacent default export.
777
+ *
778
+ * @return Whether the value can be constructed without calls, accessors, spreads, or computed keys.
779
+ */
780
+ function isStaticModuleDataExpr(expr) {
781
+ const node = ts.isParenthesizedExpression(expr) || ts.isAsExpression(expr) || ts.isTypeAssertionExpression(expr) || ts.isNonNullExpression(expr) ? expr.expression : expr;
782
+ if (ts.isIdentifier(node) || isStaticLiteralExpr(node))
783
+ return true;
784
+ if (ts.isArrayLiteralExpression(node))
785
+ return node.elements.every(el => !ts.isSpreadElement(el) && isStaticModuleDataExpr(el));
786
+ if (ts.isObjectLiteralExpression(node))
787
+ return node.properties.every(prop => ts.isPropertyAssignment(prop) && !ts.isComputedPropertyName(prop.name) && isStaticModuleDataExpr(prop.initializer));
788
+ return false;
789
+ }
790
+ /**
791
+ * Checks whether a static value is read by the immediately following module default export.
792
+ *
793
+ * @param candidate Const declaration proposed for inlining.
794
+ * @param ref Sole reference that would become the default export expression.
795
+ *
796
+ * @return Whether declaration and export are adjacent top-level statements in the same module.
797
+ */
798
+ function isAdjacentModuleDefaultExport(candidate, ref) {
799
+ const exported = ref.node.parent;
800
+ if (candidate.statement.parent !== candidate.source || !ts.isExportAssignment(exported) || exported.isExportEquals || exported.expression !== ref.node || exported.parent !== candidate.source)
801
+ return false;
802
+ const statements = candidate.source.statements;
803
+ return statements[statements.indexOf(candidate.statement) + 1] === exported;
804
+ }
805
+ /**
806
+ * Allows inlining only when the local value supplies the module's default export and no named export.
807
+ *
808
+ * @param candidate Candidate value whose module exports are inspected.
809
+ * @param checker Type checker used to resolve the module's export symbols.
810
+ * @param ref Sole reference proposed as the default export expression.
811
+ *
812
+ * @return Whether the adjacent default export is the candidate's only public module binding.
813
+ */
814
+ function isExclusiveDefaultExport(candidate, checker, ref) {
815
+ if (!isAdjacentModuleDefaultExport(candidate, ref))
816
+ return false;
817
+ const moduleSymbol = checker.getSymbolAtLocation(candidate.source);
818
+ const exports = moduleSymbol && checker.getExportsOfModule(moduleSymbol);
819
+ return Boolean(exports?.some(exported => exported.name === 'default' && canonical(checker, exported) === candidate.symbol) &&
820
+ !exports.some(exported => exported.name !== 'default' && canonical(checker, exported) === candidate.symbol));
821
+ }
822
+ /**
823
+ * Detects comment trivia inside an expression or between adjacent statements.
824
+ *
825
+ * @param src Source file containing the inspected span.
826
+ * @param start First source offset in the span.
827
+ * @param end Exclusive source offset at the end of the span.
828
+ *
829
+ * @return Whether moving the expression would also move or rewrite an authored comment.
830
+ */
831
+ function containsCommentTrivia(src, start, end) {
832
+ const scanner = ts.createScanner(src.languageVersion, false, src.languageVariant, src.text.slice(start, end));
833
+ for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan())
834
+ if (token === ts.SyntaxKind.SingleLineCommentTrivia || token === ts.SyntaxKind.MultiLineCommentTrivia)
835
+ return true;
836
+ return false;
837
+ }
838
+ // hygiene-ignore single-use -- Keep the documented isFirstConsumerEvaluation declaration so its parameter and return contract remains attached.
839
+ /**
840
+ * Checks whether a single-use reference is evaluated before any other consumer expression.
841
+ *
842
+ * @param ref Identifier being considered for inlining.
843
+ * @param init Initializer whose evaluation would move to the reference.
844
+ * @param consumerStatement Immediate statement containing the only reference.
845
+ *
846
+ * @return Whether the reference is an unconditional first operand in the next statement, including
847
+ * the first argument to a direct identifier call.
848
+ */
849
+ function isFirstConsumerEvaluation(ref, init, consumerStatement) {
850
+ let expr = ref;
851
+ const initBase = unwrapExpr(init);
852
+ let argExpr = ref;
853
+ while (ts.isParenthesizedExpression(argExpr.parent) ||
854
+ ts.isAsExpression(argExpr.parent) ||
855
+ ts.isTypeAssertionExpression(argExpr.parent) ||
856
+ ts.isNonNullExpression(argExpr.parent) ||
857
+ ts.isSatisfiesExpression(argExpr.parent))
858
+ argExpr = argExpr.parent;
859
+ const argCall = argExpr.parent;
860
+ if ((ts.isArrayLiteralExpression(initBase) || ts.isObjectLiteralExpression(initBase)) &&
861
+ !(isStaticLiteralExpr(init) && ts.isCallExpression(argCall) && argCall.arguments[0] === argExpr && ts.isIdentifier(argCall.expression) && !argCall.questionDotToken))
862
+ return false;
863
+ const initPreservesReceiver = ts.isPropertyAccessExpression(initBase) || ts.isElementAccessExpression(initBase);
864
+ while (true) {
865
+ const parent = expr.parent;
866
+ if ((ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent) || ts.isTypeAssertionExpression(parent) || ts.isNonNullExpression(parent) || ts.isSatisfiesExpression(parent)) &&
867
+ parent.expression === expr) {
868
+ expr = parent;
869
+ continue;
870
+ }
871
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === expr) {
872
+ expr = parent;
873
+ continue;
874
+ }
875
+ if (ts.isElementAccessExpression(parent) && parent.expression === expr) {
876
+ expr = parent;
877
+ continue;
878
+ }
879
+ if (ts.isBinaryExpression(parent) && parent.left === expr && parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {
880
+ expr = parent;
881
+ continue;
882
+ }
883
+ if (ts.isConditionalExpression(parent) && parent.condition === expr) {
884
+ expr = parent;
885
+ continue;
886
+ }
887
+ if (ts.isCallExpression(parent) && parent.arguments[0] === expr && ts.isIdentifier(parent.expression) && !parent.questionDotToken && isStaticLiteralExpr(init)) {
888
+ expr = parent;
889
+ continue;
890
+ }
891
+ if (ts.isPrefixUnaryExpression(parent) && parent.operand === expr) {
892
+ expr = parent;
893
+ continue;
894
+ }
895
+ if (ts.isCallExpression(parent) && parent.expression === expr && !initPreservesReceiver) {
896
+ expr = parent;
897
+ continue;
898
+ }
899
+ if (ts.isNewExpression(parent) && parent.expression === expr && !initPreservesReceiver) {
900
+ expr = parent;
901
+ continue;
902
+ }
903
+ if (ts.isArrayLiteralExpression(parent) && parent.elements[0] === expr) {
904
+ expr = parent;
905
+ continue;
906
+ }
907
+ if (ts.isSpreadElement(parent) && ts.isArrayLiteralExpression(parent.parent) && parent.parent.elements[0] === parent) {
908
+ expr = parent.parent;
909
+ continue;
910
+ }
911
+ if (ts.isPropertyAssignment(parent) &&
912
+ parent.initializer === expr &&
913
+ ts.isObjectLiteralExpression(parent.parent) &&
914
+ parent.parent.properties[0] === parent &&
915
+ (ts.isIdentifier(parent.name) || ts.isStringLiteral(parent.name) || ts.isNumericLiteral(parent.name))) {
916
+ expr = parent.parent;
917
+ continue;
918
+ }
919
+ if (ts.isVariableDeclaration(parent) &&
920
+ parent.initializer === expr &&
921
+ ts.isVariableDeclarationList(parent.parent) &&
922
+ parent.parent.declarations.length === 1 &&
923
+ parent.parent.parent === consumerStatement)
924
+ return true;
925
+ if ((ts.isReturnStatement(parent) || ts.isThrowStatement(parent) || ts.isExpressionStatement(parent)) && parent.expression === expr && parent === consumerStatement)
926
+ return true;
927
+ if ((ts.isIfStatement(parent) || ts.isSwitchStatement(parent)) && parent.expression === expr && parent === consumerStatement)
928
+ return true;
929
+ return false;
930
+ }
931
+ }
932
+ // hygiene-ignore single-use -- Keep the documented unwrapExpr declaration so its parameter and return contract remains attached.
933
+ /**
934
+ * Removes syntax-only wrappers around an initializer before checking its receiver behavior.
935
+ *
936
+ * @param expr Initializer being inspected.
937
+ *
938
+ * @return The first non-wrapper expression node.
939
+ */
940
+ function unwrapExpr(expr) {
941
+ while (ts.isParenthesizedExpression(expr) || ts.isAsExpression(expr) || ts.isTypeAssertionExpression(expr) || ts.isNonNullExpression(expr) || ts.isSatisfiesExpression(expr))
942
+ expr = expr.expression;
943
+ return expr;
944
+ }
945
+ /**
946
+ * Rejects initializers whose movement could change evaluation, identity, or side effects.
947
+ *
948
+ * @param candidate Candidate declaration whose initializer is checked.
949
+ * @param checker Type checker used to recognize lazy Playwright locator queries.
950
+ * @param ref Sole reference that would receive the initializer after inlining.
951
+ *
952
+ * @return Whether inlining preserves initialization order, async context, receiver behavior, and authored boundaries.
953
+ */
954
+ function initSafeToInline(candidate, checker, ref) {
955
+ if (candidate.kind !== 'variable' || !ts.isVariableStatement(candidate.statement))
956
+ return true;
957
+ const init = candidate.statement.declarationList.declarations[0]?.initializer;
958
+ if (!init || !(candidate.statement.declarationList.flags & ts.NodeFlags.Const))
959
+ return false;
960
+ if (ref && candidate.file === ref.file) {
961
+ let expr = ref.node;
962
+ while (ts.isParenthesizedExpression(expr.parent) ||
963
+ ts.isAsExpression(expr.parent) ||
964
+ ts.isTypeAssertionExpression(expr.parent) ||
965
+ ts.isNonNullExpression(expr.parent) ||
966
+ ts.isSatisfiesExpression(expr.parent)) {
967
+ expr = expr.parent;
968
+ }
969
+ const parent = expr.parent;
970
+ const statements = (() => {
971
+ const list = candidate.statement.parent;
972
+ return ts.isSourceFile(list) || ts.isBlock(list) || ts.isModuleBlock(list) || ts.isCaseClause(list) || ts.isDefaultClause(list) ? list.statements : undefined;
973
+ })();
974
+ let useStatement;
975
+ for (let node = expr; node; node = node.parent) {
976
+ if (ts.isStatement(node) && node.parent === candidate.statement.parent) {
977
+ useStatement = node;
978
+ break;
979
+ }
980
+ if (node.parent === candidate.statement.parent)
981
+ break;
982
+ }
983
+ const candidateIndex = statements?.indexOf(candidate.statement) ?? -1;
984
+ let hasDynamicScope = dynamicScopeCache.get(candidate.source);
985
+ if (hasDynamicScope === undefined) {
986
+ hasDynamicScope = false;
987
+ const inspect = (node) => {
988
+ if (ts.isWithStatement(node))
989
+ hasDynamicScope = true;
990
+ if (ts.isCallExpression(node)) {
991
+ let callee = node.expression;
992
+ while (ts.isParenthesizedExpression(callee))
993
+ callee = callee.expression;
994
+ if (ts.isIdentifier(callee) && callee.text === 'eval')
995
+ hasDynamicScope = true;
996
+ }
997
+ if (!hasDynamicScope)
998
+ ts.forEachChild(node, inspect);
999
+ };
1000
+ inspect(candidate.source);
1001
+ dynamicScopeCache.set(candidate.source, hasDynamicScope);
1002
+ }
1003
+ let boundarySensitive = false;
1004
+ const inspectInit = (node) => {
1005
+ if (ts.isYieldExpression(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isClassExpression(node))
1006
+ boundarySensitive = true;
1007
+ if (!boundarySensitive)
1008
+ ts.forEachChild(node, inspectInit);
1009
+ };
1010
+ inspectInit(init);
1011
+ if (useStatement &&
1012
+ candidateIndex >= 0 &&
1013
+ statements?.[candidateIndex + 1] === useStatement &&
1014
+ ((((ts.isReturnStatement(parent) && parent.expression === expr) ||
1015
+ (ts.isThrowStatement(parent) && parent.expression === expr) ||
1016
+ (ts.isIfStatement(parent) && parent.expression === expr) ||
1017
+ (ts.isSwitchStatement(parent) && parent.expression === expr) ||
1018
+ (ts.isExpressionStatement(parent) && parent.expression === expr) ||
1019
+ (ts.isVariableDeclaration(parent) && parent.initializer === expr && ts.isVariableDeclarationList(parent.parent) && parent.parent.declarations.length === 1)) &&
1020
+ (ts.isVariableDeclaration(parent) ? parent.parent.parent : parent) === useStatement) ||
1021
+ isFirstConsumerEvaluation(ref.node, init, useStatement)) &&
1022
+ !((ts.getLeadingCommentRanges(candidate.source.text, candidate.statement.getFullStart()) ?? []).length ||
1023
+ containsCommentTrivia(candidate.source, candidate.statement.getStart(candidate.source), candidate.statement.getEnd()) ||
1024
+ (useStatement && containsCommentTrivia(candidate.source, candidate.statement.getEnd(), useStatement.getStart(candidate.source)))) &&
1025
+ !hasDynamicScope &&
1026
+ !boundarySensitive)
1027
+ return true;
1028
+ }
1029
+ const declaration = candidate.name.parent;
1030
+ if (ref && ts.isVariableDeclaration(declaration) && !declaration.type && isModuleCallArg(candidate, ref) && isStaticLiteralExpr(init))
1031
+ return true;
1032
+ if (ref &&
1033
+ ts.isVariableDeclaration(declaration) &&
1034
+ !declaration.type &&
1035
+ isAdjacentModuleDefaultExport(candidate, ref) &&
1036
+ isStaticModuleDataExpr(init) &&
1037
+ !containsCommentTrivia(candidate.source, init.getFullStart(), init.getEnd()) &&
1038
+ !containsCommentTrivia(candidate.source, candidate.statement.getEnd(), ref.node.parent.getStart(candidate.source)))
1039
+ return true;
1040
+ if (init.getText(candidate.source).length > 120)
1041
+ return false;
1042
+ return (ts.isStringLiteral(init) ||
1043
+ ts.isNumericLiteral(init) ||
1044
+ ts.isNoSubstitutionTemplateLiteral(init) ||
1045
+ init.kind === ts.SyntaxKind.TrueKeyword ||
1046
+ init.kind === ts.SyntaxKind.FalseKeyword ||
1047
+ init.kind === ts.SyntaxKind.NullKeyword ||
1048
+ isStaticPlaywrightLocator(init, checker));
1049
+ }
1050
+ /**
1051
+ * Checks whether a cross-file variable initializer is a self-contained literal value.
1052
+ *
1053
+ * @param candidate Variable declaration proposed for inlining.
1054
+ *
1055
+ * @return `true` when the initializer has no references to module-local bindings.
1056
+ */
1057
+ function crossFileVariableSafe(candidate) {
1058
+ if (candidate.kind !== 'variable' || !ts.isVariableStatement(candidate.statement))
1059
+ return false;
1060
+ const init = candidate.statement.declarationList.declarations[0]?.initializer;
1061
+ if (!init)
1062
+ return false;
1063
+ let s = true;
1064
+ const visit = (node) => {
1065
+ if (ts.isIdentifier(node) && !((ts.isPropertyAssignment(node.parent) && node.parent.name === node) || (ts.isMethodDeclaration(node.parent) && node.parent.name === node)))
1066
+ s = false;
1067
+ ts.forEachChild(node, visit);
1068
+ };
1069
+ visit(init);
1070
+ return s;
1071
+ }
1072
+ /**
1073
+ * Checks whether replacing a variable reference would make it an invalid or mutating target.
1074
+ *
1075
+ * @param ref Reference to a variable candidate.
1076
+ *
1077
+ * @return `true` when the reference is used as a write target.
1078
+ */
1079
+ function isWriteRef(ref) {
1080
+ let tgt = ref.node;
1081
+ while (tgt.parent && ((ts.isPropertyAccessExpression(tgt.parent) && tgt.parent.expression === tgt) || (ts.isElementAccessExpression(tgt.parent) && tgt.parent.expression === tgt)))
1082
+ tgt = tgt.parent;
1083
+ return (((ts.isPrefixUnaryExpression(tgt.parent) || ts.isPostfixUnaryExpression(tgt.parent)) && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(tgt.parent.operator)) ||
1084
+ (ts.isBinaryExpression(tgt.parent) && tgt.parent.left === tgt && tgt.parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && tgt.parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
1085
+ ts.isDeleteExpression(tgt.parent));
1086
+ }
1087
+ /**
1088
+ * Preserves saved values used to restore mutable object or property state.
1089
+ *
1090
+ * @param ref Candidate reference whose assignment target is inspected.
1091
+ *
1092
+ * @return Whether the reference is a saved value used to restore mutable state.
1093
+ */
1094
+ function isStateRestorationRef(ref) {
1095
+ return (ts.isBinaryExpression(ref.node.parent) &&
1096
+ ref.node.parent.right === ref.node &&
1097
+ ref.node.parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1098
+ ref.node.parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
1099
+ (ts.isPropertyAccessExpression(ref.node.parent.left) || ts.isElementAccessExpression(ref.node.parent.left)));
1100
+ }
1101
+ /**
1102
+ * Checks whether a reference can execute repeatedly through an enclosing function or loop.
1103
+ *
1104
+ * A declaration outside a callback or loop can have one syntactic reference but many runtime reads.
1105
+ * A declaration and its reference inside the same execution body remain eligible because both are
1106
+ * evaluated once per invocation or iteration. Named functions passed to common repeated array
1107
+ * callbacks are treated the same way even when their identifier appears only at the call site.
1108
+ *
1109
+ * @param candidate Declaration whose consumer count is being evaluated.
1110
+ * @param ref Resolved source reference to the candidate.
1111
+ * @param checker Type checker used to recognize recursive function calls.
1112
+ *
1113
+ * @return Whether the reference may execute more than once for one declaration value.
1114
+ */
1115
+ function isRuntimeRepeatedRef(candidate, ref, checker) {
1116
+ if (candidate.kind === 'type' || candidate.kind === 'interface')
1117
+ return false;
1118
+ const init = candidate.kind === 'variable' && ts.isVariableStatement(candidate.statement) ? candidate.statement.declarationList.declarations[0]?.initializer : undefined;
1119
+ if (candidate.kind === 'function' || Boolean(init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)))) {
1120
+ const call = ref.node.parent;
1121
+ if (ts.isCallExpression(call) && ts.isPropertyAccessExpression(call.expression) && REPEATED_CALLBACK_METHODS.has(call.expression.name.text) && call.arguments.includes(ref.node))
1122
+ return true;
1123
+ }
1124
+ for (let node = ref.node.parent; node && !ts.isSourceFile(node); node = node.parent) {
1125
+ const fnName = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)
1126
+ ? node.name && ts.isIdentifier(node.name)
1127
+ ? node.name
1128
+ : undefined
1129
+ : ts.isArrowFunction(node) && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)
1130
+ ? node.parent.name
1131
+ : undefined;
1132
+ const fnSymbol = fnName ? checker.getSymbolAtLocation(fnName) : undefined;
1133
+ let recursive = false;
1134
+ const body = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) ? node.body : undefined;
1135
+ if (fnSymbol && body) {
1136
+ const pending = [body];
1137
+ while (pending.length && !recursive) {
1138
+ const current = pending.pop();
1139
+ if (current !== body && ts.isFunctionLike(current))
1140
+ continue;
1141
+ if (ts.isCallExpression(current) && ts.isIdentifier(current.expression) && checker.getSymbolAtLocation(current.expression) === fnSymbol) {
1142
+ recursive = true;
1143
+ break;
1144
+ }
1145
+ current.forEachChild(child => {
1146
+ pending.push(child);
1147
+ });
1148
+ }
1149
+ }
1150
+ let callbackOwner = false;
1151
+ if ((ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && fnName?.parent && ts.isVariableDeclaration(fnName.parent)) {
1152
+ const ownerSymbol = checker.getSymbolAtLocation(fnName);
1153
+ if (ownerSymbol) {
1154
+ let repeatedOwners = repeatedCallbackOwnerCache.get(ref.source);
1155
+ if (!repeatedOwners) {
1156
+ repeatedOwners = new Set();
1157
+ const pending = [ref.source];
1158
+ while (pending.length) {
1159
+ const current = pending.pop();
1160
+ if (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression) && REPEATED_CALLBACK_METHODS.has(current.expression.name.text))
1161
+ for (const arg of current.arguments)
1162
+ if (ts.isIdentifier(arg)) {
1163
+ const symbol = checker.getSymbolAtLocation(arg);
1164
+ if (symbol)
1165
+ repeatedOwners.add(symbol);
1166
+ }
1167
+ current.forEachChild(child => {
1168
+ pending.push(child);
1169
+ });
1170
+ }
1171
+ repeatedCallbackOwnerCache.set(ref.source, repeatedOwners);
1172
+ }
1173
+ callbackOwner = repeatedOwners.has(ownerSymbol);
1174
+ }
1175
+ }
1176
+ if (!(((ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
1177
+ ts.isCallExpression(node.parent) &&
1178
+ ts.isPropertyAccessExpression(node.parent.expression) &&
1179
+ REPEATED_CALLBACK_METHODS.has(node.parent.expression.name.text) &&
1180
+ node.parent.arguments.includes(node)) ||
1181
+ callbackOwner ||
1182
+ recursive ||
1183
+ ts.isForStatement(node) ||
1184
+ ts.isForInStatement(node) ||
1185
+ ts.isForOfStatement(node) ||
1186
+ ts.isWhileStatement(node) ||
1187
+ ts.isDoStatement(node)))
1188
+ continue;
1189
+ let containsCandidate = false;
1190
+ for (let ancestor = candidate.statement; ancestor; ancestor = ancestor.parent)
1191
+ if (ancestor === node) {
1192
+ containsCandidate = true;
1193
+ break;
1194
+ }
1195
+ if (!containsCandidate)
1196
+ return true;
1197
+ }
1198
+ return false;
1199
+ }
1200
+ /**
1201
+ * Identifies a reference that only re-exports an imported binding.
1202
+ *
1203
+ * @param ref Symbol reference being classified.
1204
+ *
1205
+ * @return `true` when the reference is part of an export list, not an inline consumer.
1206
+ */
1207
+ function isExportSpecifierRef(ref) {
1208
+ return ts.isExportSpecifier(ref.node.parent);
1209
+ }
1210
+ /**
1211
+ * Classifies single-use declarations using an existing TypeScript analysis.
1212
+ *
1213
+ * @param cfg Quality configuration defining the source scope.
1214
+ * @param checker TypeScript checker belonging to the program.
1215
+ * @param candidates Declarations eligible for single-use classification.
1216
+ * @param refs Resolved references for each declaration symbol.
1217
+ * @param astroConsumers Framework references discovered from Astro files.
1218
+ * @param program TypeScript program used for declaration and reference analysis.
1219
+ *
1220
+ * @return Single-use recommendations with their locations and safety decisions.
1221
+ */
1222
+ function findingsFromAnalysis(cfg, checker, candidates, refs, astroConsumers, program) {
1223
+ const findings = [];
1224
+ const { directives, byCandidate } = singleUseIgnoreDirectives(cfg, program.getSourceFiles(), candidates);
1225
+ const usedDirectives = new Set();
1226
+ reportProgress('Single-use classification:', 0, candidates.length);
1227
+ candidateLoop: for (const [candidateIdx, c] of candidates.entries()) {
1228
+ reportProgress('Single-use classification:', candidateIdx + 1, candidates.length);
1229
+ const directive = byCandidate.get(`${c.file}:${c.name.getStart(c.source)}`);
1230
+ const publicContract = isCfgdPublicContract(cfg, c, checker) || isPackageEntryExport(cfg, c, checker, program);
1231
+ const uses = c.kind === 'type' || c.kind === 'interface' ? typeRefs(c, refs) : (refs.get(c.symbol) ?? []).filter(r => !isImportNode(r.node) && !isExportSpecifierRef(r));
1232
+ // A package-local scan can have one consumer while the repository scan sees more.
1233
+ // Keep that declaration's specific, reasoned marker valid when another source file consumes its exported boundary.
1234
+ if (directive?.reason && uses.some(use => use.file !== c.file) && (uses.length > 1 || publicContract))
1235
+ usedDirectives.add(directive);
1236
+ // A package-only scan also misses consumers outside its sole source root. The
1237
+ // repository scan validates the same exported declaration against those consumers.
1238
+ if (directive?.reason &&
1239
+ uses.length === 0 &&
1240
+ cfg.sourceRoots.length === 1 &&
1241
+ (cfg.includeRoots?.length ?? 0) === 0 &&
1242
+ resolve(cfg.root, cfg.sourceRoots[0]) !== cfg.root &&
1243
+ isModuleExport(c, checker))
1244
+ usedDirectives.add(directive);
1245
+ if (publicContract)
1246
+ continue;
1247
+ if (uses.length !== 1)
1248
+ continue;
1249
+ const use = uses[0];
1250
+ if (isRuntimeRepeatedRef(c, use, checker))
1251
+ continue;
1252
+ if (!inSingleUseScope(cfg, use.file))
1253
+ continue;
1254
+ if (isRequiredLifecycleVal(c, use))
1255
+ continue;
1256
+ if (c.kind === 'variable' && ts.isVariableStatement(c.statement)) {
1257
+ const init = c.statement.declarationList.declarations[0]?.initializer;
1258
+ if (init && ts.isPropertyAccessExpression(init) && init.name.text === 'value' && ts.isPropertyAccessExpression(init.expression) && init.expression.name.text === 'currentTarget') {
1259
+ for (let node = use.node; node && node !== c.statement; node = node.parent) {
1260
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node))
1261
+ continue candidateLoop;
1262
+ }
1263
+ }
1264
+ }
1265
+ if (directive?.reason) {
1266
+ usedDirectives.add(directive);
1267
+ continue;
1268
+ }
1269
+ let reason = '';
1270
+ let canInline = true;
1271
+ if (c.kind === 'function') {
1272
+ canInline = false;
1273
+ reason = 'inlining a function can change its identity, closure, stack, or component behavior';
1274
+ }
1275
+ else if (c.kind === 'variable') {
1276
+ canInline = initSafeToInline(c, checker, use);
1277
+ reason = canInline
1278
+ ? 'single-use initializer can move to its first in-scope consumer without changing evaluation order or receiver behavior'
1279
+ : 'inlining is not proven to preserve evaluation order, async context, receiver behavior, or declaration boundaries';
1280
+ }
1281
+ else
1282
+ reason = `${c.kind} declaration has one in-scope consumer`;
1283
+ if (hasAstroConsumer(c, astroConsumers))
1284
+ continue;
1285
+ if (c.kind === 'function')
1286
+ [canInline, reason] = [false, 'inlining a function can change its identity, closure, stack, or component behavior'];
1287
+ else if (c.kind === 'variable' && c.file !== use.file && !crossFileVariableSafe(c))
1288
+ [canInline, reason] = [false, 'cross-file initializer depends on module-local values'];
1289
+ else if ((c.kind === 'type' || c.kind === 'interface') && !crossFileTypeSafe(c, use, checker))
1290
+ [canInline, reason] = [false, 'type depends on declarations that are not available at the consumer'];
1291
+ else if ((c.kind === 'type' || c.kind === 'interface') && containsExplicitAny(c))
1292
+ [canInline, reason] = [false, 'inlining would introduce explicit any'];
1293
+ else if (c.kind === 'variable' && containsAwait(c) && !initSafeToInline(c, checker, use))
1294
+ [canInline, reason] = [false, 'inlining would move await into another evaluation context'];
1295
+ else if (c.kind === 'variable' && !initSafeToInline(c, checker, use))
1296
+ [canInline, reason] = [false, 'inlining could change evaluation timing, hook order, or side effects'];
1297
+ else if (c.kind === 'variable' && isStateRestorationRef(use))
1298
+ [canInline, reason] = [false, 'inlining would discard a saved value needed to restore mutable state'];
1299
+ else if (c.kind === 'variable' && isWriteRef(use))
1300
+ [canInline, reason] = [false, 'the sole reference is a write target'];
1301
+ else if (c.kind === 'variable' && (ts.isJsxOpeningElement(use.node.parent) || ts.isJsxSelfClosingElement(use.node.parent)))
1302
+ [canInline, reason] = [false, 'this is a standalone JSX component; keep its component identity and declaration boundary, or export it from its definition if it is a module-level component'];
1303
+ else if (hasImportedTypeAnnotation(c, checker))
1304
+ [canInline, reason] = [false, 'inlining would remove a required imported type annotation'];
1305
+ else if (hasCallSensitiveTypeAnnotation(c, checker, use))
1306
+ [canInline, reason] = [false, 'inlining could change overload or generic call resolution'];
1307
+ if (hasMeaningfulLeadingTSDoc(c)) {
1308
+ canInline = false;
1309
+ reason = 'attached TSDoc is authored documentation and requires agent review before changing its declaration boundary';
1310
+ }
1311
+ if (hasGeneratedSourceHeader(c.source.text) || hasGeneratedSourceHeader(use.source.text)) {
1312
+ canInline = false;
1313
+ reason = 'declaration or consumer is in generated source and must be corrected in its generator';
1314
+ }
1315
+ else if (isModuleExport(c, checker) && !isExclusiveDefaultExport(c, checker, use)) {
1316
+ canInline = false;
1317
+ reason = 'declaration is exported from its module and may be part of an external contract';
1318
+ }
1319
+ const decision = canInline ? 'INLINE' : 'REVIEW';
1320
+ const rejectedReason = rejectedInlineCandidates.get(`${c.file}:${c.name.text}`);
1321
+ findings.push({
1322
+ file: relative(cfg.root, c.file),
1323
+ line: c.source.getLineAndCharacterOfPosition(c.name.getStart(c.source)).line + 1,
1324
+ name: c.name.text,
1325
+ decision: rejectedReason ? 'REVIEW' : decision,
1326
+ autofixable: !rejectedReason && decision === 'INLINE',
1327
+ reason: rejectedReason ?? reason,
1328
+ agentAction: (() => {
1329
+ const actionReason = rejectedReason ?? reason;
1330
+ if (!rejectedReason && canInline)
1331
+ return 'Run the canonical dead-code autofix, then verify the inlined type/value remains equivalent and rerun the affected test or typecheck.';
1332
+ if (actionReason.includes('generated source'))
1333
+ return 'Update the schema, query, or generator that owns this declaration; do not edit generated output directly.';
1334
+ if (actionReason.includes('external contract'))
1335
+ return 'Keep this exported declaration in its declaring module while it has external consumers; if you change that API boundary, preserve module-local dependencies and package documentation.';
1336
+ if (c.kind === 'function') {
1337
+ if (c.file !== use.file)
1338
+ return 'Keep the helper in its declaring module unless its module-local dependencies move with it; if you restructure that boundary, preserve closure capture, recursion, async behavior, and the caller contract.';
1339
+ return ts.isJsxOpeningElement(use.node.parent) || ts.isJsxSelfClosingElement(use.node.parent)
1340
+ ? 'Inline this component at its only JSX use only if React component identity, local state, hooks, effects, and render behavior remain unchanged. Otherwise retain it only for a concrete semantic boundary and verify with a focused render test.'
1341
+ : 'Inline this helper at its sole call only if closure capture, recursion, `this`, async boundaries, stack-sensitive behavior, and evaluation order remain unchanged. Otherwise retain it only for a concrete semantic boundary and run its focused test.';
1342
+ }
1343
+ if (c.kind === 'type' || c.kind === 'interface')
1344
+ return 'Inline this declaration at its sole type use only if generic arguments, imported names, and inferred specificity remain equivalent. Otherwise retain the separate type only when its name is materially useful, and verify with typecheck.';
1345
+ if (actionReason.includes('cross-file initializer'))
1346
+ return 'Keep the value in its declaring module unless its module-local dependencies move with it; if you restructure that boundary, verify initialization order and the consumer behavior.';
1347
+ if (actionReason.includes('move await'))
1348
+ return 'Keep the await at its current async boundary. Only inline after a deliberate async refactor that preserves sequencing, rejection handling, and the caller contract.';
1349
+ if (actionReason.includes('write target'))
1350
+ return 'Keep the binding because its only use is a write target. Do not substitute its initializer unless the same writable location and mutation semantics are preserved.';
1351
+ if (actionReason.includes('imported type annotation'))
1352
+ return 'Keep the binding and its imported type annotation together; only inline after preserving the annotation and confirming the affected typecheck.';
1353
+ if (actionReason.includes('explicit any'))
1354
+ return 'Keep the named type boundary unless it can be inlined without introducing explicit any; verify the consumer with typecheck.';
1355
+ return `Inline the initializer at its sole use only if ${/\.(?:tsx|jsx)$/.test(c.source.fileName) ? 'evaluation order and timing, closure capture, identity, writes, React hook order, and observable effects' : 'evaluation order and timing, closure capture, identity, writes, and observable effects'} remain unchanged. Otherwise retain the binding for the concrete semantic reason reported above and verify the focused behavior.`;
1356
+ })(),
1357
+ });
1358
+ }
1359
+ for (const directive of directives)
1360
+ if (!usedDirectives.has(directive))
1361
+ findings.push(singleUseDirectiveFinding(cfg, directive));
1362
+ return findings;
1363
+ }
1364
+ /**
1365
+ * Reports declarations that have exactly one in-scope consumer.
1366
+ *
1367
+ * @param cfg Quality configuration defining the source scope.
1368
+ *
1369
+ * @return Single-use recommendations with their locations and safety decisions.
1370
+ */
1371
+ export function singleUseFindings(cfg) {
1372
+ const program = programFor(cfg);
1373
+ const checker = program.getTypeChecker();
1374
+ const { candidates, references: refs } = collect(cfg, program, checker);
1375
+ return findingsFromAnalysis(cfg, checker, candidates, refs, astroConsumersFor(cfg, program), program);
1376
+ }
1377
+ /**
1378
+ * Expands a property or namespace access when the declaration is its right-hand identifier.
1379
+ *
1380
+ * @param node Identifier reference whose surrounding access expression is expanded.
1381
+ *
1382
+ * @return Largest qualified/property access expression containing the identifier.
1383
+ */
1384
+ function refTgt(node) {
1385
+ let tgt = node;
1386
+ while (tgt.parent && ((ts.isQualifiedName(tgt.parent) && tgt.parent.right === tgt) || (ts.isPropertyAccessExpression(tgt.parent) && tgt.parent.name === tgt)))
1387
+ tgt = tgt.parent;
1388
+ if (tgt.parent && ((ts.isTypeReferenceNode(tgt.parent) && tgt.parent.typeName === tgt) || (ts.isExpressionWithTypeArguments(tgt.parent) && tgt.parent.expression === tgt)))
1389
+ tgt = tgt.parent;
1390
+ return tgt;
1391
+ }
1392
+ /**
1393
+ * Substitutes generic arguments into an inlined type declaration.
1394
+ *
1395
+ * @param declaration Type declaration supplying the generic parameters.
1396
+ * @param ref Consumer type reference carrying the concrete arguments.
1397
+ * @param type Type body to expand.
1398
+ *
1399
+ * @return Expanded type text, or `null` when generic arity does not match.
1400
+ */
1401
+ function inlineGenericType(declaration, ref, type) {
1402
+ const params = declaration.typeParameters ?? [];
1403
+ const args = ref.typeArguments ?? [];
1404
+ if (params.length !== args.length)
1405
+ return null;
1406
+ const substitutions = new Map(params.map((p, i) => [p.name.text, args[i]]));
1407
+ const transformed = ts.transform(type, [
1408
+ ctx => {
1409
+ /**
1410
+ * Substitutes type parameters while preserving unrelated type syntax.
1411
+ *
1412
+ * @param node Type syntax node visited during generic expansion.
1413
+ *
1414
+ * @return Substituted node when it is a matching type reference, otherwise `undefined`.
1415
+ */
1416
+ const visit = node => {
1417
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && substitutions.has(node.typeName.text))
1418
+ return substitutions.get(node.typeName.text);
1419
+ if (ts.isTypeQueryNode(node) && ts.isIdentifier(node.exprName) && substitutions.has(node.exprName.text))
1420
+ return substitutions.get(node.exprName.text);
1421
+ return ts.visitEachChild(node, visit, ctx);
1422
+ };
1423
+ return root => ts.visitNode(root, visit);
1424
+ },
1425
+ ]);
1426
+ try {
1427
+ return `(${ts.createPrinter().printNode(ts.EmitHint.Unspecified, transformed.transformed[0], declaration.getSourceFile())})`;
1428
+ }
1429
+ finally {
1430
+ transformed.dispose();
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Finds a collision-free local name for React's createElement import.
1435
+ *
1436
+ * @param src Consumer source file.
1437
+ *
1438
+ * @return An identifier that does not occur in the consumer.
1439
+ */
1440
+ function reactCreateElName(src) {
1441
+ let name = '__hygieneCreateElement';
1442
+ while (src.text.includes(name))
1443
+ name += '_';
1444
+ return name;
1445
+ }
1446
+ /**
1447
+ * Rejects a batch when its edited files gain TypeScript errors.
1448
+ *
1449
+ * @param program Original TypeScript program used as the baseline.
1450
+ * @param updates Candidate source texts keyed by the edited absolute filename.
1451
+ *
1452
+ * @return Files whose proposed edits add TypeScript diagnostics.
1453
+ */
1454
+ export function deadCodeEditsIntroduceTypeErrors(program, updates) {
1455
+ const files = [...updates.keys()];
1456
+ const total = files.length * 2;
1457
+ qualityProgress('TypeScript validation', 0, total);
1458
+ const opts = program.getCompilerOptions();
1459
+ const host = ts.createCompilerHost(opts);
1460
+ const origHostMethods = { getSourceFile: host.getSourceFile.bind(host), fileExists: host.fileExists.bind(host) };
1461
+ const origDiagnostics = [];
1462
+ for (const [fileIndex, file] of files.entries()) {
1463
+ const sourceFile = program.getSourceFile(file);
1464
+ if (sourceFile)
1465
+ origDiagnostics.push(...ts.getPreEmitDiagnostics(program, sourceFile));
1466
+ qualityProgress('TypeScript validation', fileIndex + 1, total);
1467
+ }
1468
+ const virtualFiles = new Map([...updates].map(([f, text]) => [f, text]));
1469
+ host.getSourceFile = (fileName, langVersion, onErr, shouldCreateNewSrcFile) => {
1470
+ const text = virtualFiles.get(fileName);
1471
+ return text === undefined
1472
+ ? origHostMethods.getSourceFile(fileName, langVersion, onErr, shouldCreateNewSrcFile)
1473
+ : ts.createSourceFile(fileName, text, langVersion, true, fileName.endsWith('.tsx')
1474
+ ? ts.ScriptKind.TSX
1475
+ : fileName.endsWith('.jsx')
1476
+ ? ts.ScriptKind.JSX
1477
+ : fileName.endsWith('.js') || fileName.endsWith('.mjs') || fileName.endsWith('.cjs')
1478
+ ? ts.ScriptKind.JS
1479
+ : ts.ScriptKind.TS);
1480
+ };
1481
+ host.readFile = fileName => virtualFiles.get(fileName) ?? ts.sys.readFile(fileName);
1482
+ host.fileExists = fileName => virtualFiles.has(fileName) || origHostMethods.fileExists(fileName);
1483
+ const updatedProgram = ts.createProgram({ rootNames: program.getRootFileNames(), options: opts, host });
1484
+ /**
1485
+ * Creates a stable comparison key for one TypeScript diagnostic.
1486
+ *
1487
+ * @param diagnostic Diagnostic whose code and message are compared.
1488
+ *
1489
+ * @return Key combining the diagnostic code and flattened message.
1490
+ */
1491
+ const diagnosticKey = (diagnostic) => `${diagnostic.code}:${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`;
1492
+ const prevCounts = new Map();
1493
+ for (const diagnostic of origDiagnostics) {
1494
+ if (diagnostic.category !== ts.DiagnosticCategory.Error || !diagnostic.file)
1495
+ continue;
1496
+ const counts = prevCounts.get(diagnostic.file.fileName) ?? new Map();
1497
+ const key = diagnosticKey(diagnostic);
1498
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1499
+ prevCounts.set(diagnostic.file.fileName, counts);
1500
+ }
1501
+ const currCounts = new Map();
1502
+ for (const [fileIndex, file] of files.entries()) {
1503
+ const sourceFile = updatedProgram.getSourceFile(file);
1504
+ if (sourceFile) {
1505
+ for (const diagnostic of ts.getPreEmitDiagnostics(updatedProgram, sourceFile)) {
1506
+ if (diagnostic.category !== ts.DiagnosticCategory.Error || !diagnostic.file)
1507
+ continue;
1508
+ const counts = currCounts.get(diagnostic.file.fileName) ?? new Map();
1509
+ const key = diagnosticKey(diagnostic);
1510
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1511
+ currCounts.set(diagnostic.file.fileName, counts);
1512
+ }
1513
+ }
1514
+ qualityProgress('TypeScript validation', files.length + fileIndex + 1, total);
1515
+ }
1516
+ return [...currCounts].some(([file, after]) => [...after].some(([key, count]) => count > (prevCounts.get(file)?.get(key) ?? 0)));
1517
+ }
1518
+ /**
1519
+ * Repeats single-use inlining until nested edits have been applied in separate valid passes.
1520
+ *
1521
+ * @param cfg Quality configuration defining the source scope and files to rewrite.
1522
+ * @param changedFileNames Optional caller-owned set updated with files changed by this run.
1523
+ * @param onPass Optional callback invoked after each pass with its index and changed-file count.
1524
+ * @param finalFindings Optional array populated from the final pass's already-scanned declarations and references.
1525
+ *
1526
+ * @return Number of files changed across all passes.
1527
+ */
1528
+ export function fixSingleUseDeclarations(cfg, changedFileNames, onPass, finalFindings) {
1529
+ rejectedInlineCandidates.clear();
1530
+ const changedFiles = new Set();
1531
+ for (let pass = 0; pass < 1000; pass++) {
1532
+ onPass?.(pass + 1, changedFiles.size);
1533
+ const program = programFor(cfg);
1534
+ const checker = program.getTypeChecker();
1535
+ const { candidates, references: refs } = collect(cfg, program, checker);
1536
+ const astroConsumers = astroConsumersFor(cfg, program);
1537
+ const { byCandidate: directivesByCandidate } = singleUseIgnoreDirectives(cfg, program.getSourceFiles(), candidates);
1538
+ const edits = new Map();
1539
+ const pending = [];
1540
+ for (const c of candidates) {
1541
+ if (hasGeneratedSourceHeader(c.source.text))
1542
+ continue;
1543
+ if (hasAstroConsumer(c, astroConsumers) || isCfgdPublicContract(cfg, c, checker) || isPackageEntryExport(cfg, c, checker, program))
1544
+ continue;
1545
+ if (directivesByCandidate.has(`${c.file}:${c.name.getStart(c.source)}`))
1546
+ continue;
1547
+ if (hasMeaningfulLeadingTSDoc(c))
1548
+ continue;
1549
+ const uses = c.kind === 'type' || c.kind === 'interface' ? typeRefs(c, refs) : (refs.get(c.symbol) ?? []).filter(r => !isImportNode(r.node) && !isExportSpecifierRef(r));
1550
+ if (uses.length !== 1)
1551
+ continue;
1552
+ const ref = uses[0];
1553
+ if (isRuntimeRepeatedRef(c, ref, checker))
1554
+ continue;
1555
+ if (isModuleExport(c, checker) && !isExclusiveDefaultExport(c, checker, ref))
1556
+ continue;
1557
+ if (hasGeneratedSourceHeader(ref.source.text))
1558
+ continue;
1559
+ if (!inSingleUseScope(cfg, ref.file))
1560
+ continue;
1561
+ if (isRequiredLifecycleVal(c, ref))
1562
+ continue;
1563
+ if (c.kind === 'variable' && (ts.isJsxOpeningElement(ref.node.parent) || ts.isJsxSelfClosingElement(ref.node.parent)))
1564
+ continue;
1565
+ if (c.kind === 'function')
1566
+ continue;
1567
+ if (c.kind === 'variable' && c.file !== ref.file && !crossFileVariableSafe(c))
1568
+ continue;
1569
+ if ((c.kind === 'type' || c.kind === 'interface') && !crossFileTypeSafe(c, ref, checker))
1570
+ continue;
1571
+ if ((c.kind === 'type' || c.kind === 'interface') && containsExplicitAny(c))
1572
+ continue;
1573
+ if (c.kind === 'variable' && !initSafeToInline(c, checker, ref))
1574
+ continue;
1575
+ if (c.kind === 'variable' && isStateRestorationRef(ref))
1576
+ continue;
1577
+ if (c.kind === 'variable' && isWriteRef(ref))
1578
+ continue;
1579
+ if (hasImportedTypeAnnotation(c, checker) || hasCallSensitiveTypeAnnotation(c, checker, ref))
1580
+ continue;
1581
+ const replacement = (() => {
1582
+ const typeRef = refTgt(ref.node);
1583
+ if ((ts.isTypeAliasDeclaration(c.statement) || ts.isInterfaceDeclaration(c.statement)) && ts.isTypeReferenceNode(typeRef)) {
1584
+ if (ts.isTypeAliasDeclaration(c.statement))
1585
+ return inlineGenericType(c.statement, typeRef, c.statement.type);
1586
+ return inlineGenericType(c.statement, typeRef, ts.factory.createTypeLiteralNode(c.statement.members));
1587
+ }
1588
+ if (ts.isTypeAliasDeclaration(c.statement))
1589
+ return c.statement.typeParameters?.length ? null : `(${c.statement.type.getText(c.source)})`;
1590
+ if (ts.isInterfaceDeclaration(c.statement)) {
1591
+ if (c.statement.typeParameters?.length)
1592
+ return null;
1593
+ const mems = `{ ${c.statement.members.map(member => member.getText(c.source)).join(' ')} }`;
1594
+ const bases = c.statement.heritageClauses?.flatMap(clause => clause.types.map(type => type.getText(c.source))) ?? [];
1595
+ return bases.length ? `(${[...bases, mems].join(' & ')})` : `(${mems})`;
1596
+ }
1597
+ if (ts.isFunctionDeclaration(c.statement)) {
1598
+ const statement = c.statement;
1599
+ if (ts.isTypeQueryNode(ref.node.parent))
1600
+ return ts.createPrinter().printNode(ts.EmitHint.Unspecified, ts.factory.createFunctionTypeNode(statement.typeParameters, statement.parameters.map(param => ts.factory.createParameterDeclaration(undefined, param.dotDotDotToken, param.name, param.questionToken, param.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword))), statement.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)), statement.getSourceFile());
1601
+ if (!statement.body)
1602
+ return null;
1603
+ return `(${statement
1604
+ .getText(statement.getSourceFile())
1605
+ .replace(/^export\s+default\s+/, '')
1606
+ .replace(/^export\s+/, '')
1607
+ .replace(/^declare\s+/, '')})`;
1608
+ }
1609
+ if (!ts.isVariableStatement(c.statement))
1610
+ return null;
1611
+ const init = c.statement.declarationList.declarations[0]?.initializer;
1612
+ if (init && ts.isTypeQueryNode(ref.node.parent)) {
1613
+ const inferredType = checker.typeToTypeNode(checker.getTypeAtLocation(init), undefined, ts.NodeBuilderFlags.NoTruncation);
1614
+ return inferredType ? ts.createPrinter().printNode(ts.EmitHint.Unspecified, inferredType, ref.source) : null;
1615
+ }
1616
+ return init ? (isAdjacentModuleDefaultExport(c, ref) ? init.getText(c.source) : `(${init.getText(c.source)})`) : 'undefined';
1617
+ })();
1618
+ if (!replacement)
1619
+ continue;
1620
+ const comments = (isAdjacentModuleDefaultExport(c, ref) ? [] : (ts.getLeadingCommentRanges(c.source.text, c.statement.getFullStart()) ?? []))
1621
+ .filter((r, i, ranges) => r.end <= c.statement.getStart(c.source) && S_REGEX.test(c.source.text.slice(r.end, ranges[i + 1]?.pos ?? c.statement.getStart(c.source))))
1622
+ .filter(r => {
1623
+ const val = c.source.text.slice(r.pos, r.end);
1624
+ return !(S_REGEX.test(c.source.text.slice(0, r.pos)) && S_S_W_CM_JT_SX_B_REGEX.test(val)) && !/^\/\*\/{10,}/.test(val) && !/^\/\/\s*[A-Z][A-Z _-]*\s*$/.test(val);
1625
+ })
1626
+ .map(r => ({ start: r.pos, end: r.end, text: c.source.text.slice(r.pos, r.end) }));
1627
+ const commentTexts = [
1628
+ ...comments.map(({ text: val }) => val).filter(val => !val.startsWith('/**')),
1629
+ ...(() => {
1630
+ const statement = c.statement;
1631
+ if (!ts.isVariableStatement(statement))
1632
+ return [];
1633
+ const init = statement.declarationList.declarations[0]?.initializer;
1634
+ if (!init)
1635
+ return [];
1636
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, c.source.languageVariant, c.source.text.slice(statement.getStart(c.source), init.getStart(c.source)));
1637
+ const discarded = [];
1638
+ for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan())
1639
+ if (token === ts.SyntaxKind.SingleLineCommentTrivia || token === ts.SyntaxKind.MultiLineCommentTrivia)
1640
+ discarded.push(scanner.getTokenText());
1641
+ return discarded;
1642
+ })(),
1643
+ ];
1644
+ const inlineReplacement = commentTexts.length ? `${commentTexts.map(v => (v.startsWith('//') ? `/* ${v.slice(2).trim()} */` : v)).join(' ')} ${replacement}` : replacement;
1645
+ const candidateEdits = [];
1646
+ for (const comment of comments)
1647
+ candidateEdits.push({ file: c.file, start: comment.start, end: comment.end, text: '' });
1648
+ const compType = ts.isFunctionDeclaration(c.statement) && c.statement.parameters[0]?.type ? `React.ComponentType<${c.statement.parameters[0].type.getText(c.source)}>` : undefined;
1649
+ const jsxName = (() => {
1650
+ const parent = ref.node.parent;
1651
+ if ((!ts.isJsxOpeningElement(parent) && !ts.isJsxSelfClosingElement(parent)) || parent.tagName !== ref.node)
1652
+ return null;
1653
+ const el = ts.isJsxSelfClosingElement(parent) ? parent : ts.isJsxElement(parent.parent) ? parent.parent : null;
1654
+ if (!el)
1655
+ return null;
1656
+ const props = parent.attributes.properties.map(attr => {
1657
+ if (ts.isJsxSpreadAttribute(attr))
1658
+ return `...${attr.expression.getText(ref.source)}`;
1659
+ const name = JSON.stringify(attr.name.getText(ref.source));
1660
+ if (!attr.initializer)
1661
+ return `${name}: true`;
1662
+ if (ts.isStringLiteral(attr.initializer))
1663
+ return `${name}: ${JSON.stringify(attr.initializer.text)}`;
1664
+ if (ts.isJsxExpression(attr.initializer))
1665
+ return `${name}: ${attr.initializer.expression?.getText(ref.source) ?? 'undefined'}`;
1666
+ return `${name}: ${attr.initializer.getText(ref.source)}`;
1667
+ });
1668
+ if (ts.isJsxElement(el) && el.children.length)
1669
+ props.push(`children: <>${el.children.map(child => child.getText(ref.source)).join('')}</>`);
1670
+ const call = `${reactCreateElName(ref.source)}(${compType ? `(${inlineReplacement} as ${compType})` : inlineReplacement}, { ${props.join(', ')} })`;
1671
+ return { start: el.getStart(ref.source), end: el.getEnd(), text: ts.isJsxElement(el.parent) || ts.isJsxFragment(el.parent) ? `{${call}}` : call };
1672
+ })();
1673
+ let jsxFile;
1674
+ if (jsxName) {
1675
+ candidateEdits.push({ file: ref.file, ...jsxName });
1676
+ jsxFile = ref.file;
1677
+ }
1678
+ else if (ts.isShorthandPropertyAssignment(ref.node.parent)) {
1679
+ candidateEdits.push({ file: ref.file, start: ref.node.getStart(ref.source), end: ref.node.getEnd(), text: `${ref.node.text}: ${inlineReplacement}` });
1680
+ }
1681
+ else {
1682
+ const tgt = ts.isTypeQueryNode(ref.node.parent) ? ref.node.parent : refTgt(ref.node);
1683
+ candidateEdits.push({ file: ref.file, start: tgt.getStart(ref.source), end: tgt.getEnd(), text: inlineReplacement });
1684
+ }
1685
+ const removedImport = (() => {
1686
+ for (const statement of ref.source.statements) {
1687
+ if (!ts.isImportDeclaration(statement))
1688
+ continue;
1689
+ const bindings = statement.importClause?.namedBindings;
1690
+ if (!bindings || !ts.isNamedImports(bindings))
1691
+ continue;
1692
+ const specifier = bindings.elements.find(el => canonical(checker, checker.getSymbolAtLocation(el.name)) === c.symbol);
1693
+ if (!specifier)
1694
+ continue;
1695
+ if (bindings.elements.length === 1)
1696
+ return { start: statement.getStart(ref.source), end: statement.getEnd() };
1697
+ const idx = bindings.elements.indexOf(specifier);
1698
+ return idx === 0 ? { start: specifier.getStart(ref.source), end: bindings.elements[1].getStart(ref.source) } : { start: bindings.elements[idx - 1].getEnd(), end: specifier.getEnd() };
1699
+ }
1700
+ return null;
1701
+ })();
1702
+ if (removedImport)
1703
+ candidateEdits.push({ file: ref.file, ...removedImport, text: '' });
1704
+ const statementStart = c.statement.getStart(c.source);
1705
+ const statementEnd = c.statement.getEnd();
1706
+ const lineStart = c.source.text.lastIndexOf('\n', statementStart - 1) + 1;
1707
+ const lineEnd = c.source.text.indexOf('\n', statementEnd);
1708
+ const ownsLine = S_U_REGEX.test(c.source.text.slice(lineStart, statementStart)) && S_U_REGEX.test(c.source.text.slice(statementEnd, lineEnd < 0 ? c.source.text.length : lineEnd));
1709
+ candidateEdits.push({ file: c.file, start: ownsLine ? lineStart : statementStart, end: ownsLine ? (lineEnd < 0 ? statementEnd : lineEnd + 1) : statementEnd, text: '' });
1710
+ const refEdit = candidateEdits.find(e => e.file === ref.file && e.end > e.start);
1711
+ pending.push({
1712
+ fileEdits: candidateEdits,
1713
+ referenceLength: refEdit.end - refEdit.start,
1714
+ nestedReference: candidates.some(o => o !== c && o.source === ref.source && ref.node.getStart(ref.source) >= o.statement.getStart(ref.source) && ref.node.getEnd() <= o.statement.getEnd()),
1715
+ candidateKey: `${c.file}:${c.name.text}`,
1716
+ jsxFile,
1717
+ });
1718
+ }
1719
+ const selected = [];
1720
+ for (const candidate of pending.sort((l, r) => Number(r.nestedReference) - Number(l.nestedReference) || l.referenceLength - r.referenceLength)) {
1721
+ if (selected.some(other => candidate.fileEdits.some(edit => other.fileEdits.some(existing => edit.file === existing.file && edit.start < existing.end && existing.start < edit.end))))
1722
+ continue;
1723
+ selected.push(candidate);
1724
+ }
1725
+ let remaining = selected;
1726
+ while (remaining.length) {
1727
+ edits.clear();
1728
+ for (const candidate of remaining)
1729
+ for (const edit of candidate.fileEdits)
1730
+ edits.set(edit.file, [...(edits.get(edit.file) ?? []), edit]);
1731
+ for (const file of new Set(remaining.flatMap(candidate => (candidate.jsxFile ? [candidate.jsxFile] : [])))) {
1732
+ const source = program.getSourceFile(file);
1733
+ const imports = source.statements.filter(ts.isImportDeclaration);
1734
+ const pos = imports.length ? imports[imports.length - 1].end : (source.statements[0]?.getStart(source) ?? 0);
1735
+ edits.set(file, [...(edits.get(file) ?? []), { start: pos, end: pos, text: `${pos ? '\n' : ''}import { createElement as ${reactCreateElName(source)} } from 'react';\n` }]);
1736
+ }
1737
+ const invalidFiles = new Set();
1738
+ for (const [file, fileEdits] of edits) {
1739
+ const ascending = [...fileEdits].sort((a, b) => a.start - b.start || a.end - b.end);
1740
+ if (!program.getSourceFile(file) || ascending.some((edit, i) => i > 0 && edit.end > edit.start && ascending[i - 1].end > ascending[i - 1].start && edit.start < ascending[i - 1].end)) {
1741
+ invalidFiles.add(file);
1742
+ continue;
1743
+ }
1744
+ if (ts.createSourceFile(file, ascending.reverse().reduce((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), readFileSync(file, 'utf8')), ts.ScriptTarget.Latest, true, file.endsWith('.tsx') || file.endsWith('.jsx') ? ts.ScriptKind.TSX : file.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS).parseDiagnostics.length)
1745
+ invalidFiles.add(file);
1746
+ }
1747
+ if (!invalidFiles.size)
1748
+ break;
1749
+ const rejected = remaining.filter(c => c.fileEdits.some(edit => invalidFiles.has(edit.file)) || (c.jsxFile && invalidFiles.has(c.jsxFile)));
1750
+ for (const candidate of rejected)
1751
+ rejectedInlineCandidates.set(candidate.candidateKey, `the combined inline in ${[...invalidFiles].map(f => relative(cfg.root, f)).join(', ')} would produce invalid syntax; resolve this candidate manually`);
1752
+ remaining = remaining.filter(c => !rejected.includes(c));
1753
+ }
1754
+ const updates = [];
1755
+ for (const [file, fileEdits] of edits) {
1756
+ const src = readFileSync(file, 'utf8');
1757
+ const ascending = [...fileEdits].sort((a, b) => a.start - b.start || a.end - b.end);
1758
+ if (ascending.some((e, i) => e.end > e.start && i > 0 && ascending[i - 1].end > ascending[i - 1].start && e.start < ascending[i - 1].end))
1759
+ continue;
1760
+ const updated = ascending.reverse().reduce((t, e) => t.slice(0, e.start) + e.text + t.slice(e.end), src);
1761
+ if (updated === src)
1762
+ continue;
1763
+ if (ts.createSourceFile(file, updated, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') || file.endsWith('.jsx') ? ts.ScriptKind.TSX : file.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS).parseDiagnostics.length)
1764
+ continue;
1765
+ updates.push({ file, text: updated });
1766
+ }
1767
+ for (const { file, text } of updates) {
1768
+ writeFileSync(file, text);
1769
+ changedFiles.add(file);
1770
+ }
1771
+ if (!updates.length && finalFindings)
1772
+ finalFindings.splice(0, finalFindings.length, ...findingsFromAnalysis(cfg, checker, candidates, refs, astroConsumers, program));
1773
+ if (!updates.length) {
1774
+ for (const file of changedFiles)
1775
+ changedFileNames?.add(file);
1776
+ return changedFiles.size;
1777
+ }
1778
+ }
1779
+ throw new Error('Single-use inlining exceeded 1000 passes; check for a rewrite that does not converge.');
1780
+ }
1781
+ /**
1782
+ * Backwards-compatible name for callers that previously fixed only type declarations.
1783
+ *
1784
+ * @param cfg Quality configuration defining the source scope and files to rewrite.
1785
+ *
1786
+ * @return Number of files containing edits.
1787
+ */
1788
+ export function fixSingleUseTypes(cfg) {
1789
+ return fixSingleUseDeclarations(cfg);
1790
+ }
1791
+ //# sourceMappingURL=single-use.js.map