@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,1878 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ /* global BigInt */
3
+ import fs from "node:fs";
4
+ import { Console } from "node:console";
5
+ import { Writable } from "node:stream";
6
+ import vm from "node:vm";
7
+ import path from "node:path";
8
+ import NativeModule, { createRequire } from "node:module";
9
+ import { pathToFileURL } from "node:url";
10
+ import { Minimatch } from "minimatch";
11
+ class LruCache {
12
+ constructor(maxSize) {
13
+ this.maxSize = Math.max(1, maxSize);
14
+ this.map = new Map();
15
+ }
16
+ get(key) {
17
+ if (!this.map.has(key)) return undefined;
18
+ const value = this.map.get(key);
19
+ this.map.delete(key);
20
+ this.map.set(key, value);
21
+ return value;
22
+ }
23
+ set(key, value) {
24
+ if (this.map.has(key)) {
25
+ this.map.delete(key);
26
+ }
27
+ this.map.set(key, value);
28
+ if (this.map.size > this.maxSize) {
29
+ const firstKey = this.map.keys().next().value;
30
+ if (firstKey !== undefined) {
31
+ this.map.delete(firstKey);
32
+ }
33
+ }
34
+ }
35
+ delete(key) {
36
+ this.map.delete(key);
37
+ }
38
+ clear() {
39
+ this.map.clear();
40
+ }
41
+ }
42
+ const NOOP = () => {};
43
+ // stdout is reserved for the JSON IPC protocol; host-side logs must not share it.
44
+ const prefixStream = (getPrefix) => new Writable({ write(chunk, _enc, cb) {
45
+ const p = getPrefix();
46
+ const s = chunk.toString();
47
+ // Prefix interior newlines but not the trailing one — avoids
48
+ // double-prefix when consecutive writes each start with a prefix.
49
+ const tail = s.endsWith("\n") ? "\n" : "";
50
+ const body = tail ? s.slice(0, -1) : s;
51
+ process.stderr.write(p + body.replaceAll("\n", `\n${p}`) + tail, cb);
52
+ } });
53
+ // require'd modules outside vm use host console — must not write to stdout (IPC channel).
54
+ global.console = new Console({
55
+ stdout: prefixStream(() => "[wyw-runner:host stdout] "),
56
+ stderr: prefixStream(() => "[wyw-runner:host stderr] ")
57
+ });
58
+ const VITE_VIRTUAL_PREFIX = "/@";
59
+ const REACT_REFRESH_VIRTUAL_ID = "/@react-refresh";
60
+ const reactRefreshRuntime = { createSignatureFunctionForTransform: () => () => {} };
61
+ const builtins = {
62
+ assert: true,
63
+ buffer: true,
64
+ child_process: false,
65
+ cluster: false,
66
+ console: true,
67
+ constants: true,
68
+ crypto: true,
69
+ dgram: false,
70
+ dns: false,
71
+ domain: true,
72
+ events: true,
73
+ fs: false,
74
+ http: true,
75
+ https: true,
76
+ module: false,
77
+ net: false,
78
+ os: true,
79
+ path: true,
80
+ punycode: true,
81
+ process: true,
82
+ querystring: true,
83
+ readline: false,
84
+ repl: false,
85
+ stream: true,
86
+ string_decoder: true,
87
+ sys: true,
88
+ timers: true,
89
+ tls: false,
90
+ tty: true,
91
+ url: true,
92
+ util: true,
93
+ vm: true,
94
+ zlib: true
95
+ };
96
+ const RESOLVE_CACHE_SIZE = 5e3;
97
+ const LOAD_CACHE_SIZE = 1e3;
98
+ const MODULE_VARIANT_LIMIT = 8;
99
+ const isBuiltinSpecifier = (specifier) => {
100
+ const normalized = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
101
+ return NativeModule.builtinModules?.includes(normalized) || NativeModule.builtinModules?.includes(`node:${normalized}`);
102
+ };
103
+ const packageTypeCache = new Map();
104
+ const getPackageType = (filename) => {
105
+ let dir = path.dirname(filename);
106
+ while (dir && dir !== path.dirname(dir)) {
107
+ const cached = packageTypeCache.get(dir);
108
+ if (cached === "module" || cached === "commonjs") return cached;
109
+ const pkgPath = path.join(dir, "package.json");
110
+ if (fs.existsSync(pkgPath)) {
111
+ try {
112
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
113
+ const type = pkg?.type === "module" ? "module" : "commonjs";
114
+ packageTypeCache.set(dir, type);
115
+ return type;
116
+ } catch {
117
+ packageTypeCache.set(dir, null);
118
+ return null;
119
+ }
120
+ }
121
+ packageTypeCache.set(dir, null);
122
+ dir = path.dirname(dir);
123
+ }
124
+ return null;
125
+ };
126
+ const shouldPreferImport = (resolvedFile) => {
127
+ if (!resolvedFile) return false;
128
+ if (!path.isAbsolute(resolvedFile)) return false;
129
+ if (resolvedFile.endsWith(".mjs")) return true;
130
+ if (resolvedFile.endsWith(".cjs")) return false;
131
+ if (!resolvedFile.endsWith(".js")) return false;
132
+ return getPackageType(resolvedFile) === "module";
133
+ };
134
+ const isPlainObject = (value) => {
135
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
136
+ return false;
137
+ }
138
+ const prototype = Object.getPrototypeOf(value);
139
+ if (prototype === null || prototype === Object.prototype) {
140
+ return true;
141
+ }
142
+ return Object.getPrototypeOf(prototype) === null;
143
+ };
144
+ const ENCODED_GLOBAL_ENVELOPE_KEY = "__wyw_eval_global";
145
+ const ENCODED_GLOBAL_SIGNATURE = "wyw-eval-global";
146
+ const ENCODED_GLOBAL_VERSION = 1;
147
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/u;
148
+ const ARRAY_INDEX_RE = /^(?:0|[1-9]\d*)$/;
149
+ const IPC_SUPPORTED_VALUE_HINT = "Use importOverrides to mock the import or return plain data: null, booleans, strings, numbers, bigint, undefined, arrays, plain objects, and Error.";
150
+ const getObjectTypeName = (value) => {
151
+ const { constructor } = value ?? {};
152
+ if (constructor && typeof constructor.name === "string" && constructor.name.length > 0) {
153
+ return constructor.name;
154
+ }
155
+ const tag = Object.prototype.toString.call(value);
156
+ return tag.slice(8, -1) || "Object";
157
+ };
158
+ const getBoxedPrimitiveValue = (value) => {
159
+ const tag = Object.prototype.toString.call(value);
160
+ if (tag === "[object String]") {
161
+ return {
162
+ kind: "string",
163
+ value: String(value.valueOf())
164
+ };
165
+ }
166
+ if (tag === "[object Number]") {
167
+ return {
168
+ kind: "number",
169
+ value: Number(value.valueOf())
170
+ };
171
+ }
172
+ if (tag === "[object Boolean]") {
173
+ return {
174
+ kind: "boolean",
175
+ value: Boolean(value.valueOf())
176
+ };
177
+ }
178
+ return null;
179
+ };
180
+ const formatPath = (rootLabel, pathSegments) => pathSegments.reduce((acc, segment) => {
181
+ if (typeof segment === "number") {
182
+ return `${acc}[${segment}]`;
183
+ }
184
+ if (typeof segment === "symbol") {
185
+ return `${acc}[${String(segment)}]`;
186
+ }
187
+ if (IDENTIFIER_RE.test(segment)) {
188
+ return `${acc}.${segment}`;
189
+ }
190
+ return `${acc}[${JSON.stringify(segment)}]`;
191
+ }, rootLabel);
192
+ const formatGlobalsPath = (pathSegments) => formatPath("eval.globals", pathSegments);
193
+ const restoreGlobalFunction = (source, pathSegments) => {
194
+ try {
195
+ // eslint-disable-next-line no-eval
196
+ const restored = eval(`(${source})`);
197
+ if (typeof restored !== "function") {
198
+ throw new TypeError("decoded source is not a function");
199
+ }
200
+ return restored;
201
+ } catch (error) {
202
+ throw new Error(`[wyw-in-js] Failed to restore eval.globals function at ${formatGlobalsPath(pathSegments)}. ` + `Ensure the value is a user-defined function expression/arrow function. ` + `Native and bound functions are not supported. ` + `Original error: ${String(error)}`);
203
+ }
204
+ };
205
+ const isEncodedGlobalPayload = (value) => {
206
+ if (!isPlainObject(value)) {
207
+ return false;
208
+ }
209
+ if (value.signature !== ENCODED_GLOBAL_SIGNATURE || value.version !== ENCODED_GLOBAL_VERSION) {
210
+ return false;
211
+ }
212
+ if (value.kind === "function") {
213
+ return typeof value.source === "string";
214
+ }
215
+ if (value.kind === "symbol") {
216
+ return typeof value.description === "string";
217
+ }
218
+ return false;
219
+ };
220
+ const isEncodedGlobalEnvelope = (value) => {
221
+ if (!isPlainObject(value)) {
222
+ return false;
223
+ }
224
+ const keys = Object.keys(value);
225
+ if (keys.length !== 1 || keys[0] !== ENCODED_GLOBAL_ENVELOPE_KEY) {
226
+ return false;
227
+ }
228
+ return isEncodedGlobalPayload(value[ENCODED_GLOBAL_ENVELOPE_KEY]);
229
+ };
230
+ const canonicalizeForSignature = (value) => {
231
+ if (Array.isArray(value)) {
232
+ return value.map((item) => canonicalizeForSignature(item));
233
+ }
234
+ if (isPlainObject(value)) {
235
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalizeForSignature(value[key])]));
236
+ }
237
+ return value;
238
+ };
239
+ const decodeGlobals = (value, pathSegments = []) => {
240
+ if (Array.isArray(value)) {
241
+ return value.map((item, index) => decodeGlobals(item, [...pathSegments, index]));
242
+ }
243
+ if (isEncodedGlobalEnvelope(value)) {
244
+ const payload = value[ENCODED_GLOBAL_ENVELOPE_KEY];
245
+ if (payload.kind === "function") {
246
+ return restoreGlobalFunction(payload.source, pathSegments);
247
+ }
248
+ return Symbol(payload.description);
249
+ }
250
+ if (isPlainObject(value)) {
251
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeGlobals(item, [...pathSegments, key])]));
252
+ }
253
+ return value;
254
+ };
255
+ const getEnumerableSymbolKeys = (value) => Object.getOwnPropertySymbols(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
256
+ const isLikeError = (value) => typeof value === "object" && value !== null && !isPlainObject(value) && "message" in value && typeof value.message === "string" && ("stack" in value || "name" in value);
257
+ const throwUnsupportedIpcValue = (rootLabel, pathSegments, description) => {
258
+ throw new Error(`[wyw-in-js] ${rootLabel} contains ${description} at ${formatPath(rootLabel, pathSegments)}. ${IPC_SUPPORTED_VALUE_HINT}`);
259
+ };
260
+ const serializeValueAtPath = (value, rootLabel, pathSegments, seen, allowFunctions, allowSymbols) => {
261
+ if (value === null) {
262
+ return { kind: "null" };
263
+ }
264
+ if (value === undefined) return { kind: "undefined" };
265
+ if (typeof value === "boolean") {
266
+ return {
267
+ kind: "boolean",
268
+ value
269
+ };
270
+ }
271
+ if (typeof value === "string") {
272
+ return {
273
+ kind: "string",
274
+ value
275
+ };
276
+ }
277
+ if (typeof value === "number") {
278
+ if (Number.isNaN(value)) return { kind: "nan" };
279
+ if (value === Infinity) return { kind: "infinity" };
280
+ if (value === -Infinity) return { kind: "-infinity" };
281
+ return {
282
+ kind: "number",
283
+ value
284
+ };
285
+ }
286
+ if (typeof value === "bigint") {
287
+ return {
288
+ kind: "bigint",
289
+ value: value.toString()
290
+ };
291
+ }
292
+ if (typeof value === "function") {
293
+ if (allowFunctions) {
294
+ // __wywPreval consumers only rely on function-ness, not implementation
295
+ // identity. Preserve that signal explicitly instead of letting JSON
296
+ // coerce to null/undefined.
297
+ return { kind: "function" };
298
+ }
299
+ throwUnsupportedIpcValue(rootLabel, pathSegments, "an unsupported function");
300
+ }
301
+ if (typeof value === "symbol") {
302
+ if (allowSymbols) {
303
+ return {
304
+ kind: "symbol",
305
+ description: value.description ?? ""
306
+ };
307
+ }
308
+ throwUnsupportedIpcValue(rootLabel, pathSegments, "an unsupported symbol");
309
+ }
310
+ if (typeof value === "object" && value !== null) {
311
+ const boxed = getBoxedPrimitiveValue(value);
312
+ if (boxed) {
313
+ if (boxed.kind === "number") {
314
+ if (Number.isNaN(boxed.value)) return { kind: "nan" };
315
+ if (boxed.value === Infinity) return { kind: "infinity" };
316
+ if (boxed.value === -Infinity) return { kind: "-infinity" };
317
+ }
318
+ return boxed;
319
+ }
320
+ }
321
+ if (isLikeError(value)) {
322
+ return {
323
+ kind: "error",
324
+ error: {
325
+ message: value.message,
326
+ name: value.name,
327
+ stack: value.stack
328
+ }
329
+ };
330
+ }
331
+ const currentPath = formatPath(rootLabel, pathSegments);
332
+ const seenAt = seen.get(value);
333
+ if (seenAt) {
334
+ throw new Error(`[wyw-in-js] ${rootLabel} contains a circular reference at ${currentPath} (from ${seenAt}). ${IPC_SUPPORTED_VALUE_HINT}`);
335
+ }
336
+ if (Array.isArray(value)) {
337
+ const symbolKeys = getEnumerableSymbolKeys(value);
338
+ if (symbolKeys.length > 0) {
339
+ throwUnsupportedIpcValue(rootLabel, [...pathSegments, symbolKeys[0]], "an unsupported symbol-keyed property");
340
+ }
341
+ const extraKey = Object.keys(value).find((key) => !ARRAY_INDEX_RE.test(key) || Number(key) >= value.length);
342
+ if (extraKey !== undefined) {
343
+ throwUnsupportedIpcValue(rootLabel, [...pathSegments, extraKey], "an unsupported non-index array property");
344
+ }
345
+ seen.set(value, currentPath);
346
+ try {
347
+ return {
348
+ kind: "array",
349
+ items: Array.from({ length: value.length }, (_, index) => serializeValueAtPath(value[index], rootLabel, [...pathSegments, index], seen, allowFunctions, allowSymbols))
350
+ };
351
+ } finally {
352
+ seen.delete(value);
353
+ }
354
+ }
355
+ if (!isPlainObject(value)) {
356
+ throwUnsupportedIpcValue(rootLabel, pathSegments, `an unsupported non-plain object (${getObjectTypeName(value)})`);
357
+ }
358
+ const symbolKeys = getEnumerableSymbolKeys(value);
359
+ if (symbolKeys.length > 0) {
360
+ throwUnsupportedIpcValue(rootLabel, [...pathSegments, symbolKeys[0]], "an unsupported symbol-keyed property");
361
+ }
362
+ seen.set(value, currentPath);
363
+ try {
364
+ return {
365
+ kind: "object",
366
+ entries: Object.fromEntries(Object.entries(value).map(([key, item]) => [key, serializeValueAtPath(item, rootLabel, [...pathSegments, key], seen, allowFunctions, allowSymbols)]))
367
+ };
368
+ } finally {
369
+ seen.delete(value);
370
+ }
371
+ };
372
+ const isErrRequireEsm = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ERR_REQUIRE_ESM";
373
+ const serializeValue = (value, options = {}) => serializeValueAtPath(value, options.rootLabel ?? "value", options.path ?? [], new WeakMap(), options.allowFunctions ?? false, options.allowSymbols ?? false);
374
+ const deserializeValue = (value) => {
375
+ switch (value?.kind) {
376
+ case "null": return null;
377
+ case "boolean":
378
+ case "string":
379
+ case "number": return value.value;
380
+ case "undefined": return undefined;
381
+ case "bigint": return BigInt(value.value);
382
+ case "nan": return Number.NaN;
383
+ case "infinity": return Infinity;
384
+ case "-infinity": return -Infinity;
385
+ case "function": return () => {};
386
+ case "symbol":
387
+ // eslint-disable-next-line symbol-description
388
+ return value.description ? Symbol.for(value.description) : Symbol();
389
+ case "error": {
390
+ const error = new Error(value.error?.message ?? "");
391
+ if (value.error?.name) {
392
+ error.name = value.error.name;
393
+ }
394
+ if (value.error?.stack) {
395
+ error.stack = value.error.stack;
396
+ }
397
+ return error;
398
+ }
399
+ case "array": return value.items.map((item) => deserializeValue(item));
400
+ case "object": return Object.fromEntries(Object.entries(value.entries).map(([key, item]) => [key, deserializeValue(item)]));
401
+ case "value":
402
+ default: return value?.value;
403
+ }
404
+ };
405
+ const IMPORT_META_ENV = "__wyw_import_meta_env";
406
+ let importMetaEnvWarned = false;
407
+ let happyDomLoadWarned = false;
408
+ let happyDomUnavailable = false;
409
+ let happyDomImportPromise = null;
410
+ const debugEnabled = Boolean(process.env.WYW_EVAL_RUNNER_DEBUG);
411
+ const debug = (...args) => {
412
+ if (!debugEnabled) return;
413
+ // eslint-disable-next-line no-console
414
+ console.warn("[wyw-eval-runner:debug]", ...args);
415
+ };
416
+ const processShim = {
417
+ nextTick: (fn) => setTimeout(fn, 0),
418
+ platform: "browser",
419
+ arch: "browser",
420
+ execPath: "browser",
421
+ title: "browser",
422
+ pid: 1,
423
+ browser: true,
424
+ argv: [],
425
+ binding() {
426
+ throw new Error("No such module. (Possibly not yet loaded)");
427
+ },
428
+ cwd: () => "/",
429
+ exit: NOOP,
430
+ kill: NOOP,
431
+ chdir: NOOP,
432
+ umask: NOOP,
433
+ dlopen: NOOP,
434
+ uptime: NOOP,
435
+ memoryUsage: NOOP,
436
+ uvCounters: NOOP,
437
+ features: {},
438
+ env: process.env
439
+ };
440
+ const createImportMetaEnvProxy = () => {
441
+ const target = Object.create(null);
442
+ const warnOnce = () => {
443
+ if (importMetaEnvWarned) return;
444
+ importMetaEnvWarned = true;
445
+ // eslint-disable-next-line no-console
446
+ console.warn([
447
+ `[wyw-in-js] import.meta.env was accessed during build-time evaluation, but no env values were provided.`,
448
+ ``,
449
+ `If you're using Vite, make sure @wyw-in-js/vite plugin is enabled (it injects Vite env for evaluation).`,
450
+ `Otherwise provide "__wyw_import_meta_env" via pluginOptions.overrideContext.`
451
+ ].join("\n"));
452
+ };
453
+ return new Proxy(target, {
454
+ get(obj, key) {
455
+ if (typeof key === "symbol") return Reflect.get(obj, key);
456
+ warnOnce();
457
+ return obj[key];
458
+ },
459
+ has(obj, key) {
460
+ if (typeof key === "symbol") return Reflect.has(obj, key);
461
+ warnOnce();
462
+ return Reflect.has(obj, key);
463
+ },
464
+ getOwnPropertyDescriptor(obj, key) {
465
+ return Reflect.getOwnPropertyDescriptor(obj, key);
466
+ },
467
+ ownKeys(obj) {
468
+ return Reflect.ownKeys(obj);
469
+ },
470
+ set(obj, key, value) {
471
+ if (typeof key === "symbol") return Reflect.set(obj, key, value);
472
+ warnOnce();
473
+ return Reflect.set(obj, key, value);
474
+ }
475
+ });
476
+ };
477
+ const HAPPY_DOM_TIMEOUT_MS = Number(process.env.WYW_EVAL_HAPPYDOM_INIT_TIMEOUT_MS ?? process.env.WYW_HAPPYDOM_TIMEOUT_MS ?? 15e3);
478
+ const withTimeout = (promise, timeoutMs, label) => {
479
+ if (!timeoutMs || timeoutMs <= 0) return promise;
480
+ let timeoutId;
481
+ const timeout = new Promise((_, reject) => {
482
+ timeoutId = setTimeout(() => {
483
+ const error = new Error(`[wyw-in-js] Timed out while waiting for ${label}.`);
484
+ error.code = "WYW_HAPPYDOM_TIMEOUT";
485
+ reject(error);
486
+ }, timeoutMs);
487
+ });
488
+ return Promise.race([promise, timeout]).finally(() => {
489
+ if (timeoutId) clearTimeout(timeoutId);
490
+ });
491
+ };
492
+ const loadHappyDom = async () => {
493
+ if (!happyDomImportPromise) {
494
+ happyDomImportPromise = import("happy-dom");
495
+ }
496
+ return happyDomImportPromise;
497
+ };
498
+ const createWindow = async () => {
499
+ if (happyDomUnavailable) return undefined;
500
+ try {
501
+ debug("happyDom:import:start");
502
+ const importStart = Date.now();
503
+ const { Window, GlobalWindow } = await withTimeout(loadHappyDom(), HAPPY_DOM_TIMEOUT_MS, "happy-dom import");
504
+ debug("happyDom:import:done", Date.now() - importStart);
505
+ const HappyWindow = GlobalWindow || Window;
506
+ const windowStart = Date.now();
507
+ const win = new HappyWindow();
508
+ debug("happyDom:window:done", Date.now() - windowStart);
509
+ win.Buffer = Buffer;
510
+ win.Uint8Array = Uint8Array;
511
+ return win;
512
+ } catch (error) {
513
+ happyDomUnavailable = true;
514
+ happyDomImportPromise = null;
515
+ if (!happyDomLoadWarned) {
516
+ happyDomLoadWarned = true;
517
+ // eslint-disable-next-line no-console
518
+ console.warn([
519
+ `[wyw-in-js] DOM emulation is enabled (features.happyDOM), but "happy-dom" could not be loaded in this build-time runtime.`,
520
+ `WyW will continue without DOM emulation (as if features.happyDOM:false).`,
521
+ ``,
522
+ `To silence this warning: set features: { happyDOM: false }.`,
523
+ `To restore DOM emulation, ensure "happy-dom" can be imported in the build-time runtime.`
524
+ ].join("\n"));
525
+ }
526
+ return undefined;
527
+ }
528
+ };
529
+ const setReferencePropertyIfNotPresent = (context, key) => {
530
+ if (context[key] === context) return;
531
+ context[key] = context;
532
+ };
533
+ const createBaseContext = (win, additionalContext) => {
534
+ const baseContext = win ?? {};
535
+ setReferencePropertyIfNotPresent(baseContext, "window");
536
+ setReferencePropertyIfNotPresent(baseContext, "self");
537
+ setReferencePropertyIfNotPresent(baseContext, "top");
538
+ setReferencePropertyIfNotPresent(baseContext, "parent");
539
+ setReferencePropertyIfNotPresent(baseContext, "global");
540
+ setReferencePropertyIfNotPresent(baseContext, "process");
541
+ baseContext.document = win?.document;
542
+ baseContext.process = processShim;
543
+ baseContext.clearImmediate = NOOP;
544
+ baseContext.clearInterval = NOOP;
545
+ baseContext.clearTimeout = NOOP;
546
+ baseContext.setImmediate = NOOP;
547
+ baseContext.requestAnimationFrame = NOOP;
548
+ baseContext.setInterval = NOOP;
549
+ baseContext.setTimeout = NOOP;
550
+ Object.assign(baseContext, additionalContext);
551
+ return baseContext;
552
+ };
553
+ const featureMatchers = new Map();
554
+ const isFeatureEnabled = (features, featureName, filename) => {
555
+ const value = features?.[featureName] ?? false;
556
+ if (typeof value === "boolean") return value;
557
+ if (value === "*" || value === "**/*") return true;
558
+ const array = Array.isArray(value) ? value : [value];
559
+ return array.map((pattern) => {
560
+ let matcher = featureMatchers.get(pattern);
561
+ if (!matcher) {
562
+ matcher = [pattern.startsWith("!"), new Minimatch(pattern)];
563
+ featureMatchers.set(pattern, matcher);
564
+ }
565
+ return [matcher[0], matcher[1].match(filename)];
566
+ }).reduce((acc, [negated, match]) => negated ? acc && match : acc || match, false);
567
+ };
568
+ const createVmContext = async (filename, features, globals) => {
569
+ const isHappyDomEnabled = isFeatureEnabled(features, "happyDOM", filename);
570
+ const win = isHappyDomEnabled ? await createWindow() : undefined;
571
+ const envContext = { [IMPORT_META_ENV]: createImportMetaEnvProxy() };
572
+ const baseContext = createBaseContext(win, {
573
+ __filename: filename,
574
+ ...envContext,
575
+ ...globals
576
+ });
577
+ // Evaluated code must never write to stdout — it is the IPC channel.
578
+ const vmIdent = () => `vm(${path.basename(baseContext.__filename ?? "?")})`;
579
+ baseContext.console = new Console({
580
+ stdout: prefixStream(() => `[wyw-runner:${vmIdent()} stdout] `),
581
+ stderr: prefixStream(() => `[wyw-runner:${vmIdent()} stderr] `)
582
+ });
583
+ const context = vm.createContext(baseContext);
584
+ return {
585
+ context,
586
+ teardown: () => {
587
+ if (win?.happyDOM) {
588
+ win.happyDOM.abort();
589
+ }
590
+ }
591
+ };
592
+ };
593
+ const stripQueryAndHash = (value) => value.split("?")[0]?.split("#")[0] ?? value;
594
+ const normalizeResolvedId = (resolvedId, specifier, importer, extensions) => {
595
+ const stripped = stripQueryAndHash(resolvedId);
596
+ if (!stripped) return resolvedId;
597
+ if (path.extname(stripped)) return resolvedId;
598
+ const isFileSpecifier = specifier.startsWith(".") || path.isAbsolute(specifier);
599
+ if (!isFileSpecifier && !path.isAbsolute(stripped)) {
600
+ return resolvedId;
601
+ }
602
+ let candidate = stripped;
603
+ if (!path.isAbsolute(candidate)) {
604
+ if (!importer) {
605
+ return resolvedId;
606
+ }
607
+ const importerFile = stripQueryAndHash(importer);
608
+ candidate = path.resolve(path.dirname(importerFile), candidate);
609
+ }
610
+ const suffix = resolvedId.slice(stripped.length);
611
+ const resolvedExtensions = extensions ?? [];
612
+ for (let index = 0; index < resolvedExtensions.length; index += 1) {
613
+ const ext = resolvedExtensions[index];
614
+ const fileCandidate = `${candidate}${ext}`;
615
+ if (fs.existsSync(fileCandidate)) {
616
+ return `${fileCandidate}${suffix}`;
617
+ }
618
+ const indexCandidate = path.join(candidate, `index${ext}`);
619
+ if (fs.existsSync(indexCandidate)) {
620
+ return `${indexCandidate}${suffix}`;
621
+ }
622
+ }
623
+ if (importer) {
624
+ try {
625
+ const importerFile = stripQueryAndHash(importer);
626
+ const nodeRequire = createRequire(pathToFileURL(importerFile).href);
627
+ const resolved = nodeRequire.resolve(stripQueryAndHash(specifier));
628
+ if (resolved && resolved !== stripped) {
629
+ return `${resolved}${suffix}`;
630
+ }
631
+ } catch {}
632
+ }
633
+ return resolvedId;
634
+ };
635
+ const isNodeModulesId = (id) => {
636
+ if (!id) return false;
637
+ const normalized = stripQueryAndHash(id).replace(/\\/g, "/");
638
+ return normalized.includes("/node_modules/");
639
+ };
640
+ const mergeOnly = (current, next) => {
641
+ if (!current || current.length === 0) return next ?? [];
642
+ if (!next || next.length === 0) return current;
643
+ if (current.includes("*") || next.includes("*")) {
644
+ return ["*"];
645
+ }
646
+ return Array.from(new Set([...current, ...next]));
647
+ };
648
+ const toCanonicalFileKey = (resolved, root) => {
649
+ const rootDir = root ? path.resolve(root) : process.cwd();
650
+ const normalizedResolved = path.resolve(resolved);
651
+ let relative = path.relative(rootDir, normalizedResolved);
652
+ if (path.sep !== path.posix.sep) {
653
+ relative = relative.split(path.sep).join(path.posix.sep);
654
+ }
655
+ if (!relative.startsWith(".")) {
656
+ relative = `./${relative}`;
657
+ }
658
+ return relative;
659
+ };
660
+ const toImportKey = ({ source, resolved, root }) => {
661
+ const isFileImport = source.startsWith(".") || path.isAbsolute(source);
662
+ if (isFileImport && resolved) {
663
+ return {
664
+ key: toCanonicalFileKey(resolved, root),
665
+ kind: "file"
666
+ };
667
+ }
668
+ return {
669
+ key: source,
670
+ kind: "package"
671
+ };
672
+ };
673
+ const minimatchOptions = {
674
+ dot: true,
675
+ nocomment: true,
676
+ nonegate: true
677
+ };
678
+ const compileImportOverrides = (importOverrides) => {
679
+ const matchers = Object.entries(importOverrides).map(([pattern, override]) => ({
680
+ matcher: new Minimatch(pattern, minimatchOptions),
681
+ override,
682
+ pattern
683
+ })).sort((a, b) => b.pattern.length - a.pattern.length);
684
+ return { matchers };
685
+ };
686
+ const compiledOverridesCache = new WeakMap();
687
+ const getImportOverride = (importOverrides, key) => {
688
+ if (!importOverrides) return undefined;
689
+ const direct = importOverrides[key];
690
+ if (direct) return direct;
691
+ let compiled = compiledOverridesCache.get(importOverrides);
692
+ if (!compiled) {
693
+ compiled = compileImportOverrides(importOverrides);
694
+ compiledOverridesCache.set(importOverrides, compiled);
695
+ }
696
+ return compiled.matchers.find(({ matcher }) => matcher.match(key))?.override;
697
+ };
698
+ const resolveMockSpecifier = ({ mock, importer, root }) => {
699
+ const specifier = mock.startsWith(".") && root ? path.resolve(root, mock) : mock;
700
+ const nodeRequire = createRequire(pathToFileURL(importer).href);
701
+ return nodeRequire.resolve(specifier);
702
+ };
703
+ const state = {
704
+ context: null,
705
+ teardown: null,
706
+ happyDomEnabled: null,
707
+ globalsSignature: null,
708
+ evalOptions: {
709
+ errors: "strict",
710
+ require: "warn-and-run",
711
+ globals: {},
712
+ importOverrides: undefined,
713
+ root: undefined,
714
+ extensions: []
715
+ },
716
+ features: {},
717
+ debugEvalFiles: false,
718
+ entrypoint: "eval-runner"
719
+ };
720
+ const moduleCache = new LruCache(LOAD_CACHE_SIZE);
721
+ const moduleHashes = new Map();
722
+ const moduleData = new Map();
723
+ const moduleOnly = new Map();
724
+ const moduleVariants = new Map();
725
+ const moduleLastVariant = new Map();
726
+ const linkPromises = new Map();
727
+ const loadInFlight = new Map();
728
+ const externalInFlight = new Map();
729
+ const resolveCache = new LruCache(RESOLVE_CACHE_SIZE);
730
+ const resolveInFlight = new Map();
731
+ const pending = new Map();
732
+ const loadResultChunks = new Map();
733
+ // Ids evicted during the in-flight EVAL session via resetSingleModuleState.
734
+ // Surfaced in EVAL_RESULT so the broker can drop matching entries from its
735
+ // "what runner has" mirror (lastSentLoadByModule) — otherwise the broker would
736
+ // keep short-circuiting subsequent LOADs with empty `code` and the runner
737
+ // would have no way to obtain fresh source.
738
+ const evictedThisSession = new Set();
739
+ let nextId = 0;
740
+ const stdoutWriteQueue = [];
741
+ let stdoutWriteInFlight = false;
742
+ let stdoutWriteFailed = null;
743
+ let shutdownRequested = false;
744
+ let shutdownFinished = false;
745
+ // Tracks the SourceTextModule identifier (versioned with hash) that was last
746
+ // included in an EVAL_RESULT for each id. Reused module variants don't need
747
+ // re-serialization across eval sessions — same variant = same namespace =
748
+ // same exports the broker already has cached.
749
+ const sentNamespaceIdentifiers = new Map();
750
+ const resetModuleState = () => {
751
+ moduleCache.clear();
752
+ moduleHashes.clear();
753
+ moduleData.clear();
754
+ moduleOnly.clear();
755
+ moduleVariants.clear();
756
+ moduleLastVariant.clear();
757
+ linkPromises.clear();
758
+ loadInFlight.clear();
759
+ externalInFlight.clear();
760
+ resolveInFlight.clear();
761
+ resolveCache.clear();
762
+ sentNamespaceIdentifiers.clear();
763
+ };
764
+ const resetSingleModuleState = (id, cachedModule = moduleCache.get(id)) => {
765
+ if (cachedModule) {
766
+ linkPromises.delete(cachedModule);
767
+ }
768
+ const variants = moduleVariants.get(id);
769
+ if (variants) {
770
+ variants.forEach((variant) => linkPromises.delete(variant));
771
+ }
772
+ moduleCache.delete(id);
773
+ moduleHashes.delete(id);
774
+ moduleData.delete(id);
775
+ moduleVariants.delete(id);
776
+ moduleLastVariant.delete(id);
777
+ sentNamespaceIdentifiers.delete(id);
778
+ };
779
+ // Stronger reset for error paths: clears moduleOnly too and records the id so
780
+ // the broker can drop its lastSentLoadByModule entry. Used when a module's
781
+ // SourceTextModule has reached an unrecoverable state (e.g. link errored
782
+ // against a transient missing import) and should not be reused.
783
+ const evictPoisonedModule = (id) => {
784
+ resetSingleModuleState(id);
785
+ moduleOnly.delete(id);
786
+ evictedThisSession.add(id);
787
+ };
788
+ const isFullModuleLoad = (loaded) => !loaded.only || loaded.only.length === 1 && loaded.only[0] === "*";
789
+ const getModuleVariant = (id, hash) => moduleVariants.get(id)?.get(hash);
790
+ const setModuleVariant = (id, hash, module) => {
791
+ let variants = moduleVariants.get(id);
792
+ if (!variants) {
793
+ variants = new Map();
794
+ moduleVariants.set(id, variants);
795
+ }
796
+ variants.set(hash, module);
797
+ moduleLastVariant.set(id, module);
798
+ if (variants.size > MODULE_VARIANT_LIMIT) {
799
+ const oldestHash = variants.keys().next().value;
800
+ if (oldestHash !== undefined) {
801
+ const oldest = variants.get(oldestHash);
802
+ if (oldest) {
803
+ linkPromises.delete(oldest);
804
+ }
805
+ variants.delete(oldestHash);
806
+ }
807
+ }
808
+ };
809
+ const toSourceModuleId = (id) => stripQueryAndHash(String(id));
810
+ const toVersionedModuleIdentifier = (id, hash) => {
811
+ if (!hash) return id;
812
+ const separator = id.includes("?") ? "&" : "?";
813
+ return `${id}${separator}wyw-hash=${hash}`;
814
+ };
815
+ const resetEvaluationState = () => {
816
+ if (state.teardown) {
817
+ state.teardown();
818
+ }
819
+ state.context = null;
820
+ state.teardown = null;
821
+ state.happyDomEnabled = null;
822
+ state.globalsSignature = null;
823
+ resetModuleState();
824
+ };
825
+ const normalizeWriteError = (label, error) => {
826
+ if (error instanceof Error) {
827
+ return error;
828
+ }
829
+ return new Error(`[wyw-in-js] Failed to write to ${label}: ${String(error)}`);
830
+ };
831
+ const keepAlive = setInterval(() => {}, 6e4);
832
+ const finishShutdown = (exitCode = 0) => {
833
+ if (shutdownFinished) {
834
+ return;
835
+ }
836
+ shutdownFinished = true;
837
+ clearInterval(keepAlive);
838
+ if (state.teardown) {
839
+ state.teardown();
840
+ }
841
+ process.exit(exitCode);
842
+ };
843
+ const flushStdoutWriteQueue = () => {
844
+ if (stdoutWriteInFlight || stdoutWriteFailed) {
845
+ return;
846
+ }
847
+ const next = stdoutWriteQueue.shift();
848
+ if (!next) {
849
+ if (shutdownRequested) {
850
+ finishShutdown(0);
851
+ }
852
+ return;
853
+ }
854
+ stdoutWriteInFlight = true;
855
+ let settled = false;
856
+ let writeCompleted = false;
857
+ let drainCompleted = true;
858
+ let onClose;
859
+ let onDrain;
860
+ let onError;
861
+ const cleanup = () => {
862
+ process.stdout.off("close", onClose);
863
+ process.stdout.off("drain", onDrain);
864
+ process.stdout.off("error", onError);
865
+ };
866
+ const finish = (error) => {
867
+ if (settled) {
868
+ return;
869
+ }
870
+ if (error) {
871
+ settled = true;
872
+ stdoutWriteInFlight = false;
873
+ cleanup();
874
+ stdoutWriteFailed = normalizeWriteError("eval runner stdout", error);
875
+ next.reject(stdoutWriteFailed);
876
+ while (stdoutWriteQueue.length > 0) {
877
+ stdoutWriteQueue.shift().reject(stdoutWriteFailed);
878
+ }
879
+ process.stderr.write(`[wyw-eval-runner] ${stdoutWriteFailed.message}\n`);
880
+ finishShutdown(1);
881
+ return;
882
+ }
883
+ if (!writeCompleted || !drainCompleted) {
884
+ return;
885
+ }
886
+ settled = true;
887
+ stdoutWriteInFlight = false;
888
+ cleanup();
889
+ next.resolve();
890
+ flushStdoutWriteQueue();
891
+ };
892
+ onClose = () => {
893
+ finish(new Error("eval runner stdout closed before pending write completed"));
894
+ };
895
+ onDrain = () => {
896
+ drainCompleted = true;
897
+ finish();
898
+ };
899
+ onError = (error) => {
900
+ finish(error);
901
+ };
902
+ process.stdout.once("close", onClose);
903
+ process.stdout.once("error", onError);
904
+ const needsDrain = !process.stdout.write(next.chunk, (error) => {
905
+ writeCompleted = true;
906
+ if (error) {
907
+ finish(error);
908
+ return;
909
+ }
910
+ finish();
911
+ });
912
+ if (needsDrain) {
913
+ drainCompleted = false;
914
+ process.stdout.once("drain", onDrain);
915
+ }
916
+ };
917
+ const queueStdoutWrite = (chunk) => new Promise((resolve, reject) => {
918
+ if (stdoutWriteFailed) {
919
+ reject(stdoutWriteFailed);
920
+ return;
921
+ }
922
+ stdoutWriteQueue.push({
923
+ chunk,
924
+ resolve,
925
+ reject
926
+ });
927
+ flushStdoutWriteQueue();
928
+ });
929
+ const sendMessage = (message) => {
930
+ queueStdoutWrite(`${JSON.stringify(message)}\n`).catch(() => {});
931
+ };
932
+ const shutdown = () => {
933
+ shutdownRequested = true;
934
+ if (!stdoutWriteInFlight && stdoutWriteQueue.length === 0) {
935
+ finishShutdown(0);
936
+ }
937
+ };
938
+ const sendWarn = (warning) => {
939
+ sendMessage({
940
+ type: "WARN",
941
+ payload: warning
942
+ });
943
+ };
944
+ const reviveSerializedError = (error) => {
945
+ if (error instanceof Error) {
946
+ return error;
947
+ }
948
+ const revived = new Error(error?.message ?? String(error));
949
+ if (error?.name) {
950
+ revived.name = error.name;
951
+ }
952
+ if (error?.stack) {
953
+ revived.stack = error.stack;
954
+ }
955
+ if (error?.cause) {
956
+ revived.cause = reviveSerializedError(error.cause);
957
+ }
958
+ return revived;
959
+ };
960
+ const serializeError = (error) => {
961
+ const result = {
962
+ message: error?.message ?? String(error),
963
+ stack: error?.stack
964
+ };
965
+ if (error?.cause instanceof Error) {
966
+ result.cause = serializeError(error.cause);
967
+ }
968
+ return result;
969
+ };
970
+ const request = (type, payload) => {
971
+ nextId += 1;
972
+ const id = `${nextId}`;
973
+ sendMessage({
974
+ type,
975
+ id,
976
+ payload
977
+ });
978
+ return new Promise((resolve, reject) => {
979
+ pending.set(id, {
980
+ resolve,
981
+ reject
982
+ });
983
+ });
984
+ };
985
+ const resolvePending = (id, payload) => {
986
+ const pendingItem = pending.get(id);
987
+ if (!pendingItem) return;
988
+ pending.delete(id);
989
+ pendingItem.resolve(payload);
990
+ };
991
+ const handleLoadResult = (id, payload) => {
992
+ if (!payload || typeof payload.codeChunk !== "string" || typeof payload.chunkIndex !== "number" || typeof payload.chunkCount !== "number") {
993
+ resolvePending(id, payload);
994
+ return;
995
+ }
996
+ let entry = loadResultChunks.get(id);
997
+ if (!entry) {
998
+ entry = {
999
+ chunks: new Array(payload.chunkCount),
1000
+ received: 0,
1001
+ meta: null
1002
+ };
1003
+ loadResultChunks.set(id, entry);
1004
+ }
1005
+ if (!entry.chunks[payload.chunkIndex]) {
1006
+ entry.received += 1;
1007
+ }
1008
+ entry.chunks[payload.chunkIndex] = payload.codeChunk;
1009
+ if (payload.chunkIndex === 0) {
1010
+ const { codeChunk, chunkIndex, chunkCount, ...meta } = payload;
1011
+ entry.meta = meta;
1012
+ }
1013
+ if (entry.received >= payload.chunkCount) {
1014
+ const code = entry.chunks.join("");
1015
+ const finalPayload = {
1016
+ ...entry.meta ?? {},
1017
+ code
1018
+ };
1019
+ loadResultChunks.delete(id);
1020
+ resolvePending(id, finalPayload);
1021
+ }
1022
+ };
1023
+ const buildPreamble = (id) => [
1024
+ `const __wyw_module = __wyw_getModule(${JSON.stringify(id)});`,
1025
+ `let exports = __wyw_module.exports;`,
1026
+ `const module = __wyw_module.module;`,
1027
+ `const require = __wyw_module.require;`,
1028
+ `const __filename = __wyw_module.filename;`,
1029
+ `const __dirname = __wyw_module.dirname;`,
1030
+ `const __wyw_dynamic_import = __wyw_module.dynamicImport;`,
1031
+ ``
1032
+ ].join("\n");
1033
+ const getImporterPackage = (importer) => {
1034
+ const normalized = importer.replace(/\\/g, "/");
1035
+ const marker = "/node_modules/";
1036
+ const idx = normalized.lastIndexOf(marker);
1037
+ if (idx === -1) return path.basename(importer);
1038
+ const rest = normalized.slice(idx + marker.length);
1039
+ if (rest.startsWith("@")) {
1040
+ const [scope, name] = rest.split("/").slice(0, 2);
1041
+ return `${scope}/${name}`;
1042
+ }
1043
+ return rest.split("/")[0];
1044
+ };
1045
+ const warnedRequires = new Set();
1046
+ const createRequireFn = (importer) => {
1047
+ const importerFile = stripQueryAndHash(importer);
1048
+ const nodeRequire = createRequire(pathToFileURL(importerFile).href);
1049
+ return (specifier, nonLiteralOrResolved, maybeResolved) => {
1050
+ const hasNonLiteralFlag = typeof nonLiteralOrResolved === "boolean";
1051
+ const nonLiteral = hasNonLiteralFlag ? nonLiteralOrResolved : false;
1052
+ const resolvedOverride = hasNonLiteralFlag ? maybeResolved : nonLiteralOrResolved;
1053
+ const hasResolvedOverride = typeof resolvedOverride === "string" && resolvedOverride.length > 0;
1054
+ if (state.evalOptions.require === "off") {
1055
+ throw new Error(`[wyw-in-js] require() fallback is disabled by eval.require: 'off'.`);
1056
+ }
1057
+ if (nonLiteral || typeof specifier !== "string") {
1058
+ if (state.evalOptions.errors === "strict") {
1059
+ throw new Error(`[wyw-in-js] Non-literal require() is not supported during eval.\n` + `importer: ${importerFile}\n` + `hint: make it a string literal or mock the import via importOverrides.`);
1060
+ }
1061
+ sendWarn({
1062
+ code: "require-error",
1063
+ message: "[wyw-in-js] Non-literal require() reached during eval (eval.errors: \"loose\").",
1064
+ importer: importerFile
1065
+ });
1066
+ return {};
1067
+ }
1068
+ if (specifier === REACT_REFRESH_VIRTUAL_ID) {
1069
+ return reactRefreshRuntime;
1070
+ }
1071
+ if (specifier.startsWith(VITE_VIRTUAL_PREFIX) || specifier.startsWith("virtual:")) {
1072
+ return {};
1073
+ }
1074
+ const normalized = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
1075
+ if (NativeModule.builtinModules?.includes(normalized) || NativeModule.builtinModules?.includes(`node:${normalized}`)) {
1076
+ if (normalized in builtins) {
1077
+ if (builtins[normalized]) {
1078
+ return nodeRequire(normalized);
1079
+ }
1080
+ return null;
1081
+ }
1082
+ }
1083
+ const extensions = NativeModule._extensions;
1084
+ const added = [];
1085
+ try {
1086
+ state.evalOptions.extensions?.forEach((ext) => {
1087
+ if (ext === ".cjs" || ext === ".mjs") return;
1088
+ if (ext in extensions) return;
1089
+ extensions[ext] = NOOP;
1090
+ added.push(ext);
1091
+ });
1092
+ let resolved = hasResolvedOverride ? stripQueryAndHash(resolvedOverride) : nodeRequire.resolve(stripQueryAndHash(specifier));
1093
+ const isFileSpecifier = specifier.startsWith(".") || path.isAbsolute(specifier);
1094
+ if (isFileSpecifier && path.extname(specifier) === "" && resolved.endsWith(".cjs")) {
1095
+ const candidate = `${resolved.slice(0, -4)}.js`;
1096
+ if (fs.existsSync(candidate)) {
1097
+ resolved = candidate;
1098
+ }
1099
+ }
1100
+ const keyInfo = toImportKey({
1101
+ source: specifier,
1102
+ resolved,
1103
+ root: state.evalOptions.root
1104
+ });
1105
+ const override = getImportOverride(state.evalOptions.importOverrides, keyInfo.key);
1106
+ let finalResolved = resolved;
1107
+ if (override?.mock) {
1108
+ finalResolved = resolveMockSpecifier({
1109
+ mock: override.mock,
1110
+ importer: importerFile,
1111
+ root: state.evalOptions.root,
1112
+ stack: [importerFile]
1113
+ });
1114
+ }
1115
+ const basePolicy = state.evalOptions.require === "warn-and-run" ? "warn" : "error";
1116
+ let policy = override?.unknown ?? (override ? "allow" : basePolicy);
1117
+ if (state.evalOptions.require === "off" && policy !== "error") {
1118
+ policy = "error";
1119
+ }
1120
+ if (policy === "error") {
1121
+ throw new Error([
1122
+ `[wyw-in-js] require() fallback reached during eval but eval.require='error'.`,
1123
+ ``,
1124
+ `importer: ${importerFile}`,
1125
+ `source: ${specifier}`,
1126
+ `hint: add importOverrides or set eval.require to "warn-and-run".`
1127
+ ].join("\n"));
1128
+ }
1129
+ if (policy === "warn") {
1130
+ const key = `${specifier}::${getImporterPackage(importerFile)}`;
1131
+ if (!warnedRequires.has(key)) {
1132
+ warnedRequires.add(key);
1133
+ sendWarn({
1134
+ code: "require-fallback",
1135
+ message: [
1136
+ `[wyw-in-js] Runtime require() fallback during eval`,
1137
+ ``,
1138
+ `importer: ${importerFile}`,
1139
+ `source: ${specifier}`,
1140
+ `resolved: ${resolved}`,
1141
+ override?.mock ? `mock: ${override.mock} -> ${finalResolved}` : ``,
1142
+ ``,
1143
+ `hint: use importOverrides to mock runtime-only deps and avoid eval-time requires.`
1144
+ ].filter(Boolean).join("\n"),
1145
+ importer: importerFile,
1146
+ specifier,
1147
+ resolved
1148
+ });
1149
+ }
1150
+ }
1151
+ return nodeRequire(finalResolved);
1152
+ } finally {
1153
+ added.forEach((ext) => delete extensions[ext]);
1154
+ }
1155
+ };
1156
+ };
1157
+ function createSyntheticModule(id, exportsValue, cache = true) {
1158
+ const exportNames = new Set(Object.keys(exportsValue));
1159
+ if (!exportNames.has("default")) {
1160
+ exportNames.add("default");
1161
+ }
1162
+ const module = new vm.SyntheticModule([...exportNames], function init() {
1163
+ exportNames.forEach((key) => {
1164
+ const value = key === "default" ? exportsValue.default : exportsValue[key];
1165
+ this.setExport(key, value);
1166
+ });
1167
+ }, {
1168
+ context: state.context,
1169
+ identifier: id
1170
+ });
1171
+ if (cache) {
1172
+ moduleCache.set(id, module);
1173
+ }
1174
+ return module;
1175
+ }
1176
+ const toSyntheticExports = (value) => {
1177
+ if (value && (typeof value === "object" || typeof value === "function")) {
1178
+ const exportsValue = {};
1179
+ Object.keys(value).forEach((key) => {
1180
+ exportsValue[key] = value[key];
1181
+ });
1182
+ exportsValue.default = Object.prototype.hasOwnProperty.call(value, "default") || Object.prototype.hasOwnProperty.call(exportsValue, "default") ? value.default : value;
1183
+ return exportsValue;
1184
+ }
1185
+ return { default: value };
1186
+ };
1187
+ const loadExternalModule = async (resolvedId, importer, specifier) => {
1188
+ const cacheId = resolvedId ?? specifier;
1189
+ const cached = moduleCache.get(cacheId);
1190
+ if (cached) return cached;
1191
+ const inFlight = externalInFlight.get(cacheId);
1192
+ if (inFlight) return inFlight;
1193
+ const task = (async () => {
1194
+ const start = Date.now();
1195
+ debug("external:start", {
1196
+ specifier,
1197
+ resolvedId,
1198
+ importer
1199
+ });
1200
+ const requireFn = createRequireFn(importer);
1201
+ let value;
1202
+ let hasValue = false;
1203
+ const resolvedFile = resolvedId ? stripQueryAndHash(resolvedId) : null;
1204
+ const importTarget = resolvedFile && path.isAbsolute(resolvedFile) ? pathToFileURL(resolvedFile).href : specifier;
1205
+ if (shouldPreferImport(resolvedFile)) {
1206
+ value = await import(importTarget);
1207
+ hasValue = true;
1208
+ }
1209
+ if (!hasValue) {
1210
+ try {
1211
+ value = requireFn(specifier, resolvedId ?? null);
1212
+ hasValue = true;
1213
+ } catch (error) {
1214
+ if (!isErrRequireEsm(error)) {
1215
+ throw error;
1216
+ }
1217
+ const isFileSpecifier = specifier.startsWith(".") || path.isAbsolute(specifier);
1218
+ const isPackageSpecifier = !isFileSpecifier && !isBuiltinSpecifier(specifier);
1219
+ if (resolvedId && isPackageSpecifier) {
1220
+ try {
1221
+ value = requireFn(specifier, null);
1222
+ hasValue = true;
1223
+ } catch (retryError) {
1224
+ if (!isErrRequireEsm(retryError)) {
1225
+ throw retryError;
1226
+ }
1227
+ }
1228
+ }
1229
+ if (!hasValue) {
1230
+ value = await import(importTarget);
1231
+ hasValue = true;
1232
+ }
1233
+ }
1234
+ }
1235
+ const module = createSyntheticModule(cacheId, toSyntheticExports(value));
1236
+ debug("external:done", {
1237
+ specifier,
1238
+ resolvedId,
1239
+ durationMs: Date.now() - start
1240
+ });
1241
+ return module;
1242
+ })();
1243
+ externalInFlight.set(cacheId, task);
1244
+ try {
1245
+ return await task;
1246
+ } finally {
1247
+ externalInFlight.delete(cacheId);
1248
+ }
1249
+ };
1250
+ let resolveModule;
1251
+ let loadModule;
1252
+ const linkModule = async (module) => {
1253
+ const cached = linkPromises.get(module);
1254
+ if (cached) return cached;
1255
+ if (module.status !== "unlinked") return module;
1256
+ const linking = (async () => {
1257
+ try {
1258
+ await module.link((specifier, referencingModule) => resolveModule(specifier, referencingModule.identifier, "import"));
1259
+ return module;
1260
+ } catch (error) {
1261
+ // The vm SourceTextModule is now in 'errored' (or partially-linked)
1262
+ // state and can never be re-linked. With reuseModules:true the cached
1263
+ // module would otherwise stick around and short-circuit linkModule's
1264
+ // status guard above on the next session — surfacing the original
1265
+ // failure forever even after the user fixes the underlying problem.
1266
+ // Drop it so the next LOAD rebuilds a fresh SourceTextModule.
1267
+ const identifier = typeof module.identifier === "string" ? module.identifier : null;
1268
+ if (identifier) {
1269
+ evictPoisonedModule(toSourceModuleId(identifier));
1270
+ }
1271
+ // ERR_VM_MODULE_LINK_FAILURE means a dependency is in "errored" state.
1272
+ // Node chains .cause through the link failure hierarchy. Walk to the
1273
+ // deepest cause to surface the original evaluation error (e.g. a
1274
+ // TypeError in user code), not intermediate "resolved to errored" hops.
1275
+ if (error?.code === "ERR_VM_MODULE_LINK_FAILURE") {
1276
+ let rootCause = error;
1277
+ while (rootCause.cause instanceof Error) {
1278
+ rootCause = rootCause.cause;
1279
+ }
1280
+ if (rootCause !== error) {
1281
+ const enhanced = new Error(`${error.message}\n` + ` Root cause: ${rootCause.name ?? "Error"}: ${rootCause.message}`);
1282
+ enhanced.cause = rootCause;
1283
+ throw enhanced;
1284
+ }
1285
+ }
1286
+ throw error;
1287
+ } finally {
1288
+ linkPromises.delete(module);
1289
+ }
1290
+ })();
1291
+ linkPromises.set(module, linking);
1292
+ return linking;
1293
+ };
1294
+ resolveModule = async (specifier, importer, kind) => {
1295
+ const importerId = toSourceModuleId(importer);
1296
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1297
+ process.stderr.write(`[wyw-eval-runner:resolve] ${JSON.stringify({
1298
+ specifier,
1299
+ importer: importerId,
1300
+ kind
1301
+ })}\n`);
1302
+ }
1303
+ if (specifier === REACT_REFRESH_VIRTUAL_ID) {
1304
+ return createSyntheticModule(specifier, reactRefreshRuntime);
1305
+ }
1306
+ if (specifier.startsWith(VITE_VIRTUAL_PREFIX) || specifier.startsWith("virtual:")) {
1307
+ return createSyntheticModule(specifier, { default: {} });
1308
+ }
1309
+ const key = `${kind}:${importerId}:${specifier}`;
1310
+ const cached = resolveCache.get(key);
1311
+ if (cached) {
1312
+ if (!cached.resolvedId) {
1313
+ if (state.evalOptions.errors === "loose") {
1314
+ return createSyntheticModule(specifier, { default: undefined });
1315
+ }
1316
+ throw new Error([
1317
+ `[wyw-in-js] Unable to resolve "${specifier}" during evaluation.`,
1318
+ ``,
1319
+ `importer: ${importerId}`,
1320
+ `hint: check eval.resolver/customResolver or add importOverrides for this specifier.`
1321
+ ].join("\n"));
1322
+ }
1323
+ const treatExternal = cached.external || isBuiltinSpecifier(specifier) || isNodeModulesId(cached.resolvedId);
1324
+ if (treatExternal) {
1325
+ const normalized = normalizeResolvedId(cached.resolvedId, specifier, importerId, state.evalOptions.extensions);
1326
+ const externalModule = await loadExternalModule(normalized, importerId, specifier);
1327
+ return externalModule;
1328
+ }
1329
+ const normalized = normalizeResolvedId(cached.resolvedId, specifier, importerId, state.evalOptions.extensions);
1330
+ return loadModule(normalized, importerId, specifier);
1331
+ }
1332
+ const inFlight = resolveInFlight.get(key);
1333
+ if (inFlight) return inFlight;
1334
+ const task = (async () => {
1335
+ const resolved = await request("RESOLVE", {
1336
+ specifier,
1337
+ importerId,
1338
+ kind
1339
+ });
1340
+ if (resolved.error) {
1341
+ throw new Error(resolved.error.message);
1342
+ }
1343
+ const normalized = resolved.resolvedId ? normalizeResolvedId(resolved.resolvedId, specifier, importerId, state.evalOptions.extensions) : resolved.resolvedId;
1344
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1345
+ process.stderr.write(`[wyw-eval-runner:resolved] ${JSON.stringify({
1346
+ specifier,
1347
+ importer: importerId,
1348
+ resolved: resolved.resolvedId ?? null,
1349
+ normalized: normalized ?? null,
1350
+ external: Boolean(resolved.external)
1351
+ })}\n`);
1352
+ }
1353
+ resolveCache.set(key, {
1354
+ resolvedId: normalized,
1355
+ external: Boolean(resolved.external)
1356
+ });
1357
+ if (!normalized) {
1358
+ if (state.evalOptions.errors === "loose") {
1359
+ return createSyntheticModule(specifier, { default: undefined });
1360
+ }
1361
+ throw new Error([
1362
+ `[wyw-in-js] Unable to resolve "${specifier}" during evaluation.`,
1363
+ ``,
1364
+ `importer: ${importerId}`,
1365
+ `hint: check eval.resolver/customResolver or add importOverrides for this specifier.`
1366
+ ].join("\n"));
1367
+ }
1368
+ const treatExternal = resolved.external || isBuiltinSpecifier(specifier) || isNodeModulesId(normalized);
1369
+ if (treatExternal) {
1370
+ return loadExternalModule(normalized, importerId, specifier);
1371
+ }
1372
+ return loadModule(normalized, importerId, specifier);
1373
+ })();
1374
+ resolveInFlight.set(key, task);
1375
+ try {
1376
+ return await task;
1377
+ } finally {
1378
+ resolveInFlight.delete(key);
1379
+ }
1380
+ };
1381
+ loadModule = async (id, importer, requestSpec) => {
1382
+ let cached = moduleCache.get(id);
1383
+ const inFlight = loadInFlight.get(id);
1384
+ if (inFlight) {
1385
+ await inFlight;
1386
+ cached = moduleCache.get(id);
1387
+ }
1388
+ const task = (async () => {
1389
+ const loadStart = Date.now();
1390
+ const loaded = await request("LOAD", {
1391
+ id,
1392
+ importerId: importer,
1393
+ request: requestSpec ?? null
1394
+ });
1395
+ debug("load:done", {
1396
+ id,
1397
+ importer,
1398
+ durationMs: Date.now() - loadStart
1399
+ });
1400
+ if (loaded.error) {
1401
+ // Surface the importer + specifier alongside the broker's message.
1402
+ // Without this, ENOENT and similar load failures bubble up as a bare
1403
+ // path (or, after Node's VM wraps them, as the opaque
1404
+ // ERR_VM_MODULE_STATUS) leaving no clue which file's import is broken.
1405
+ const detail = [
1406
+ `[wyw-in-js] Failed to load module during evaluation.`,
1407
+ ` importer: ${importer ?? "(unknown)"}`,
1408
+ ` request: ${requestSpec ?? id}`,
1409
+ ` resolved: ${id}`,
1410
+ ` cause: ${loaded.error.message}`
1411
+ ].join("\n");
1412
+ // The importer's SourceTextModule (if it was already created and
1413
+ // cached) compiled this `import` against `id`; reusing it next session
1414
+ // would link against the same id and either re-trigger the failure or
1415
+ // skip linking via the status guard. Drop both so the next session
1416
+ // pulls fresh code for both ends of the broken edge.
1417
+ if (importer && importer !== id) {
1418
+ evictPoisonedModule(toSourceModuleId(importer));
1419
+ }
1420
+ evictPoisonedModule(id);
1421
+ const enhanced = new Error(detail);
1422
+ enhanced.cause = reviveSerializedError(loaded.error);
1423
+ throw enhanced;
1424
+ }
1425
+ if (loaded.only) {
1426
+ const current = moduleOnly.get(id) ?? [];
1427
+ moduleOnly.set(id, mergeOnly(current, loaded.only));
1428
+ }
1429
+ if (loaded.exports) {
1430
+ // Serialized exports are a narrow slice — only the keys the importer
1431
+ // requested. If we have a fully evaluated module (in moduleCache or as
1432
+ // a variant), prefer it: its namespace has ALL exports, so any consumer
1433
+ // can link against it without "does not provide export" errors.
1434
+ //
1435
+ // An evaluated variant is only safe to reuse when its namespace covers
1436
+ // the serialized key set. A narrow variant that was evaluated first may
1437
+ // lack exports that a wider consumer needs (the 4df6e915 race).
1438
+ const requiredKeys = Object.keys(loaded.exports);
1439
+ const coversKeys = (mod) => {
1440
+ const ns = mod.namespace;
1441
+ return requiredKeys.every((k) => k in ns);
1442
+ };
1443
+ let evaluated = cached && cached.status === "evaluated" && coversKeys(cached) ? cached : undefined;
1444
+ if (!evaluated) {
1445
+ const variants = moduleVariants.get(id);
1446
+ if (variants) {
1447
+ evaluated = Array.from(variants.values()).find((variant) => variant.status === "evaluated" && coversKeys(variant));
1448
+ }
1449
+ }
1450
+ if (evaluated) {
1451
+ return evaluated;
1452
+ }
1453
+ // Reuse a previously created SyntheticModule for this exact serialized set
1454
+ if (loaded.hash) {
1455
+ const existing = getModuleVariant(id, loaded.hash);
1456
+ if (existing) {
1457
+ return existing;
1458
+ }
1459
+ }
1460
+ const exportsValue = {};
1461
+ Object.entries(loaded.exports).forEach(([key, serialized]) => {
1462
+ exportsValue[key] = deserializeValue(serialized);
1463
+ });
1464
+ const module = createSyntheticModule(id, exportsValue, false);
1465
+ if (loaded.hash) {
1466
+ setModuleVariant(id, loaded.hash, module);
1467
+ }
1468
+ return module;
1469
+ }
1470
+ const usePrimaryCache = isFullModuleLoad(loaded);
1471
+ if (usePrimaryCache) {
1472
+ if (cached && loaded.hash && moduleHashes.get(id) === loaded.hash) {
1473
+ return cached;
1474
+ }
1475
+ } else if (loaded.hash) {
1476
+ const variant = getModuleVariant(id, loaded.hash);
1477
+ if (variant) {
1478
+ return variant;
1479
+ }
1480
+ }
1481
+ // The broker only ships empty `code` when it expects the runner to reuse
1482
+ // a cached module via the hash-match short-circuit above. Reaching this
1483
+ // point with no code means the broker's "what runner has" mirror is out
1484
+ // of sync with our actual moduleCache/moduleVariants — fail loudly rather
1485
+ // than feeding empty source into vm.SourceTextModule.
1486
+ if (loaded.code == null || loaded.code === "") {
1487
+ throw new Error(`[wyw-in-js] LoadResult for ${id} has empty code but no cached module ` + `matched hash ${loaded.hash ?? "(none)"}. ` + `This indicates a broker/runner cache desync.`);
1488
+ }
1489
+ if (usePrimaryCache) {
1490
+ resetSingleModuleState(id, cached);
1491
+ }
1492
+ const module = new vm.SourceTextModule(`${buildPreamble(id)}${loaded.code ?? ""}`, {
1493
+ context: state.context,
1494
+ identifier: toVersionedModuleIdentifier(id, loaded.hash),
1495
+ initializeImportMeta(meta, targetModule) {
1496
+ const identifier = typeof targetModule.identifier === "string" ? targetModule.identifier : id;
1497
+ const fileId = stripQueryAndHash(identifier);
1498
+ // eslint-disable-next-line no-param-reassign
1499
+ meta.url = path.isAbsolute(fileId) ? pathToFileURL(fileId).href : fileId;
1500
+ },
1501
+ importModuleDynamically(specifier, referencingModule) {
1502
+ return resolveModule(specifier, referencingModule.identifier, "dynamic-import");
1503
+ }
1504
+ });
1505
+ if (usePrimaryCache) {
1506
+ moduleCache.set(id, module);
1507
+ if (loaded.hash) {
1508
+ moduleHashes.set(id, loaded.hash);
1509
+ }
1510
+ } else if (loaded.hash) {
1511
+ setModuleVariant(id, loaded.hash, module);
1512
+ }
1513
+ return module;
1514
+ })();
1515
+ loadInFlight.set(id, task);
1516
+ try {
1517
+ return await task;
1518
+ } finally {
1519
+ loadInFlight.delete(id);
1520
+ }
1521
+ };
1522
+ const createDynamicImportFn = (importer) => {
1523
+ return async (specifier) => {
1524
+ if (typeof specifier !== "string") {
1525
+ sendWarn({
1526
+ code: "eval-error",
1527
+ message: "[wyw-in-js] Dynamic import with non-string specifier during eval.",
1528
+ importer
1529
+ });
1530
+ if (state.evalOptions.errors === "strict") {
1531
+ throw new Error(`[wyw-in-js] Dynamic import with non-string specifier is not supported during eval.\n` + `importer: ${importer}\n` + `hint: make it a string literal or mock the import via importOverrides.`);
1532
+ }
1533
+ return createSyntheticModule(`dynamic:${String(specifier)}`, { default: undefined });
1534
+ }
1535
+ sendWarn({
1536
+ code: "dynamic-import",
1537
+ message: `[wyw-in-js] Dynamic import executed during eval: ${specifier}`,
1538
+ importer,
1539
+ specifier
1540
+ });
1541
+ const resolved = await resolveModule(specifier, importer, "dynamic-import");
1542
+ await linkModule(resolved);
1543
+ await resolved.evaluate();
1544
+ return resolved;
1545
+ };
1546
+ };
1547
+ const getModuleData = (id) => {
1548
+ const cached = moduleData.get(id);
1549
+ if (cached) return cached;
1550
+ const filename = stripQueryAndHash(id);
1551
+ const exportsValue = {};
1552
+ const moduleObj = { exports: exportsValue };
1553
+ const data = {
1554
+ exports: exportsValue,
1555
+ module: moduleObj,
1556
+ require: createRequireFn(id),
1557
+ filename,
1558
+ dirname: path.dirname(filename),
1559
+ dynamicImport: createDynamicImportFn(id)
1560
+ };
1561
+ moduleData.set(id, data);
1562
+ return data;
1563
+ };
1564
+ const resolveExportValue = (source, key) => {
1565
+ if (key === "default") {
1566
+ if (source && typeof source === "object" && "default" in source) {
1567
+ return source.default;
1568
+ }
1569
+ return source;
1570
+ }
1571
+ if (source && (typeof source === "object" || typeof source === "function")) {
1572
+ if (key in source) {
1573
+ return source[key];
1574
+ }
1575
+ if (source.default && typeof source.default === "object" && key in source.default) {
1576
+ return source.default[key];
1577
+ }
1578
+ }
1579
+ return undefined;
1580
+ };
1581
+ const stringifyDebugValue = (value) => {
1582
+ try {
1583
+ const json = JSON.stringify(value);
1584
+ if (json !== undefined) return json;
1585
+ } catch {}
1586
+ try {
1587
+ return String(value);
1588
+ } catch {
1589
+ return Object.prototype.toString.call(value);
1590
+ }
1591
+ };
1592
+ const serializeDebugReason = (error) => error instanceof Error ? error.message : String(error);
1593
+ const collectModuleExports = () => {
1594
+ const exportsByModule = {};
1595
+ const debugEvalFiles = state.debugEvalFiles ? {} : undefined;
1596
+ moduleOnly.forEach((only, id) => {
1597
+ if (!only || only.length === 0) return;
1598
+ const module = moduleCache.get(id) ?? moduleLastVariant.get(id);
1599
+ const data = moduleData.get(id);
1600
+ if (!module || !data) return;
1601
+ // The broker already has the serialized exports for this exact variant
1602
+ // from a prior eval session. Re-serializing here just wastes CPU on the
1603
+ // runner side and bloats the EVAL_RESULT payload. Same variant identifier
1604
+ // ⇒ same namespace ⇒ no change to send.
1605
+ const moduleIdentifier = typeof module.identifier === "string" ? module.identifier : id;
1606
+ if (sentNamespaceIdentifiers.get(id) === moduleIdentifier) {
1607
+ return;
1608
+ }
1609
+ // .namespace is only safe on fully evaluated modules. Modules that
1610
+ // errored or were never evaluated (stale from a prior failed session
1611
+ // with reuseModules) have TDZ bindings that crash Object.keys().
1612
+ if (module.status !== "evaluated") {
1613
+ sendWarn({
1614
+ code: "eval-stale-module",
1615
+ message: `[wyw-in-js] Skipping export collection for ${id}: ` + `module status is "${module.status}" (expected "evaluated"). ` + `Cached exports for this module may be stale.`
1616
+ });
1617
+ return;
1618
+ }
1619
+ const { namespace } = module;
1620
+ const hasNamespace = namespace && typeof namespace === "object" && Object.keys(namespace).length;
1621
+ const source = hasNamespace ? namespace : data.module.exports;
1622
+ const discoveredKeys = Object.keys(source ?? {}).filter((key) => key !== "__wywPreval" && key !== "side-effect" && key !== "*");
1623
+ const requestedKeys = only.filter((key) => key !== "__wywPreval" && key !== "side-effect" && key !== "*");
1624
+ const keys = Array.from(new Set([...requestedKeys, ...discoveredKeys]));
1625
+ if (keys.length === 0) return;
1626
+ const serialized = {};
1627
+ const debugExports = state.debugEvalFiles ? {} : undefined;
1628
+ keys.forEach((key) => {
1629
+ const value = resolveExportValue(source, key);
1630
+ try {
1631
+ serialized[key] = serializeValue(value, {
1632
+ rootLabel: "module exports",
1633
+ path: [id, key]
1634
+ });
1635
+ if (debugExports) {
1636
+ debugExports[key] = {
1637
+ serialized: serialized[key],
1638
+ status: "serialized"
1639
+ };
1640
+ }
1641
+ } catch (error) {
1642
+ if (debugExports) {
1643
+ debugExports[key] = {
1644
+ reason: serializeDebugReason(error),
1645
+ status: "stringified",
1646
+ stringified: stringifyDebugValue(value)
1647
+ };
1648
+ }
1649
+ }
1650
+ });
1651
+ if (debugEvalFiles && debugExports && Object.keys(debugExports).length) {
1652
+ debugEvalFiles[id] = { exports: debugExports };
1653
+ }
1654
+ if (Object.keys(serialized).length) {
1655
+ exportsByModule[id] = serialized;
1656
+ sentNamespaceIdentifiers.set(id, moduleIdentifier);
1657
+ }
1658
+ });
1659
+ return {
1660
+ debugEvalFiles,
1661
+ modules: exportsByModule
1662
+ };
1663
+ };
1664
+ async function evaluateEntrypoint(id) {
1665
+ const evalStart = Date.now();
1666
+ debug("eval:start", id);
1667
+ const module = await loadModule(id, id, id);
1668
+ debug("eval:loaded", {
1669
+ id,
1670
+ durationMs: Date.now() - evalStart
1671
+ });
1672
+ await linkModule(module);
1673
+ debug("eval:linked", {
1674
+ id,
1675
+ durationMs: Date.now() - evalStart
1676
+ });
1677
+ await module.evaluate();
1678
+ debug("eval:evaluated", {
1679
+ id,
1680
+ durationMs: Date.now() - evalStart
1681
+ });
1682
+ const data = getModuleData(id);
1683
+ const exportsValue = data.module.exports;
1684
+ const hasPrevalExport = exportsValue && typeof exportsValue === "object" && "__wywPreval" in exportsValue;
1685
+ const { namespace } = module;
1686
+ const hasPrevalNamespace = namespace && typeof namespace === "object" && "__wywPreval" in namespace;
1687
+ const { debugEvalFiles, modules } = collectModuleExports();
1688
+ if (!hasPrevalExport && !hasPrevalNamespace) {
1689
+ return {
1690
+ debugEvalFiles,
1691
+ values: null,
1692
+ modules
1693
+ };
1694
+ }
1695
+ const preval = hasPrevalExport ? exportsValue.__wywPreval : namespace.__wywPreval;
1696
+ if (!preval || typeof preval !== "object") {
1697
+ return {
1698
+ debugEvalFiles,
1699
+ values: null,
1700
+ modules
1701
+ };
1702
+ }
1703
+ const values = {};
1704
+ const debugPreval = state.debugEvalFiles ? {} : undefined;
1705
+ Object.entries(preval).forEach(([key, lazy]) => {
1706
+ let value;
1707
+ try {
1708
+ value = typeof lazy === "function" ? lazy() : lazy;
1709
+ } catch (error) {
1710
+ value = error;
1711
+ }
1712
+ values[key] = serializeValue(value, {
1713
+ allowFunctions: true,
1714
+ allowSymbols: true,
1715
+ rootLabel: "__wywPreval",
1716
+ path: [key]
1717
+ });
1718
+ if (debugPreval) {
1719
+ debugPreval[key] = {
1720
+ serialized: values[key],
1721
+ status: "serialized"
1722
+ };
1723
+ }
1724
+ });
1725
+ if (debugEvalFiles && debugPreval && Object.keys(debugPreval).length) {
1726
+ debugEvalFiles[id] = {
1727
+ ...debugEvalFiles[id] ?? {},
1728
+ preval: debugPreval
1729
+ };
1730
+ }
1731
+ return {
1732
+ debugEvalFiles,
1733
+ values,
1734
+ modules
1735
+ };
1736
+ }
1737
+ const handleMessage = async (message) => {
1738
+ switch (message.type) {
1739
+ case "INIT": {
1740
+ try {
1741
+ const initStart = Date.now();
1742
+ debug("init:start", message.payload.entrypoint ?? "eval-runner");
1743
+ const encodedGlobals = message.payload.evalOptions.globals ?? {};
1744
+ const nextGlobalsSignature = JSON.stringify(canonicalizeForSignature(encodedGlobals));
1745
+ const nextFeatures = message.payload.features ?? {};
1746
+ const nextDebugEvalFiles = Boolean(message.payload.debugEvalFiles);
1747
+ const nextEntrypoint = message.payload.entrypoint ?? "eval-runner";
1748
+ const nextHappyDomEnabled = isFeatureEnabled(nextFeatures, "happyDOM", nextEntrypoint);
1749
+ const globalsChanged = state.globalsSignature !== null && state.globalsSignature !== nextGlobalsSignature;
1750
+ const nextGlobals = !globalsChanged && state.globalsSignature !== null ? state.evalOptions.globals : decodeGlobals(encodedGlobals);
1751
+ const nextEvalOptions = {
1752
+ ...state.evalOptions,
1753
+ ...message.payload.evalOptions,
1754
+ globals: nextGlobals
1755
+ };
1756
+ const canReuseContext = state.context && state.happyDomEnabled === nextHappyDomEnabled && !globalsChanged;
1757
+ const reuseModules = Boolean(message.payload.reuseModules);
1758
+ if (canReuseContext) {
1759
+ const modulesReset = !reuseModules;
1760
+ if (modulesReset) {
1761
+ resetModuleState();
1762
+ } else {
1763
+ // Clear resolution caches between sessions even when reusing modules.
1764
+ // The broker rebuilds onlyByModule from scratch each session (cleared
1765
+ // in evaluate()). If the runner's resolveCache persists, RESOLVE
1766
+ // requests for previously-seen (importer, specifier) pairs are
1767
+ // skipped, preventing the broker from learning what exports are
1768
+ // needed. This can cause a barrel module to be served with a stale
1769
+ // `only` set that's missing exports a consumer actually imports,
1770
+ // leading to "does not provide an export named 'X'" link errors.
1771
+ resolveCache.clear();
1772
+ resolveInFlight.clear();
1773
+ loadInFlight.clear();
1774
+ }
1775
+ state.evalOptions = nextEvalOptions;
1776
+ state.features = nextFeatures;
1777
+ state.debugEvalFiles = nextDebugEvalFiles;
1778
+ state.entrypoint = nextEntrypoint;
1779
+ Object.assign(state.context, {
1780
+ __dirname: path.dirname(nextEntrypoint),
1781
+ __filename: nextEntrypoint,
1782
+ ...nextEvalOptions.globals,
1783
+ __wyw_getModule: (moduleId) => getModuleData(moduleId)
1784
+ });
1785
+ state.globalsSignature = nextGlobalsSignature;
1786
+ debug("init:reuse", Date.now() - initStart);
1787
+ sendMessage({
1788
+ type: "INIT_ACK",
1789
+ id: message.id,
1790
+ modulesReset
1791
+ });
1792
+ break;
1793
+ }
1794
+ resetEvaluationState();
1795
+ state.evalOptions = nextEvalOptions;
1796
+ state.features = nextFeatures;
1797
+ state.debugEvalFiles = nextDebugEvalFiles;
1798
+ state.entrypoint = nextEntrypoint;
1799
+ debug("init:globals", Date.now() - initStart);
1800
+ const windowStart = Date.now();
1801
+ const { context, teardown } = await createVmContext(state.entrypoint, state.features, {
1802
+ ...state.evalOptions.globals,
1803
+ __wyw_getModule: (moduleId) => getModuleData(moduleId)
1804
+ });
1805
+ debug("init:context", Date.now() - windowStart);
1806
+ state.context = context;
1807
+ state.teardown = teardown;
1808
+ state.happyDomEnabled = nextHappyDomEnabled;
1809
+ state.globalsSignature = nextGlobalsSignature;
1810
+ // Full context rebuild ⇒ moduleCache was cleared by resetEvaluationState.
1811
+ sendMessage({
1812
+ type: "INIT_ACK",
1813
+ id: message.id,
1814
+ modulesReset: true
1815
+ });
1816
+ debug("init:done", Date.now() - initStart);
1817
+ } catch (error) {
1818
+ sendMessage({
1819
+ type: "INIT_ACK",
1820
+ id: message.id,
1821
+ error: serializeError(error)
1822
+ });
1823
+ }
1824
+ break;
1825
+ }
1826
+ case "EVAL": {
1827
+ evictedThisSession.clear();
1828
+ try {
1829
+ const { debugEvalFiles, values, modules } = await evaluateEntrypoint(message.payload.id);
1830
+ sendMessage({
1831
+ type: "EVAL_RESULT",
1832
+ id: message.id,
1833
+ payload: {
1834
+ ...debugEvalFiles ? { debugEvalFiles } : {},
1835
+ values,
1836
+ modules,
1837
+ evictedIds: Array.from(evictedThisSession)
1838
+ }
1839
+ });
1840
+ } catch (error) {
1841
+ sendMessage({
1842
+ type: "EVAL_RESULT",
1843
+ id: message.id,
1844
+ payload: {
1845
+ values: null,
1846
+ evictedIds: Array.from(evictedThisSession)
1847
+ },
1848
+ error: serializeError(error)
1849
+ });
1850
+ }
1851
+ break;
1852
+ }
1853
+ case "RESOLVE_RESULT": {
1854
+ resolvePending(message.id, message.payload);
1855
+ break;
1856
+ }
1857
+ case "LOAD_RESULT": {
1858
+ handleLoadResult(message.id, message.payload);
1859
+ break;
1860
+ }
1861
+ default: break;
1862
+ }
1863
+ };
1864
+ let buffer = "";
1865
+ process.stdin.setEncoding("utf8");
1866
+ process.stdin.resume();
1867
+ process.stdin.on("data", (chunk) => {
1868
+ buffer += chunk;
1869
+ const lines = buffer.split("\n");
1870
+ buffer = lines.pop() ?? "";
1871
+ lines.forEach((line) => {
1872
+ if (!line.trim()) return;
1873
+ const message = JSON.parse(line);
1874
+ handleMessage(message);
1875
+ });
1876
+ });
1877
+ process.stdin.on("close", shutdown);
1878
+ //# sourceMappingURL=runner.js.map