@wyw-in-js/transform 2.0.0-alpha.0 → 2.0.0-alpha.1

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 (270) hide show
  1. package/esm/cache.js +7 -0
  2. package/esm/cache.js.map +1 -1
  3. package/esm/debug/fileReporter.js +35 -1
  4. package/esm/debug/fileReporter.js.map +1 -1
  5. package/esm/eval/broker.js +230 -89
  6. package/esm/eval/broker.js.map +1 -1
  7. package/esm/eval/protocol.js.map +1 -1
  8. package/esm/eval/runner.js +143 -24
  9. package/esm/eval/runner.js.map +1 -1
  10. package/esm/module.js +70 -43
  11. package/esm/module.js.map +1 -1
  12. package/esm/transform/Entrypoint.types.js.map +1 -1
  13. package/esm/transform/generators/processEntrypoint.js +35 -20
  14. package/esm/transform/generators/processEntrypoint.js.map +1 -1
  15. package/esm/transform/generators/resolveImports.js +48 -2
  16. package/esm/transform/generators/resolveImports.js.map +1 -1
  17. package/esm/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  18. package/esm/transform/generators/resolveStaticOxcValues/cache.js.map +1 -0
  19. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js +146 -0
  20. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js.map +1 -0
  21. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js +33 -0
  22. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js.map +1 -0
  23. package/esm/transform/generators/resolveStaticOxcValues/environment.js +29 -0
  24. package/esm/transform/generators/resolveStaticOxcValues/environment.js.map +1 -0
  25. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js +351 -0
  26. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js.map +1 -0
  27. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js +253 -0
  28. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js.map +1 -0
  29. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js +310 -0
  30. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js.map +1 -0
  31. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +74 -0
  32. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js.map +1 -0
  33. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +229 -0
  34. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js.map +1 -0
  35. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js +172 -0
  36. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js.map +1 -0
  37. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js +476 -0
  38. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js.map +1 -0
  39. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js +55 -0
  40. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js.map +1 -0
  41. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js +123 -0
  42. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js.map +1 -0
  43. package/esm/transform/generators/resolveStaticOxcValues/prune.js +186 -0
  44. package/esm/transform/generators/resolveStaticOxcValues/prune.js.map +1 -0
  45. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +183 -0
  46. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js.map +1 -0
  47. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js +298 -0
  48. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js.map +1 -0
  49. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +298 -0
  50. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js.map +1 -0
  51. package/esm/transform/generators/resolveStaticOxcValues/types.js +3 -0
  52. package/esm/transform/generators/resolveStaticOxcValues/types.js.map +1 -0
  53. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +59 -0
  54. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js.map +1 -0
  55. package/esm/transform/generators/resolveStaticOxcValues.js +1 -2910
  56. package/esm/transform/generators/resolveStaticOxcValues.js.map +1 -1
  57. package/esm/transform/generators/transform.js +57 -45
  58. package/esm/transform/generators/transform.js.map +1 -1
  59. package/esm/transform/helpers/loadWywOptions.js +33 -4
  60. package/esm/transform/helpers/loadWywOptions.js.map +1 -1
  61. package/esm/transform.js +3 -1
  62. package/esm/transform.js.map +1 -1
  63. package/esm/utils/EventEmitter.js +42 -9
  64. package/esm/utils/EventEmitter.js.map +1 -1
  65. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js +160 -0
  66. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js.map +1 -0
  67. package/esm/utils/applyOxcProcessors/cleanupBindings.js +157 -0
  68. package/esm/utils/applyOxcProcessors/cleanupBindings.js.map +1 -0
  69. package/esm/utils/applyOxcProcessors/cleanupRemovals.js +431 -0
  70. package/esm/utils/applyOxcProcessors/cleanupRemovals.js.map +1 -0
  71. package/esm/utils/applyOxcProcessors/displayName.js +93 -0
  72. package/esm/utils/applyOxcProcessors/displayName.js.map +1 -0
  73. package/esm/utils/applyOxcProcessors/expressionValues.js +152 -0
  74. package/esm/utils/applyOxcProcessors/expressionValues.js.map +1 -0
  75. package/esm/utils/applyOxcProcessors/processorFactory.js +62 -0
  76. package/esm/utils/applyOxcProcessors/processorFactory.js.map +1 -0
  77. package/esm/utils/applyOxcProcessors/processorUsages.js +143 -0
  78. package/esm/utils/applyOxcProcessors/processorUsages.js.map +1 -0
  79. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js +207 -0
  80. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js.map +1 -0
  81. package/esm/utils/applyOxcProcessors/shared.js +29 -0
  82. package/esm/utils/applyOxcProcessors/shared.js.map +1 -0
  83. package/esm/utils/applyOxcProcessors/types.js +2 -0
  84. package/esm/utils/applyOxcProcessors/types.js.map +1 -0
  85. package/esm/utils/applyOxcProcessors.js +1 -1216
  86. package/esm/utils/applyOxcProcessors.js.map +1 -1
  87. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js +157 -0
  88. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js.map +1 -0
  89. package/esm/utils/collectOxcRuntime/sourceMap.js +36 -0
  90. package/esm/utils/collectOxcRuntime/sourceMap.js.map +1 -0
  91. package/esm/utils/collectOxcRuntime/types.js +2 -0
  92. package/esm/utils/collectOxcRuntime/types.js.map +1 -0
  93. package/esm/utils/collectOxcRuntime.js +5 -193
  94. package/esm/utils/collectOxcRuntime.js.map +1 -1
  95. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js +496 -0
  96. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js.map +1 -0
  97. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js +113 -0
  98. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js.map +1 -0
  99. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js +387 -0
  100. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js.map +1 -0
  101. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js +17 -0
  102. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js.map +1 -0
  103. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js +540 -0
  104. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js.map +1 -0
  105. package/esm/utils/collectOxcTemplateDependencies/types.js +2 -0
  106. package/esm/utils/collectOxcTemplateDependencies/types.js.map +1 -0
  107. package/esm/utils/collectOxcTemplateDependencies.js +3 -1397
  108. package/esm/utils/collectOxcTemplateDependencies.js.map +1 -1
  109. package/esm/utils/nativeResolver.js +93 -0
  110. package/esm/utils/nativeResolver.js.map +1 -0
  111. package/esm/utils/oxc/ast.js +28 -0
  112. package/esm/utils/oxc/ast.js.map +1 -0
  113. package/esm/utils/oxc/parse.js +3 -0
  114. package/esm/utils/oxc/parse.js.map +1 -0
  115. package/esm/utils/oxc/replacements.js +14 -0
  116. package/esm/utils/oxc/replacements.js.map +1 -0
  117. package/esm/utils/oxc/sourceLocations.js +59 -0
  118. package/esm/utils/oxc/sourceLocations.js.map +1 -0
  119. package/esm/utils/oxcPreevalStage/evalStrategy.js +3 -0
  120. package/esm/utils/oxcPreevalStage/evalStrategy.js.map +1 -0
  121. package/esm/utils/oxcPreevalStage/prepareCode.js +21 -0
  122. package/esm/utils/oxcPreevalStage/prepareCode.js.map +1 -0
  123. package/esm/utils/oxcPreevalStage/prevalExport.js +23 -0
  124. package/esm/utils/oxcPreevalStage/prevalExport.js.map +1 -0
  125. package/esm/utils/oxcPreevalStage/processors.js +17 -0
  126. package/esm/utils/oxcPreevalStage/processors.js.map +1 -0
  127. package/esm/utils/oxcPreevalStage/staticOverlay.js +18 -0
  128. package/esm/utils/oxcPreevalStage/staticOverlay.js.map +1 -0
  129. package/esm/utils/oxcPreevalStage/types.js +2 -0
  130. package/esm/utils/oxcPreevalStage/types.js.map +1 -0
  131. package/esm/utils/oxcPreevalStage.js +17 -73
  132. package/esm/utils/oxcPreevalStage.js.map +1 -1
  133. package/esm/utils/oxcPreevalTransforms.js +12 -1
  134. package/esm/utils/oxcPreevalTransforms.js.map +1 -1
  135. package/esm/utils/processorStaticSemantics.js +157 -0
  136. package/esm/utils/processorStaticSemantics.js.map +1 -0
  137. package/esm/utils/resolveWithConditions.js +3 -3
  138. package/esm/utils/resolveWithConditions.js.map +1 -1
  139. package/package.json +4 -3
  140. package/types/cache.js +8 -0
  141. package/types/debug/fileReporter.js +46 -1
  142. package/types/eval/broker.d.ts +6 -2
  143. package/types/eval/broker.js +244 -95
  144. package/types/eval/protocol.d.ts +15 -1
  145. package/types/module.d.ts +4 -1
  146. package/types/module.js +97 -48
  147. package/types/transform/Entrypoint.types.d.ts +3 -0
  148. package/types/transform/generators/resolveImports.d.ts +3 -1
  149. package/types/transform/generators/resolveImports.js +49 -2
  150. package/types/transform/generators/resolveStaticOxcValues/cache.d.ts +25 -0
  151. package/types/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  152. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.d.ts +5 -0
  153. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.js +149 -0
  154. package/types/transform/generators/resolveStaticOxcValues/dependencies.d.ts +6 -0
  155. package/types/transform/generators/resolveStaticOxcValues/dependencies.js +37 -0
  156. package/types/transform/generators/resolveStaticOxcValues/environment.d.ts +12 -0
  157. package/types/transform/generators/resolveStaticOxcValues/environment.js +32 -0
  158. package/types/transform/generators/resolveStaticOxcValues/exportResolver.d.ts +4 -0
  159. package/types/transform/generators/resolveStaticOxcValues/exportResolver.js +358 -0
  160. package/types/transform/generators/resolveStaticOxcValues/exportTargets.d.ts +20 -0
  161. package/types/transform/generators/resolveStaticOxcValues/exportTargets.js +285 -0
  162. package/types/transform/generators/resolveStaticOxcValues/objectAssign.d.ts +41 -0
  163. package/types/transform/generators/resolveStaticOxcValues/objectAssign.js +352 -0
  164. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.d.ts +6 -0
  165. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +88 -0
  166. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.d.ts +13 -0
  167. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +263 -0
  168. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.d.ts +4 -0
  169. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.js +191 -0
  170. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.d.ts +40 -0
  171. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.js +516 -0
  172. package/types/transform/generators/resolveStaticOxcValues/processorTarget.d.ts +5 -0
  173. package/types/transform/generators/resolveStaticOxcValues/processorTarget.js +62 -0
  174. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.d.ts +11 -0
  175. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.js +133 -0
  176. package/types/transform/generators/resolveStaticOxcValues/prune.d.ts +15 -0
  177. package/types/transform/generators/resolveStaticOxcValues/prune.js +220 -0
  178. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.d.ts +2 -0
  179. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +197 -0
  180. package/types/transform/generators/resolveStaticOxcValues/staticExpression.d.ts +25 -0
  181. package/types/transform/generators/resolveStaticOxcValues/staticExpression.js +391 -0
  182. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.d.ts +14 -0
  183. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +304 -0
  184. package/types/transform/generators/resolveStaticOxcValues/types.d.ts +99 -0
  185. package/types/transform/generators/resolveStaticOxcValues/types.js +2 -0
  186. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.d.ts +7 -0
  187. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +64 -0
  188. package/types/transform/generators/resolveStaticOxcValues.d.ts +1 -2
  189. package/types/transform/generators/resolveStaticOxcValues.js +1 -3235
  190. package/types/transform/generators/transform.js +63 -49
  191. package/types/transform/helpers/loadWywOptions.js +23 -3
  192. package/types/transform.js +3 -1
  193. package/types/utils/EventEmitter.d.ts +16 -1
  194. package/types/utils/EventEmitter.js +44 -9
  195. package/types/utils/applyOxcProcessors/applyOxcProcessors.d.ts +8 -0
  196. package/types/utils/applyOxcProcessors/applyOxcProcessors.js +167 -0
  197. package/types/utils/applyOxcProcessors/cleanupBindings.d.ts +12 -0
  198. package/types/utils/applyOxcProcessors/cleanupBindings.js +189 -0
  199. package/types/utils/applyOxcProcessors/cleanupRemovals.d.ts +16 -0
  200. package/types/utils/applyOxcProcessors/cleanupRemovals.js +482 -0
  201. package/types/utils/applyOxcProcessors/displayName.d.ts +9 -0
  202. package/types/utils/applyOxcProcessors/displayName.js +113 -0
  203. package/types/utils/applyOxcProcessors/expressionValues.d.ts +11 -0
  204. package/types/utils/applyOxcProcessors/expressionValues.js +170 -0
  205. package/types/utils/applyOxcProcessors/processorFactory.d.ts +7 -0
  206. package/types/utils/applyOxcProcessors/processorFactory.js +70 -0
  207. package/types/utils/applyOxcProcessors/processorUsages.d.ts +16 -0
  208. package/types/utils/applyOxcProcessors/processorUsages.js +163 -0
  209. package/types/utils/applyOxcProcessors/sameFileStaticValues.d.ts +23 -0
  210. package/types/utils/applyOxcProcessors/sameFileStaticValues.js +211 -0
  211. package/types/utils/applyOxcProcessors/shared.d.ts +10 -0
  212. package/types/utils/applyOxcProcessors/shared.js +37 -0
  213. package/types/utils/applyOxcProcessors/types.d.ts +88 -0
  214. package/types/utils/applyOxcProcessors/types.js +1 -0
  215. package/types/utils/applyOxcProcessors.d.ts +1 -16
  216. package/types/utils/applyOxcProcessors.js +1 -1391
  217. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.d.ts +1 -0
  218. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.js +185 -0
  219. package/types/utils/collectOxcRuntime/sourceMap.d.ts +2 -0
  220. package/types/utils/collectOxcRuntime/sourceMap.js +37 -0
  221. package/types/utils/collectOxcRuntime/types.d.ts +16 -0
  222. package/types/utils/collectOxcRuntime/types.js +1 -0
  223. package/types/utils/collectOxcRuntime.d.ts +2 -12
  224. package/types/utils/collectOxcRuntime.js +5 -224
  225. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.d.ts +6 -0
  226. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.js +550 -0
  227. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.d.ts +11 -0
  228. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.js +131 -0
  229. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.d.ts +20 -0
  230. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.js +434 -0
  231. package/types/utils/collectOxcTemplateDependencies/staticBindings.d.ts +7 -0
  232. package/types/utils/collectOxcTemplateDependencies/staticBindings.js +13 -0
  233. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.d.ts +13 -0
  234. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.js +626 -0
  235. package/types/utils/collectOxcTemplateDependencies/types.d.ts +116 -0
  236. package/types/utils/collectOxcTemplateDependencies/types.js +1 -0
  237. package/types/utils/collectOxcTemplateDependencies.d.ts +4 -38
  238. package/types/utils/collectOxcTemplateDependencies.js +3 -1580
  239. package/types/utils/nativeResolver.d.ts +13 -0
  240. package/types/utils/nativeResolver.js +91 -0
  241. package/types/utils/oxc/ast.d.ts +4 -0
  242. package/types/utils/oxc/ast.js +37 -0
  243. package/types/utils/oxc/parse.d.ts +3 -0
  244. package/types/utils/oxc/parse.js +2 -0
  245. package/types/utils/oxc/replacements.d.ts +12 -0
  246. package/types/utils/oxc/replacements.js +18 -0
  247. package/types/utils/oxc/sourceLocations.d.ts +5 -0
  248. package/types/utils/oxc/sourceLocations.js +63 -0
  249. package/types/utils/oxcPreevalStage/evalStrategy.d.ts +3 -0
  250. package/types/utils/oxcPreevalStage/evalStrategy.js +2 -0
  251. package/types/utils/oxcPreevalStage/prepareCode.d.ts +3 -0
  252. package/types/utils/oxcPreevalStage/prepareCode.js +20 -0
  253. package/types/utils/oxcPreevalStage/prevalExport.d.ts +1 -0
  254. package/types/utils/oxcPreevalStage/prevalExport.js +22 -0
  255. package/types/utils/oxcPreevalStage/processors.d.ts +10 -0
  256. package/types/utils/oxcPreevalStage/processors.js +16 -0
  257. package/types/utils/oxcPreevalStage/staticOverlay.d.ts +3 -0
  258. package/types/utils/oxcPreevalStage/staticOverlay.js +23 -0
  259. package/types/utils/oxcPreevalStage/types.d.ts +22 -0
  260. package/types/utils/oxcPreevalStage/types.js +1 -0
  261. package/types/utils/oxcPreevalStage.d.ts +2 -18
  262. package/types/utils/oxcPreevalStage.js +17 -79
  263. package/types/utils/oxcPreevalTransforms.js +14 -1
  264. package/types/utils/processorStaticSemantics.d.ts +13 -0
  265. package/types/utils/processorStaticSemantics.js +191 -0
  266. package/types/utils/resolveWithConditions.js +3 -3
  267. package/esm/eval/resolverStrategy.js +0 -51
  268. package/esm/eval/resolverStrategy.js.map +0 -1
  269. package/types/eval/resolverStrategy.d.ts +0 -13
  270. package/types/eval/resolverStrategy.js +0 -46
@@ -1,1391 +1 @@
1
- /* eslint-disable no-restricted-syntax */
2
- import { basename, dirname } from 'path';
3
- import { BaseProcessor, expressionToCode } from '@wyw-in-js/processor-utils';
4
- import { ValueType } from '@wyw-in-js/shared';
5
- import { collectOxcProcessorImportsFromProgram } from './collectOxcExportsAndImports';
6
- import { EventEmitter } from './EventEmitter';
7
- import { collectOxcExpressionDependencies, } from './collectOxcTemplateDependencies';
8
- import { isNotNull } from './isNotNull';
9
- import { createOxcAstService, printOxcAstServiceImport, } from './oxcAstService';
10
- import { parseOxcProgramCached } from './parseOxc';
11
- import { getProcessorForImport } from './processorLookup';
12
- let didWarnSkipSymbolMismatch = false;
13
- const GENERATED_HELPER_NAME_RE = /^_exp\d*$/;
14
- const isNode = (value) => !!value &&
15
- typeof value === 'object' &&
16
- 'type' in value &&
17
- typeof value.type === 'string';
18
- const getChildren = (node) => {
19
- const result = [];
20
- const record = node;
21
- Object.keys(record).forEach((key) => {
22
- if (key === 'type' || key === 'start' || key === 'end' || key === 'range') {
23
- return;
24
- }
25
- const value = record[key];
26
- if (isNode(value)) {
27
- result.push(value);
28
- return;
29
- }
30
- if (Array.isArray(value)) {
31
- value.forEach((item) => {
32
- if (isNode(item)) {
33
- result.push(item);
34
- }
35
- });
36
- }
37
- });
38
- return result;
39
- };
40
- const parseOxc = (code, filename) => {
41
- return parseOxcProgramCached(filename, code, 'module');
42
- };
43
- const visit = (node, enter, parent = null) => {
44
- enter(node, parent);
45
- getChildren(node).forEach((child) => visit(child, enter, node));
46
- };
47
- const applyReplacements = (code, replacements) => {
48
- let result = code;
49
- replacements
50
- .sort((a, b) => b.start - a.start)
51
- .forEach((replacement) => {
52
- result =
53
- result.slice(0, replacement.start) +
54
- replacement.value +
55
- result.slice(replacement.end);
56
- });
57
- return result;
58
- };
59
- const insertAddedImports = (code, program, addedImports) => {
60
- if (addedImports.length === 0) {
61
- return code;
62
- }
63
- const uniqueImports = [
64
- ...new Map(addedImports.map((item) => [
65
- `${item.source}\0${item.imported}\0${item.local}`,
66
- item,
67
- ])).values(),
68
- ];
69
- const importBlock = uniqueImports.map(printOxcAstServiceImport).join('\n');
70
- const lastImport = [...program.body]
71
- .reverse()
72
- .find((statement) => statement.type === 'ImportDeclaration');
73
- const hashbangEnd = code.startsWith('#!')
74
- ? (() => {
75
- const newline = code.indexOf('\n');
76
- return newline === -1 ? code.length : newline + 1;
77
- })()
78
- : 0;
79
- const insertionPoint = lastImport?.end ?? hashbangEnd;
80
- const prefix = code.slice(0, insertionPoint);
81
- const suffix = code.slice(insertionPoint);
82
- const leadingBreak = prefix.length > 0 && !prefix.endsWith('\n') ? '\n' : '';
83
- const trailingBreak = suffix.length > 0 && !suffix.startsWith('\n') ? '\n' : '';
84
- return `${prefix}${leadingBreak}${importBlock}${trailingBreak}${suffix}`;
85
- };
86
- const createLocationLookup = (code) => {
87
- const lineStarts = [0];
88
- for (let idx = 0; idx < code.length; idx += 1) {
89
- if (code[idx] === '\n') {
90
- lineStarts.push(idx + 1);
91
- }
92
- }
93
- return (offset) => {
94
- let low = 0;
95
- let high = lineStarts.length - 1;
96
- while (low <= high) {
97
- const mid = Math.floor((low + high) / 2);
98
- const next = lineStarts[mid + 1] ?? Infinity;
99
- if (lineStarts[mid] <= offset && offset < next) {
100
- return {
101
- column: offset - lineStarts[mid],
102
- line: mid + 1,
103
- };
104
- }
105
- if (offset < lineStarts[mid]) {
106
- high = mid - 1;
107
- }
108
- else {
109
- low = mid + 1;
110
- }
111
- }
112
- const lastLine = lineStarts.length - 1;
113
- return {
114
- column: Math.max(0, offset - lineStarts[lastLine]),
115
- line: lastLine + 1,
116
- };
117
- };
118
- };
119
- const getSourceLocation = (start, end, loc, filename) => ({
120
- end: loc(end),
121
- filename: filename ?? undefined,
122
- start: loc(start),
123
- });
124
- const buildCodeFrameError = (code, location, message) => {
125
- const lines = code.split('\n');
126
- const startLine = location.start.line;
127
- const endLine = location.end.line;
128
- const frameStart = Math.max(1, startLine - 2);
129
- const frameEnd = Math.min(lines.length, endLine + 2);
130
- const lineNoWidth = String(frameEnd).length;
131
- const frame = [];
132
- for (let lineNo = frameStart; lineNo <= frameEnd; lineNo += 1) {
133
- const marker = lineNo === startLine ? '>' : ' ';
134
- const line = lines[lineNo - 1] ?? '';
135
- frame.push(line.length > 0
136
- ? `${marker} ${String(lineNo).padStart(lineNoWidth)} | ${line}`
137
- : `${marker} ${String(lineNo).padStart(lineNoWidth)} |`);
138
- if (lineNo === startLine) {
139
- const pointerLength = startLine === endLine
140
- ? Math.max(1, location.end.column - location.start.column)
141
- : 1;
142
- frame.push(` ${' '.repeat(lineNoWidth)} | ${' '.repeat(location.start.column)}${'^'.repeat(pointerLength)}`);
143
- }
144
- }
145
- const prefix = location.filename ? `${location.filename}: ` : '';
146
- return new Error(`${prefix}${message}\n${frame.join('\n')}`);
147
- };
148
- const collectUsedNames = (program) => {
149
- const names = new Set();
150
- visit(program, (node) => {
151
- if (node.type === 'Identifier') {
152
- names.add(node.name);
153
- }
154
- });
155
- return names;
156
- };
157
- const isNodeReference = (node, parent) => {
158
- if (node.type === 'Identifier') {
159
- const parentRecord = parent;
160
- if (!parentRecord) {
161
- return true;
162
- }
163
- if (parent?.type === 'ImportDeclaration' ||
164
- parent?.type === 'ImportSpecifier' ||
165
- parent?.type === 'ImportDefaultSpecifier' ||
166
- parent?.type === 'ImportNamespaceSpecifier') {
167
- return false;
168
- }
169
- if (parent?.type === 'MemberExpression' &&
170
- parentRecord.property === node &&
171
- !parentRecord.computed) {
172
- return false;
173
- }
174
- if ((parent?.type === 'VariableDeclarator' ||
175
- parent?.type === 'FunctionDeclaration' ||
176
- parent?.type === 'ClassDeclaration' ||
177
- parent?.type === 'ClassExpression') &&
178
- parentRecord.id === node) {
179
- return false;
180
- }
181
- if ((parent?.type === 'PropertyDefinition' ||
182
- parent?.type === 'MethodDefinition') &&
183
- parentRecord.key === node &&
184
- !parentRecord.computed) {
185
- return false;
186
- }
187
- if (parent?.type === 'Property' &&
188
- parentRecord.key === node &&
189
- parentRecord.value !== node &&
190
- !parentRecord.computed) {
191
- return false;
192
- }
193
- return true;
194
- }
195
- if (node.type === 'JSXIdentifier') {
196
- const parentRecord = parent;
197
- if (parent?.type === 'JSXAttribute' && parentRecord?.name === node) {
198
- return false;
199
- }
200
- return true;
201
- }
202
- return false;
203
- };
204
- const collectReferencedNames = (root) => {
205
- const names = new Set();
206
- const walk = (node, parent = null) => {
207
- if (node.type === 'ImportDeclaration') {
208
- return;
209
- }
210
- if (isNodeReference(node, parent) &&
211
- 'name' in node &&
212
- typeof node.name === 'string') {
213
- names.add(node.name);
214
- }
215
- getChildren(node).forEach((child) => walk(child, node));
216
- };
217
- walk(root);
218
- return names;
219
- };
220
- const collectImportLocalNames = (node) => {
221
- if (node.type !== 'ImportDeclaration') {
222
- return [];
223
- }
224
- const { specifiers } = node;
225
- if (!Array.isArray(specifiers)) {
226
- return [];
227
- }
228
- return specifiers
229
- .map((specifier) => {
230
- const { local } = specifier;
231
- return isNode(local) && 'name' in local && typeof local.name === 'string'
232
- ? local.name
233
- : null;
234
- })
235
- .filter(isNotNull);
236
- };
237
- const getImportSpecifierLocalName = (node) => {
238
- const { local } = node;
239
- return isNode(local) && 'name' in local && typeof local.name === 'string'
240
- ? local.name
241
- : null;
242
- };
243
- const collectDeclaredNames = (node) => {
244
- if (node.type === 'Identifier') {
245
- return [node.name];
246
- }
247
- if (node.type === 'RestElement') {
248
- return collectDeclaredNames(node.argument);
249
- }
250
- if (node.type === 'AssignmentPattern') {
251
- return collectDeclaredNames(node.left);
252
- }
253
- if (node.type === 'ObjectPattern') {
254
- return node.properties.flatMap((property) => property.type === 'RestElement'
255
- ? collectDeclaredNames(property.argument)
256
- : collectDeclaredNames(property.value));
257
- }
258
- if (node.type === 'ArrayPattern') {
259
- return node.elements.flatMap((element) => element ? collectDeclaredNames(element) : []);
260
- }
261
- if (node.type === 'TSParameterProperty') {
262
- return collectDeclaredNames(node.parameter);
263
- }
264
- return [];
265
- };
266
- const collectTopLevelBindings = (statement) => {
267
- const bindings = new Set();
268
- if (statement.type === 'ImportDeclaration') {
269
- collectImportLocalNames(statement).forEach((name) => bindings.add(name));
270
- return bindings;
271
- }
272
- if (statement.type === 'VariableDeclaration') {
273
- const { declarations } = statement;
274
- if (!Array.isArray(declarations)) {
275
- return bindings;
276
- }
277
- declarations.forEach((declarator) => {
278
- const { id } = declarator;
279
- if (isNode(id)) {
280
- collectDeclaredNames(id).forEach((name) => bindings.add(name));
281
- }
282
- });
283
- return bindings;
284
- }
285
- if ((statement.type === 'FunctionDeclaration' ||
286
- statement.type === 'ClassDeclaration' ||
287
- statement.type === 'TSEnumDeclaration') &&
288
- 'id' in statement) {
289
- const { id } = statement;
290
- if (isNode(id) && id.type === 'Identifier') {
291
- bindings.add(id.name);
292
- }
293
- return bindings;
294
- }
295
- if (statement.type === 'ExportNamedDeclaration') {
296
- const { declaration } = statement;
297
- return isNode(declaration)
298
- ? collectTopLevelBindings(declaration)
299
- : bindings;
300
- }
301
- return bindings;
302
- };
303
- const collectTopLevelStatementInfos = (program) => program.body.map((statement) => ({
304
- bindings: collectTopLevelBindings(statement),
305
- node: statement,
306
- references: collectReferencedNames(statement),
307
- }));
308
- const collectTopLevelBindingsFromStatements = (statements) => new Set(statements.flatMap((statement) => [...statement.bindings]));
309
- const collectRemovableNamesFromStatements = (statements, initialNames) => {
310
- const removable = new Set(initialNames);
311
- const bindingToStatement = new Map();
312
- statements.forEach((statement) => {
313
- statement.bindings.forEach((name) => {
314
- bindingToStatement.set(name, statement);
315
- });
316
- });
317
- const queue = [...removable];
318
- while (queue.length > 0) {
319
- const name = queue.shift();
320
- const statement = bindingToStatement.get(name);
321
- if (statement) {
322
- statement.references.forEach((reference) => {
323
- if (bindingToStatement.has(reference) && !removable.has(reference)) {
324
- removable.add(reference);
325
- queue.push(reference);
326
- }
327
- });
328
- }
329
- }
330
- return removable;
331
- };
332
- const createScopedCleanupScope = (parent) => ({
333
- bindings: new Map(),
334
- parent,
335
- });
336
- const resolveScopedBinding = (scope, name) => {
337
- let current = scope;
338
- while (current) {
339
- const bindingId = current.bindings.get(name);
340
- if (bindingId) {
341
- return bindingId;
342
- }
343
- current = current.parent;
344
- }
345
- return null;
346
- };
347
- const collectScopedBindingInfos = (program) => {
348
- const bindings = new Map();
349
- let sequence = 0;
350
- const addBinding = (scope, name, kind, declaration) => {
351
- const id = `${kind}:${name}:${declaration.start}:${sequence}`;
352
- sequence += 1;
353
- bindings.set(id, {
354
- declaration,
355
- dependencies: new Set(),
356
- externalReferences: 0,
357
- id,
358
- incomingFromBindings: new Set(),
359
- kind,
360
- name,
361
- });
362
- scope.bindings.set(name, id);
363
- return id;
364
- };
365
- const addPatternBindings = (scope, pattern, kind, declaration) => {
366
- collectDeclaredNames(pattern).forEach((name) => {
367
- addBinding(scope, name, kind, declaration);
368
- });
369
- };
370
- const recordReference = (scope, name, ownerBindingId) => {
371
- const targetId = resolveScopedBinding(scope, name);
372
- if (!targetId) {
373
- return;
374
- }
375
- const target = bindings.get(targetId);
376
- if (!target) {
377
- return;
378
- }
379
- if (ownerBindingId && ownerBindingId !== targetId) {
380
- target.incomingFromBindings.add(ownerBindingId);
381
- bindings.get(ownerBindingId)?.dependencies.add(targetId);
382
- return;
383
- }
384
- target.externalReferences += 1;
385
- };
386
- let walk;
387
- function walkPatternReferenceSubexpressions(node, scope, ownerBindingId) {
388
- if (node.type === 'Identifier') {
389
- return;
390
- }
391
- if (node.type === 'TSParameterProperty') {
392
- walkPatternReferenceSubexpressions(node.parameter, scope, ownerBindingId);
393
- return;
394
- }
395
- if (node.type === 'RestElement') {
396
- walkPatternReferenceSubexpressions(node.argument, scope, ownerBindingId);
397
- return;
398
- }
399
- if (node.type === 'AssignmentPattern') {
400
- walkPatternReferenceSubexpressions(node.left, scope, ownerBindingId);
401
- walk(node.right, scope, node, ownerBindingId);
402
- return;
403
- }
404
- if (node.type === 'ObjectPattern') {
405
- node.properties.forEach((property) => {
406
- if (property.type === 'RestElement') {
407
- walkPatternReferenceSubexpressions(property.argument, scope, ownerBindingId);
408
- return;
409
- }
410
- if (property.computed && isNode(property.key)) {
411
- walk(property.key, scope, property, ownerBindingId);
412
- }
413
- walkPatternReferenceSubexpressions(property.value, scope, ownerBindingId);
414
- });
415
- return;
416
- }
417
- if (node.type === 'ArrayPattern') {
418
- node.elements.forEach((element) => {
419
- if (element && isNode(element)) {
420
- walkPatternReferenceSubexpressions(element, scope, ownerBindingId);
421
- }
422
- });
423
- }
424
- }
425
- walk = (node, scope, parent = null, ownerBindingId = null) => {
426
- if (node.type === 'ImportDeclaration') {
427
- const { specifiers } = node;
428
- if (Array.isArray(specifiers)) {
429
- specifiers.forEach((specifier) => {
430
- const { local } = specifier;
431
- if (isNode(local) &&
432
- local.type === 'Identifier' &&
433
- typeof local.name === 'string') {
434
- addBinding(scope, local.name, 'import', node);
435
- }
436
- });
437
- }
438
- return;
439
- }
440
- if (node.type === 'ExportNamedDeclaration' && node.declaration) {
441
- walk(node.declaration, scope, node, ownerBindingId);
442
- collectTopLevelBindings(node).forEach((name) => {
443
- recordReference(scope, name, ownerBindingId);
444
- });
445
- return;
446
- }
447
- if (node.type === 'ExportDefaultDeclaration') {
448
- const { declaration } = node;
449
- if (isNode(declaration)) {
450
- walk(declaration, scope, node, ownerBindingId);
451
- if ((declaration.type === 'FunctionDeclaration' ||
452
- declaration.type === 'ClassDeclaration') &&
453
- declaration.id) {
454
- recordReference(scope, declaration.id.name, ownerBindingId);
455
- }
456
- }
457
- return;
458
- }
459
- if (node.type === 'VariableDeclaration') {
460
- const { declarations } = node;
461
- if (!Array.isArray(declarations)) {
462
- return;
463
- }
464
- declarations.forEach((declarator) => {
465
- const { id } = declarator;
466
- if (isNode(id)) {
467
- addPatternBindings(scope, id, 'variable', node);
468
- }
469
- });
470
- declarations.forEach((declarator) => {
471
- const { id } = declarator;
472
- const { init } = declarator;
473
- if (!isNode(id) || !isNode(init)) {
474
- return;
475
- }
476
- const ownerName = collectDeclaredNames(id)[0] ?? null;
477
- const nextOwner = ownerName !== null ? resolveScopedBinding(scope, ownerName) : null;
478
- walk(init, scope, declarator, nextOwner);
479
- });
480
- return;
481
- }
482
- if (node.type === 'FunctionDeclaration' && node.id) {
483
- const functionBindingId = addBinding(scope, node.id.name, 'function', node);
484
- const fnScope = createScopedCleanupScope(scope);
485
- node.params.forEach((param) => {
486
- addPatternBindings(fnScope, param, 'param', param);
487
- walkPatternReferenceSubexpressions(param, fnScope, functionBindingId);
488
- });
489
- if (node.body) {
490
- walk(node.body, fnScope, node, functionBindingId);
491
- }
492
- return;
493
- }
494
- if (node.type === 'FunctionExpression' ||
495
- node.type === 'ArrowFunctionExpression') {
496
- const fnScope = createScopedCleanupScope(scope);
497
- if (node.type === 'FunctionExpression' && node.id) {
498
- addBinding(fnScope, node.id.name, 'function', node);
499
- }
500
- node.params.forEach((param) => {
501
- addPatternBindings(fnScope, param, 'param', param);
502
- walkPatternReferenceSubexpressions(param, fnScope, ownerBindingId);
503
- });
504
- if (node.body) {
505
- walk(node.body, fnScope, node, ownerBindingId);
506
- }
507
- return;
508
- }
509
- if (node.type === 'BlockStatement') {
510
- const blockScope = createScopedCleanupScope(scope);
511
- getChildren(node).forEach((child) => walk(child, blockScope, node, ownerBindingId));
512
- return;
513
- }
514
- if (isNodeReference(node, parent) &&
515
- 'name' in node &&
516
- typeof node.name === 'string') {
517
- recordReference(scope, node.name, ownerBindingId);
518
- }
519
- getChildren(node).forEach((child) => walk(child, scope, node, ownerBindingId));
520
- };
521
- walk(program, createScopedCleanupScope(null));
522
- return bindings;
523
- };
524
- const collectScopedRemovableBindingIds = (bindings, initialNames) => {
525
- const removable = new Set();
526
- let changed = true;
527
- while (changed) {
528
- changed = false;
529
- for (const binding of bindings.values()) {
530
- if (!removable.has(binding.id) &&
531
- binding.kind !== 'import' &&
532
- binding.kind !== 'param' &&
533
- binding.externalReferences === 0) {
534
- const seededByName = initialNames.has(binding.name) ||
535
- (GENERATED_HELPER_NAME_RE.test(binding.name) &&
536
- binding.incomingFromBindings.size === 0);
537
- const allIncomingRemovable = binding.incomingFromBindings.size > 0 &&
538
- [...binding.incomingFromBindings].every((sourceId) => removable.has(sourceId));
539
- if ((seededByName && binding.incomingFromBindings.size === 0) ||
540
- allIncomingRemovable) {
541
- removable.add(binding.id);
542
- changed = true;
543
- }
544
- }
545
- }
546
- }
547
- return removable;
548
- };
549
- function expandImportRemovalRange(code, start, end) {
550
- let removalStart = start;
551
- while (removalStart > 0 &&
552
- (code[removalStart - 1] === ' ' || code[removalStart - 1] === '\t')) {
553
- removalStart -= 1;
554
- }
555
- let removalEnd = end;
556
- if (code[removalEnd] === ';') {
557
- removalEnd += 1;
558
- }
559
- while (removalEnd < code.length &&
560
- (code[removalEnd] === ' ' || code[removalEnd] === '\t')) {
561
- removalEnd += 1;
562
- }
563
- if (code[removalEnd] === '\r' && code[removalEnd + 1] === '\n') {
564
- removalEnd += 2;
565
- }
566
- else if (code[removalEnd] === '\n') {
567
- removalEnd += 1;
568
- }
569
- return {
570
- end: removalEnd,
571
- start: removalStart,
572
- value: '',
573
- };
574
- }
575
- const collectUnusedScopedDeclarationRemovals = (code, bindings, initialRemovableNames) => {
576
- const removableBindingIds = collectScopedRemovableBindingIds(bindings, initialRemovableNames);
577
- const removals = new Map();
578
- bindings.forEach((binding) => {
579
- if (!removableBindingIds.has(binding.id) ||
580
- binding.kind === 'import' ||
581
- binding.kind === 'param' ||
582
- binding.externalReferences > 0 ||
583
- [...binding.incomingFromBindings].some((sourceId) => !removableBindingIds.has(sourceId))) {
584
- return;
585
- }
586
- if (binding.kind === 'function' &&
587
- binding.declaration.type === 'FunctionDeclaration') {
588
- const range = expandImportRemovalRange(code, binding.declaration.start, binding.declaration.end);
589
- removals.set(`${range.start}:${range.end}`, range);
590
- return;
591
- }
592
- if (binding.declaration.type !== 'VariableDeclaration') {
593
- return;
594
- }
595
- const { declarations } = binding.declaration;
596
- if (!Array.isArray(declarations) || declarations.length !== 1) {
597
- return;
598
- }
599
- const range = expandImportRemovalRange(code, binding.declaration.start, binding.declaration.end);
600
- removals.set(`${range.start}:${range.end}`, range);
601
- });
602
- return [...removals.values()];
603
- };
604
- const expandImportSpecifierRemovalRange = (code, start, end) => {
605
- let removalStart = start;
606
- let removalEnd = end;
607
- let whitespaceStart = removalStart;
608
- while (whitespaceStart > 0 &&
609
- (code[whitespaceStart - 1] === ' ' || code[whitespaceStart - 1] === '\t')) {
610
- whitespaceStart -= 1;
611
- }
612
- if (code[whitespaceStart - 1] !== '{') {
613
- removalStart = whitespaceStart;
614
- }
615
- while (removalEnd < code.length &&
616
- (code[removalEnd] === ' ' || code[removalEnd] === '\t')) {
617
- removalEnd += 1;
618
- }
619
- if (code[removalEnd] === ',') {
620
- removalEnd += 1;
621
- while (removalEnd < code.length &&
622
- (code[removalEnd] === ' ' || code[removalEnd] === '\t')) {
623
- removalEnd += 1;
624
- }
625
- }
626
- else {
627
- while (removalStart > 0 &&
628
- (code[removalStart - 1] === ' ' || code[removalStart - 1] === '\t')) {
629
- removalStart -= 1;
630
- }
631
- if (code[removalStart - 1] === ',') {
632
- removalStart -= 1;
633
- while (removalStart > 0 &&
634
- (code[removalStart - 1] === ' ' || code[removalStart - 1] === '\t')) {
635
- removalStart -= 1;
636
- }
637
- }
638
- }
639
- return {
640
- end: removalEnd,
641
- start: removalStart,
642
- value: '',
643
- };
644
- };
645
- const mergeEmptyRemovalRanges = (removals) => {
646
- if (removals.length <= 1) {
647
- return removals;
648
- }
649
- const sorted = [...removals].sort((a, b) => a.start - b.start);
650
- const merged = [];
651
- sorted.forEach((removal) => {
652
- const previous = merged[merged.length - 1];
653
- if (previous &&
654
- previous.value === '' &&
655
- removal.value === '' &&
656
- removal.start <= previous.end) {
657
- previous.end = Math.max(previous.end, removal.end);
658
- return;
659
- }
660
- merged.push({ ...removal });
661
- });
662
- return merged;
663
- };
664
- const collectUnusedImportRemovals = (code, program, referencedNames, removableNames, preserveSideEffectImportLocals) => {
665
- const removals = [];
666
- program.body.forEach((statement) => {
667
- if (statement.type !== 'ImportDeclaration') {
668
- return;
669
- }
670
- const localNames = collectImportLocalNames(statement);
671
- const removableLocalNames = localNames.filter((localName) => removableNames.has(localName));
672
- if (removableLocalNames.length > 0 &&
673
- removableLocalNames.length === localNames.length &&
674
- removableLocalNames.every((localName) => !referencedNames.has(localName))) {
675
- if (removableLocalNames.some((localName) => preserveSideEffectImportLocals.has(localName))) {
676
- removals.push({
677
- end: statement.end,
678
- start: statement.start,
679
- value: `import ${code.slice(statement.source.start, statement.source.end)};`,
680
- });
681
- return;
682
- }
683
- removals.push(expandImportRemovalRange(code, statement.start, statement.end));
684
- return;
685
- }
686
- const { specifiers } = statement;
687
- if (!Array.isArray(specifiers) || specifiers.length <= 1) {
688
- return;
689
- }
690
- specifiers.forEach((specifier) => {
691
- if (!isNode(specifier)) {
692
- return;
693
- }
694
- const localName = getImportSpecifierLocalName(specifier);
695
- if (localName &&
696
- removableNames.has(localName) &&
697
- !referencedNames.has(localName)) {
698
- removals.push(expandImportSpecifierRemovalRange(code, specifier.start, specifier.end));
699
- }
700
- });
701
- });
702
- return removals;
703
- };
704
- const collectUnusedTopLevelDeclarationRemovals = (code, program, referencedNames, removableNames) => {
705
- const removals = [];
706
- program.body.forEach((statement) => {
707
- if (statement.type !== 'VariableDeclaration') {
708
- return;
709
- }
710
- const localNames = [...collectTopLevelBindings(statement)];
711
- if (localNames.length > 0 &&
712
- localNames.every((localName) => removableNames.has(localName)) &&
713
- localNames.every((localName) => !referencedNames.has(localName))) {
714
- removals.push(expandImportRemovalRange(code, statement.start, statement.end));
715
- }
716
- });
717
- return removals;
718
- };
719
- const collectUnusedGeneratedHelperDeclarationRemovals = (code, program, referencedNames) => {
720
- const removals = [];
721
- program.body.forEach((statement) => {
722
- if (statement.type !== 'VariableDeclaration') {
723
- return;
724
- }
725
- const localNames = [...collectTopLevelBindings(statement)];
726
- if (localNames.length > 0 &&
727
- localNames.every((localName) => GENERATED_HELPER_NAME_RE.test(localName)) &&
728
- localNames.every((localName) => !referencedNames.has(localName))) {
729
- removals.push(expandImportRemovalRange(code, statement.start, statement.end));
730
- }
731
- });
732
- return removals;
733
- };
734
- const collectTopLevelExpressionStatementRemovals = (code, statements, topLevelBindings, removableExpressionRefs) => {
735
- const removals = [];
736
- statements.forEach((statement) => {
737
- if (statement.node.type !== 'ExpressionStatement') {
738
- return;
739
- }
740
- const { expression } = statement.node;
741
- const isPureExpression = expression.type === 'Identifier' ||
742
- expression.type === 'Literal' ||
743
- expression.type === 'ObjectExpression' ||
744
- expression.type === 'ArrayExpression' ||
745
- expression.type === 'ArrowFunctionExpression' ||
746
- expression.type === 'FunctionExpression' ||
747
- (expression.type === 'TemplateLiteral' &&
748
- expression.expressions.length === 0);
749
- if (!isPureExpression) {
750
- return;
751
- }
752
- const localReferences = [...statement.references].filter((name) => topLevelBindings.has(name));
753
- if (localReferences.length > 0 &&
754
- localReferences.every((name) => removableExpressionRefs.has(name))) {
755
- removals.push(expandImportRemovalRange(code, statement.node.start, statement.node.end));
756
- }
757
- });
758
- return removals;
759
- };
760
- const collectEmptyTopLevelBlockRemovals = (code, program) => {
761
- const removals = [];
762
- program.body.forEach((statement) => {
763
- if (statement.type !== 'BlockStatement' || statement.body.length > 0) {
764
- return;
765
- }
766
- removals.push(expandImportRemovalRange(code, statement.start, statement.end));
767
- });
768
- return removals;
769
- };
770
- const removeUnusedAfterReplacement = (code, filename, initialRemovableNames, removableExpressionRefs, preserveSideEffectImportLocals) => {
771
- let current = code;
772
- const cumulativeRemovableNames = new Set(initialRemovableNames);
773
- const applyIfParsable = (next) => {
774
- try {
775
- parseOxc(next, filename);
776
- return next;
777
- }
778
- catch {
779
- return current;
780
- }
781
- };
782
- for (let idx = 0; idx < 5; idx += 1) {
783
- const previous = current;
784
- const program = parseOxc(current, filename);
785
- const statements = collectTopLevelStatementInfos(program);
786
- const removableNames = collectRemovableNamesFromStatements(statements, cumulativeRemovableNames);
787
- removableNames.forEach((name) => cumulativeRemovableNames.add(name));
788
- const referencedNames = collectReferencedNames(program);
789
- const topLevelBindings = collectTopLevelBindingsFromStatements(statements);
790
- const scopedBindings = collectScopedBindingInfos(program);
791
- const removals = mergeEmptyRemovalRanges([
792
- ...collectUnusedScopedDeclarationRemovals(current, scopedBindings, cumulativeRemovableNames),
793
- ...collectUnusedTopLevelDeclarationRemovals(current, program, referencedNames, cumulativeRemovableNames),
794
- ...collectUnusedGeneratedHelperDeclarationRemovals(current, program, referencedNames),
795
- ...collectUnusedImportRemovals(current, program, referencedNames, cumulativeRemovableNames, preserveSideEffectImportLocals),
796
- ...collectTopLevelExpressionStatementRemovals(current, statements, topLevelBindings, removableExpressionRefs),
797
- ...collectEmptyTopLevelBlockRemovals(current, program),
798
- ]);
799
- current =
800
- removals.length > 0
801
- ? applyIfParsable(applyReplacements(current, removals))
802
- : current;
803
- if (current === previous) {
804
- return current;
805
- }
806
- }
807
- return current;
808
- };
809
- const getMemberName = (node) => {
810
- if (node.computed) {
811
- return node.property.type === 'Literal' &&
812
- typeof node.property.value === 'string'
813
- ? node.property.value
814
- : null;
815
- }
816
- return node.property.type === 'Identifier' ? node.property.name : null;
817
- };
818
- const unwrapQualifiedExpression = (node) => {
819
- if (node.type === 'TSAsExpression' ||
820
- node.type === 'TSSatisfiesExpression' ||
821
- node.type === 'TSNonNullExpression' ||
822
- node.type === 'TSTypeAssertion' ||
823
- node.type === 'ParenthesizedExpression') {
824
- return unwrapQualifiedExpression(node.expression);
825
- }
826
- if (node.type === 'SequenceExpression') {
827
- const sequence = node;
828
- return unwrapQualifiedExpression(sequence.expressions[sequence.expressions.length - 1] ?? node);
829
- }
830
- return node;
831
- };
832
- const getRootIdentifier = (node) => {
833
- const expression = unwrapQualifiedExpression(node);
834
- if (expression.type === 'Identifier') {
835
- return expression;
836
- }
837
- if (expression.type === 'MemberExpression') {
838
- return getRootIdentifier(expression.object);
839
- }
840
- if (expression.type === 'CallExpression') {
841
- return getRootIdentifier(expression.callee);
842
- }
843
- return null;
844
- };
845
- const getQualifiedName = (node) => {
846
- const expression = unwrapQualifiedExpression(node);
847
- if (expression.type === 'Identifier') {
848
- return expression.name;
849
- }
850
- if (expression.type === 'MemberExpression') {
851
- const object = getQualifiedName(expression.object);
852
- const member = getMemberName(expression);
853
- return object && member ? `${object}.${member}` : null;
854
- }
855
- if (expression.type === 'CallExpression') {
856
- return getQualifiedName(expression.callee);
857
- }
858
- return null;
859
- };
860
- const resolveDefinedProcessor = (callee, definedProcessors) => {
861
- const qualified = getQualifiedName(callee);
862
- if (qualified) {
863
- const definedProcessor = definedProcessors.get(qualified);
864
- if (definedProcessor) {
865
- return {
866
- collapseQualifiedCallee: qualified.includes('.'),
867
- definedProcessor,
868
- };
869
- }
870
- }
871
- const root = getRootIdentifier(callee);
872
- if (!root) {
873
- return null;
874
- }
875
- const definedProcessor = definedProcessors.get(root.name);
876
- return definedProcessor
877
- ? {
878
- collapseQualifiedCallee: false,
879
- definedProcessor,
880
- }
881
- : null;
882
- };
883
- const isCallTagOfTaggedTemplate = (node, parent) => parent?.type === 'TaggedTemplateExpression' && parent.tag === node;
884
- const expandReplacementTarget = (target, ancestors) => {
885
- let current = target;
886
- for (let idx = ancestors.length - 1; idx >= 0; idx -= 1) {
887
- const ancestor = ancestors[idx];
888
- if (ancestor.type === 'SequenceExpression' &&
889
- ancestor.expressions[ancestor.expressions.length - 1] === current) {
890
- current = ancestor;
891
- }
892
- else if (ancestor.type === 'ParenthesizedExpression' &&
893
- ancestor.expression === current) {
894
- current = ancestor;
895
- }
896
- else {
897
- break;
898
- }
899
- }
900
- return current;
901
- };
902
- const collectProcessorUsages = (program, definedProcessors) => {
903
- const usages = [];
904
- const walk = (node, ancestors, parent = null) => {
905
- if (node.type === 'TaggedTemplateExpression') {
906
- const callee = node.tag;
907
- const resolvedProcessor = resolveDefinedProcessor(callee, definedProcessors);
908
- if (resolvedProcessor) {
909
- usages.push({
910
- ancestors,
911
- callee,
912
- collapseQualifiedCallee: resolvedProcessor.collapseQualifiedCallee,
913
- definedProcessor: resolvedProcessor.definedProcessor,
914
- kind: 'template',
915
- replacementTarget: expandReplacementTarget(node, ancestors),
916
- target: node,
917
- });
918
- }
919
- }
920
- else if (node.type === 'CallExpression' &&
921
- !isCallTagOfTaggedTemplate(node, parent)) {
922
- const { callee } = node;
923
- const resolvedProcessor = resolveDefinedProcessor(callee, definedProcessors);
924
- if (resolvedProcessor) {
925
- usages.push({
926
- ancestors,
927
- callee,
928
- collapseQualifiedCallee: resolvedProcessor.collapseQualifiedCallee,
929
- definedProcessor: resolvedProcessor.definedProcessor,
930
- kind: 'call',
931
- replacementTarget: expandReplacementTarget(node, ancestors),
932
- target: node,
933
- });
934
- }
935
- }
936
- getChildren(node).forEach((child) => walk(child, [...ancestors, node], node));
937
- };
938
- walk(program, []);
939
- return usages.sort((a, b) => a.target.start - b.target.start);
940
- };
941
- const expressionSpan = (expression) => ({
942
- end: expression.end,
943
- start: expression.start,
944
- });
945
- const collectCallArgumentSpans = (node) => {
946
- const expression = unwrapQualifiedExpression(node);
947
- if (expression.type === 'CallExpression') {
948
- const call = expression;
949
- const calleeSpans = collectCallArgumentSpans(call.callee);
950
- const argumentSpans = call.arguments.flatMap((arg) => arg.type === 'SpreadElement' ? [] : [expressionSpan(arg)]);
951
- return [...calleeSpans, ...argumentSpans];
952
- }
953
- if (expression.type === 'MemberExpression') {
954
- return collectCallArgumentSpans(expression.object);
955
- }
956
- return [];
957
- };
958
- const collectUsageExpressionSpans = (usage) => {
959
- const calleeSpans = collectCallArgumentSpans(usage.callee);
960
- if (usage.kind === 'template') {
961
- return [
962
- ...calleeSpans,
963
- ...usage.target.quasi.expressions.map((expression) => expressionSpan(expression)),
964
- ];
965
- }
966
- return [
967
- ...calleeSpans,
968
- ...usage.target.arguments.flatMap((arg) => arg.type === 'SpreadElement' ? [] : [expressionSpan(arg)]),
969
- ];
970
- };
971
- const literalExpressionValue = (expression, code, source, location) => {
972
- if (expression.type !== 'Literal') {
973
- return null;
974
- }
975
- if (expression.value === null ||
976
- typeof expression.value === 'string' ||
977
- typeof expression.value === 'number' ||
978
- typeof expression.value === 'boolean') {
979
- let type;
980
- if (expression.value === null) {
981
- type = 'NullLiteral';
982
- }
983
- else if (typeof expression.value === 'string') {
984
- type = 'StringLiteral';
985
- }
986
- else if (typeof expression.value === 'number') {
987
- type = 'NumericLiteral';
988
- }
989
- else {
990
- type = 'BooleanLiteral';
991
- }
992
- const ex = expression.value === null
993
- ? { loc: location, type }
994
- : {
995
- loc: location,
996
- type,
997
- value: expression.value,
998
- };
999
- return {
1000
- buildCodeFrameError: (message) => buildCodeFrameError(code, location, message),
1001
- ex,
1002
- kind: ValueType.CONST,
1003
- source,
1004
- value: expression.value,
1005
- };
1006
- }
1007
- return null;
1008
- };
1009
- const expressionValue = (expression, code, loc, filename) => {
1010
- const source = code.slice(expression.start, expression.end);
1011
- const location = getSourceLocation(expression.start, expression.end, loc, filename);
1012
- const literal = literalExpressionValue(expression, code, source, location);
1013
- if (literal) {
1014
- return literal;
1015
- }
1016
- const helperCallName = expression.type === 'CallExpression' &&
1017
- expression.arguments.length === 0 &&
1018
- expression.callee.type === 'Identifier' &&
1019
- GENERATED_HELPER_NAME_RE.test(expression.callee.name)
1020
- ? expression.callee.name
1021
- : null;
1022
- let ex;
1023
- if (expression.type === 'Identifier') {
1024
- ex = { loc: location, name: expression.name, type: 'Identifier' };
1025
- }
1026
- else if (helperCallName) {
1027
- ex = { loc: location, name: helperCallName, type: 'Identifier' };
1028
- }
1029
- else {
1030
- ex = {
1031
- loc: location,
1032
- name: code.slice(expression.start, expression.end),
1033
- type: 'Identifier',
1034
- };
1035
- }
1036
- return {
1037
- buildCodeFrameError: (message) => buildCodeFrameError(code, location, message),
1038
- ex,
1039
- kind: expression.type === 'ArrowFunctionExpression' ||
1040
- expression.type === 'FunctionExpression'
1041
- ? ValueType.FUNCTION
1042
- : ValueType.LAZY,
1043
- source,
1044
- };
1045
- };
1046
- const withCurrentExpressionLocation = (value, expression, loc, filename) => {
1047
- const location = getSourceLocation(expression.start, expression.end, loc, filename);
1048
- if (value.kind === ValueType.CONST) {
1049
- return {
1050
- ...value,
1051
- ex: {
1052
- ...value.ex,
1053
- loc: location,
1054
- },
1055
- };
1056
- }
1057
- if (value.kind === ValueType.FUNCTION) {
1058
- return {
1059
- ...value,
1060
- ex: {
1061
- ...value.ex,
1062
- loc: location,
1063
- },
1064
- };
1065
- }
1066
- return {
1067
- ...value,
1068
- ex: {
1069
- ...value.ex,
1070
- loc: location,
1071
- },
1072
- };
1073
- };
1074
- const shiftExpressionValue = (expressionValues, expression, code, loc, filename) => expressionValues.length > 0
1075
- ? withCurrentExpressionLocation(expressionValues.shift(), expression, loc, filename)
1076
- : expressionValue(expression, code, loc, filename);
1077
- const zipTemplate = (template, code, loc, filename, expressionValues) => {
1078
- const parts = template.quasi.quasis.flatMap((quasi, idx) => {
1079
- const expression = template.quasi.expressions[idx];
1080
- const templateElement = {
1081
- ...quasi,
1082
- loc: getSourceLocation(quasi.start, quasi.end, loc, filename),
1083
- };
1084
- return [
1085
- templateElement,
1086
- expression
1087
- ? shiftExpressionValue(expressionValues, expression, code, loc, filename)
1088
- : null,
1089
- ].filter(isNotNull);
1090
- });
1091
- return ['template', parts];
1092
- };
1093
- const buildCalleeParams = (node, code, loc, filename, expressionValues, collapseQualifiedCallee = false) => {
1094
- const expression = unwrapQualifiedExpression(node);
1095
- if (collapseQualifiedCallee &&
1096
- (expression.type === 'Identifier' || expression.type === 'MemberExpression')) {
1097
- return [['callee', expression]];
1098
- }
1099
- if (expression.type === 'Identifier') {
1100
- return [['callee', { name: expression.name, type: 'Identifier' }]];
1101
- }
1102
- if (expression.type === 'MemberExpression') {
1103
- const params = buildCalleeParams(expression.object, code, loc, filename, expressionValues, collapseQualifiedCallee);
1104
- const member = getMemberName(expression);
1105
- return params && member ? [...params, ['member', member]] : null;
1106
- }
1107
- if (expression.type === 'CallExpression') {
1108
- const call = expression;
1109
- const params = buildCalleeParams(call.callee, code, loc, filename, expressionValues, collapseQualifiedCallee);
1110
- if (!params) {
1111
- return null;
1112
- }
1113
- const callValues = call.arguments
1114
- .filter((arg) => arg.type !== 'SpreadElement')
1115
- .map((arg) => shiftExpressionValue(expressionValues, arg, code, loc, filename));
1116
- return [...params, ['call', ...callValues]];
1117
- }
1118
- return null;
1119
- };
1120
- const buildParams = (usage, code, loc, filename, expressionValues, collapseQualifiedCallee) => {
1121
- const params = buildCalleeParams(usage.callee, code, loc, filename, expressionValues, collapseQualifiedCallee);
1122
- if (!params) {
1123
- return null;
1124
- }
1125
- if (usage.kind === 'template') {
1126
- return [
1127
- ...params,
1128
- zipTemplate(usage.target, code, loc, filename, expressionValues),
1129
- ];
1130
- }
1131
- const callValues = usage.target.arguments
1132
- .filter((arg) => arg.type !== 'SpreadElement')
1133
- .map((arg) => shiftExpressionValue(expressionValues, arg, code, loc, filename));
1134
- return [...params, ['call', ...callValues]];
1135
- };
1136
- const getPropertyKeyName = (property, code) => {
1137
- const { key } = property;
1138
- if (!isNode(key)) {
1139
- return null;
1140
- }
1141
- if (key.type === 'Identifier') {
1142
- return key.name;
1143
- }
1144
- if (key.type === 'Literal') {
1145
- return String(key.value);
1146
- }
1147
- return typeof key.start === 'number' && typeof key.end === 'number'
1148
- ? code.slice(key.start, key.end)
1149
- : null;
1150
- };
1151
- const getDisplayName = (ancestors, idx, code, filename) => {
1152
- const owner = [...ancestors].reverse().find((node) => {
1153
- return (node.type === 'Property' ||
1154
- node.type === 'JSXOpeningElement' ||
1155
- node.type === 'VariableDeclarator');
1156
- });
1157
- if (owner?.type === 'Property') {
1158
- const keyName = getPropertyKeyName(owner, code);
1159
- if (keyName) {
1160
- return keyName;
1161
- }
1162
- }
1163
- else if (owner?.type === 'JSXOpeningElement') {
1164
- const { name } = owner;
1165
- if (isNode(name) && name.type === 'JSXIdentifier') {
1166
- return name.name;
1167
- }
1168
- }
1169
- else if (owner?.type === 'VariableDeclarator') {
1170
- const { id } = owner;
1171
- if (isNode(id) && id.type === 'Identifier') {
1172
- return id.name;
1173
- }
1174
- }
1175
- let displayName = basename(filename ?? 'unknown').replace(/\.[a-z\d]+$/, '');
1176
- if (filename && /^index\.[a-z\d]+$/.test(basename(filename))) {
1177
- displayName = basename(dirname(filename));
1178
- }
1179
- if (!displayName) {
1180
- throw new Error("Couldn't determine a name for the component. Ensure that it's either:\n" +
1181
- '- Assigned to a variable\n' +
1182
- '- Is an object property\n' +
1183
- '- Is a prop in a JSX element\n');
1184
- }
1185
- return `${displayName}${idx}`;
1186
- };
1187
- const getTagOwner = (ancestors) => {
1188
- const owner = [...ancestors]
1189
- .reverse()
1190
- .find((node) => node.type === 'Property' ||
1191
- node.type === 'JSXOpeningElement' ||
1192
- node.type === 'VariableDeclarator');
1193
- return owner ?? null;
1194
- };
1195
- const isTagReferenced = (program, ancestors) => {
1196
- const owner = getTagOwner(ancestors);
1197
- if (owner?.type !== 'VariableDeclarator') {
1198
- return true;
1199
- }
1200
- const { id } = owner;
1201
- if (!isNode(id) || id.type !== 'Identifier') {
1202
- return true;
1203
- }
1204
- if (ancestors.some((node) => node.type === 'ExportNamedDeclaration')) {
1205
- return true;
1206
- }
1207
- let referenced = false;
1208
- visit(program, (node, parent) => {
1209
- const referenceName = node.type === 'Identifier' || node.type === 'JSXIdentifier'
1210
- ? node.name
1211
- : null;
1212
- if (referenced ||
1213
- referenceName !== id.name ||
1214
- (node.type === 'Identifier' &&
1215
- node.start === id.start &&
1216
- node.end === id.end)) {
1217
- return;
1218
- }
1219
- referenced = isNodeReference(node, parent);
1220
- });
1221
- return referenced;
1222
- };
1223
- const isReplacementPure = (replacement) => replacement.type === 'CallExpression';
1224
- const createProcessor = (definedProcessor, params, target, replacementTarget, ancestors, fileContext, options, code, loc, idx, isReferenced, usedNames, replacements) => {
1225
- const [Processor, tagSource] = definedProcessor;
1226
- const astService = createOxcAstService(usedNames);
1227
- const replacer = (replacement, isPure) => {
1228
- const next = typeof replacement === 'function' ? replacement(target) : replacement;
1229
- const replacementCode = expressionToCode(next);
1230
- replacements.push({
1231
- start: replacementTarget.start,
1232
- end: replacementTarget.end,
1233
- value: isPure && isReplacementPure(next)
1234
- ? `/*#__PURE__*/${replacementCode}`
1235
- : replacementCode,
1236
- });
1237
- };
1238
- try {
1239
- let displayName;
1240
- try {
1241
- displayName = getDisplayName(ancestors, idx, code, fileContext.filename);
1242
- }
1243
- catch (error) {
1244
- if (error instanceof Error &&
1245
- error.message.startsWith("Couldn't determine a name for the component")) {
1246
- let displayNameNode = target;
1247
- if (target.type === 'TaggedTemplateExpression') {
1248
- displayNameNode = target.tag;
1249
- }
1250
- else if (target.type === 'CallExpression') {
1251
- displayNameNode = target.callee;
1252
- }
1253
- const pointerNode = displayNameNode.type === 'MemberExpression'
1254
- ? getRootIdentifier(displayNameNode) ?? displayNameNode
1255
- : displayNameNode;
1256
- throw buildCodeFrameError(code, getSourceLocation(pointerNode.start, pointerNode.end, loc, fileContext.filename), error.message);
1257
- }
1258
- throw error;
1259
- }
1260
- return {
1261
- astService,
1262
- processor: new Processor(params, tagSource, astService, getSourceLocation(target.start, target.end, loc, fileContext.filename), replacer, displayName, isReferenced, idx, options, fileContext),
1263
- };
1264
- }
1265
- catch (e) {
1266
- if (e === BaseProcessor.SKIP) {
1267
- return null;
1268
- }
1269
- if (typeof e === 'symbol' &&
1270
- e.description === BaseProcessor.SKIP.description) {
1271
- if (!didWarnSkipSymbolMismatch) {
1272
- didWarnSkipSymbolMismatch = true;
1273
- // eslint-disable-next-line no-console
1274
- console.warn([
1275
- "[wyw-in-js] Processor threw Symbol('skip') that does not match BaseProcessor.SKIP identity.",
1276
- 'This usually means duplicate copies of @wyw-in-js/processor-utils (or the processor) are bundled/installed.',
1277
- 'Consider deduping dependencies to avoid subtle issues (instanceof checks, sentinels, etc).',
1278
- ].join('\n'));
1279
- }
1280
- return null;
1281
- }
1282
- throw e;
1283
- }
1284
- };
1285
- export const applyOxcProcessors = (code, fileContext, options, callback, cleanupUnused = false) => {
1286
- const filename = fileContext.filename ?? 'unknown.js';
1287
- const eventEmitter = options.eventEmitter ?? EventEmitter.dummy;
1288
- let workingCode = code;
1289
- let program = parseOxc(workingCode, filename);
1290
- const definedProcessors = new Map();
1291
- const removableImportLocals = new Set();
1292
- const removableExpressionRefs = new Set();
1293
- eventEmitter.perf('transform:preeval:processTemplate:imports', () => {
1294
- const imports = eventEmitter.perf('transform:preeval:processTemplate:imports:analysis', () => collectOxcProcessorImportsFromProgram(program, workingCode));
1295
- eventEmitter.perf('transform:preeval:processTemplate:imports:lookup', () => {
1296
- imports.forEach((item) => {
1297
- const localName = item.local.name ?? item.local.code;
1298
- if (item.imported === 'side-effect' || !localName) {
1299
- return;
1300
- }
1301
- const [processor, tagSource] = getProcessorForImport({
1302
- imported: item.imported,
1303
- source: item.source,
1304
- }, filename, options);
1305
- if (processor) {
1306
- definedProcessors.set(localName, [processor, tagSource]);
1307
- removableImportLocals.add(localName);
1308
- const rootLocalName = localName.split('.')[0];
1309
- if (rootLocalName) {
1310
- removableImportLocals.add(rootLocalName);
1311
- }
1312
- }
1313
- });
1314
- });
1315
- });
1316
- if (definedProcessors.size === 0) {
1317
- return {
1318
- code: workingCode,
1319
- processors: [],
1320
- staticValueCandidates: [],
1321
- staticValues: [],
1322
- };
1323
- }
1324
- let processorUsages = eventEmitter.perf('transform:preeval:processTemplate:usages', () => collectProcessorUsages(program, definedProcessors));
1325
- if (processorUsages.length === 0) {
1326
- return {
1327
- code: workingCode,
1328
- processors: [],
1329
- staticValueCandidates: [],
1330
- staticValues: [],
1331
- };
1332
- }
1333
- const targetExpressionSpans = processorUsages.flatMap(collectUsageExpressionSpans);
1334
- const extracted = targetExpressionSpans.length > 0
1335
- ? eventEmitter.perf('transform:preeval:processTemplate:deps', () => collectOxcExpressionDependencies(workingCode, filename, options.evaluate, targetExpressionSpans))
1336
- : {
1337
- code: workingCode,
1338
- dependencyNames: [],
1339
- expressionValues: [],
1340
- staticValueCandidates: [],
1341
- staticValues: [],
1342
- };
1343
- if (extracted.code !== workingCode) {
1344
- workingCode = extracted.code;
1345
- program = eventEmitter.perf('transform:preeval:processTemplate:reparse', () => parseOxc(workingCode, filename));
1346
- processorUsages = eventEmitter.perf('transform:preeval:processTemplate:usages', () => collectProcessorUsages(program, definedProcessors));
1347
- }
1348
- const templateExpressionValues = extracted.expressionValues.map((value) => ({
1349
- ...value,
1350
- buildCodeFrameError: (message) => buildCodeFrameError(code, value.ex.loc, message),
1351
- }));
1352
- const loc = createLocationLookup(workingCode);
1353
- const usedNames = eventEmitter.perf('transform:preeval:processTemplate:usedNames', () => collectUsedNames(program));
1354
- const addedImports = [];
1355
- const replacements = [];
1356
- const processors = [];
1357
- extracted.dependencyNames.forEach((name) => removableImportLocals.add(name));
1358
- eventEmitter.perf('transform:preeval:processTemplate:processors', () => {
1359
- processorUsages.forEach((usage, idx) => {
1360
- const params = buildParams(usage, workingCode, loc, filename, templateExpressionValues, usage.collapseQualifiedCallee);
1361
- if (!params) {
1362
- return;
1363
- }
1364
- const created = createProcessor(usage.definedProcessor, params, usage.target, usage.replacementTarget, usage.ancestors, fileContext, options, workingCode, loc, idx, isTagReferenced(program, usage.ancestors), usedNames, replacements);
1365
- if (!created) {
1366
- return;
1367
- }
1368
- const { astService, processor } = created;
1369
- const owner = getTagOwner(usage.ancestors);
1370
- if (owner?.type === 'VariableDeclarator') {
1371
- const { id } = owner;
1372
- if (isNode(id) && id.type === 'Identifier') {
1373
- removableExpressionRefs.add(id.name);
1374
- }
1375
- }
1376
- processors.push(processor);
1377
- callback(processor);
1378
- addedImports.push(...astService.getAddedImports());
1379
- });
1380
- });
1381
- const replacedCode = applyReplacements(workingCode, replacements);
1382
- const codeWithAddedImports = insertAddedImports(replacedCode, program, addedImports);
1383
- return {
1384
- code: cleanupUnused
1385
- ? eventEmitter.perf('transform:preeval:processTemplate:cleanup', () => removeUnusedAfterReplacement(codeWithAddedImports, filename, removableImportLocals, new Set([...removableExpressionRefs, ...extracted.dependencyNames]), options.preserveSideEffectImportLocals ?? new Set()))
1386
- : codeWithAddedImports,
1387
- processors,
1388
- staticValueCandidates: extracted.staticValueCandidates,
1389
- staticValues: extracted.staticValues,
1390
- };
1391
- };
1
+ export { applyOxcProcessors } from './applyOxcProcessors/applyOxcProcessors';