@wyw-in-js/transform 1.1.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 (801) hide show
  1. package/esm/cache.js +433 -289
  2. package/esm/cache.js.map +1 -1
  3. package/esm/debug/fileReporter.js +171 -134
  4. package/esm/debug/fileReporter.js.map +1 -1
  5. package/esm/eval/broker.js +2275 -0
  6. package/esm/eval/broker.js.map +1 -0
  7. package/esm/eval/lru.js +36 -0
  8. package/esm/eval/lru.js.map +1 -0
  9. package/esm/eval/prepareModuleOnDemand.js +21 -0
  10. package/esm/eval/prepareModuleOnDemand.js.map +1 -0
  11. package/esm/eval/protocol.js +2 -0
  12. package/esm/eval/protocol.js.map +1 -0
  13. package/esm/eval/runner.js +1878 -0
  14. package/esm/eval/runner.js.map +1 -0
  15. package/esm/eval/serialize.js +333 -0
  16. package/esm/eval/serialize.js.map +1 -0
  17. package/esm/eval/writeQueue.js +81 -0
  18. package/esm/eval/writeQueue.js.map +1 -0
  19. package/esm/evaluators/index.js +11 -12
  20. package/esm/evaluators/index.js.map +1 -1
  21. package/esm/index.js +25 -29
  22. package/esm/index.js.map +1 -1
  23. package/esm/module.js +923 -520
  24. package/esm/module.js.map +1 -1
  25. package/esm/shaker.js +14 -80
  26. package/esm/shaker.js.map +1 -1
  27. package/esm/transform/BaseEntrypoint.js +162 -164
  28. package/esm/transform/BaseEntrypoint.js.map +1 -1
  29. package/esm/transform/Entrypoint.helpers.js +96 -253
  30. package/esm/transform/Entrypoint.helpers.js.map +1 -1
  31. package/esm/transform/Entrypoint.js +336 -270
  32. package/esm/transform/Entrypoint.js.map +1 -1
  33. package/esm/transform/Entrypoint.types.js +1 -1
  34. package/esm/transform/Entrypoint.types.js.map +1 -1
  35. package/esm/transform/EvaluatedEntrypoint.js +10 -4
  36. package/esm/transform/EvaluatedEntrypoint.js.map +1 -1
  37. package/esm/transform/actions/AbortError.js +6 -6
  38. package/esm/transform/actions/AbortError.js.map +1 -1
  39. package/esm/transform/actions/BaseAction.js +140 -136
  40. package/esm/transform/actions/BaseAction.js.map +1 -1
  41. package/esm/transform/actions/UnprocessedEntrypointError.js +6 -6
  42. package/esm/transform/actions/UnprocessedEntrypointError.js.map +1 -1
  43. package/esm/transform/actions/actionRunner.js +63 -66
  44. package/esm/transform/actions/actionRunner.js.map +1 -1
  45. package/esm/transform/actions/types.js +1 -1
  46. package/esm/transform/actions/types.js.map +1 -1
  47. package/esm/transform/barrelManifest.types.js +2 -0
  48. package/esm/transform/barrelManifest.types.js.map +1 -0
  49. package/esm/transform/generators/baseProcessingHandlers.js +15 -17
  50. package/esm/transform/generators/baseProcessingHandlers.js.map +1 -1
  51. package/esm/transform/generators/collect.js +27 -55
  52. package/esm/transform/generators/collect.js.map +1 -1
  53. package/esm/transform/generators/createStylisPreprocessor.js +353 -321
  54. package/esm/transform/generators/createStylisPreprocessor.js.map +1 -1
  55. package/esm/transform/generators/evalFile.js +48 -47
  56. package/esm/transform/generators/evalFile.js.map +1 -1
  57. package/esm/transform/generators/extract.js +78 -90
  58. package/esm/transform/generators/extract.js.map +1 -1
  59. package/esm/transform/generators/getExports.js +57 -74
  60. package/esm/transform/generators/getExports.js.map +1 -1
  61. package/esm/transform/generators/index.js +11 -11
  62. package/esm/transform/generators/index.js.map +1 -1
  63. package/esm/transform/generators/processEntrypoint.js +93 -67
  64. package/esm/transform/generators/processEntrypoint.js.map +1 -1
  65. package/esm/transform/generators/processImports.js +102 -67
  66. package/esm/transform/generators/processImports.js.map +1 -1
  67. package/esm/transform/generators/resolveImports.js +212 -197
  68. package/esm/transform/generators/resolveImports.js.map +1 -1
  69. package/esm/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  70. package/esm/transform/generators/resolveStaticOxcValues/cache.js.map +1 -0
  71. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js +146 -0
  72. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js.map +1 -0
  73. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js +33 -0
  74. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js.map +1 -0
  75. package/esm/transform/generators/resolveStaticOxcValues/environment.js +29 -0
  76. package/esm/transform/generators/resolveStaticOxcValues/environment.js.map +1 -0
  77. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js +351 -0
  78. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js.map +1 -0
  79. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js +253 -0
  80. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js.map +1 -0
  81. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js +310 -0
  82. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js.map +1 -0
  83. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +74 -0
  84. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js.map +1 -0
  85. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +229 -0
  86. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js.map +1 -0
  87. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js +172 -0
  88. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js.map +1 -0
  89. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js +476 -0
  90. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js.map +1 -0
  91. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js +55 -0
  92. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js.map +1 -0
  93. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js +123 -0
  94. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js.map +1 -0
  95. package/esm/transform/generators/resolveStaticOxcValues/prune.js +186 -0
  96. package/esm/transform/generators/resolveStaticOxcValues/prune.js.map +1 -0
  97. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +183 -0
  98. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js.map +1 -0
  99. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js +298 -0
  100. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js.map +1 -0
  101. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +298 -0
  102. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js.map +1 -0
  103. package/esm/transform/generators/resolveStaticOxcValues/types.js +3 -0
  104. package/esm/transform/generators/resolveStaticOxcValues/types.js.map +1 -0
  105. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +59 -0
  106. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js.map +1 -0
  107. package/esm/transform/generators/resolveStaticOxcValues.js +2 -0
  108. package/esm/transform/generators/resolveStaticOxcValues.js.map +1 -0
  109. package/esm/transform/generators/rewriteOxcBarrelImports.js +822 -0
  110. package/esm/transform/generators/rewriteOxcBarrelImports.js.map +1 -0
  111. package/esm/transform/generators/transform.js +251 -248
  112. package/esm/transform/generators/transform.js.map +1 -1
  113. package/esm/transform/generators/workflow.js +87 -90
  114. package/esm/transform/generators/workflow.js.map +1 -1
  115. package/esm/transform/helpers/loadWywOptions.js +183 -74
  116. package/esm/transform/helpers/loadWywOptions.js.map +1 -1
  117. package/esm/transform/helpers/withDefaultServices.js +13 -22
  118. package/esm/transform/helpers/withDefaultServices.js.map +1 -1
  119. package/esm/transform/isStaticallyEvaluatableModule.js +140 -152
  120. package/esm/transform/isStaticallyEvaluatableModule.js.map +1 -1
  121. package/esm/transform/oxcBarrelManifest.js +349 -0
  122. package/esm/transform/oxcBarrelManifest.js.map +1 -0
  123. package/esm/transform/rootLog.js +3 -3
  124. package/esm/transform/rootLog.js.map +1 -1
  125. package/esm/transform/syntax.js +2 -0
  126. package/esm/transform/syntax.js.map +1 -0
  127. package/esm/transform/types.js +2 -2
  128. package/esm/transform/types.js.map +1 -1
  129. package/esm/transform.js +125 -147
  130. package/esm/transform.js.map +1 -1
  131. package/esm/types.js +4 -1
  132. package/esm/types.js.map +1 -1
  133. package/esm/utils/EventEmitter.js +79 -48
  134. package/esm/utils/EventEmitter.js.map +1 -1
  135. package/esm/utils/ShakerMetadata.js +2 -2
  136. package/esm/utils/ShakerMetadata.js.map +1 -1
  137. package/esm/utils/TransformDiagnostics.js +9 -9
  138. package/esm/utils/TransformDiagnostics.js.map +1 -1
  139. package/esm/utils/TransformMetadata.js +24 -26
  140. package/esm/utils/TransformMetadata.js.map +1 -1
  141. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js +160 -0
  142. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js.map +1 -0
  143. package/esm/utils/applyOxcProcessors/cleanupBindings.js +157 -0
  144. package/esm/utils/applyOxcProcessors/cleanupBindings.js.map +1 -0
  145. package/esm/utils/applyOxcProcessors/cleanupRemovals.js +431 -0
  146. package/esm/utils/applyOxcProcessors/cleanupRemovals.js.map +1 -0
  147. package/esm/utils/applyOxcProcessors/displayName.js +93 -0
  148. package/esm/utils/applyOxcProcessors/displayName.js.map +1 -0
  149. package/esm/utils/applyOxcProcessors/expressionValues.js +152 -0
  150. package/esm/utils/applyOxcProcessors/expressionValues.js.map +1 -0
  151. package/esm/utils/applyOxcProcessors/processorFactory.js +62 -0
  152. package/esm/utils/applyOxcProcessors/processorFactory.js.map +1 -0
  153. package/esm/utils/applyOxcProcessors/processorUsages.js +143 -0
  154. package/esm/utils/applyOxcProcessors/processorUsages.js.map +1 -0
  155. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js +207 -0
  156. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js.map +1 -0
  157. package/esm/utils/applyOxcProcessors/shared.js +29 -0
  158. package/esm/utils/applyOxcProcessors/shared.js.map +1 -0
  159. package/esm/utils/applyOxcProcessors/types.js +2 -0
  160. package/esm/utils/applyOxcProcessors/types.js.map +1 -0
  161. package/esm/utils/applyOxcProcessors.js +2 -0
  162. package/esm/utils/applyOxcProcessors.js.map +1 -0
  163. package/esm/utils/collectOxcExportsAndImports.js +934 -0
  164. package/esm/utils/collectOxcExportsAndImports.js.map +1 -0
  165. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js +157 -0
  166. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js.map +1 -0
  167. package/esm/utils/collectOxcRuntime/sourceMap.js +36 -0
  168. package/esm/utils/collectOxcRuntime/sourceMap.js.map +1 -0
  169. package/esm/utils/collectOxcRuntime/types.js +2 -0
  170. package/esm/utils/collectOxcRuntime/types.js.map +1 -0
  171. package/esm/utils/collectOxcRuntime.js +32 -0
  172. package/esm/utils/collectOxcRuntime.js.map +1 -0
  173. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js +496 -0
  174. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js.map +1 -0
  175. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js +113 -0
  176. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js.map +1 -0
  177. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js +387 -0
  178. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js.map +1 -0
  179. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js +17 -0
  180. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js.map +1 -0
  181. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js +540 -0
  182. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js.map +1 -0
  183. package/esm/utils/collectOxcTemplateDependencies/types.js +2 -0
  184. package/esm/utils/collectOxcTemplateDependencies/types.js.map +1 -0
  185. package/esm/utils/collectOxcTemplateDependencies.js +4 -0
  186. package/esm/utils/collectOxcTemplateDependencies.js.map +1 -0
  187. package/esm/utils/dispose-polyfill.js +3 -4
  188. package/esm/utils/dispose-polyfill.js.map +1 -1
  189. package/esm/utils/getFileIdx.js +6 -6
  190. package/esm/utils/getFileIdx.js.map +1 -1
  191. package/esm/utils/getPluginKey.js +12 -12
  192. package/esm/utils/getPluginKey.js.map +1 -1
  193. package/esm/utils/getVisitorKeys.js +9 -3
  194. package/esm/utils/getVisitorKeys.js.map +1 -1
  195. package/esm/utils/hasCachedWywPrevalExport.js +23 -0
  196. package/esm/utils/hasCachedWywPrevalExport.js.map +1 -0
  197. package/esm/utils/hasWywPreval.js +5 -5
  198. package/esm/utils/hasWywPreval.js.map +1 -1
  199. package/esm/utils/importOverrides.js +75 -90
  200. package/esm/utils/importOverrides.js.map +1 -1
  201. package/esm/utils/isNode.js +2 -2
  202. package/esm/utils/isNode.js.map +1 -1
  203. package/esm/utils/isNotNull.js +2 -2
  204. package/esm/utils/isNotNull.js.map +1 -1
  205. package/esm/utils/isSerializable.js +11 -11
  206. package/esm/utils/isSerializable.js.map +1 -1
  207. package/esm/utils/nativeResolver.js +93 -0
  208. package/esm/utils/nativeResolver.js.map +1 -0
  209. package/esm/utils/oxc/ast.js +28 -0
  210. package/esm/utils/oxc/ast.js.map +1 -0
  211. package/esm/utils/oxc/parse.js +3 -0
  212. package/esm/utils/oxc/parse.js.map +1 -0
  213. package/esm/utils/oxc/replacements.js +14 -0
  214. package/esm/utils/oxc/replacements.js.map +1 -0
  215. package/esm/utils/oxc/sourceLocations.js +59 -0
  216. package/esm/utils/oxc/sourceLocations.js.map +1 -0
  217. package/esm/utils/oxcAstService.js +121 -0
  218. package/esm/utils/oxcAstService.js.map +1 -0
  219. package/esm/utils/oxcEmit.js +447 -0
  220. package/esm/utils/oxcEmit.js.map +1 -0
  221. package/esm/utils/oxcPreevalStage/evalStrategy.js +3 -0
  222. package/esm/utils/oxcPreevalStage/evalStrategy.js.map +1 -0
  223. package/esm/utils/oxcPreevalStage/prepareCode.js +21 -0
  224. package/esm/utils/oxcPreevalStage/prepareCode.js.map +1 -0
  225. package/esm/utils/oxcPreevalStage/prevalExport.js +23 -0
  226. package/esm/utils/oxcPreevalStage/prevalExport.js.map +1 -0
  227. package/esm/utils/oxcPreevalStage/processors.js +17 -0
  228. package/esm/utils/oxcPreevalStage/processors.js.map +1 -0
  229. package/esm/utils/oxcPreevalStage/staticOverlay.js +18 -0
  230. package/esm/utils/oxcPreevalStage/staticOverlay.js.map +1 -0
  231. package/esm/utils/oxcPreevalStage/types.js +2 -0
  232. package/esm/utils/oxcPreevalStage/types.js.map +1 -0
  233. package/esm/utils/oxcPreevalStage.js +41 -0
  234. package/esm/utils/oxcPreevalStage.js.map +1 -0
  235. package/esm/utils/oxcPreevalTransforms.js +1065 -0
  236. package/esm/utils/oxcPreevalTransforms.js.map +1 -0
  237. package/esm/utils/oxcShaker.js +662 -0
  238. package/esm/utils/oxcShaker.js.map +1 -0
  239. package/esm/utils/parseOxc.js +37 -0
  240. package/esm/utils/parseOxc.js.map +1 -0
  241. package/esm/utils/parseRequest.js +27 -27
  242. package/esm/utils/parseRequest.js.map +1 -1
  243. package/esm/utils/peek.js +1 -1
  244. package/esm/utils/peek.js.map +1 -1
  245. package/esm/utils/processorLookup.js +125 -0
  246. package/esm/utils/processorLookup.js.map +1 -0
  247. package/esm/utils/processorStaticSemantics.js +157 -0
  248. package/esm/utils/processorStaticSemantics.js.map +1 -0
  249. package/esm/utils/resolveWithConditions.js +99 -0
  250. package/esm/utils/resolveWithConditions.js.map +1 -0
  251. package/esm/vm/createVmContext.js +140 -141
  252. package/esm/vm/createVmContext.js.map +1 -1
  253. package/esm/vm/process.js +11 -13
  254. package/esm/vm/process.js.map +1 -1
  255. package/package.json +19 -26
  256. package/types/cache.d.ts +17 -8
  257. package/types/cache.js +245 -95
  258. package/types/debug/fileReporter.js +68 -23
  259. package/types/eval/broker.d.ts +92 -0
  260. package/types/eval/broker.js +2411 -0
  261. package/types/eval/lru.d.ts +10 -0
  262. package/types/eval/lru.js +36 -0
  263. package/types/eval/prepareModuleOnDemand.d.ts +7 -0
  264. package/types/eval/prepareModuleOnDemand.js +24 -0
  265. package/types/eval/protocol.d.ts +111 -0
  266. package/types/eval/protocol.js +1 -0
  267. package/types/eval/serialize.d.ts +78 -0
  268. package/types/eval/serialize.js +357 -0
  269. package/types/eval/writeQueue.d.ts +13 -0
  270. package/types/eval/writeQueue.js +80 -0
  271. package/types/evaluators/index.d.ts +2 -2
  272. package/types/evaluators/index.js +6 -9
  273. package/types/index.d.ts +3 -6
  274. package/types/index.js +24 -82
  275. package/types/module.d.ts +38 -7
  276. package/types/module.js +613 -192
  277. package/types/shaker.d.ts +2 -10
  278. package/types/shaker.js +10 -100
  279. package/types/transform/BaseEntrypoint.js +6 -11
  280. package/types/transform/Entrypoint.d.ts +15 -15
  281. package/types/transform/Entrypoint.helpers.d.ts +2 -5
  282. package/types/transform/Entrypoint.helpers.js +43 -203
  283. package/types/transform/Entrypoint.js +130 -53
  284. package/types/transform/Entrypoint.types.d.ts +31 -6
  285. package/types/transform/Entrypoint.types.js +1 -2
  286. package/types/transform/EvaluatedEntrypoint.d.ts +13 -2
  287. package/types/transform/EvaluatedEntrypoint.js +7 -6
  288. package/types/transform/actions/AbortError.js +2 -7
  289. package/types/transform/actions/BaseAction.js +4 -8
  290. package/types/transform/actions/UnprocessedEntrypointError.js +2 -7
  291. package/types/transform/actions/actionRunner.js +8 -12
  292. package/types/transform/actions/types.d.ts +2 -2
  293. package/types/transform/actions/types.js +1 -2
  294. package/types/transform/{barrelManifest.d.ts → barrelManifest.types.d.ts} +0 -2
  295. package/types/transform/barrelManifest.types.js +1 -0
  296. package/types/transform/generators/baseProcessingHandlers.d.ts +4 -5
  297. package/types/transform/generators/baseProcessingHandlers.js +10 -14
  298. package/types/transform/generators/collect.js +13 -39
  299. package/types/transform/generators/createStylisPreprocessor.js +19 -60
  300. package/types/transform/generators/evalFile.d.ts +2 -2
  301. package/types/transform/generators/evalFile.js +26 -28
  302. package/types/transform/generators/extract.js +5 -8
  303. package/types/transform/generators/getExports.js +23 -30
  304. package/types/transform/generators/index.d.ts +2 -2
  305. package/types/transform/generators/index.js +11 -14
  306. package/types/transform/generators/processEntrypoint.d.ts +2 -2
  307. package/types/transform/generators/processEntrypoint.js +60 -26
  308. package/types/transform/generators/processImports.d.ts +0 -3
  309. package/types/transform/generators/processImports.js +60 -20
  310. package/types/transform/generators/resolveImports.d.ts +3 -1
  311. package/types/transform/generators/resolveImports.js +66 -23
  312. package/types/transform/generators/resolveStaticOxcValues/cache.d.ts +25 -0
  313. package/types/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  314. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.d.ts +5 -0
  315. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.js +149 -0
  316. package/types/transform/generators/resolveStaticOxcValues/dependencies.d.ts +6 -0
  317. package/types/transform/generators/resolveStaticOxcValues/dependencies.js +37 -0
  318. package/types/transform/generators/resolveStaticOxcValues/environment.d.ts +12 -0
  319. package/types/transform/generators/resolveStaticOxcValues/environment.js +32 -0
  320. package/types/transform/generators/resolveStaticOxcValues/exportResolver.d.ts +4 -0
  321. package/types/transform/generators/resolveStaticOxcValues/exportResolver.js +358 -0
  322. package/types/transform/generators/resolveStaticOxcValues/exportTargets.d.ts +20 -0
  323. package/types/transform/generators/resolveStaticOxcValues/exportTargets.js +285 -0
  324. package/types/transform/generators/resolveStaticOxcValues/objectAssign.d.ts +41 -0
  325. package/types/transform/generators/resolveStaticOxcValues/objectAssign.js +352 -0
  326. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.d.ts +6 -0
  327. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +88 -0
  328. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.d.ts +13 -0
  329. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +263 -0
  330. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.d.ts +4 -0
  331. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.js +191 -0
  332. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.d.ts +40 -0
  333. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.js +516 -0
  334. package/types/transform/generators/resolveStaticOxcValues/processorTarget.d.ts +5 -0
  335. package/types/transform/generators/resolveStaticOxcValues/processorTarget.js +62 -0
  336. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.d.ts +11 -0
  337. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.js +133 -0
  338. package/types/transform/generators/resolveStaticOxcValues/prune.d.ts +15 -0
  339. package/types/transform/generators/resolveStaticOxcValues/prune.js +220 -0
  340. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.d.ts +2 -0
  341. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +197 -0
  342. package/types/transform/generators/resolveStaticOxcValues/staticExpression.d.ts +25 -0
  343. package/types/transform/generators/resolveStaticOxcValues/staticExpression.js +391 -0
  344. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.d.ts +14 -0
  345. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +304 -0
  346. package/types/transform/generators/resolveStaticOxcValues/types.d.ts +99 -0
  347. package/types/transform/generators/resolveStaticOxcValues/types.js +2 -0
  348. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.d.ts +7 -0
  349. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +64 -0
  350. package/types/transform/generators/resolveStaticOxcValues.d.ts +1 -0
  351. package/types/transform/generators/resolveStaticOxcValues.js +1 -0
  352. package/types/transform/generators/{rewriteBarrelImports.d.ts → rewriteOxcBarrelImports.d.ts} +2 -3
  353. package/types/transform/generators/{rewriteBarrelImports.js → rewriteOxcBarrelImports.js} +282 -225
  354. package/types/transform/generators/transform.d.ts +3 -7
  355. package/types/transform/generators/transform.js +217 -199
  356. package/types/transform/generators/workflow.js +62 -45
  357. package/types/transform/helpers/loadWywOptions.js +115 -21
  358. package/types/transform/helpers/withDefaultServices.d.ts +1 -1
  359. package/types/transform/helpers/withDefaultServices.js +6 -44
  360. package/types/transform/isStaticallyEvaluatableModule.d.ts +1 -2
  361. package/types/transform/isStaticallyEvaluatableModule.js +125 -126
  362. package/types/transform/oxcBarrelManifest.d.ts +2 -0
  363. package/types/transform/{barrelManifest.js → oxcBarrelManifest.js} +156 -97
  364. package/types/transform/rootLog.js +2 -5
  365. package/types/transform/syntax.d.ts +38 -0
  366. package/types/transform/syntax.js +1 -0
  367. package/types/transform/types.d.ts +9 -6
  368. package/types/transform/types.js +1 -4
  369. package/types/transform.d.ts +2 -2
  370. package/types/transform.js +90 -101
  371. package/types/types.d.ts +0 -23
  372. package/types/types.js +1 -2
  373. package/types/utils/EventEmitter.d.ts +16 -1
  374. package/types/utils/EventEmitter.js +47 -18
  375. package/types/utils/ShakerMetadata.js +1 -5
  376. package/types/utils/TransformDiagnostics.js +3 -7
  377. package/types/utils/TransformMetadata.js +8 -16
  378. package/types/utils/applyOxcProcessors/applyOxcProcessors.d.ts +8 -0
  379. package/types/utils/applyOxcProcessors/applyOxcProcessors.js +167 -0
  380. package/types/utils/applyOxcProcessors/cleanupBindings.d.ts +12 -0
  381. package/types/utils/applyOxcProcessors/cleanupBindings.js +189 -0
  382. package/types/utils/applyOxcProcessors/cleanupRemovals.d.ts +16 -0
  383. package/types/utils/applyOxcProcessors/cleanupRemovals.js +482 -0
  384. package/types/utils/applyOxcProcessors/displayName.d.ts +9 -0
  385. package/types/utils/applyOxcProcessors/displayName.js +113 -0
  386. package/types/utils/applyOxcProcessors/expressionValues.d.ts +11 -0
  387. package/types/utils/applyOxcProcessors/expressionValues.js +170 -0
  388. package/types/utils/applyOxcProcessors/processorFactory.d.ts +7 -0
  389. package/types/utils/applyOxcProcessors/processorFactory.js +70 -0
  390. package/types/utils/applyOxcProcessors/processorUsages.d.ts +16 -0
  391. package/types/utils/applyOxcProcessors/processorUsages.js +163 -0
  392. package/types/utils/applyOxcProcessors/sameFileStaticValues.d.ts +23 -0
  393. package/types/utils/applyOxcProcessors/sameFileStaticValues.js +211 -0
  394. package/types/utils/applyOxcProcessors/shared.d.ts +10 -0
  395. package/types/utils/applyOxcProcessors/shared.js +37 -0
  396. package/types/utils/applyOxcProcessors/types.d.ts +88 -0
  397. package/types/utils/applyOxcProcessors/types.js +1 -0
  398. package/types/utils/applyOxcProcessors.d.ts +1 -0
  399. package/types/utils/applyOxcProcessors.js +1 -0
  400. package/types/utils/collectOxcExportsAndImports.d.ts +35 -0
  401. package/types/utils/collectOxcExportsAndImports.js +957 -0
  402. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.d.ts +1 -0
  403. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.js +185 -0
  404. package/types/utils/collectOxcRuntime/sourceMap.d.ts +2 -0
  405. package/types/utils/collectOxcRuntime/sourceMap.js +37 -0
  406. package/types/utils/collectOxcRuntime/types.d.ts +16 -0
  407. package/types/utils/collectOxcRuntime/types.js +1 -0
  408. package/types/utils/collectOxcRuntime.d.ts +4 -0
  409. package/types/utils/collectOxcRuntime.js +31 -0
  410. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.d.ts +6 -0
  411. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.js +550 -0
  412. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.d.ts +11 -0
  413. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.js +131 -0
  414. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.d.ts +20 -0
  415. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.js +434 -0
  416. package/types/utils/collectOxcTemplateDependencies/staticBindings.d.ts +7 -0
  417. package/types/utils/collectOxcTemplateDependencies/staticBindings.js +13 -0
  418. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.d.ts +13 -0
  419. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.js +626 -0
  420. package/types/utils/collectOxcTemplateDependencies/types.d.ts +116 -0
  421. package/types/utils/collectOxcTemplateDependencies/types.js +1 -0
  422. package/types/utils/collectOxcTemplateDependencies.d.ts +4 -0
  423. package/types/utils/collectOxcTemplateDependencies.js +3 -0
  424. package/types/utils/getFileIdx.js +1 -4
  425. package/types/utils/getPluginKey.d.ts +5 -2
  426. package/types/utils/getPluginKey.js +2 -6
  427. package/types/utils/getVisitorKeys.d.ts +4 -4
  428. package/types/utils/getVisitorKeys.js +9 -6
  429. package/types/utils/hasCachedWywPrevalExport.d.ts +14 -0
  430. package/types/utils/hasCachedWywPrevalExport.js +30 -0
  431. package/types/utils/hasWywPreval.js +1 -4
  432. package/types/utils/importOverrides.js +17 -27
  433. package/types/utils/isNode.d.ts +2 -2
  434. package/types/utils/isNode.js +2 -6
  435. package/types/utils/isNotNull.js +1 -4
  436. package/types/utils/isSerializable.js +3 -6
  437. package/types/utils/nativeResolver.d.ts +13 -0
  438. package/types/utils/nativeResolver.js +91 -0
  439. package/types/utils/oxc/ast.d.ts +4 -0
  440. package/types/utils/oxc/ast.js +37 -0
  441. package/types/utils/oxc/parse.d.ts +3 -0
  442. package/types/utils/oxc/parse.js +2 -0
  443. package/types/utils/oxc/replacements.d.ts +12 -0
  444. package/types/utils/oxc/replacements.js +18 -0
  445. package/types/utils/oxc/sourceLocations.d.ts +5 -0
  446. package/types/utils/oxc/sourceLocations.js +63 -0
  447. package/types/utils/oxcAstService.d.ts +11 -0
  448. package/types/utils/oxcAstService.js +79 -0
  449. package/types/utils/oxcEmit.d.ts +19 -0
  450. package/types/utils/oxcEmit.js +506 -0
  451. package/types/utils/oxcPreevalStage/evalStrategy.d.ts +3 -0
  452. package/types/utils/oxcPreevalStage/evalStrategy.js +2 -0
  453. package/types/utils/oxcPreevalStage/prepareCode.d.ts +3 -0
  454. package/types/utils/oxcPreevalStage/prepareCode.js +20 -0
  455. package/types/utils/oxcPreevalStage/prevalExport.d.ts +1 -0
  456. package/types/utils/oxcPreevalStage/prevalExport.js +22 -0
  457. package/types/utils/oxcPreevalStage/processors.d.ts +10 -0
  458. package/types/utils/oxcPreevalStage/processors.js +16 -0
  459. package/types/utils/oxcPreevalStage/staticOverlay.d.ts +3 -0
  460. package/types/utils/oxcPreevalStage/staticOverlay.js +23 -0
  461. package/types/utils/oxcPreevalStage/types.d.ts +22 -0
  462. package/types/utils/oxcPreevalStage/types.js +1 -0
  463. package/types/utils/oxcPreevalStage.d.ts +4 -0
  464. package/types/utils/oxcPreevalStage.js +40 -0
  465. package/types/utils/oxcPreevalTransforms.d.ts +13 -0
  466. package/types/utils/oxcPreevalTransforms.js +1192 -0
  467. package/types/utils/oxcShaker.d.ts +13 -0
  468. package/types/utils/oxcShaker.js +751 -0
  469. package/types/utils/parseOxc.d.ts +11 -0
  470. package/types/utils/parseOxc.js +38 -0
  471. package/types/utils/parseRequest.js +2 -7
  472. package/types/utils/peek.js +1 -5
  473. package/types/utils/processorLookup.d.ts +8 -0
  474. package/types/utils/processorLookup.js +135 -0
  475. package/types/utils/processorStaticSemantics.d.ts +13 -0
  476. package/types/utils/processorStaticSemantics.js +191 -0
  477. package/types/utils/resolveWithConditions.d.ts +12 -0
  478. package/types/utils/resolveWithConditions.js +103 -0
  479. package/types/vm/createVmContext.d.ts +2 -2
  480. package/types/vm/createVmContext.js +25 -62
  481. package/types/vm/process.js +20 -26
  482. package/esm/babel.js +0 -2
  483. package/esm/babel.js.map +0 -1
  484. package/esm/options/buildOptions.js +0 -168
  485. package/esm/options/buildOptions.js.map +0 -1
  486. package/esm/options/buildOptions.test.js +0 -138
  487. package/esm/options/buildOptions.test.js.map +0 -1
  488. package/esm/options/loadBabelOptions.js +0 -24
  489. package/esm/options/loadBabelOptions.js.map +0 -1
  490. package/esm/plugins/babel-transform.js +0 -53
  491. package/esm/plugins/babel-transform.js.map +0 -1
  492. package/esm/plugins/collector.js +0 -60
  493. package/esm/plugins/collector.js.map +0 -1
  494. package/esm/plugins/dynamic-import.js +0 -56
  495. package/esm/plugins/dynamic-import.js.map +0 -1
  496. package/esm/plugins/preeval.js +0 -73
  497. package/esm/plugins/preeval.js.map +0 -1
  498. package/esm/plugins/shaker.js +0 -680
  499. package/esm/plugins/shaker.js.map +0 -1
  500. package/esm/transform/barrelManifest.js +0 -291
  501. package/esm/transform/barrelManifest.js.map +0 -1
  502. package/esm/transform/generators/explodeReexports.js +0 -64
  503. package/esm/transform/generators/explodeReexports.js.map +0 -1
  504. package/esm/transform/generators/rewriteBarrelImports.js +0 -733
  505. package/esm/transform/generators/rewriteBarrelImports.js.map +0 -1
  506. package/esm/utils/addIdentifierToWywPreval.js +0 -68
  507. package/esm/utils/addIdentifierToWywPreval.js.map +0 -1
  508. package/esm/utils/collectExportsAndImports.js +0 -1157
  509. package/esm/utils/collectExportsAndImports.js.map +0 -1
  510. package/esm/utils/collectTemplateDependencies.js +0 -228
  511. package/esm/utils/collectTemplateDependencies.js.map +0 -1
  512. package/esm/utils/createId.js +0 -6
  513. package/esm/utils/createId.js.map +0 -1
  514. package/esm/utils/findIdentifiers.js +0 -62
  515. package/esm/utils/findIdentifiers.js.map +0 -1
  516. package/esm/utils/getConstantStringValue.js +0 -58
  517. package/esm/utils/getConstantStringValue.js.map +0 -1
  518. package/esm/utils/getMemberExpressionPropertyName.js +0 -11
  519. package/esm/utils/getMemberExpressionPropertyName.js.map +0 -1
  520. package/esm/utils/getScope.js +0 -6
  521. package/esm/utils/getScope.js.map +0 -1
  522. package/esm/utils/getSource.js +0 -15
  523. package/esm/utils/getSource.js.map +0 -1
  524. package/esm/utils/getTagProcessor.js +0 -404
  525. package/esm/utils/getTagProcessor.js.map +0 -1
  526. package/esm/utils/isExports.js +0 -22
  527. package/esm/utils/isExports.js.map +0 -1
  528. package/esm/utils/isGlobal.js +0 -6
  529. package/esm/utils/isGlobal.js.map +0 -1
  530. package/esm/utils/isNodePath.js +0 -4
  531. package/esm/utils/isNodePath.js.map +0 -1
  532. package/esm/utils/isRemoved.js +0 -46
  533. package/esm/utils/isRemoved.js.map +0 -1
  534. package/esm/utils/isRequire.js +0 -13
  535. package/esm/utils/isRequire.js.map +0 -1
  536. package/esm/utils/isTypedNode.js +0 -6
  537. package/esm/utils/isTypedNode.js.map +0 -1
  538. package/esm/utils/isUnnecessaryReactCall.js +0 -72
  539. package/esm/utils/isUnnecessaryReactCall.js.map +0 -1
  540. package/esm/utils/removeDangerousCode.js +0 -276
  541. package/esm/utils/removeDangerousCode.js.map +0 -1
  542. package/esm/utils/replaceImportMetaEnv.js +0 -44
  543. package/esm/utils/replaceImportMetaEnv.js.map +0 -1
  544. package/esm/utils/scopeHelpers.js +0 -527
  545. package/esm/utils/scopeHelpers.js.map +0 -1
  546. package/esm/utils/traversalCache.js +0 -23
  547. package/esm/utils/traversalCache.js.map +0 -1
  548. package/esm/utils/unwrapExpression.js +0 -18
  549. package/esm/utils/unwrapExpression.js.map +0 -1
  550. package/esm/utils/unwrapSequence.js +0 -14
  551. package/esm/utils/unwrapSequence.js.map +0 -1
  552. package/esm/utils/valueToLiteral.js +0 -59
  553. package/esm/utils/valueToLiteral.js.map +0 -1
  554. package/esm/utils/visitors/JSXElementsRemover.js +0 -51
  555. package/esm/utils/visitors/JSXElementsRemover.js.map +0 -1
  556. package/lib/babel.js +0 -2
  557. package/lib/babel.js.map +0 -1
  558. package/lib/cache.js +0 -308
  559. package/lib/cache.js.map +0 -1
  560. package/lib/debug/fileReporter.js +0 -153
  561. package/lib/debug/fileReporter.js.map +0 -1
  562. package/lib/evaluators/index.js +0 -20
  563. package/lib/evaluators/index.js.map +0 -1
  564. package/lib/index.js +0 -286
  565. package/lib/index.js.map +0 -1
  566. package/lib/module.js +0 -552
  567. package/lib/module.js.map +0 -1
  568. package/lib/options/buildOptions.js +0 -176
  569. package/lib/options/buildOptions.js.map +0 -1
  570. package/lib/options/buildOptions.test.js +0 -141
  571. package/lib/options/buildOptions.test.js.map +0 -1
  572. package/lib/options/loadBabelOptions.js +0 -31
  573. package/lib/options/loadBabelOptions.js.map +0 -1
  574. package/lib/plugins/babel-transform.js +0 -60
  575. package/lib/plugins/babel-transform.js.map +0 -1
  576. package/lib/plugins/collector.js +0 -70
  577. package/lib/plugins/collector.js.map +0 -1
  578. package/lib/plugins/dynamic-import.js +0 -61
  579. package/lib/plugins/dynamic-import.js.map +0 -1
  580. package/lib/plugins/preeval.js +0 -81
  581. package/lib/plugins/preeval.js.map +0 -1
  582. package/lib/plugins/shaker.js +0 -691
  583. package/lib/plugins/shaker.js.map +0 -1
  584. package/lib/shaker.js +0 -95
  585. package/lib/shaker.js.map +0 -1
  586. package/lib/transform/BaseEntrypoint.js +0 -179
  587. package/lib/transform/BaseEntrypoint.js.map +0 -1
  588. package/lib/transform/Entrypoint.helpers.js +0 -279
  589. package/lib/transform/Entrypoint.helpers.js.map +0 -1
  590. package/lib/transform/Entrypoint.js +0 -289
  591. package/lib/transform/Entrypoint.js.map +0 -1
  592. package/lib/transform/Entrypoint.types.js +0 -2
  593. package/lib/transform/Entrypoint.types.js.map +0 -1
  594. package/lib/transform/EvaluatedEntrypoint.js +0 -13
  595. package/lib/transform/EvaluatedEntrypoint.js.map +0 -1
  596. package/lib/transform/actions/AbortError.js +0 -16
  597. package/lib/transform/actions/AbortError.js.map +0 -1
  598. package/lib/transform/actions/BaseAction.js +0 -150
  599. package/lib/transform/actions/BaseAction.js.map +0 -1
  600. package/lib/transform/actions/UnprocessedEntrypointError.js +0 -16
  601. package/lib/transform/actions/UnprocessedEntrypointError.js.map +0 -1
  602. package/lib/transform/actions/actionRunner.js +0 -82
  603. package/lib/transform/actions/actionRunner.js.map +0 -1
  604. package/lib/transform/actions/types.js +0 -2
  605. package/lib/transform/actions/types.js.map +0 -1
  606. package/lib/transform/barrelManifest.js +0 -300
  607. package/lib/transform/barrelManifest.js.map +0 -1
  608. package/lib/transform/generators/baseProcessingHandlers.js +0 -27
  609. package/lib/transform/generators/baseProcessingHandlers.js.map +0 -1
  610. package/lib/transform/generators/collect.js +0 -66
  611. package/lib/transform/generators/collect.js.map +0 -1
  612. package/lib/transform/generators/createStylisPreprocessor.js +0 -372
  613. package/lib/transform/generators/createStylisPreprocessor.js.map +0 -1
  614. package/lib/transform/generators/evalFile.js +0 -57
  615. package/lib/transform/generators/evalFile.js.map +0 -1
  616. package/lib/transform/generators/explodeReexports.js +0 -71
  617. package/lib/transform/generators/explodeReexports.js.map +0 -1
  618. package/lib/transform/generators/extract.js +0 -102
  619. package/lib/transform/generators/extract.js.map +0 -1
  620. package/lib/transform/generators/getExports.js +0 -85
  621. package/lib/transform/generators/getExports.js.map +0 -1
  622. package/lib/transform/generators/index.js +0 -19
  623. package/lib/transform/generators/index.js.map +0 -1
  624. package/lib/transform/generators/processEntrypoint.js +0 -76
  625. package/lib/transform/generators/processEntrypoint.js.map +0 -1
  626. package/lib/transform/generators/processImports.js +0 -82
  627. package/lib/transform/generators/processImports.js.map +0 -1
  628. package/lib/transform/generators/resolveImports.js +0 -221
  629. package/lib/transform/generators/resolveImports.js.map +0 -1
  630. package/lib/transform/generators/rewriteBarrelImports.js +0 -743
  631. package/lib/transform/generators/rewriteBarrelImports.js.map +0 -1
  632. package/lib/transform/generators/transform.js +0 -272
  633. package/lib/transform/generators/transform.js.map +0 -1
  634. package/lib/transform/generators/workflow.js +0 -100
  635. package/lib/transform/generators/workflow.js.map +0 -1
  636. package/lib/transform/helpers/loadWywOptions.js +0 -88
  637. package/lib/transform/helpers/loadWywOptions.js.map +0 -1
  638. package/lib/transform/helpers/withDefaultServices.js +0 -31
  639. package/lib/transform/helpers/withDefaultServices.js.map +0 -1
  640. package/lib/transform/isStaticallyEvaluatableModule.js +0 -159
  641. package/lib/transform/isStaticallyEvaluatableModule.js.map +0 -1
  642. package/lib/transform/rootLog.js +0 -9
  643. package/lib/transform/rootLog.js.map +0 -1
  644. package/lib/transform/types.js +0 -8
  645. package/lib/transform/types.js.map +0 -1
  646. package/lib/transform.js +0 -160
  647. package/lib/transform.js.map +0 -1
  648. package/lib/types.js +0 -2
  649. package/lib/types.js.map +0 -1
  650. package/lib/utils/EventEmitter.js +0 -61
  651. package/lib/utils/EventEmitter.js.map +0 -1
  652. package/lib/utils/ShakerMetadata.js +0 -9
  653. package/lib/utils/ShakerMetadata.js.map +0 -1
  654. package/lib/utils/TransformDiagnostics.js +0 -20
  655. package/lib/utils/TransformDiagnostics.js.map +0 -1
  656. package/lib/utils/TransformMetadata.js +0 -45
  657. package/lib/utils/TransformMetadata.js.map +0 -1
  658. package/lib/utils/addIdentifierToWywPreval.js +0 -75
  659. package/lib/utils/addIdentifierToWywPreval.js.map +0 -1
  660. package/lib/utils/collectExportsAndImports.js +0 -1173
  661. package/lib/utils/collectExportsAndImports.js.map +0 -1
  662. package/lib/utils/collectTemplateDependencies.js +0 -242
  663. package/lib/utils/collectTemplateDependencies.js.map +0 -1
  664. package/lib/utils/createId.js +0 -13
  665. package/lib/utils/createId.js.map +0 -1
  666. package/lib/utils/dispose-polyfill.js +0 -9
  667. package/lib/utils/dispose-polyfill.js.map +0 -1
  668. package/lib/utils/findIdentifiers.js +0 -73
  669. package/lib/utils/findIdentifiers.js.map +0 -1
  670. package/lib/utils/getConstantStringValue.js +0 -66
  671. package/lib/utils/getConstantStringValue.js.map +0 -1
  672. package/lib/utils/getFileIdx.js +0 -16
  673. package/lib/utils/getFileIdx.js.map +0 -1
  674. package/lib/utils/getMemberExpressionPropertyName.js +0 -18
  675. package/lib/utils/getMemberExpressionPropertyName.js.map +0 -1
  676. package/lib/utils/getPluginKey.js +0 -21
  677. package/lib/utils/getPluginKey.js.map +0 -1
  678. package/lib/utils/getScope.js +0 -12
  679. package/lib/utils/getScope.js.map +0 -1
  680. package/lib/utils/getSource.js +0 -24
  681. package/lib/utils/getSource.js.map +0 -1
  682. package/lib/utils/getTagProcessor.js +0 -424
  683. package/lib/utils/getTagProcessor.js.map +0 -1
  684. package/lib/utils/getVisitorKeys.js +0 -11
  685. package/lib/utils/getVisitorKeys.js.map +0 -1
  686. package/lib/utils/hasWywPreval.js +0 -13
  687. package/lib/utils/hasWywPreval.js.map +0 -1
  688. package/lib/utils/importOverrides.js +0 -119
  689. package/lib/utils/importOverrides.js.map +0 -1
  690. package/lib/utils/isExports.js +0 -27
  691. package/lib/utils/isExports.js.map +0 -1
  692. package/lib/utils/isGlobal.js +0 -13
  693. package/lib/utils/isGlobal.js.map +0 -1
  694. package/lib/utils/isNode.js +0 -9
  695. package/lib/utils/isNode.js.map +0 -1
  696. package/lib/utils/isNodePath.js +0 -10
  697. package/lib/utils/isNodePath.js.map +0 -1
  698. package/lib/utils/isNotNull.js +0 -10
  699. package/lib/utils/isNotNull.js.map +0 -1
  700. package/lib/utils/isRemoved.js +0 -52
  701. package/lib/utils/isRemoved.js.map +0 -1
  702. package/lib/utils/isRequire.js +0 -18
  703. package/lib/utils/isRequire.js.map +0 -1
  704. package/lib/utils/isSerializable.js +0 -19
  705. package/lib/utils/isSerializable.js.map +0 -1
  706. package/lib/utils/isTypedNode.js +0 -13
  707. package/lib/utils/isTypedNode.js.map +0 -1
  708. package/lib/utils/isUnnecessaryReactCall.js +0 -81
  709. package/lib/utils/isUnnecessaryReactCall.js.map +0 -1
  710. package/lib/utils/parseRequest.js +0 -37
  711. package/lib/utils/parseRequest.js.map +0 -1
  712. package/lib/utils/peek.js +0 -9
  713. package/lib/utils/peek.js.map +0 -1
  714. package/lib/utils/removeDangerousCode.js +0 -284
  715. package/lib/utils/removeDangerousCode.js.map +0 -1
  716. package/lib/utils/replaceImportMetaEnv.js +0 -50
  717. package/lib/utils/replaceImportMetaEnv.js.map +0 -1
  718. package/lib/utils/scopeHelpers.js +0 -557
  719. package/lib/utils/scopeHelpers.js.map +0 -1
  720. package/lib/utils/traversalCache.js +0 -31
  721. package/lib/utils/traversalCache.js.map +0 -1
  722. package/lib/utils/unwrapExpression.js +0 -25
  723. package/lib/utils/unwrapExpression.js.map +0 -1
  724. package/lib/utils/unwrapSequence.js +0 -20
  725. package/lib/utils/unwrapSequence.js.map +0 -1
  726. package/lib/utils/valueToLiteral.js +0 -65
  727. package/lib/utils/valueToLiteral.js.map +0 -1
  728. package/lib/utils/visitors/JSXElementsRemover.js +0 -57
  729. package/lib/utils/visitors/JSXElementsRemover.js.map +0 -1
  730. package/lib/vm/createVmContext.js +0 -166
  731. package/lib/vm/createVmContext.js.map +0 -1
  732. package/lib/vm/process.js +0 -38
  733. package/lib/vm/process.js.map +0 -1
  734. package/types/babel.d.ts +0 -2
  735. package/types/babel.js +0 -2
  736. package/types/options/buildOptions.d.ts +0 -6
  737. package/types/options/buildOptions.js +0 -178
  738. package/types/options/loadBabelOptions.d.ts +0 -3
  739. package/types/options/loadBabelOptions.js +0 -26
  740. package/types/plugins/babel-transform.d.ts +0 -4
  741. package/types/plugins/babel-transform.js +0 -49
  742. package/types/plugins/collector.d.ts +0 -23
  743. package/types/plugins/collector.js +0 -62
  744. package/types/plugins/dynamic-import.d.ts +0 -6
  745. package/types/plugins/dynamic-import.js +0 -60
  746. package/types/plugins/preeval.d.ts +0 -16
  747. package/types/plugins/preeval.js +0 -69
  748. package/types/plugins/shaker.d.ts +0 -14
  749. package/types/plugins/shaker.js +0 -724
  750. package/types/transform/generators/explodeReexports.d.ts +0 -7
  751. package/types/transform/generators/explodeReexports.js +0 -65
  752. package/types/utils/addIdentifierToWywPreval.d.ts +0 -4
  753. package/types/utils/addIdentifierToWywPreval.js +0 -74
  754. package/types/utils/collectExportsAndImports.d.ts +0 -31
  755. package/types/utils/collectExportsAndImports.js +0 -1147
  756. package/types/utils/collectTemplateDependencies.d.ts +0 -17
  757. package/types/utils/collectTemplateDependencies.js +0 -220
  758. package/types/utils/createId.d.ts +0 -2
  759. package/types/utils/createId.js +0 -9
  760. package/types/utils/findIdentifiers.d.ts +0 -6
  761. package/types/utils/findIdentifiers.js +0 -67
  762. package/types/utils/getConstantStringValue.d.ts +0 -2
  763. package/types/utils/getConstantStringValue.js +0 -94
  764. package/types/utils/getMemberExpressionPropertyName.d.ts +0 -2
  765. package/types/utils/getMemberExpressionPropertyName.js +0 -46
  766. package/types/utils/getScope.d.ts +0 -2
  767. package/types/utils/getScope.js +0 -10
  768. package/types/utils/getSource.d.ts +0 -2
  769. package/types/utils/getSource.js +0 -22
  770. package/types/utils/getTagProcessor.d.ts +0 -13
  771. package/types/utils/getTagProcessor.js +0 -411
  772. package/types/utils/isExports.d.ts +0 -6
  773. package/types/utils/isExports.js +0 -19
  774. package/types/utils/isGlobal.d.ts +0 -2
  775. package/types/utils/isGlobal.js +0 -9
  776. package/types/utils/isNodePath.d.ts +0 -3
  777. package/types/utils/isNodePath.js +0 -6
  778. package/types/utils/isRemoved.d.ts +0 -5
  779. package/types/utils/isRemoved.js +0 -41
  780. package/types/utils/isRequire.d.ts +0 -6
  781. package/types/utils/isRequire.js +0 -14
  782. package/types/utils/isTypedNode.d.ts +0 -5
  783. package/types/utils/isTypedNode.js +0 -9
  784. package/types/utils/isUnnecessaryReactCall.d.ts +0 -3
  785. package/types/utils/isUnnecessaryReactCall.js +0 -75
  786. package/types/utils/removeDangerousCode.d.ts +0 -4
  787. package/types/utils/removeDangerousCode.js +0 -326
  788. package/types/utils/replaceImportMetaEnv.d.ts +0 -3
  789. package/types/utils/replaceImportMetaEnv.js +0 -39
  790. package/types/utils/scopeHelpers.d.ts +0 -12
  791. package/types/utils/scopeHelpers.js +0 -580
  792. package/types/utils/traversalCache.d.ts +0 -4
  793. package/types/utils/traversalCache.js +0 -27
  794. package/types/utils/unwrapExpression.d.ts +0 -2
  795. package/types/utils/unwrapExpression.js +0 -57
  796. package/types/utils/unwrapSequence.d.ts +0 -8
  797. package/types/utils/unwrapSequence.js +0 -16
  798. package/types/utils/valueToLiteral.d.ts +0 -3
  799. package/types/utils/valueToLiteral.js +0 -63
  800. package/types/utils/visitors/JSXElementsRemover.d.ts +0 -3
  801. package/types/utils/visitors/JSXElementsRemover.js +0 -51
@@ -0,0 +1,2275 @@
1
+ /* eslint-disable no-continue, no-plusplus, no-nested-ternary, no-void, no-await-in-loop, @typescript-eslint/no-use-before-define */
2
+ import { createHash } from "crypto";
3
+ import fs from "fs";
4
+ import NativeModule from "module";
5
+ import path from "path";
6
+ import { fileURLToPath } from "url";
7
+ import { spawn } from "child_process";
8
+ import { invariant } from "ts-invariant";
9
+ import { isFeatureEnabled } from "@wyw-in-js/shared";
10
+ import { isStaticallyEvaluatableModule } from "../transform/isStaticallyEvaluatableModule.js";
11
+ import { applyImportOverrideToOnly, getImportOverride, resolveMockSpecifier, toImportKey } from "../utils/importOverrides.js";
12
+ import { getFileIdx } from "../utils/getFileIdx.js";
13
+ import { collectOxcExportsAndImports } from "../utils/collectOxcExportsAndImports.js";
14
+ import { resolveWithNativeResolver } from "../utils/nativeResolver.js";
15
+ import { parseRequest, stripQueryAndHash } from "../utils/parseRequest.js";
16
+ import { hasCachedWywPrevalExport } from "../utils/hasCachedWywPrevalExport.js";
17
+ import { isSuperSet, mergeOnly } from "../transform/Entrypoint.helpers.js";
18
+ import { oxcShaker } from "../shaker.js";
19
+ import { analyzeOxcBarrelFile } from "../transform/oxcBarrelManifest.js";
20
+ import { LruCache } from "./lru.js";
21
+ import { prepareModuleOnDemand } from "./prepareModuleOnDemand.js";
22
+ import { deserializeValue, encodeGlobals, serializeValue } from "./serialize.js";
23
+ import { createWriteQueue, writeToStream } from "./writeQueue.js";
24
+ const DefaultModuleImplementation = NativeModule;
25
+ const isBuiltinSpecifier = (specifier) => {
26
+ const normalized = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
27
+ return DefaultModuleImplementation.builtinModules?.includes(normalized) || DefaultModuleImplementation.builtinModules?.includes(`node:${normalized}`);
28
+ };
29
+ const isVirtualSpecifier = (specifier) => specifier.startsWith("/@") || specifier.startsWith("virtual:") || specifier.startsWith("\0");
30
+ const isEvalOnlyKey = (key) => key === "__wywPreval" || key === "side-effect";
31
+ const isPreparedOnlySuperSet = (currentOnly, requestedOnly) => {
32
+ if (requestedOnly.includes("__wywPreval") && !currentOnly.includes("__wywPreval")) {
33
+ return false;
34
+ }
35
+ return isSuperSet(currentOnly, requestedOnly);
36
+ };
37
+ const hasPreparedExportKeys = (prepared, requestedOnly) => {
38
+ const requestedKeys = requestedOnly.filter((key) => !isEvalOnlyKey(key) && key !== "*");
39
+ if (requestedKeys.length === 0) {
40
+ return true;
41
+ }
42
+ if (!prepared.exports) {
43
+ if (!prepared.code) {
44
+ return false;
45
+ }
46
+ try {
47
+ const collected = collectOxcExportsAndImports(prepared.code, "prepared-module.js");
48
+ if (collected.reexports.some((reexport) => reexport.exported === "*")) {
49
+ return true;
50
+ }
51
+ const exportNames = new Set([...Object.keys(collected.exports), ...collected.reexports.filter((reexport) => reexport.exported !== "*").map((reexport) => reexport.exported)]);
52
+ return requestedKeys.every((key) => exportNames.has(key));
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+ return requestedKeys.every((key) => Object.prototype.hasOwnProperty.call(prepared.exports, key));
58
+ };
59
+ const isPreparedCacheHit = (prepared, requestedOnly) => isPreparedOnlySuperSet(prepared.only, requestedOnly) && hasPreparedExportKeys(prepared, requestedOnly);
60
+ const isExportContainer = (value) => value !== null && (typeof value === "object" || typeof value === "function");
61
+ const hasCachedExport = (source, key) => {
62
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
63
+ return true;
64
+ }
65
+ if (key === "default") {
66
+ return false;
67
+ }
68
+ const fallback = source.default;
69
+ return isExportContainer(fallback) && Object.prototype.hasOwnProperty.call(fallback, key);
70
+ };
71
+ const resolveCachedExport = (source, key) => {
72
+ if (key === "default") {
73
+ return Object.prototype.hasOwnProperty.call(source, "default") ? source.default : undefined;
74
+ }
75
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
76
+ return source[key];
77
+ }
78
+ const fallback = source.default;
79
+ if (isExportContainer(fallback) && Object.prototype.hasOwnProperty.call(fallback, key)) {
80
+ return fallback[key];
81
+ }
82
+ return undefined;
83
+ };
84
+ const serializeCachedExports = (exportsValue, requiredOnly) => {
85
+ if (requiredOnly.some(isEvalOnlyKey)) {
86
+ return null;
87
+ }
88
+ const keys = requiredOnly.includes("*") ? Object.keys(exportsValue).filter((key) => !isEvalOnlyKey(key)) : requiredOnly.filter((key) => !isEvalOnlyKey(key));
89
+ if (keys.length === 0) {
90
+ return null;
91
+ }
92
+ const serialized = {};
93
+ for (const key of keys) {
94
+ if (!hasCachedExport(exportsValue, key)) {
95
+ return null;
96
+ }
97
+ try {
98
+ const encoded = serializeValue(resolveCachedExport(exportsValue, key));
99
+ if (encoded.kind === "function") {
100
+ return null;
101
+ }
102
+ serialized[key] = encoded;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+ return serialized;
108
+ };
109
+ const collectKnownExportNames = (services, id, cachedEntrypoint) => {
110
+ let knownExports = services.cache.get("exports", id);
111
+ if (knownExports || !cachedEntrypoint) {
112
+ return knownExports;
113
+ }
114
+ const { loadedAndParsed } = cachedEntrypoint;
115
+ if (loadedAndParsed?.evaluator !== oxcShaker || !loadedAndParsed.code) {
116
+ return undefined;
117
+ }
118
+ const analyzed = collectOxcExportsAndImports(loadedAndParsed.code, loadedAndParsed.evalConfig?.filename ?? id);
119
+ if (analyzed.reexports.some((reexport) => reexport.exported === "*")) {
120
+ return undefined;
121
+ }
122
+ knownExports = Array.from(new Set([...Object.keys(analyzed.exports), ...analyzed.reexports.map((reexport) => reexport.exported)]));
123
+ services.cache.add("exports", id, knownExports);
124
+ return knownExports;
125
+ };
126
+ const getSerializableStaticImportKeys = (services, id, cachedEntrypoint, requiredOnly, request, importerId) => {
127
+ const isStaticImportLoad = Boolean(request && importerId);
128
+ const requestedExports = requiredOnly.includes("*") ? null : requiredOnly.filter((key) => !isEvalOnlyKey(key) && key !== "*");
129
+ const knownExports = collectKnownExportNames(services, id, cachedEntrypoint)?.filter((key) => !isEvalOnlyKey(key) && key !== "*");
130
+ if (isStaticImportLoad) {
131
+ if (!requestedExports?.length || !knownExports?.length || !isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], knownExports)) {
132
+ return null;
133
+ }
134
+ if (!requestedExports.every((key) => knownExports.includes(key))) {
135
+ return null;
136
+ }
137
+ return isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], requestedExports) ? requestedExports : null;
138
+ }
139
+ if (knownExports?.length) {
140
+ return isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], knownExports) ? knownExports : null;
141
+ }
142
+ const evaluatedOnly = cachedEntrypoint.evaluatedOnly ?? requiredOnly;
143
+ return requiredOnly.includes("*") ? evaluatedOnly : requiredOnly;
144
+ };
145
+ const DEFAULT_EVAL_OPTIONS = {
146
+ errors: "strict",
147
+ require: "warn-and-run",
148
+ resolver: "bundler"
149
+ };
150
+ const MAX_MESSAGE_SIZE = 10 * 1024 * 1024;
151
+ const MAX_CHUNK_SIZE = 512 * 1024;
152
+ const RESOLVE_CACHE_SIZE = 5e3;
153
+ const LOAD_CACHE_SIZE = 1e3;
154
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/u;
155
+ const REQUEST_TIMEOUT_MS = 3e4;
156
+ const EVAL_TIMEOUT_MS = Number(process.env.WYW_EVAL_TIMEOUT_MS ?? 3e5);
157
+ const INIT_TIMEOUT_MS = 12e4;
158
+ const HAPPYDOM_INIT_TIMEOUT_MS = Number(process.env.WYW_EVAL_HAPPYDOM_INIT_TIMEOUT_MS ?? process.env.WYW_HAPPYDOM_TIMEOUT_MS ?? 15e3);
159
+ // Mirrors runner.js `isFullModuleLoad`: wildcard `['*']` (or empty) is the
160
+ // only shape stored in the runner's moduleCache; everything else lands in
161
+ // moduleVariants. The shipped-code dedup must respect this shape because the
162
+ // runner picks its lookup map based on the LoadResult's `only`.
163
+ const isWildcardOnly = (only) => !only || only.length === 0 || only.length === 1 && only[0] === "*";
164
+ const isEvalTimeoutError = (error) => {
165
+ if (!error || typeof error !== "object") return false;
166
+ if ("code" in error && error.code) {
167
+ return error.code === "WYW_EVAL_TIMEOUT";
168
+ }
169
+ return false;
170
+ };
171
+ // ---------------------------------------------------------------------------
172
+ // WYW_DEBUG eval dump
173
+ // ---------------------------------------------------------------------------
174
+ const resolveDebugEvalDir = () => {
175
+ const override = process.env.WYW_DUMP_EVALS_DIR;
176
+ if (override) {
177
+ return path.resolve(override);
178
+ }
179
+ const base = process.env.WYW_DUMP_EVALS;
180
+ if (!base) {
181
+ return undefined;
182
+ }
183
+ const ts = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, (c) => c === "T" ? "-" : "");
184
+ const root = base === "1" || base === "true" ? "./tmp" : base;
185
+ return path.resolve(root, `wyw-dump-evals-${ts}`);
186
+ };
187
+ const debugEvalDir = resolveDebugEvalDir();
188
+ let debugEvalDirReady = false;
189
+ const toBase64 = (value) => Buffer.from(value, "utf8").toString("base64");
190
+ const toJsonBase64 = (value) => toBase64(JSON.stringify(value));
191
+ const serializedExportsToDebugValues = (serializedExports) => ({ exports: Object.fromEntries(Object.entries(serializedExports).map(([key, serialized]) => [key, {
192
+ serialized,
193
+ status: "serialized"
194
+ }])) });
195
+ const getDebugValuesStatus = (values) => {
196
+ const statuses = [...Object.values(values?.exports ?? {}), ...Object.values(values?.preval ?? {})].map((value) => value.status);
197
+ if (statuses.length === 0) {
198
+ return "none";
199
+ }
200
+ const hasSerialized = statuses.includes("serialized");
201
+ const hasStringified = statuses.includes("stringified");
202
+ if (hasSerialized && hasStringified) {
203
+ return "mixed";
204
+ }
205
+ return hasStringified ? "stringified" : "serialized";
206
+ };
207
+ const ensureDebugEvalDir = () => {
208
+ if (!debugEvalDir || debugEvalDirReady) {
209
+ return;
210
+ }
211
+ fs.mkdirSync(debugEvalDir, { recursive: true });
212
+ debugEvalDirReady = true;
213
+ };
214
+ let debugEvalSeq = 0;
215
+ const dumpEvalCode = (id, code, only, source, evalSeq) => {
216
+ if (!debugEvalDir) {
217
+ return;
218
+ }
219
+ ensureDebugEvalDir();
220
+ const seq = String(++debugEvalSeq).padStart(5, "0");
221
+ const eSeq = String(evalSeq).padStart(5, "0");
222
+ const relId = path.relative(process.cwd(), stripQueryAndHash(id));
223
+ const safeName = relId.replace(/[/\\]/g, "__").replace(/^__/, "");
224
+ const filename = `seq${seq}_eval${eSeq}_${safeName}.js`;
225
+ const header = [
226
+ `// id: ${id}`,
227
+ `// only: ${JSON.stringify(only)}`,
228
+ `// source: ${source}`,
229
+ `// seq: ${seq}`,
230
+ `// eval: #${eSeq}`,
231
+ ""
232
+ ].join("\n");
233
+ fs.writeFileSync(path.join(debugEvalDir, filename), header + code);
234
+ };
235
+ let debugActionStream = null;
236
+ const debugAction = (event) => {
237
+ if (!debugEvalDir) {
238
+ return;
239
+ }
240
+ ensureDebugEvalDir();
241
+ if (!debugActionStream) {
242
+ debugActionStream = fs.createWriteStream(path.join(debugEvalDir, "actions.jsonl"));
243
+ }
244
+ debugActionStream.write(`${JSON.stringify(event)}\n`);
245
+ };
246
+ const flushDebugStreams = () => {
247
+ debugActionStream?.end();
248
+ debugActionStream = null;
249
+ };
250
+ // ---------------------------------------------------------------------------
251
+ const warnedUnknownImportsByServices = new WeakMap();
252
+ const getWarnedUnknownImports = (services) => {
253
+ const cached = warnedUnknownImportsByServices.get(services);
254
+ if (cached) return cached;
255
+ const created = new Set();
256
+ warnedUnknownImportsByServices.set(services, created);
257
+ return created;
258
+ };
259
+ const warnedSlowImportsByServices = new WeakMap();
260
+ const getWarnedSlowImports = (services) => {
261
+ const cached = warnedSlowImportsByServices.get(services);
262
+ if (cached) return cached;
263
+ const created = new Set();
264
+ warnedSlowImportsByServices.set(services, created);
265
+ return created;
266
+ };
267
+ const isWarningEnabled = (value) => Boolean(value) && value !== "0" && value !== "false";
268
+ const getSlowImportThresholdMs = () => {
269
+ const raw = process.env.WYW_WARN_SLOW_IMPORTS_MS;
270
+ if (!raw) return 50;
271
+ const parsed = Number(raw);
272
+ if (!Number.isFinite(parsed)) return 50;
273
+ return parsed;
274
+ };
275
+ const getEvalOptions = (services) => ({
276
+ ...DEFAULT_EVAL_OPTIONS,
277
+ ...services.options.pluginOptions.eval ?? {}
278
+ });
279
+ const buildRunnerPath = () => {
280
+ const url = new URL("./runner.js", import.meta.url);
281
+ return fileURLToPath(url);
282
+ };
283
+ export const stripEntrypointGlobalsFromRunnerContext = (globals, entrypoint) => {
284
+ const entrypointDir = path.dirname(entrypoint);
285
+ const shouldStripFilename = Object.prototype.hasOwnProperty.call(globals, "__filename") && globals.__filename === entrypoint;
286
+ const shouldStripDirname = Object.prototype.hasOwnProperty.call(globals, "__dirname") && globals.__dirname === entrypointDir;
287
+ if (!shouldStripFilename && !shouldStripDirname) {
288
+ return globals;
289
+ }
290
+ const nextGlobals = { ...globals };
291
+ if (shouldStripFilename) {
292
+ delete nextGlobals.__filename;
293
+ }
294
+ if (shouldStripDirname) {
295
+ delete nextGlobals.__dirname;
296
+ }
297
+ return nextGlobals;
298
+ };
299
+ const getEntrypointResolveRoot = (entrypoint) => {
300
+ let current = entrypoint;
301
+ const seen = new Set();
302
+ while (current.parents.length > 0 && !seen.has(current.name)) {
303
+ seen.add(current.name);
304
+ [current] = current.parents;
305
+ }
306
+ return current.name;
307
+ };
308
+ const buildRunnerInitPayload = (services, entrypoint, featuresOverride) => {
309
+ const evalOptions = getEvalOptions(services);
310
+ const { pluginOptions } = services.options;
311
+ const root = services.options.root ?? process.cwd();
312
+ const { overrideContext, importOverrides, extensions } = pluginOptions;
313
+ const features = featuresOverride ?? pluginOptions.features;
314
+ const baseGlobals = { ...evalOptions.globals ?? {} };
315
+ const withFilename = {
316
+ ...baseGlobals,
317
+ __filename: entrypoint.name,
318
+ __dirname: path.dirname(entrypoint.name)
319
+ };
320
+ const globals = overrideContext ? overrideContext(withFilename, entrypoint.name) : baseGlobals;
321
+ const sanitizedGlobals = stripEntrypointGlobalsFromRunnerContext(globals, entrypoint.name);
322
+ return {
323
+ evalOptions: {
324
+ globals: encodeGlobalsCached(sanitizedGlobals),
325
+ importOverrides,
326
+ errors: evalOptions.errors ?? "strict",
327
+ require: evalOptions.require ?? "warn-and-run",
328
+ root,
329
+ extensions
330
+ },
331
+ features,
332
+ entrypoint: entrypoint.name
333
+ };
334
+ };
335
+ const emitWarning = (services, message) => {
336
+ if (services.emitWarning) {
337
+ services.emitWarning(message);
338
+ return;
339
+ }
340
+ // eslint-disable-next-line no-console
341
+ console.warn(message);
342
+ };
343
+ const emitEvalWarning = (services, warning) => {
344
+ const { onWarn } = getEvalOptions(services);
345
+ onWarn?.(warning);
346
+ emitWarning(services, warning.message);
347
+ };
348
+ const defaultImportLoaders = {
349
+ raw: "raw",
350
+ url: "url"
351
+ };
352
+ const loadByImportLoaders = (services, request, resolved, importer) => {
353
+ const { pluginOptions } = services.options;
354
+ const importLoaders = pluginOptions.importLoaders === undefined ? defaultImportLoaders : {
355
+ ...defaultImportLoaders,
356
+ ...pluginOptions.importLoaders
357
+ };
358
+ const { query, hash } = parseRequest(request);
359
+ if (!query) return {
360
+ handled: false,
361
+ value: undefined
362
+ };
363
+ const params = new URLSearchParams(query);
364
+ const matchedKey = Array.from(params.keys()).find((key) => importLoaders[key] !== undefined && importLoaders[key] !== false);
365
+ if (!matchedKey) return {
366
+ handled: false,
367
+ value: undefined
368
+ };
369
+ const loader = importLoaders[matchedKey];
370
+ const filename = stripQueryAndHash(resolved);
371
+ const importerFilename = stripQueryAndHash(importer);
372
+ const importerDir = path.dirname(importerFilename);
373
+ const toUrl = () => {
374
+ const relative = path.relative(importerDir, filename).replace(/\\/g, path.posix.sep);
375
+ if (relative.startsWith(".") || path.isAbsolute(relative)) {
376
+ return relative;
377
+ }
378
+ return `./${relative}`;
379
+ };
380
+ const readFile = () => fs.readFileSync(filename, "utf-8");
381
+ const context = {
382
+ importer: importerFilename,
383
+ request,
384
+ resolved,
385
+ filename,
386
+ query,
387
+ hash,
388
+ emitWarning: (message) => emitWarning(services, message),
389
+ readFile,
390
+ toUrl
391
+ };
392
+ if (loader === "raw") {
393
+ return {
394
+ handled: true,
395
+ value: context.readFile()
396
+ };
397
+ }
398
+ if (loader === "url") {
399
+ return {
400
+ handled: true,
401
+ value: context.toUrl()
402
+ };
403
+ }
404
+ if (typeof loader === "function") {
405
+ return {
406
+ handled: true,
407
+ value: loader(context)
408
+ };
409
+ }
410
+ return {
411
+ handled: false,
412
+ value: undefined
413
+ };
414
+ };
415
+ const hashContent = (content) => createHash("sha256").update(content).digest("hex");
416
+ const isTypeOnlyImport = (statement) => {
417
+ if (statement.type !== "ImportDeclaration") {
418
+ return false;
419
+ }
420
+ if (statement.importKind === "type") {
421
+ return true;
422
+ }
423
+ if (statement.specifiers.length === 0) {
424
+ return false;
425
+ }
426
+ return statement.specifiers.every((specifier) => specifier.type === "ImportSpecifier" && specifier.importKind === "type");
427
+ };
428
+ const isTypeOnlyExport = (statement) => statement.exportKind === "type";
429
+ const getModuleExportName = (node) => node.type === "Identifier" ? node.name : node.value;
430
+ const getImportSpecifierName = (specifier) => getModuleExportName(specifier.imported);
431
+ const buildDirectBarrelProxy = (services, id, only) => {
432
+ const requested = only.filter((key) => !isEvalOnlyKey(key));
433
+ if (requested.length === 0 || requested.includes("*")) {
434
+ return null;
435
+ }
436
+ const loadedAndParsed = services.loadAndParseFn(services, id, undefined, services.log);
437
+ if (loadedAndParsed.evaluator === "ignored" || loadedAndParsed.ast === undefined) {
438
+ return null;
439
+ }
440
+ if (loadedAndParsed.evaluator === oxcShaker) {
441
+ return buildDirectOxcBarrelProxy(id, loadedAndParsed.code, only);
442
+ }
443
+ const importedBindings = new Map();
444
+ const exportedBindings = new Map();
445
+ const ast = loadedAndParsed.ast;
446
+ for (const statement of ast.program.body) {
447
+ if (statement.type === "ImportDeclaration") {
448
+ if (isTypeOnlyImport(statement)) {
449
+ continue;
450
+ }
451
+ if (statement.specifiers.length === 0) {
452
+ return null;
453
+ }
454
+ for (const specifier of statement.specifiers) {
455
+ if (specifier.type === "ImportSpecifier" && specifier.importKind === "type") {
456
+ continue;
457
+ }
458
+ if (specifier.type === "ImportSpecifier") {
459
+ importedBindings.set(specifier.local.name, {
460
+ kind: "named",
461
+ imported: getImportSpecifierName(specifier),
462
+ source: statement.source.value
463
+ });
464
+ continue;
465
+ }
466
+ if (specifier.type === "ImportDefaultSpecifier") {
467
+ importedBindings.set(specifier.local.name, {
468
+ kind: "named",
469
+ imported: "default",
470
+ source: statement.source.value
471
+ });
472
+ continue;
473
+ }
474
+ importedBindings.set(specifier.local.name, {
475
+ kind: "namespace",
476
+ source: statement.source.value
477
+ });
478
+ }
479
+ continue;
480
+ }
481
+ if (statement.type === "ExportNamedDeclaration") {
482
+ if (isTypeOnlyExport(statement)) {
483
+ continue;
484
+ }
485
+ if (statement.source) {
486
+ for (const specifier of statement.specifiers) {
487
+ if (specifier.type === "ExportSpecifier") {
488
+ if (specifier.exportKind === "type") {
489
+ continue;
490
+ }
491
+ exportedBindings.set(getModuleExportName(specifier.exported), {
492
+ kind: "named",
493
+ imported: getModuleExportName(specifier.local),
494
+ source: statement.source.value
495
+ });
496
+ continue;
497
+ }
498
+ if (specifier.type === "ExportDefaultSpecifier") {
499
+ exportedBindings.set(getModuleExportName(specifier.exported), {
500
+ kind: "named",
501
+ imported: "default",
502
+ source: statement.source.value
503
+ });
504
+ continue;
505
+ }
506
+ if (specifier.type === "ExportNamespaceSpecifier") {
507
+ exportedBindings.set(getModuleExportName(specifier.exported), {
508
+ kind: "namespace",
509
+ source: statement.source.value
510
+ });
511
+ continue;
512
+ }
513
+ return null;
514
+ }
515
+ continue;
516
+ }
517
+ if (statement.declaration) {
518
+ return null;
519
+ }
520
+ for (const specifier of statement.specifiers) {
521
+ if (specifier.type !== "ExportSpecifier" || specifier.exportKind === "type") {
522
+ return null;
523
+ }
524
+ if (specifier.local.type !== "Identifier") {
525
+ return null;
526
+ }
527
+ const binding = importedBindings.get(specifier.local.name);
528
+ if (!binding) {
529
+ return null;
530
+ }
531
+ exportedBindings.set(getModuleExportName(specifier.exported), binding);
532
+ }
533
+ continue;
534
+ }
535
+ if (statement.type === "ExportDefaultDeclaration") {
536
+ if (statement.declaration.type !== "Identifier") {
537
+ return null;
538
+ }
539
+ const binding = importedBindings.get(statement.declaration.name);
540
+ if (!binding || binding.kind !== "named") {
541
+ return null;
542
+ }
543
+ exportedBindings.set("default", binding);
544
+ continue;
545
+ }
546
+ if (statement.type === "EmptyStatement" || statement.type === "TSDeclareFunction" || statement.type === "TSInterfaceDeclaration" || statement.type === "TSTypeAliasDeclaration") {
547
+ continue;
548
+ }
549
+ return null;
550
+ }
551
+ const imports = new Map();
552
+ const lines = [];
553
+ let namespaceIdx = 0;
554
+ const addImport = (source, imported) => {
555
+ if (!imports.has(source)) {
556
+ imports.set(source, []);
557
+ }
558
+ const bucket = imports.get(source);
559
+ if (!bucket.includes(imported)) {
560
+ bucket.push(imported);
561
+ }
562
+ };
563
+ for (const exported of requested) {
564
+ const binding = exportedBindings.get(exported);
565
+ if (!binding) {
566
+ return null;
567
+ }
568
+ if (binding.kind === "namespace") {
569
+ if (exported === "default" || !IDENTIFIER_RE.test(exported)) {
570
+ return null;
571
+ }
572
+ const local = `__wyw_ns_${namespaceIdx++}`;
573
+ lines.push(`import * as ${local} from ${JSON.stringify(binding.source)};`);
574
+ lines.push(`export { ${local} as ${exported} };`);
575
+ addImport(binding.source, "*");
576
+ continue;
577
+ }
578
+ if (binding.imported !== "default" && !IDENTIFIER_RE.test(binding.imported)) {
579
+ return null;
580
+ }
581
+ if (exported !== "default" && !IDENTIFIER_RE.test(exported)) {
582
+ return null;
583
+ }
584
+ const imported = binding.imported === "default" ? "default" : binding.imported;
585
+ const exportClause = exported === "default" ? `${imported} as default` : imported === exported ? imported : `${imported} as ${exported}`;
586
+ lines.push(`export { ${exportClause} } from ${JSON.stringify(binding.source)};`);
587
+ addImport(binding.source, binding.imported);
588
+ }
589
+ if (lines.length === 0) {
590
+ return null;
591
+ }
592
+ return {
593
+ code: `${lines.join("\n")}\n`,
594
+ imports,
595
+ only
596
+ };
597
+ };
598
+ const buildDirectOxcBarrelProxy = (id, code, only) => {
599
+ const requested = only.filter((key) => !isEvalOnlyKey(key));
600
+ const analyzed = analyzeOxcBarrelFile(code, id);
601
+ if (!("reexports" in analyzed)) {
602
+ return null;
603
+ }
604
+ const imports = new Map();
605
+ const lines = [];
606
+ let namespaceIdx = 0;
607
+ const addImport = (source, imported) => {
608
+ if (!imports.has(source)) {
609
+ imports.set(source, []);
610
+ }
611
+ const bucket = imports.get(source);
612
+ if (!bucket.includes(imported)) {
613
+ bucket.push(imported);
614
+ }
615
+ };
616
+ for (const exported of requested) {
617
+ const binding = analyzed.reexports.find((reexport) => reexport.exported === exported);
618
+ if (!binding) {
619
+ return null;
620
+ }
621
+ if (binding.kind === "namespace") {
622
+ if (exported === "default" || !IDENTIFIER_RE.test(exported)) {
623
+ return null;
624
+ }
625
+ const local = `__wyw_ns_${namespaceIdx++}`;
626
+ lines.push(`import * as ${local} from ${JSON.stringify(binding.source)};`);
627
+ lines.push(`export { ${local} as ${exported} };`);
628
+ addImport(binding.source, "*");
629
+ continue;
630
+ }
631
+ if (binding.imported !== "default" && !IDENTIFIER_RE.test(binding.imported)) {
632
+ return null;
633
+ }
634
+ if (exported !== "default" && !IDENTIFIER_RE.test(exported)) {
635
+ return null;
636
+ }
637
+ const imported = binding.imported === "default" ? "default" : binding.imported;
638
+ const exportClause = exported === "default" ? `${imported} as default` : imported === exported ? imported : `${imported} as ${exported}`;
639
+ lines.push(`export { ${exportClause} } from ${JSON.stringify(binding.source)};`);
640
+ addImport(binding.source, binding.imported);
641
+ }
642
+ if (lines.length === 0) {
643
+ return null;
644
+ }
645
+ return {
646
+ code: `${lines.join("\n")}\n`,
647
+ imports,
648
+ only
649
+ };
650
+ };
651
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
652
+ const canonicalizeForHash = (value) => {
653
+ if (Array.isArray(value)) {
654
+ return value.map((item) => canonicalizeForHash(item));
655
+ }
656
+ if (isPlainObject(value)) {
657
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalizeForHash(value[key])]));
658
+ }
659
+ return value;
660
+ };
661
+ // Hash everything in the init payload that affects whether the runner needs
662
+ // a fresh INIT — i.e. everything except `entrypoint` (which only affects
663
+ // __filename/__dirname rebinding, not context reuse). The broker memoizes
664
+ // this per-services so we replace per-evaluate SHA-256 of the full payload
665
+ // with one SHA-256 of the stable bits + a cheap string concat per
666
+ // entrypoint.
667
+ const getStableInitPayloadHash = (payload) => {
668
+ const { entrypoint, ...stable } = payload;
669
+ void entrypoint;
670
+ return createHash("sha256").update(JSON.stringify(canonicalizeForHash(stable))).digest("hex");
671
+ };
672
+ // Memoize encodeGlobals on input reference. The user's globals object is
673
+ // stable across a build, so we can encode it once instead of per evaluate.
674
+ // If the input ref changes, fall through to a fresh encode (and reset the
675
+ // cache).
676
+ const encodeGlobalsMemo = new WeakMap();
677
+ const encodeGlobalsCached = (input) => {
678
+ if (input !== null && typeof input === "object") {
679
+ const obj = input;
680
+ const cached = encodeGlobalsMemo.get(obj);
681
+ if (cached) return cached;
682
+ const encoded = encodeGlobals(input);
683
+ encodeGlobalsMemo.set(obj, encoded);
684
+ return encoded;
685
+ }
686
+ return encodeGlobals(input);
687
+ };
688
+ const formatLoaderResult = (code, loader) => {
689
+ if (loader === "json") {
690
+ return `export default ${JSON.stringify(JSON.parse(code))};`;
691
+ }
692
+ if (loader === "raw" || loader === "text") {
693
+ return `export default ${JSON.stringify(code)};`;
694
+ }
695
+ return code;
696
+ };
697
+ const toSerializedError = (error) => {
698
+ const err = error instanceof Error ? error : new Error(String(error));
699
+ return {
700
+ message: err.message,
701
+ name: err.name,
702
+ stack: err.stack
703
+ };
704
+ };
705
+ export class EvalBroker {
706
+ runner = null;
707
+ runnerInputQueue = null;
708
+ runnerReady = null;
709
+ lastInitKey = null;
710
+ lastHappyDomEnabled = false;
711
+ evalQueue = Promise.resolve();
712
+ pending = new Map();
713
+ nextId = 0;
714
+ resolveCache = new LruCache(RESOLVE_CACHE_SIZE);
715
+ resolveInFlight = new Map();
716
+ loadCache = new LruCache(LOAD_CACHE_SIZE);
717
+ loadInFlight = new Map();
718
+ importsByModule = new Map();
719
+ onlyByModule = new Map();
720
+ // Modules that are part of the current eval session's link graph. Used
721
+ // to scope `mergeKnownDependencyOnly` to entrypoints that share the
722
+ // current runner's VM, instead of unioning across every cached
723
+ // entrypoint project-wide. Cleared whenever the runner is killed or
724
+ // respawned (mirrors lastSentLoadByModule).
725
+ sessionLinkGraph = new Set();
726
+ runtimeDependenciesByModule = new Map();
727
+ emittedDependencies = new Set();
728
+ // Mirrors the runner's view: for each module id, the (hash, mergedOnly) of
729
+ // the most recent LoadResult we shipped with non-empty `code`. Subsequent
730
+ // loads with a matching hash and a subset `only` skip the code transmission
731
+ // (and the eval dump) — the runner's hash-match branch returns its cached
732
+ // SourceTextModule. Cleared whenever the runner is killed/respawned so the
733
+ // mirror cannot drift from the runner's actual moduleCache.
734
+ lastSentLoadByModule = new Map();
735
+ // Batch queue: concurrent evaluate() callers (e.g. parallel webpack-loader
736
+ // transform() invocations) pile up here within one event-loop turn, then a
737
+ // microtask flushes them as a single sequential runner pass. Each call
738
+ // still gets its own resolved Promise; this only collapses the per-call
739
+ // evalQueue chain + state-clear churn.
740
+ pendingEvals = [];
741
+ evalFlushScheduled = false;
742
+ // Cached stable init payload hash. Keyed on the refs that feed the stable
743
+ // bits (pluginOptions.eval and pluginOptions itself). Any reference change
744
+ // invalidates the cache. The full per-entrypoint init key is
745
+ // `${stableHash}::${entrypoint.name}` — cheap string concat instead of
746
+ // re-canonicalizing+stringifying+SHA-256ing the whole payload per call.
747
+ stableInitHashCache = null;
748
+ evalSeq = 0;
749
+ evalFileDebugLines = null;
750
+ happyDomDisabled = false;
751
+ happyDomDisableWarned = false;
752
+ activeResolveRootId = null;
753
+ currentServices;
754
+ constructor(services, asyncResolve) {
755
+ this.services = services;
756
+ this.asyncResolve = asyncResolve;
757
+ this.currentServices = services;
758
+ }
759
+ ensureImportsMapping(id, imports) {
760
+ if (!imports || imports.size === 0) {
761
+ if (!this.importsByModule.has(id)) {
762
+ this.importsByModule.set(id, new Map());
763
+ }
764
+ return;
765
+ }
766
+ const existing = this.importsByModule.get(id);
767
+ if (!existing || existing.size === 0) {
768
+ this.importsByModule.set(id, imports);
769
+ return;
770
+ }
771
+ // Merge: widen each specifier's import list rather than replacing.
772
+ // Different variants of the same module may import different subsets
773
+ // from the same dependency. The widest set must be preserved so that
774
+ // any still-linking variant can resolve all its bindings.
775
+ for (const [specifier, keys] of imports) {
776
+ const existingKeys = existing.get(specifier);
777
+ if (!existingKeys) {
778
+ existing.set(specifier, keys);
779
+ } else {
780
+ existing.set(specifier, mergeOnly(existingKeys, keys));
781
+ }
782
+ }
783
+ }
784
+ getImportOnly(importerId, specifier) {
785
+ const importsOnly = importerId ? this.importsByModule.get(importerId)?.get(specifier) : undefined;
786
+ const importerOnly = importerId ? this.onlyByModule.get(importerId) ?? ["*"] : ["*"];
787
+ return importerOnly.includes("__wywPreval") ? mergeOnly(importsOnly ?? ["*"], ["__wywPreval"]) : importsOnly ?? ["*"];
788
+ }
789
+ getLoadRequestOnly(id, importerId, request) {
790
+ if (!request || !importerId || importerId === id) {
791
+ return null;
792
+ }
793
+ const imports = this.importsByModule.get(importerId);
794
+ if (!imports?.has(request)) {
795
+ return null;
796
+ }
797
+ const { root } = this.services.options;
798
+ const keyInfo = toImportKey({
799
+ source: request,
800
+ resolved: id,
801
+ root
802
+ });
803
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
804
+ let nextOnly = applyImportOverrideToOnly(this.getImportOnly(importerId, request), override);
805
+ const cached = this.services.cache.get("entrypoints", id);
806
+ if (nextOnly.includes("__wywPreval") && cached?.evaluated && !cached.ignored && !hasCachedWywPrevalExport(this.services, id, cached)) {
807
+ nextOnly = nextOnly.filter((item) => item !== "__wywPreval");
808
+ }
809
+ return nextOnly;
810
+ }
811
+ async evaluate(entrypoint, services) {
812
+ return new Promise((resolve, reject) => {
813
+ this.pendingEvals.push({
814
+ entrypoint,
815
+ services,
816
+ resolve,
817
+ reject
818
+ });
819
+ this.scheduleEvalFlush();
820
+ });
821
+ }
822
+ scheduleEvalFlush() {
823
+ if (this.evalFlushScheduled) return;
824
+ this.evalFlushScheduled = true;
825
+ queueMicrotask(() => {
826
+ this.evalFlushScheduled = false;
827
+ if (this.pendingEvals.length === 0) return;
828
+ const batch = this.pendingEvals;
829
+ this.pendingEvals = [];
830
+ this.evalQueue = this.evalQueue.then(() => this.runEvalBatch(batch));
831
+ });
832
+ }
833
+ async runEvalBatch(batch) {
834
+ try {
835
+ await this.ensureRunner();
836
+ } catch (error) {
837
+ for (const member of batch) member.reject(error);
838
+ return;
839
+ }
840
+ for (const member of batch) {
841
+ try {
842
+ const result = await this.runOneEntrypoint(member.entrypoint, member.services);
843
+ member.resolve(result);
844
+ } catch (error) {
845
+ member.reject(error);
846
+ }
847
+ }
848
+ }
849
+ async runOneEntrypoint(entrypoint, services) {
850
+ const activeServices = services ?? this.currentServices;
851
+ const resolveRootId = getEntrypointResolveRoot(entrypoint);
852
+ this.currentServices = activeServices;
853
+ this.activeResolveRootId = resolveRootId;
854
+ this.resetPerEntrypointState(entrypoint);
855
+ this.evalSeq += 1;
856
+ this.evalFileDebugLines = activeServices.eventEmitter.enabled ? [] : null;
857
+ if (debugEvalDir) {
858
+ debugAction({
859
+ type: "eval:start",
860
+ evalSeq: this.evalSeq,
861
+ entrypoint: entrypoint.name,
862
+ ts: performance.now()
863
+ });
864
+ }
865
+ try {
866
+ await this.initRunner(entrypoint);
867
+ const payload = await this.request("EVAL", { id: entrypoint.name }, EVAL_TIMEOUT_MS);
868
+ this.flushEvalFileDebugLines(payload.debugEvalFiles);
869
+ if (debugEvalDir) {
870
+ debugAction({
871
+ type: "eval:finish",
872
+ evalSeq: this.evalSeq,
873
+ entrypoint: entrypoint.name,
874
+ hasValues: Boolean(payload.values),
875
+ ts: performance.now()
876
+ });
877
+ }
878
+ if (payload.modules) {
879
+ this.applyModuleExports(payload.modules);
880
+ }
881
+ if (!payload.values) {
882
+ return {
883
+ values: null,
884
+ dependencies: []
885
+ };
886
+ }
887
+ const values = new Map();
888
+ Object.entries(payload.values).forEach(([key, serialized]) => {
889
+ values.set(key, deserializeValue(serialized));
890
+ });
891
+ return {
892
+ values,
893
+ dependencies: this.collectEntrypointDependencies(entrypoint.name)
894
+ };
895
+ } finally {
896
+ this.evalFileDebugLines = null;
897
+ if (this.activeResolveRootId === resolveRootId) {
898
+ this.activeResolveRootId = null;
899
+ }
900
+ }
901
+ }
902
+ recordEvalFileDebugLine(payload, prepared, shouldShipCode) {
903
+ if (!this.evalFileDebugLines) {
904
+ return;
905
+ }
906
+ if (shouldShipCode && prepared.code) {
907
+ this.evalFileDebugLines.push({
908
+ contentBase64: toBase64(prepared.code),
909
+ evalSeq: this.evalSeq,
910
+ hash: prepared.hash ?? null,
911
+ id: payload.id,
912
+ importer: payload.importerId ?? null,
913
+ only: prepared.only,
914
+ payloadKind: "code",
915
+ request: payload.request ?? null,
916
+ type: "eval-file",
917
+ valueStatus: "none",
918
+ valuesBase64: null
919
+ });
920
+ return;
921
+ }
922
+ if (prepared.exports) {
923
+ const values = serializedExportsToDebugValues(prepared.exports);
924
+ this.evalFileDebugLines.push({
925
+ contentBase64: null,
926
+ evalSeq: this.evalSeq,
927
+ hash: prepared.hash ?? null,
928
+ id: payload.id,
929
+ importer: payload.importerId ?? null,
930
+ only: prepared.only,
931
+ payloadKind: "serialized-exports",
932
+ request: payload.request ?? null,
933
+ type: "eval-file",
934
+ valueStatus: getDebugValuesStatus(values),
935
+ valuesBase64: toJsonBase64(values)
936
+ });
937
+ }
938
+ }
939
+ flushEvalFileDebugLines(valuesById) {
940
+ const lines = this.evalFileDebugLines;
941
+ if (!lines) {
942
+ return;
943
+ }
944
+ for (const line of lines) {
945
+ this.currentServices.eventEmitter.single({
946
+ ...line,
947
+ valueStatus: line.valueStatus === "none" ? getDebugValuesStatus(valuesById?.[line.id]) : line.valueStatus,
948
+ valuesBase64: line.valuesBase64 ?? toJsonBase64(valuesById?.[line.id] ?? {})
949
+ });
950
+ }
951
+ }
952
+ resetPerEntrypointState(entrypoint) {
953
+ this.runtimeDependenciesByModule.clear();
954
+ this.emittedDependencies.clear();
955
+ this.importsByModule.clear();
956
+ this.onlyByModule.clear();
957
+ this.resolveCache.clear();
958
+ this.resolveInFlight.clear();
959
+ this.sessionLinkGraph.clear();
960
+ this.sessionLinkGraph.add(entrypoint.name);
961
+ this.onlyByModule.set(entrypoint.name, ["__wywPreval"]);
962
+ }
963
+ applyModuleExports(modules) {
964
+ Object.entries(modules).forEach(([id, serializedExports]) => {
965
+ if (!serializedExports || Object.keys(serializedExports).length === 0) {
966
+ return;
967
+ }
968
+ const cached = this.services.cache.get("entrypoints", id);
969
+ if (!cached || cached.ignored) {
970
+ return;
971
+ }
972
+ const existingEvaluatedOnly = cached.evaluatedOnly ?? [];
973
+ const target = cached.evaluated || !("createEvaluated" in cached) ? cached : cached.createEvaluated();
974
+ const exportsProxy = target.exports;
975
+ Object.entries(serializedExports).forEach(([key, serialized]) => {
976
+ exportsProxy[key] = deserializeValue(serialized);
977
+ });
978
+ const knownExports = collectKnownExportNames(this.services, id, target);
979
+ const serializedKeys = Object.keys(serializedExports);
980
+ const coversAllKnownExports = Array.isArray(knownExports) && knownExports.filter((key) => !isEvalOnlyKey(key)).length > 0 && knownExports.filter((key) => !isEvalOnlyKey(key)).every((key) => serializedKeys.includes(key));
981
+ const coversModule = coversAllKnownExports;
982
+ const merged = mergeOnly(existingEvaluatedOnly, coversModule ? ["*"] : serializedKeys);
983
+ if (target.evaluatedOnly) {
984
+ target.evaluatedOnly.splice(0, target.evaluatedOnly.length, ...merged);
985
+ }
986
+ this.services.cache.add("entrypoints", id, target);
987
+ });
988
+ }
989
+ dispose() {
990
+ if (this.runner) {
991
+ this.runner.removeAllListeners();
992
+ this.runner.kill();
993
+ this.runner = null;
994
+ this.runnerReady = null;
995
+ this.runnerInputQueue = null;
996
+ }
997
+ this.lastInitKey = null;
998
+ this.lastHappyDomEnabled = false;
999
+ this.lastSentLoadByModule.clear();
1000
+ this.sessionLinkGraph.clear();
1001
+ this.stableInitHashCache = null;
1002
+ flushDebugStreams();
1003
+ }
1004
+ createRunnerProcess() {
1005
+ const runnerPath = buildRunnerPath();
1006
+ const nodeBinary = process.env.WYW_NODE_BINARY || (process.execPath.includes("bun") ? "node" : process.execPath);
1007
+ const runner = spawn(nodeBinary, ["--experimental-vm-modules", runnerPath], {
1008
+ stdio: [
1009
+ "pipe",
1010
+ "pipe",
1011
+ "pipe"
1012
+ ],
1013
+ cwd: this.services.options.root ?? process.cwd(),
1014
+ env: {
1015
+ ...process.env,
1016
+ WYW_EVAL_RUNNER: "1",
1017
+ NODE_NO_WARNINGS: "1"
1018
+ }
1019
+ });
1020
+ runner.stdout.setEncoding("utf8");
1021
+ return runner;
1022
+ }
1023
+ attachRunnerListeners(runner) {
1024
+ runner.stdout.on("data", (chunk) => this.onData(String(chunk)));
1025
+ runner.stderr.on("data", (chunk) => {
1026
+ this.handleRunnerStderr(chunk);
1027
+ });
1028
+ runner.on("exit", (code, signal) => {
1029
+ if (this.runner !== runner) {
1030
+ return;
1031
+ }
1032
+ const reason = `Eval runner exited (${code ?? "null"} / ${signal ?? "null"})`;
1033
+ this.rejectAllPending(new Error(reason));
1034
+ this.runner = null;
1035
+ this.runnerInputQueue = null;
1036
+ this.runnerReady = null;
1037
+ this.lastInitKey = null;
1038
+ this.lastHappyDomEnabled = false;
1039
+ this.lastSentLoadByModule.clear();
1040
+ this.sessionLinkGraph.clear();
1041
+ });
1042
+ }
1043
+ async ensureRunner() {
1044
+ if (this.runnerReady) {
1045
+ await this.runnerReady;
1046
+ return;
1047
+ }
1048
+ this.runner = this.createRunnerProcess();
1049
+ this.runnerInputQueue = createWriteQueue(this.runner.stdin, "eval runner stdin");
1050
+ this.attachRunnerListeners(this.runner);
1051
+ this.runnerReady = Promise.resolve();
1052
+ await this.runnerReady;
1053
+ }
1054
+ async initIsolatedRunner(payload, timeoutMs) {
1055
+ const runner = this.createRunnerProcess();
1056
+ const requestId = `candidate-init-${++this.nextId}`;
1057
+ let buffer = "";
1058
+ return new Promise((resolve, reject) => {
1059
+ let settled = false;
1060
+ const cleanup = () => {
1061
+ runner.stdout.off("data", onStdout);
1062
+ runner.stderr.off("data", onStderr);
1063
+ runner.off("exit", onExit);
1064
+ };
1065
+ const finalizeResolve = (value) => {
1066
+ if (settled) {
1067
+ return;
1068
+ }
1069
+ settled = true;
1070
+ clearTimeout(timeout);
1071
+ cleanup();
1072
+ resolve(value);
1073
+ };
1074
+ const finalizeReject = (value) => {
1075
+ if (settled) {
1076
+ return;
1077
+ }
1078
+ settled = true;
1079
+ clearTimeout(timeout);
1080
+ cleanup();
1081
+ reject(value);
1082
+ };
1083
+ const onStderr = (chunk) => {
1084
+ this.handleRunnerStderr(chunk);
1085
+ };
1086
+ const onExit = (code, signal) => {
1087
+ finalizeReject(new Error(`Eval runner exited during init (${code ?? "null"} / ${signal ?? "null"})`));
1088
+ };
1089
+ const onStdout = (chunk) => {
1090
+ const next = `${buffer}${chunk.toString()}`;
1091
+ const lines = next.split("\n");
1092
+ buffer = lines.pop() ?? "";
1093
+ lines.forEach((line) => {
1094
+ if (!line.trim()) return;
1095
+ let message;
1096
+ try {
1097
+ message = JSON.parse(line);
1098
+ } catch {
1099
+ emitWarning(this.services, `[wyw-eval-runner] Failed to parse message: ${line}`);
1100
+ return;
1101
+ }
1102
+ if (message.type === "WARN") {
1103
+ this.handleWarn(message.payload);
1104
+ return;
1105
+ }
1106
+ if (message.type !== "INIT_ACK" || message.id !== requestId) {
1107
+ return;
1108
+ }
1109
+ if (message.error) {
1110
+ runner.kill();
1111
+ finalizeReject(message.error);
1112
+ return;
1113
+ }
1114
+ finalizeResolve(runner);
1115
+ });
1116
+ };
1117
+ const timeout = setTimeout(() => {
1118
+ const error = new Error(`[wyw-in-js] Eval runner timed out for INIT`);
1119
+ error.code = "WYW_EVAL_TIMEOUT";
1120
+ runner.kill();
1121
+ finalizeReject(error);
1122
+ }, timeoutMs);
1123
+ runner.stdout.on("data", onStdout);
1124
+ runner.stderr.on("data", onStderr);
1125
+ runner.on("exit", onExit);
1126
+ const message = {
1127
+ type: "INIT",
1128
+ id: requestId,
1129
+ payload
1130
+ };
1131
+ writeToStream(runner.stdin, `${JSON.stringify(message)}\n`, "eval runner stdin").catch((error) => {
1132
+ runner.kill();
1133
+ finalizeReject(error instanceof Error ? error : new Error(String(error)));
1134
+ });
1135
+ });
1136
+ }
1137
+ replaceRunner(nextRunner) {
1138
+ if (this.runner) {
1139
+ this.runner.removeAllListeners();
1140
+ this.runner.kill();
1141
+ }
1142
+ this.runner = nextRunner;
1143
+ this.runnerInputQueue = createWriteQueue(nextRunner.stdin, "eval runner stdin");
1144
+ this.attachRunnerListeners(nextRunner);
1145
+ this.runnerReady = Promise.resolve();
1146
+ // New process ⇒ runner's moduleCache/moduleHashes are empty, so our mirror
1147
+ // of "what we already shipped" is stale.
1148
+ this.lastSentLoadByModule.clear();
1149
+ this.sessionLinkGraph.clear();
1150
+ }
1151
+ getStableInitHash(services, features) {
1152
+ const pluginOptionsRef = services.options.pluginOptions;
1153
+ const evalOptionsRef = pluginOptionsRef.eval;
1154
+ const rootRef = services.options.root;
1155
+ if (this.stableInitHashCache !== null && this.stableInitHashCache.pluginOptionsRef === pluginOptionsRef && this.stableInitHashCache.evalOptionsRef === evalOptionsRef && this.stableInitHashCache.featuresRef === features && this.stableInitHashCache.rootRef === rootRef) {
1156
+ return this.stableInitHashCache.hash;
1157
+ }
1158
+ // Build a sample payload (entrypoint name doesn't affect stable hash; we
1159
+ // pass any name and strip it inside getStableInitPayloadHash).
1160
+ // encodeGlobals is memoized so this is the only place it actually runs
1161
+ // per config change.
1162
+ const samplePayload = buildRunnerInitPayload(services, { name: "\0stable-init-sample\0" }, features);
1163
+ samplePayload.reuseModules = true;
1164
+ const hash = getStableInitPayloadHash(samplePayload);
1165
+ this.stableInitHashCache = {
1166
+ pluginOptionsRef,
1167
+ evalOptionsRef,
1168
+ featuresRef: features,
1169
+ rootRef,
1170
+ hash
1171
+ };
1172
+ return hash;
1173
+ }
1174
+ async initRunner(entrypoint) {
1175
+ const features = this.getRunnerFeatures();
1176
+ const stableHash = this.getStableInitHash(this.currentServices, features);
1177
+ const debugEvalFiles = this.currentServices.eventEmitter.enabled;
1178
+ const debugEvalFilesKeyPart = debugEvalFiles ? "1" : "0";
1179
+ const initKey = `${stableHash}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1180
+ if (this.lastInitKey === initKey) {
1181
+ return;
1182
+ }
1183
+ const nextHappyDomEnabled = isFeatureEnabled(features, "happyDOM", entrypoint.name);
1184
+ const payload = buildRunnerInitPayload(this.services, entrypoint, features);
1185
+ payload.reuseModules = true;
1186
+ if (debugEvalFiles) {
1187
+ payload.debugEvalFiles = true;
1188
+ }
1189
+ const timeoutMs = this.getInitTimeoutMs(entrypoint, features);
1190
+ if (this.runner && this.lastInitKey !== null && nextHappyDomEnabled && !this.lastHappyDomEnabled && !this.happyDomDisabled) {
1191
+ try {
1192
+ const nextRunner = await this.initIsolatedRunner(payload, timeoutMs);
1193
+ this.replaceRunner(nextRunner);
1194
+ this.lastInitKey = initKey;
1195
+ this.lastHappyDomEnabled = true;
1196
+ return;
1197
+ } catch (error) {
1198
+ if (isEvalTimeoutError(error)) {
1199
+ this.happyDomDisabled = true;
1200
+ this.warnHappyDomDisabledOnce(timeoutMs);
1201
+ const fallbackFeatures = this.getRunnerFeatures();
1202
+ const fallbackPayload = buildRunnerInitPayload(this.services, entrypoint, fallbackFeatures);
1203
+ fallbackPayload.reuseModules = true;
1204
+ if (debugEvalFiles) {
1205
+ fallbackPayload.debugEvalFiles = true;
1206
+ }
1207
+ await this.request("INIT", fallbackPayload, INIT_TIMEOUT_MS);
1208
+ this.lastInitKey = `${this.getStableInitHash(this.currentServices, fallbackFeatures)}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1209
+ this.lastHappyDomEnabled = false;
1210
+ return;
1211
+ }
1212
+ throw error;
1213
+ }
1214
+ }
1215
+ try {
1216
+ await this.request("INIT", payload, timeoutMs);
1217
+ this.lastInitKey = initKey;
1218
+ this.lastHappyDomEnabled = nextHappyDomEnabled;
1219
+ } catch (error) {
1220
+ if (isEvalTimeoutError(error) && !this.happyDomDisabled && isFeatureEnabled(features, "happyDOM", entrypoint.name)) {
1221
+ this.happyDomDisabled = true;
1222
+ this.warnHappyDomDisabledOnce(timeoutMs);
1223
+ this.dispose();
1224
+ await this.ensureRunner();
1225
+ const fallbackFeatures = this.getRunnerFeatures();
1226
+ const fallbackPayload = buildRunnerInitPayload(this.services, entrypoint, fallbackFeatures);
1227
+ fallbackPayload.reuseModules = true;
1228
+ if (debugEvalFiles) {
1229
+ fallbackPayload.debugEvalFiles = true;
1230
+ }
1231
+ await this.request("INIT", fallbackPayload, INIT_TIMEOUT_MS);
1232
+ this.lastInitKey = `${this.getStableInitHash(this.currentServices, fallbackFeatures)}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1233
+ this.lastHappyDomEnabled = false;
1234
+ return;
1235
+ }
1236
+ throw error;
1237
+ }
1238
+ }
1239
+ getRunnerFeatures() {
1240
+ const base = this.services.options.pluginOptions.features;
1241
+ if (!this.happyDomDisabled) return base;
1242
+ return {
1243
+ ...base,
1244
+ happyDOM: false
1245
+ };
1246
+ }
1247
+ getInitTimeoutMs(entrypoint, features) {
1248
+ if (this.happyDomDisabled || !HAPPYDOM_INIT_TIMEOUT_MS || HAPPYDOM_INIT_TIMEOUT_MS <= 0) {
1249
+ return INIT_TIMEOUT_MS;
1250
+ }
1251
+ if (isFeatureEnabled(features, "happyDOM", entrypoint.name)) {
1252
+ return Math.min(INIT_TIMEOUT_MS, HAPPYDOM_INIT_TIMEOUT_MS);
1253
+ }
1254
+ return INIT_TIMEOUT_MS;
1255
+ }
1256
+ warnHappyDomDisabledOnce(timeoutMs) {
1257
+ if (this.happyDomDisableWarned) return;
1258
+ this.happyDomDisableWarned = true;
1259
+ emitWarning(this.services, [
1260
+ `[wyw-in-js] DOM emulation initialization exceeded ${timeoutMs}ms and will be disabled for this run.`,
1261
+ `WyW will continue without DOM emulation (as if features.happyDOM:false).`,
1262
+ ``,
1263
+ `To silence this warning: set features: { happyDOM: false }.`,
1264
+ `To restore DOM emulation, ensure "happy-dom" can be imported in the build-time runtime.`,
1265
+ `You can tune the timeout with WYW_EVAL_HAPPYDOM_INIT_TIMEOUT_MS.`
1266
+ ].join("\n"));
1267
+ }
1268
+ onData(chunk) {
1269
+ const buffer = this.onData.buffer ?? "";
1270
+ const next = `${buffer}${chunk}`;
1271
+ const lines = next.split("\n");
1272
+ this.onData.buffer = lines.pop() ?? "";
1273
+ lines.forEach((line) => {
1274
+ if (!line.trim()) return;
1275
+ let message;
1276
+ try {
1277
+ message = JSON.parse(line);
1278
+ } catch (error) {
1279
+ emitWarning(this.services, `[wyw-eval-runner] Failed to parse message: ${line}`);
1280
+ return;
1281
+ }
1282
+ this.handleMessage(message);
1283
+ });
1284
+ }
1285
+ handleMessage(message) {
1286
+ switch (message.type) {
1287
+ case "INIT_ACK":
1288
+ if (message.error) {
1289
+ this.rejectPending(message.id, message.error);
1290
+ this.runner?.kill();
1291
+ return;
1292
+ }
1293
+ if (message.modulesReset) {
1294
+ // Runner just cleared its moduleCache during this INIT (full
1295
+ // context rebuild or reuseModules:false). Drop our shipped-code
1296
+ // mirror so handleLoad ships fresh code on the next LOAD.
1297
+ this.lastSentLoadByModule.clear();
1298
+ this.sessionLinkGraph.clear();
1299
+ }
1300
+ this.resolvePending(message.id, {});
1301
+ return;
1302
+ case "EVAL_RESULT": {
1303
+ // Runner reports any ids it dropped from its caches during this
1304
+ // session (e.g. modules whose link errored after a transient missing
1305
+ // import). Mirror those evictions here — otherwise lastSentLoadByModule
1306
+ // would keep claiming the runner has them and handleLoad would ship
1307
+ // empty `code` on the next session, leaving the runner stuck.
1308
+ const evictedIds = message.payload?.evictedIds;
1309
+ if (evictedIds && evictedIds.length > 0) {
1310
+ for (const evictedId of evictedIds) {
1311
+ this.lastSentLoadByModule.delete(evictedId);
1312
+ }
1313
+ }
1314
+ if (message.error) {
1315
+ this.rejectPending(message.id, message.error);
1316
+ return;
1317
+ }
1318
+ this.resolvePending(message.id, message.payload);
1319
+ return;
1320
+ }
1321
+ case "RESOLVE":
1322
+ this.handleResolve(message.id, message.payload).catch((error) => {
1323
+ void this.sendMessage({
1324
+ type: "RESOLVE_RESULT",
1325
+ id: message.id,
1326
+ payload: {
1327
+ resolvedId: null,
1328
+ error: toSerializedError(error)
1329
+ }
1330
+ }).catch((sendError) => this.handleSendMessageError(sendError));
1331
+ });
1332
+ return;
1333
+ case "LOAD":
1334
+ this.handleLoad(message.id, message.payload).catch((error) => {
1335
+ void this.sendMessage({
1336
+ type: "LOAD_RESULT",
1337
+ id: message.id,
1338
+ payload: {
1339
+ id: message.payload.id,
1340
+ error: toSerializedError(error)
1341
+ }
1342
+ }).catch((sendError) => this.handleSendMessageError(sendError));
1343
+ });
1344
+ return;
1345
+ case "WARN":
1346
+ this.handleWarn(message.payload);
1347
+ break;
1348
+ default: break;
1349
+ }
1350
+ }
1351
+ handleRunnerStderr(chunk) {
1352
+ const evalConsole = this.currentServices.options.pluginOptions.evalConsole ?? "pipe";
1353
+ if (evalConsole === "warning") {
1354
+ const text = chunk.toString("utf8");
1355
+ for (const line of text.split("\n")) {
1356
+ const trimmed = line.trim();
1357
+ if (trimmed) {
1358
+ emitWarning(this.currentServices, trimmed);
1359
+ }
1360
+ }
1361
+ } else if (evalConsole === "pipe") {
1362
+ process.stderr.write(chunk);
1363
+ }
1364
+ }
1365
+ handleWarn(warning) {
1366
+ if (warning.importer && warning.specifier) {
1367
+ this.trackRuntimeDependency(warning.importer, warning.specifier);
1368
+ }
1369
+ emitEvalWarning(this.currentServices, warning);
1370
+ }
1371
+ async handleResolve(id, payload) {
1372
+ const result = await this.resolveImport(payload);
1373
+ if (debugEvalDir) {
1374
+ debugAction({
1375
+ type: "resolve",
1376
+ evalSeq: this.evalSeq,
1377
+ specifier: payload.specifier,
1378
+ importer: payload.importerId,
1379
+ kind: payload.kind,
1380
+ resolvedId: result.resolvedId ?? null,
1381
+ external: result.external ?? false,
1382
+ ts: performance.now()
1383
+ });
1384
+ }
1385
+ await this.sendMessage({
1386
+ type: "RESOLVE_RESULT",
1387
+ id,
1388
+ payload: {
1389
+ resolvedId: result.resolvedId,
1390
+ external: result.external
1391
+ }
1392
+ });
1393
+ }
1394
+ normalizeResolvedId(resolvedId, specifier, importerId, kind) {
1395
+ const stripped = stripQueryAndHash(resolvedId);
1396
+ if (!stripped) return resolvedId;
1397
+ if (path.extname(stripped)) return resolvedId;
1398
+ const isFileSpecifier = specifier.startsWith(".") || path.isAbsolute(specifier);
1399
+ if (!isFileSpecifier && !path.isAbsolute(stripped)) {
1400
+ return resolvedId;
1401
+ }
1402
+ let candidate = stripped;
1403
+ if (!path.isAbsolute(candidate)) {
1404
+ if (!importerId) {
1405
+ return resolvedId;
1406
+ }
1407
+ const importerFile = stripQueryAndHash(importerId);
1408
+ candidate = path.resolve(path.dirname(importerFile), candidate);
1409
+ }
1410
+ const suffix = resolvedId.slice(stripped.length);
1411
+ for (const ext of this.services.options.pluginOptions.extensions) {
1412
+ const fileCandidate = `${candidate}${ext}`;
1413
+ if (fs.existsSync(fileCandidate)) {
1414
+ return `${fileCandidate}${suffix}`;
1415
+ }
1416
+ const indexCandidate = path.join(candidate, `index${ext}`);
1417
+ if (fs.existsSync(indexCandidate)) {
1418
+ return `${indexCandidate}${suffix}`;
1419
+ }
1420
+ }
1421
+ if (importerId) {
1422
+ try {
1423
+ const importerFile = stripQueryAndHash(importerId);
1424
+ const { conditionNames, extensions, oxcOptions } = this.services.options.pluginOptions;
1425
+ const resolved = resolveWithNativeResolver({
1426
+ conditionNames,
1427
+ extensions,
1428
+ importer: importerFile,
1429
+ kind,
1430
+ oxcOptions,
1431
+ specifier: resolvedId
1432
+ });
1433
+ if (resolved && resolved !== stripped) {
1434
+ return resolved;
1435
+ }
1436
+ } catch (error) {
1437
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1438
+ // eslint-disable-next-line no-console
1439
+ console.warn("[wyw-eval:resolve:native-normalize-miss]", {
1440
+ specifier,
1441
+ importerId,
1442
+ kind,
1443
+ error
1444
+ });
1445
+ }
1446
+ }
1447
+ }
1448
+ return resolvedId;
1449
+ }
1450
+ async resolveImport({ specifier, importerId, kind }) {
1451
+ return this.services.eventEmitter.action("eval:resolveImport", `${importerId}\0${kind}\0${specifier}`, importerId, () => this.resolveImportImpl({
1452
+ specifier,
1453
+ importerId,
1454
+ kind
1455
+ }));
1456
+ }
1457
+ getResolveStack(importerId) {
1458
+ if (!this.activeResolveRootId || this.activeResolveRootId === importerId) {
1459
+ return [importerId];
1460
+ }
1461
+ return [importerId, this.activeResolveRootId];
1462
+ }
1463
+ async resolveImportImpl({ specifier, importerId, kind }) {
1464
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1465
+ // eslint-disable-next-line no-console
1466
+ console.warn("[wyw-eval:resolve]", {
1467
+ specifier,
1468
+ importerId,
1469
+ kind
1470
+ });
1471
+ }
1472
+ const key = `${kind}:${importerId}:${specifier}`;
1473
+ const evalOptions = getEvalOptions(this.services);
1474
+ const stack = this.getResolveStack(importerId);
1475
+ const importsOnly = this.importsByModule.get(importerId)?.get(specifier);
1476
+ const only = this.getImportOnly(importerId, specifier);
1477
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE && !importsOnly) {
1478
+ // eslint-disable-next-line no-console
1479
+ console.warn("[wyw-eval:resolve:only-miss]", {
1480
+ specifier,
1481
+ importerId,
1482
+ kind
1483
+ });
1484
+ }
1485
+ const strippedSpecifier = stripQueryAndHash(specifier);
1486
+ if (path.isAbsolute(strippedSpecifier)) {
1487
+ const normalized = this.normalizeResolvedId(specifier, specifier, importerId, kind);
1488
+ const overridden = this.applyImportOverrides({
1489
+ source: specifier,
1490
+ resolved: normalized,
1491
+ only,
1492
+ external: false
1493
+ }, importerId, stack);
1494
+ this.resolveCache.set(key, {
1495
+ resolvedId: normalized,
1496
+ external: false
1497
+ });
1498
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1499
+ }
1500
+ const cached = this.resolveCache.get(key);
1501
+ if (cached) {
1502
+ if (!cached.resolvedId) {
1503
+ return this.finalizeResolvedImport(importerId, specifier, {
1504
+ resolvedId: null,
1505
+ only: ["*"]
1506
+ });
1507
+ }
1508
+ const normalized = this.normalizeResolvedId(cached.resolvedId, specifier, importerId, kind);
1509
+ const overridden = this.applyImportOverrides({
1510
+ source: specifier,
1511
+ resolved: normalized,
1512
+ only,
1513
+ external: cached.external
1514
+ }, importerId, stack);
1515
+ if (cached.usedNativeFallback) {
1516
+ this.maybeWarnNativeFallback({
1517
+ importerId,
1518
+ specifier,
1519
+ resolvedId: normalized,
1520
+ kind
1521
+ });
1522
+ }
1523
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1524
+ }
1525
+ const inFlight = this.resolveInFlight.get(key);
1526
+ if (inFlight) {
1527
+ const cachedResult = await inFlight;
1528
+ if (!cachedResult.resolvedId) {
1529
+ return this.finalizeResolvedImport(importerId, specifier, {
1530
+ resolvedId: null,
1531
+ only: ["*"]
1532
+ });
1533
+ }
1534
+ const normalized = this.normalizeResolvedId(cachedResult.resolvedId, specifier, importerId, kind);
1535
+ const overridden = this.applyImportOverrides({
1536
+ source: specifier,
1537
+ resolved: normalized,
1538
+ only,
1539
+ external: cachedResult.external
1540
+ }, importerId, stack);
1541
+ if (cachedResult.usedNativeFallback) {
1542
+ this.maybeWarnNativeFallback({
1543
+ importerId,
1544
+ specifier,
1545
+ resolvedId: normalized,
1546
+ kind
1547
+ });
1548
+ }
1549
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1550
+ }
1551
+ const task = (async () => {
1552
+ if (evalOptions.customResolver) {
1553
+ const customResolved = await evalOptions.customResolver(specifier, importerId, kind);
1554
+ if (customResolved) {
1555
+ const normalized = this.normalizeResolvedId(customResolved.id, specifier, importerId, kind);
1556
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1557
+ // eslint-disable-next-line no-console
1558
+ console.warn("[wyw-eval:resolve:custom]", {
1559
+ specifier,
1560
+ importerId,
1561
+ resolved: customResolved.id,
1562
+ normalized,
1563
+ external: customResolved.external
1564
+ });
1565
+ }
1566
+ return {
1567
+ resolvedId: normalized,
1568
+ external: customResolved.external
1569
+ };
1570
+ }
1571
+ if (evalOptions.resolver === "custom") {
1572
+ return { resolvedId: null };
1573
+ }
1574
+ }
1575
+ if (evalOptions.resolver === "hybrid") {
1576
+ try {
1577
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1578
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1579
+ // eslint-disable-next-line no-console
1580
+ console.warn("[wyw-eval:resolve:native]", {
1581
+ specifier,
1582
+ importerId,
1583
+ resolved: nativeResolved.resolvedId
1584
+ });
1585
+ }
1586
+ return nativeResolved;
1587
+ } catch (error) {
1588
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1589
+ // eslint-disable-next-line no-console
1590
+ console.warn("[wyw-eval:resolve:native-miss]", {
1591
+ specifier,
1592
+ importerId,
1593
+ kind,
1594
+ error
1595
+ });
1596
+ }
1597
+ }
1598
+ }
1599
+ if (evalOptions.resolver === "native") {
1600
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1601
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1602
+ // eslint-disable-next-line no-console
1603
+ console.warn("[wyw-eval:resolve:native]", {
1604
+ specifier,
1605
+ importerId,
1606
+ resolved: nativeResolved.resolvedId
1607
+ });
1608
+ }
1609
+ return nativeResolved;
1610
+ }
1611
+ if (evalOptions.resolver === "bundler" || evalOptions.resolver === "hybrid") {
1612
+ let resolved = null;
1613
+ try {
1614
+ resolved = await this.asyncResolve(specifier, importerId, stack);
1615
+ } catch {
1616
+ resolved = null;
1617
+ }
1618
+ if (resolved) {
1619
+ const normalized = this.normalizeResolvedId(resolved, specifier, importerId, kind);
1620
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1621
+ // eslint-disable-next-line no-console
1622
+ console.warn("[wyw-eval:resolve:async]", {
1623
+ specifier,
1624
+ importerId,
1625
+ resolved,
1626
+ normalized
1627
+ });
1628
+ }
1629
+ return { resolvedId: normalized };
1630
+ }
1631
+ }
1632
+ if (evalOptions.resolver === "bundler" && evalOptions.require !== "off") {
1633
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1634
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1635
+ // eslint-disable-next-line no-console
1636
+ console.warn("[wyw-eval:resolve:native-fallback]", {
1637
+ specifier,
1638
+ importerId,
1639
+ resolved: nativeResolved.resolvedId
1640
+ });
1641
+ }
1642
+ return {
1643
+ ...nativeResolved,
1644
+ usedNativeFallback: true
1645
+ };
1646
+ }
1647
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1648
+ // eslint-disable-next-line no-console
1649
+ console.warn("[wyw-eval:resolve:none]", {
1650
+ specifier,
1651
+ importerId
1652
+ });
1653
+ }
1654
+ return { resolvedId: null };
1655
+ })();
1656
+ this.resolveInFlight.set(key, task);
1657
+ try {
1658
+ const result = await task;
1659
+ this.resolveCache.set(key, result);
1660
+ if (!result.resolvedId) {
1661
+ return this.finalizeResolvedImport(importerId, specifier, {
1662
+ resolvedId: null,
1663
+ only: ["*"]
1664
+ });
1665
+ }
1666
+ const overridden = this.applyImportOverrides({
1667
+ source: specifier,
1668
+ resolved: result.resolvedId,
1669
+ only,
1670
+ external: result.external
1671
+ }, importerId, stack);
1672
+ if (result.usedNativeFallback && result.resolvedId) {
1673
+ this.maybeWarnNativeFallback({
1674
+ importerId,
1675
+ specifier,
1676
+ resolvedId: result.resolvedId,
1677
+ kind
1678
+ });
1679
+ }
1680
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1681
+ } finally {
1682
+ this.resolveInFlight.delete(key);
1683
+ }
1684
+ }
1685
+ finalizeResolvedImport(importerId, specifier, result) {
1686
+ this.trackImporterDependency(importerId, specifier, result.resolvedId, result.only);
1687
+ this.emitDependency(importerId, specifier, result.resolvedId, result.only);
1688
+ return result;
1689
+ }
1690
+ emitDependency(importerId, specifier, resolvedId, only) {
1691
+ if (resolvedId === null) {
1692
+ return;
1693
+ }
1694
+ const key = `${importerId}\0${specifier}\0${resolvedId}\0${only.join(",")}`;
1695
+ if (this.emittedDependencies.has(key)) {
1696
+ return;
1697
+ }
1698
+ this.emittedDependencies.add(key);
1699
+ this.services.eventEmitter.single({
1700
+ type: "dependency",
1701
+ file: importerId,
1702
+ only,
1703
+ imports: [{
1704
+ from: resolvedId,
1705
+ what: only
1706
+ }],
1707
+ fileIdx: getFileIdx(importerId)
1708
+ });
1709
+ }
1710
+ trackRuntimeDependency(importerId, specifier) {
1711
+ if (isBuiltinSpecifier(specifier) || isVirtualSpecifier(specifier)) {
1712
+ return;
1713
+ }
1714
+ const dependencies = this.runtimeDependenciesByModule.get(importerId) ?? new Set();
1715
+ dependencies.add(specifier);
1716
+ this.runtimeDependenciesByModule.set(importerId, dependencies);
1717
+ }
1718
+ trackImporterDependency(importerId, source, resolved, only) {
1719
+ const importerEntrypoint = this.services.cache.get("entrypoints", importerId);
1720
+ const dependencies = importerEntrypoint?.dependencies;
1721
+ if (!dependencies) return;
1722
+ if (resolved === null) {
1723
+ dependencies.delete(source);
1724
+ return;
1725
+ }
1726
+ const cached = dependencies.get(source);
1727
+ dependencies.set(source, {
1728
+ source,
1729
+ resolved,
1730
+ only: cached ? mergeOnly(cached.only, only) : [...only]
1731
+ });
1732
+ }
1733
+ collectEntrypointDependencies(entrypointId) {
1734
+ const collected = new Set(this.runtimeDependenciesByModule.get(entrypointId) ?? []);
1735
+ const cachedEntrypoint = this.services.cache.get("entrypoints", entrypointId);
1736
+ cachedEntrypoint?.dependencies?.forEach((dependency, specifier) => {
1737
+ if (dependency.resolved !== null && !isBuiltinSpecifier(specifier) && !isVirtualSpecifier(specifier)) {
1738
+ collected.add(specifier);
1739
+ }
1740
+ });
1741
+ return Array.from(collected);
1742
+ }
1743
+ applyImportOverrides(resolved, importerId, stack) {
1744
+ const { root } = this.services.options;
1745
+ const keyInfo = toImportKey({
1746
+ source: resolved.source,
1747
+ resolved: resolved.resolved,
1748
+ root
1749
+ });
1750
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
1751
+ let nextResolved = resolved.resolved;
1752
+ let nextExternal = resolved.external;
1753
+ if (override?.mock) {
1754
+ nextResolved = resolveMockSpecifier({
1755
+ mock: override.mock,
1756
+ importer: importerId,
1757
+ root,
1758
+ stack
1759
+ });
1760
+ nextExternal = false;
1761
+ }
1762
+ let nextOnly = applyImportOverrideToOnly(resolved.only, override);
1763
+ const cached = this.services.cache.get("entrypoints", nextResolved);
1764
+ if (nextOnly.includes("__wywPreval") && cached?.evaluated && !cached.ignored && !hasCachedWywPrevalExport(this.services, nextResolved, cached)) {
1765
+ nextOnly = nextOnly.filter((item) => item !== "__wywPreval");
1766
+ }
1767
+ const storedOnly = this.onlyByModule.get(nextResolved);
1768
+ this.onlyByModule.set(nextResolved, storedOnly ? mergeOnly(storedOnly, nextOnly) : nextOnly);
1769
+ return {
1770
+ resolvedId: nextResolved,
1771
+ external: nextExternal,
1772
+ only: nextOnly
1773
+ };
1774
+ }
1775
+ resolveWithNativeFallback(specifier, importerId, kind) {
1776
+ const { conditionNames, extensions, oxcOptions } = this.services.options.pluginOptions;
1777
+ try {
1778
+ const resolved = resolveWithNativeResolver({
1779
+ conditionNames,
1780
+ extensions,
1781
+ importer: importerId,
1782
+ kind,
1783
+ oxcOptions,
1784
+ specifier
1785
+ });
1786
+ return { resolvedId: this.normalizeResolvedId(resolved, specifier, importerId, kind) };
1787
+ } catch (error) {
1788
+ throw new Error([
1789
+ `[wyw-in-js] Native resolver failed during eval.`,
1790
+ ``,
1791
+ `importer: ${importerId}`,
1792
+ `source: ${specifier}`,
1793
+ ``,
1794
+ `error: ${error instanceof Error ? error.message : String(error)}`
1795
+ ].join("\n"));
1796
+ }
1797
+ }
1798
+ maybeWarnNativeFallback({ importerId, specifier, resolvedId, kind }) {
1799
+ const evalOptions = getEvalOptions(this.services);
1800
+ const { root } = this.services.options;
1801
+ const keyInfo = toImportKey({
1802
+ source: specifier,
1803
+ resolved: resolvedId,
1804
+ root
1805
+ });
1806
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
1807
+ if (override && override.unknown === undefined) {
1808
+ return;
1809
+ }
1810
+ const basePolicy = evalOptions.require === "warn-and-run" ? "warn" : "error";
1811
+ let policy = override?.unknown ?? basePolicy;
1812
+ if (evalOptions.require === "off" && policy !== "error") {
1813
+ policy = "error";
1814
+ }
1815
+ if (policy === "error") {
1816
+ throw new Error([
1817
+ `[wyw-in-js] Unknown import reached during eval (native resolver fallback)`,
1818
+ ``,
1819
+ `importer: ${importerId}`,
1820
+ `source: ${specifier}`,
1821
+ `resolved: ${resolvedId}`,
1822
+ ``,
1823
+ `config key: ${keyInfo.key}`,
1824
+ `docs: https://wyw-in-js.dev/troubleshooting`
1825
+ ].filter(Boolean).join("\n"));
1826
+ }
1827
+ const warnedUnknownImports = getWarnedUnknownImports(this.services);
1828
+ if (policy === "warn" && !warnedUnknownImports.has(keyInfo.key)) {
1829
+ warnedUnknownImports.add(keyInfo.key);
1830
+ const warningMessage = [
1831
+ `[wyw-in-js] Unknown import reached during eval (native resolver fallback)`,
1832
+ ``,
1833
+ `importer: ${importerId}`,
1834
+ `source: ${specifier}`,
1835
+ `resolved: ${resolvedId}`,
1836
+ ``,
1837
+ `config key: ${keyInfo.key}`,
1838
+ `hint: add { importOverrides: { ${JSON.stringify(keyInfo.key)}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`,
1839
+ `docs: https://wyw-in-js.dev/troubleshooting`
1840
+ ].filter(Boolean).join("\n");
1841
+ emitEvalWarning(this.currentServices, {
1842
+ code: kind === "require" ? "require-fallback" : "resolve-fallback",
1843
+ message: warningMessage,
1844
+ importer: importerId,
1845
+ specifier,
1846
+ resolved: resolvedId ?? null,
1847
+ callstack: [importerId],
1848
+ hint: `Use importOverrides or eval.require settings to avoid fallback.`
1849
+ });
1850
+ }
1851
+ }
1852
+ async handleLoad(id, payload) {
1853
+ const prepared = await this.loadModule(payload);
1854
+ // Decide once whether the runner already has this exact prepared variant.
1855
+ // The runner caches by id and short-circuits when the LoadResult hash
1856
+ // matches `moduleHashes.get(id)` (runner.js:1834). So when our prior
1857
+ // shipment under the same hash already covered the requested `only`,
1858
+ // re-shipping the code is pure waste — both over IPC and to the dump dir.
1859
+ const previouslySent = prepared.hash ? this.lastSentLoadByModule.get(payload.id) : undefined;
1860
+ // Runner stores by hash but classifies storage by `only` shape: wildcard
1861
+ // (`['*']`) ⇒ moduleCache, anything else ⇒ moduleVariants (runner.js
1862
+ // isFullModuleLoad / runner.js:1832-1842). Reusing across shapes would
1863
+ // hit the wrong map and miss. Require the same shape AND the prepared
1864
+ // `only` to be a subset of what we already shipped — same hash already
1865
+ // implies identical bytes.
1866
+ const sameStorageShape = Boolean(previouslySent && isWildcardOnly(previouslySent.only) === isWildcardOnly(prepared.only));
1867
+ const runnerHasCachedVariant = Boolean(prepared.hash && previouslySent && previouslySent.hash === prepared.hash && sameStorageShape && isSuperSet(previouslySent.only, prepared.only));
1868
+ const shouldShipCode = Boolean(prepared.code && !prepared.exports && !runnerHasCachedVariant);
1869
+ if (debugEvalDir) {
1870
+ if (shouldShipCode) {
1871
+ dumpEvalCode(payload.id, prepared.code, prepared.only, prepared.hash ? `cache:${prepared.hash}` : "fresh", this.evalSeq);
1872
+ }
1873
+ debugAction({
1874
+ type: "load",
1875
+ evalSeq: this.evalSeq,
1876
+ id: payload.id,
1877
+ importer: payload.importerId ?? null,
1878
+ only: prepared.only,
1879
+ hasCode: Boolean(prepared.code),
1880
+ hasExports: Boolean(prepared.exports),
1881
+ hash: prepared.hash ?? null,
1882
+ shipped: shouldShipCode,
1883
+ ts: performance.now()
1884
+ });
1885
+ }
1886
+ this.recordEvalFileDebugLine(payload, prepared, shouldShipCode);
1887
+ await this.sendLoadResult(id, {
1888
+ id: payload.id,
1889
+ code: shouldShipCode ? prepared.code : "",
1890
+ map: null,
1891
+ hash: prepared.hash,
1892
+ only: prepared.only,
1893
+ exports: prepared.exports
1894
+ });
1895
+ if (shouldShipCode && prepared.hash) {
1896
+ const merged = previouslySent?.hash === prepared.hash ? mergeOnly(previouslySent.only, prepared.only) : [...prepared.only];
1897
+ this.lastSentLoadByModule.set(payload.id, {
1898
+ hash: prepared.hash,
1899
+ only: merged
1900
+ });
1901
+ }
1902
+ // Session link graph tracks every module that's been admitted into
1903
+ // the current runner's VM. mergeKnownDependencyOnly uses this to
1904
+ // narrow its consumer-set to entrypoints actually linking against
1905
+ // the same module instance.
1906
+ this.sessionLinkGraph.add(payload.id);
1907
+ if (payload.importerId) {
1908
+ this.sessionLinkGraph.add(payload.importerId);
1909
+ }
1910
+ }
1911
+ async loadModule({ id, importerId, request }) {
1912
+ const actionEntrypoint = importerId ?? id;
1913
+ return this.services.eventEmitter.action("eval:loadModule", `${actionEntrypoint}\0${id}`, actionEntrypoint, () => this.loadModuleImpl({
1914
+ id,
1915
+ importerId,
1916
+ request
1917
+ }));
1918
+ }
1919
+ async loadModuleImpl({ id, importerId, request }) {
1920
+ let cached = this.loadCache.get(id);
1921
+ if (this.services.cache.consumeInvalidation(id)) {
1922
+ this.loadCache.delete(id);
1923
+ cached = undefined;
1924
+ }
1925
+ const loadRequestOnly = this.getLoadRequestOnly(id, importerId, request);
1926
+ if (loadRequestOnly) {
1927
+ const storedOnly = this.onlyByModule.get(id);
1928
+ this.onlyByModule.set(id, storedOnly ? mergeOnly(storedOnly, loadRequestOnly) : loadRequestOnly);
1929
+ this.trackImporterDependency(importerId, request, id, loadRequestOnly);
1930
+ this.emitDependency(importerId, request, id, loadRequestOnly);
1931
+ }
1932
+ let requiredOnly = this.mergeKnownDependencyOnly(id);
1933
+ // Merge the specific exports the importer needs from this module.
1934
+ // The broker's onlyByModule is populated by RESOLVE handlers, but
1935
+ // concurrent message processing can cause a LOAD to arrive before
1936
+ // all pending RESOLVEs are complete. Directly consulting the
1937
+ // importer's imports map ensures we never serve a module with
1938
+ // fewer exports than the requesting importer actually imports.
1939
+ if (importerId && request) {
1940
+ const importerImports = this.importsByModule.get(importerId);
1941
+ if (importerImports) {
1942
+ const specifierOnly = importerImports.get(request);
1943
+ if (specifierOnly && specifierOnly.length > 0) {
1944
+ requiredOnly = requiredOnly.includes("*") ? requiredOnly : mergeOnly(requiredOnly, specifierOnly);
1945
+ }
1946
+ }
1947
+ }
1948
+ const cachedEntrypoint = this.services.cache.get("entrypoints", id);
1949
+ if (cachedEntrypoint && cachedEntrypoint.evaluated && !cachedEntrypoint.ignored && cachedEntrypoint.exports && !requiredOnly.includes("*") && !requiredOnly.some(isEvalOnlyKey) && isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], requiredOnly)) {
1950
+ const serializeOnly = getSerializableStaticImportKeys(this.services, id, cachedEntrypoint, requiredOnly, request, importerId);
1951
+ if (serializeOnly) {
1952
+ const serialized = serializeCachedExports(cachedEntrypoint.exports, serializeOnly);
1953
+ if (serialized) {
1954
+ const hash = hashContent(`exports:${JSON.stringify(serialized)}`);
1955
+ return {
1956
+ code: "",
1957
+ imports: null,
1958
+ only: serializeOnly,
1959
+ hash,
1960
+ exports: serialized
1961
+ };
1962
+ }
1963
+ }
1964
+ }
1965
+ // prepareModuleOnDemand is deterministic given (id, requiredOnly): the
1966
+ // shaker output depends only on source bytes (invalidated via
1967
+ // consumeInvalidation when the file changes) and the requested `only`.
1968
+ // Side effects from __wywPreval happen at runtime in the runner, not at
1969
+ // preparation time — so caching prepared bytes is safe even for self-loads
1970
+ // with __wywPreval. This lets incremental rebuilds reuse the prepared
1971
+ // entrypoint when its source is unchanged; my IPC dedup mirror then
1972
+ // suppresses re-shipping to the runner.
1973
+ if (cached && isPreparedCacheHit(cached, requiredOnly)) {
1974
+ this.ensureImportsMapping(id, cached.imports);
1975
+ return cached;
1976
+ }
1977
+ const inflight = this.loadInFlight.get(id);
1978
+ if (inflight) {
1979
+ const result = await inflight;
1980
+ if (isPreparedCacheHit(result, requiredOnly)) {
1981
+ this.ensureImportsMapping(id, result.imports);
1982
+ return result;
1983
+ }
1984
+ }
1985
+ const slowImportWarningsEnabled = isWarningEnabled(process.env.WYW_WARN_SLOW_IMPORTS);
1986
+ const slowImportThresholdMs = slowImportWarningsEnabled ? getSlowImportThresholdMs() : 0;
1987
+ const warnedSlowImports = slowImportWarningsEnabled ? getWarnedSlowImports(this.services) : null;
1988
+ const shouldWarnSlowImport = Boolean(slowImportWarningsEnabled && warnedSlowImports && slowImportThresholdMs > 0 && request && importerId && importerId !== id);
1989
+ const slowImportStartedAt = shouldWarnSlowImport ? performance.now() : 0;
1990
+ const task = (async () => {
1991
+ const evalOptions = getEvalOptions(this.services);
1992
+ if (evalOptions.customLoader) {
1993
+ const loaded = await evalOptions.customLoader(id);
1994
+ if (loaded) {
1995
+ const code = formatLoaderResult(loaded.code, loaded.loader);
1996
+ return {
1997
+ code,
1998
+ imports: null,
1999
+ only: requiredOnly,
2000
+ hash: hashContent(code)
2001
+ };
2002
+ }
2003
+ }
2004
+ if (request && importerId) {
2005
+ const loaded = loadByImportLoaders(this.services, request, id, importerId);
2006
+ if (loaded.handled) {
2007
+ const code = `export default ${JSON.stringify(loaded.value)};`;
2008
+ return {
2009
+ code,
2010
+ imports: null,
2011
+ only: requiredOnly,
2012
+ hash: hashContent(code)
2013
+ };
2014
+ }
2015
+ }
2016
+ const strippedId = stripQueryAndHash(id);
2017
+ const extension = path.extname(strippedId);
2018
+ if (extension === ".json") {
2019
+ const jsonSource = fs.readFileSync(strippedId, "utf-8");
2020
+ const code = `export default ${JSON.stringify(JSON.parse(jsonSource))};`;
2021
+ return {
2022
+ code,
2023
+ imports: null,
2024
+ only: requiredOnly,
2025
+ hash: hashContent(code)
2026
+ };
2027
+ }
2028
+ if (extension && !this.services.options.pluginOptions.extensions.includes(extension)) {
2029
+ const code = `export default ${JSON.stringify(id)};`;
2030
+ return {
2031
+ code,
2032
+ imports: null,
2033
+ only: requiredOnly,
2034
+ hash: hashContent(code)
2035
+ };
2036
+ }
2037
+ const directBarrelProxy = buildDirectBarrelProxy(this.services, id, requiredOnly);
2038
+ if (directBarrelProxy) {
2039
+ return {
2040
+ ...directBarrelProxy,
2041
+ hash: hashContent(directBarrelProxy.code)
2042
+ };
2043
+ }
2044
+ if (!requiredOnly.includes("*")) {
2045
+ const loadedAndParsed = this.services.loadAndParseFn(this.services, id, undefined, this.services.log);
2046
+ if (loadedAndParsed.evaluator !== "ignored" && loadedAndParsed.evaluator === oxcShaker && isStaticallyEvaluatableModule(loadedAndParsed.code, id)) {
2047
+ requiredOnly = ["*"];
2048
+ this.onlyByModule.set(id, requiredOnly);
2049
+ }
2050
+ }
2051
+ const prepareOnly = requiredOnly.includes("__wywPreval") || !cached ? requiredOnly : mergeOnly(cached.only, requiredOnly);
2052
+ const prepared = prepareModuleOnDemand(this.services, id, prepareOnly);
2053
+ this.ensureImportsMapping(id, prepared.imports);
2054
+ if (shouldWarnSlowImport && request && importerId) {
2055
+ const durationMs = performance.now() - slowImportStartedAt;
2056
+ if (durationMs >= slowImportThresholdMs) {
2057
+ const { root } = this.services.options;
2058
+ const resolvedKey = stripQueryAndHash(id);
2059
+ const { key: importKey } = toImportKey({
2060
+ source: request,
2061
+ resolved: resolvedKey,
2062
+ root
2063
+ });
2064
+ const dedupeKey = `${importerId}::${importKey}`;
2065
+ if (warnedSlowImports && !warnedSlowImports.has(dedupeKey)) {
2066
+ warnedSlowImports.add(dedupeKey);
2067
+ const warning = [
2068
+ `[wyw-in-js] Slow import during prepare stage`,
2069
+ ``,
2070
+ `file: ${importerId}`,
2071
+ `import: ${request}`,
2072
+ `resolved: ${resolvedKey}`,
2073
+ `duration: ${durationMs.toFixed(1)}ms`,
2074
+ ``,
2075
+ `tip: if this import is runtime-only or heavy, mock it during evaluation via importOverrides:`,
2076
+ ` importOverrides: {`,
2077
+ ` '${importKey}': { mock: './path/to/mock' },`,
2078
+ ` }`,
2079
+ ``,
2080
+ `note: importOverrides affects only build-time evaluation (it does not change your bundler runtime behavior)`,
2081
+ ``,
2082
+ `note: configure threshold with WYW_WARN_SLOW_IMPORTS_MS (current: ${slowImportThresholdMs}ms)`
2083
+ ].join("\n");
2084
+ emitWarning(this.currentServices, warning);
2085
+ }
2086
+ }
2087
+ }
2088
+ const hash = hashContent(prepared.code);
2089
+ return {
2090
+ ...prepared,
2091
+ hash
2092
+ };
2093
+ })();
2094
+ this.loadInFlight.set(id, task);
2095
+ try {
2096
+ const result = await task;
2097
+ // Register imports for ALL code paths (barrel proxy, prepareModuleOnDemand,
2098
+ // custom loaders). Without this, the barrel proxy path skips
2099
+ // ensureImportsMapping, so getLoadRequestOnly can't determine what a barrel
2100
+ // module imports from its sub-dependencies.
2101
+ this.ensureImportsMapping(id, result.imports);
2102
+ this.loadCache.set(id, result);
2103
+ return result;
2104
+ } finally {
2105
+ this.loadInFlight.delete(id);
2106
+ }
2107
+ }
2108
+ async sendLoadResult(id, payload) {
2109
+ if (!payload.code) {
2110
+ await this.sendMessage({
2111
+ type: "LOAD_RESULT",
2112
+ id,
2113
+ payload
2114
+ });
2115
+ return;
2116
+ }
2117
+ const message = {
2118
+ type: "LOAD_RESULT",
2119
+ id,
2120
+ payload
2121
+ };
2122
+ const serialized = JSON.stringify(message);
2123
+ if (serialized.length < MAX_MESSAGE_SIZE) {
2124
+ await this.sendMessage(message);
2125
+ return;
2126
+ }
2127
+ const { code } = payload;
2128
+ const chunkCount = Math.ceil(code.length / MAX_CHUNK_SIZE);
2129
+ for (let index = 0; index < chunkCount; index += 1) {
2130
+ const start = index * MAX_CHUNK_SIZE;
2131
+ const end = start + MAX_CHUNK_SIZE;
2132
+ const codeChunk = code.slice(start, end);
2133
+ const chunkPayload = {
2134
+ id: payload.id,
2135
+ codeChunk,
2136
+ chunkIndex: index,
2137
+ chunkCount
2138
+ };
2139
+ if (index === 0) {
2140
+ chunkPayload.map = payload.map;
2141
+ chunkPayload.hash = payload.hash;
2142
+ chunkPayload.only = payload.only;
2143
+ chunkPayload.exports = payload.exports;
2144
+ chunkPayload.error = payload.error;
2145
+ }
2146
+ await this.sendMessage({
2147
+ type: "LOAD_RESULT",
2148
+ id,
2149
+ payload: chunkPayload
2150
+ });
2151
+ }
2152
+ }
2153
+ sendMessage(message) {
2154
+ const payload = `${JSON.stringify(message)}\n`;
2155
+ invariant(payload.length < MAX_MESSAGE_SIZE, "Message too large");
2156
+ if (!this.runnerInputQueue) {
2157
+ return Promise.reject(new Error("Eval runner is not ready"));
2158
+ }
2159
+ return this.runnerInputQueue.write(payload);
2160
+ }
2161
+ handleSendMessageError(error, id) {
2162
+ const serialized = error instanceof Error ? {
2163
+ message: error.message,
2164
+ stack: error.stack
2165
+ } : { message: String(error) };
2166
+ if (id) {
2167
+ this.rejectPending(id, serialized);
2168
+ }
2169
+ this.runner?.kill();
2170
+ }
2171
+ request(type, payload, timeoutMs = REQUEST_TIMEOUT_MS) {
2172
+ this.nextId += 1;
2173
+ const id = `${this.nextId}`;
2174
+ const message = {
2175
+ type,
2176
+ id,
2177
+ payload
2178
+ };
2179
+ return new Promise((resolve, reject) => {
2180
+ const timeout = setTimeout(() => {
2181
+ this.pending.delete(id);
2182
+ this.runner?.kill();
2183
+ const error = new Error(`[wyw-in-js] Eval runner timed out for ${type}`);
2184
+ error.code = "WYW_EVAL_TIMEOUT";
2185
+ reject(error);
2186
+ }, timeoutMs);
2187
+ this.pending.set(id, {
2188
+ resolve,
2189
+ reject,
2190
+ timeout
2191
+ });
2192
+ this.sendMessage(message).catch((error) => this.handleSendMessageError(error, id));
2193
+ });
2194
+ }
2195
+ resolvePending(id, payload) {
2196
+ const pending = this.pending.get(id);
2197
+ if (!pending) return;
2198
+ clearTimeout(pending.timeout);
2199
+ this.pending.delete(id);
2200
+ pending.resolve(payload);
2201
+ }
2202
+ rejectPending(id, error) {
2203
+ const pending = this.pending.get(id);
2204
+ if (!pending) return;
2205
+ clearTimeout(pending.timeout);
2206
+ this.pending.delete(id);
2207
+ const cause = error.cause ? Object.assign(new Error(error.cause.message), { stack: error.cause.stack }) : undefined;
2208
+ const err = cause ? new Error(error.message, { cause }) : new Error(error.message);
2209
+ if (error.stack) {
2210
+ err.stack = error.stack;
2211
+ }
2212
+ pending.reject(err);
2213
+ }
2214
+ rejectAllPending(error) {
2215
+ this.pending.forEach((pending) => {
2216
+ clearTimeout(pending.timeout);
2217
+ pending.reject(error);
2218
+ });
2219
+ this.pending.clear();
2220
+ }
2221
+ mergeKnownDependencyOnly(id) {
2222
+ const storedOnly = this.onlyByModule.get(id) ?? ["*"];
2223
+ if (storedOnly.includes("*")) {
2224
+ return storedOnly;
2225
+ }
2226
+ let mergedOnly = storedOnly;
2227
+ for (const cachedEntrypoint of this.services.cache.entrypoints.values()) {
2228
+ // Scope the union to entrypoints that are part of the CURRENT
2229
+ // session's link graph. Cached entrypoints from prior transforms
2230
+ // already evaluated against their own VMs; their imports must not
2231
+ // widen this load. Empty session graph (initial load) falls back
2232
+ // to project-wide for safety.
2233
+ if (this.sessionLinkGraph.size > 0 && !this.sessionLinkGraph.has(cachedEntrypoint.name)) {
2234
+ continue;
2235
+ }
2236
+ const { dependencies } = cachedEntrypoint;
2237
+ if (!dependencies) {
2238
+ continue;
2239
+ }
2240
+ for (const dependency of dependencies.values()) {
2241
+ if (dependency.resolved !== id || !dependency.only) {
2242
+ continue;
2243
+ }
2244
+ mergedOnly = mergeOnly(mergedOnly, dependency.only);
2245
+ if (mergedOnly.includes("*")) {
2246
+ this.onlyByModule.set(id, mergedOnly);
2247
+ return mergedOnly;
2248
+ }
2249
+ }
2250
+ }
2251
+ this.onlyByModule.set(id, mergedOnly);
2252
+ return mergedOnly;
2253
+ }
2254
+ }
2255
+ const evalBrokers = new WeakMap();
2256
+ export const disposeEvalBroker = (cache) => {
2257
+ const cached = evalBrokers.get(cache);
2258
+ if (!cached) return;
2259
+ cached.broker.dispose();
2260
+ evalBrokers.delete(cache);
2261
+ };
2262
+ export const getEvalBroker = (services, asyncResolve, cacheKey) => {
2263
+ const cached = evalBrokers.get(services.cache);
2264
+ if (cached && cached.key === cacheKey) return cached.broker;
2265
+ if (cached) {
2266
+ disposeEvalBroker(services.cache);
2267
+ }
2268
+ const broker = new EvalBroker(services, asyncResolve);
2269
+ evalBrokers.set(services.cache, {
2270
+ key: cacheKey,
2271
+ broker
2272
+ });
2273
+ return broker;
2274
+ };
2275
+ //# sourceMappingURL=broker.js.map