@vxrn/vite-plugin-metro 1.27.1 → 2.0.0-beta.101.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 (335) hide show
  1. package/dist/cjs/babel-plugins/import-meta-env-plugin.cjs +84 -102
  2. package/dist/cjs/babel-plugins/import-meta-env-plugin.native.cjs +108 -0
  3. package/dist/cjs/babel-plugins/import-meta-env-plugin.native.js +90 -107
  4. package/dist/cjs/babel-plugins/import-meta-env-plugin.native.js.map +1 -1
  5. package/dist/cjs/env/platformEnv.cjs +57 -57
  6. package/dist/cjs/env/platformEnv.native.cjs +95 -0
  7. package/dist/cjs/env/platformEnv.native.js +74 -75
  8. package/dist/cjs/env/platformEnv.native.js.map +1 -1
  9. package/dist/cjs/index.cjs +21 -25
  10. package/dist/cjs/index.native.cjs +39 -0
  11. package/dist/cjs/index.native.js +21 -24
  12. package/dist/cjs/index.native.js.map +1 -1
  13. package/dist/cjs/metro-config/getMetroBabelConfigFromViteConfig.cjs +54 -51
  14. package/dist/cjs/metro-config/getMetroBabelConfigFromViteConfig.native.cjs +108 -0
  15. package/dist/cjs/metro-config/getMetroBabelConfigFromViteConfig.native.js +95 -94
  16. package/dist/cjs/metro-config/getMetroBabelConfigFromViteConfig.native.js.map +1 -1
  17. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.cjs +287 -272
  18. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.cjs +346 -0
  19. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js +309 -282
  20. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  21. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.cjs +38 -44
  22. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.cjs +53 -0
  23. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +39 -44
  24. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  25. package/dist/cjs/metro-config/types.cjs +9 -11
  26. package/dist/cjs/metro-config/types.native.cjs +18 -0
  27. package/dist/cjs/metro-config/types.native.js +9 -10
  28. package/dist/cjs/metro-config/types.native.js.map +1 -1
  29. package/dist/cjs/plugins/metroPlugin.cjs +210 -248
  30. package/dist/cjs/plugins/metroPlugin.native.cjs +242 -0
  31. package/dist/cjs/plugins/metroPlugin.native.js +216 -253
  32. package/dist/cjs/plugins/metroPlugin.native.js.map +1 -1
  33. package/dist/cjs/rn-commands/bundle/assetCatalogIOS.cjs +56 -65
  34. package/dist/cjs/rn-commands/bundle/assetCatalogIOS.native.cjs +121 -0
  35. package/dist/cjs/rn-commands/bundle/assetCatalogIOS.native.js +94 -106
  36. package/dist/cjs/rn-commands/bundle/assetCatalogIOS.native.js.map +1 -1
  37. package/dist/cjs/rn-commands/bundle/assetPathUtils.cjs +51 -55
  38. package/dist/cjs/rn-commands/bundle/assetPathUtils.native.cjs +72 -0
  39. package/dist/cjs/rn-commands/bundle/assetPathUtils.native.js +51 -54
  40. package/dist/cjs/rn-commands/bundle/assetPathUtils.native.js.map +1 -1
  41. package/dist/cjs/rn-commands/bundle/buildBundle.cjs +37 -46
  42. package/dist/cjs/rn-commands/bundle/buildBundle.native.cjs +57 -0
  43. package/dist/cjs/rn-commands/bundle/buildBundle.native.js +39 -47
  44. package/dist/cjs/rn-commands/bundle/buildBundle.native.js.map +1 -1
  45. package/dist/cjs/rn-commands/bundle/buildBundleWithConfig.cjs +57 -68
  46. package/dist/cjs/rn-commands/bundle/buildBundleWithConfig.native.cjs +81 -0
  47. package/dist/cjs/rn-commands/bundle/buildBundleWithConfig.native.js +59 -70
  48. package/dist/cjs/rn-commands/bundle/buildBundleWithConfig.native.js.map +1 -1
  49. package/dist/cjs/rn-commands/bundle/filterPlatformAssetScales.cjs +37 -39
  50. package/dist/cjs/rn-commands/bundle/filterPlatformAssetScales.native.cjs +70 -0
  51. package/dist/cjs/rn-commands/bundle/filterPlatformAssetScales.native.js +56 -59
  52. package/dist/cjs/rn-commands/bundle/filterPlatformAssetScales.native.js.map +1 -1
  53. package/dist/cjs/rn-commands/bundle/getAssetDestPathAndroid.cjs +20 -29
  54. package/dist/cjs/rn-commands/bundle/getAssetDestPathAndroid.native.cjs +39 -0
  55. package/dist/cjs/rn-commands/bundle/getAssetDestPathAndroid.native.js +20 -28
  56. package/dist/cjs/rn-commands/bundle/getAssetDestPathAndroid.native.js.map +1 -1
  57. package/dist/cjs/rn-commands/bundle/getAssetDestPathIOS.cjs +20 -33
  58. package/dist/cjs/rn-commands/bundle/getAssetDestPathIOS.native.cjs +38 -0
  59. package/dist/cjs/rn-commands/bundle/getAssetDestPathIOS.native.js +20 -32
  60. package/dist/cjs/rn-commands/bundle/getAssetDestPathIOS.native.js.map +1 -1
  61. package/dist/cjs/rn-commands/bundle/getBuildBundleFn.cjs +23 -32
  62. package/dist/cjs/rn-commands/bundle/getBuildBundleFn.native.cjs +38 -0
  63. package/dist/cjs/rn-commands/bundle/getBuildBundleFn.native.js +23 -31
  64. package/dist/cjs/rn-commands/bundle/getBuildBundleFn.native.js.map +1 -1
  65. package/dist/cjs/rn-commands/bundle/index.cjs +15 -17
  66. package/dist/cjs/rn-commands/bundle/index.native.cjs +30 -0
  67. package/dist/cjs/rn-commands/bundle/index.native.js +15 -16
  68. package/dist/cjs/rn-commands/bundle/index.native.js.map +1 -1
  69. package/dist/cjs/rn-commands/bundle/saveAssets.cjs +85 -96
  70. package/dist/cjs/rn-commands/bundle/saveAssets.native.cjs +129 -0
  71. package/dist/cjs/rn-commands/bundle/saveAssets.native.js +102 -114
  72. package/dist/cjs/rn-commands/bundle/saveAssets.native.js.map +1 -1
  73. package/dist/cjs/rn-commands/bundle/types.cjs +9 -11
  74. package/dist/cjs/rn-commands/bundle/types.native.cjs +18 -0
  75. package/dist/cjs/rn-commands/bundle/types.native.js +9 -10
  76. package/dist/cjs/rn-commands/bundle/types.native.js.map +1 -1
  77. package/dist/cjs/rn-commands/index.cjs +17 -26
  78. package/dist/cjs/rn-commands/index.native.cjs +32 -0
  79. package/dist/cjs/rn-commands/index.native.js +17 -25
  80. package/dist/cjs/rn-commands/index.native.js.map +1 -1
  81. package/dist/cjs/transformer/babel-core.cjs +16 -18
  82. package/dist/cjs/transformer/babel-core.native.cjs +30 -0
  83. package/dist/cjs/transformer/babel-core.native.js +16 -17
  84. package/dist/cjs/transformer/babel-core.native.js.map +1 -1
  85. package/dist/cjs/transformer/babel-transformer.cjs +149 -151
  86. package/dist/cjs/transformer/babel-transformer.native.cjs +190 -0
  87. package/dist/cjs/transformer/babel-transformer.native.js +164 -158
  88. package/dist/cjs/transformer/babel-transformer.native.js.map +1 -1
  89. package/dist/cjs/transformer/expoVirtualEnv.cjs +92 -0
  90. package/dist/cjs/transformer/expoVirtualEnv.native.cjs +113 -0
  91. package/dist/cjs/transformer/expoVirtualEnv.native.js +115 -0
  92. package/dist/cjs/transformer/expoVirtualEnv.native.js.map +1 -0
  93. package/dist/cjs/transformer/loadBabelConfig.cjs +44 -49
  94. package/dist/cjs/transformer/loadBabelConfig.native.cjs +64 -0
  95. package/dist/cjs/transformer/loadBabelConfig.native.js +48 -52
  96. package/dist/cjs/transformer/loadBabelConfig.native.js.map +1 -1
  97. package/dist/cjs/transformer/metroNativeWorker.cjs +1430 -1488
  98. package/dist/cjs/transformer/metroNativeWorker.native.cjs +2519 -0
  99. package/dist/cjs/transformer/metroNativeWorker.native.js +2407 -2560
  100. package/dist/cjs/transformer/metroNativeWorker.native.js.map +1 -1
  101. package/dist/cjs/transformer/transformSync.cjs +48 -64
  102. package/dist/cjs/transformer/transformSync.native.cjs +74 -0
  103. package/dist/cjs/transformer/transformSync.native.js +50 -65
  104. package/dist/cjs/transformer/transformSync.native.js.map +1 -1
  105. package/dist/cjs/transformer/types.cjs +9 -11
  106. package/dist/cjs/transformer/types.native.cjs +18 -0
  107. package/dist/cjs/transformer/types.native.js +9 -10
  108. package/dist/cjs/transformer/types.native.js.map +1 -1
  109. package/dist/cjs/utils/exit.cjs +141 -139
  110. package/dist/cjs/utils/exit.native.cjs +266 -0
  111. package/dist/cjs/utils/exit.native.js +228 -241
  112. package/dist/cjs/utils/exit.native.js.map +1 -1
  113. package/dist/cjs/utils/getTerminalReporter.cjs +35 -47
  114. package/dist/cjs/utils/getTerminalReporter.native.cjs +57 -0
  115. package/dist/cjs/utils/getTerminalReporter.native.js +38 -49
  116. package/dist/cjs/utils/getTerminalReporter.native.js.map +1 -1
  117. package/dist/cjs/utils/metroCacheManager.cjs +84 -99
  118. package/dist/cjs/utils/metroCacheManager.native.cjs +130 -0
  119. package/dist/cjs/utils/metroCacheManager.native.js +102 -118
  120. package/dist/cjs/utils/metroCacheManager.native.js.map +1 -1
  121. package/dist/cjs/utils/projectImport.cjs +40 -51
  122. package/dist/cjs/utils/projectImport.native.cjs +64 -0
  123. package/dist/cjs/utils/projectImport.native.js +41 -58
  124. package/dist/cjs/utils/projectImport.native.js.map +1 -1
  125. package/dist/esm/babel-plugins/import-meta-env-plugin.mjs +72 -86
  126. package/dist/esm/babel-plugins/import-meta-env-plugin.mjs.map +1 -1
  127. package/dist/esm/babel-plugins/import-meta-env-plugin.native.js +78 -92
  128. package/dist/esm/babel-plugins/import-meta-env-plugin.native.js.map +1 -1
  129. package/dist/esm/env/platformEnv.mjs +42 -39
  130. package/dist/esm/env/platformEnv.mjs.map +1 -1
  131. package/dist/esm/env/platformEnv.native.js +59 -58
  132. package/dist/esm/env/platformEnv.native.js.map +1 -1
  133. package/dist/esm/index.js +3 -4
  134. package/dist/esm/index.mjs +3 -4
  135. package/dist/esm/index.native.js +3 -4
  136. package/dist/esm/metro-config/getMetroBabelConfigFromViteConfig.mjs +42 -33
  137. package/dist/esm/metro-config/getMetroBabelConfigFromViteConfig.mjs.map +1 -1
  138. package/dist/esm/metro-config/getMetroBabelConfigFromViteConfig.native.js +83 -77
  139. package/dist/esm/metro-config/getMetroBabelConfigFromViteConfig.native.js.map +1 -1
  140. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs +271 -247
  141. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs.map +1 -1
  142. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js +293 -258
  143. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  144. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs +26 -26
  145. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs.map +1 -1
  146. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +27 -27
  147. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  148. package/dist/esm/metro-config/types.mjs +0 -2
  149. package/dist/esm/metro-config/types.native.js +0 -2
  150. package/dist/esm/plugins/metroPlugin.mjs +195 -222
  151. package/dist/esm/plugins/metroPlugin.mjs.map +1 -1
  152. package/dist/esm/plugins/metroPlugin.native.js +201 -228
  153. package/dist/esm/plugins/metroPlugin.native.js.map +1 -1
  154. package/dist/esm/rn-commands/bundle/assetCatalogIOS.mjs +38 -38
  155. package/dist/esm/rn-commands/bundle/assetCatalogIOS.mjs.map +1 -1
  156. package/dist/esm/rn-commands/bundle/assetCatalogIOS.native.js +76 -80
  157. package/dist/esm/rn-commands/bundle/assetCatalogIOS.native.js.map +1 -1
  158. package/dist/esm/rn-commands/bundle/assetPathUtils.mjs +38 -37
  159. package/dist/esm/rn-commands/bundle/assetPathUtils.mjs.map +1 -1
  160. package/dist/esm/rn-commands/bundle/assetPathUtils.native.js +38 -37
  161. package/dist/esm/rn-commands/bundle/assetPathUtils.native.js.map +1 -1
  162. package/dist/esm/rn-commands/bundle/buildBundle.mjs +25 -28
  163. package/dist/esm/rn-commands/bundle/buildBundle.mjs.map +1 -1
  164. package/dist/esm/rn-commands/bundle/buildBundle.native.js +27 -30
  165. package/dist/esm/rn-commands/bundle/buildBundle.native.js.map +1 -1
  166. package/dist/esm/rn-commands/bundle/buildBundleWithConfig.mjs +43 -43
  167. package/dist/esm/rn-commands/bundle/buildBundleWithConfig.mjs.map +1 -1
  168. package/dist/esm/rn-commands/bundle/buildBundleWithConfig.native.js +45 -46
  169. package/dist/esm/rn-commands/bundle/buildBundleWithConfig.native.js.map +1 -1
  170. package/dist/esm/rn-commands/bundle/filterPlatformAssetScales.mjs +24 -21
  171. package/dist/esm/rn-commands/bundle/filterPlatformAssetScales.mjs.map +1 -1
  172. package/dist/esm/rn-commands/bundle/filterPlatformAssetScales.native.js +43 -42
  173. package/dist/esm/rn-commands/bundle/filterPlatformAssetScales.native.js.map +1 -1
  174. package/dist/esm/rn-commands/bundle/getAssetDestPathAndroid.mjs +5 -3
  175. package/dist/esm/rn-commands/bundle/getAssetDestPathAndroid.mjs.map +1 -1
  176. package/dist/esm/rn-commands/bundle/getAssetDestPathAndroid.native.js +5 -3
  177. package/dist/esm/rn-commands/bundle/getAssetDestPathAndroid.native.js.map +1 -1
  178. package/dist/esm/rn-commands/bundle/getAssetDestPathIOS.mjs +5 -7
  179. package/dist/esm/rn-commands/bundle/getAssetDestPathIOS.mjs.map +1 -1
  180. package/dist/esm/rn-commands/bundle/getAssetDestPathIOS.native.js +5 -7
  181. package/dist/esm/rn-commands/bundle/getAssetDestPathIOS.native.js.map +1 -1
  182. package/dist/esm/rn-commands/bundle/getBuildBundleFn.mjs +11 -14
  183. package/dist/esm/rn-commands/bundle/getBuildBundleFn.mjs.map +1 -1
  184. package/dist/esm/rn-commands/bundle/getBuildBundleFn.native.js +11 -14
  185. package/dist/esm/rn-commands/bundle/getBuildBundleFn.native.js.map +1 -1
  186. package/dist/esm/rn-commands/bundle/index.mjs +2 -2
  187. package/dist/esm/rn-commands/bundle/index.native.js +2 -2
  188. package/dist/esm/rn-commands/bundle/saveAssets.mjs +70 -70
  189. package/dist/esm/rn-commands/bundle/saveAssets.mjs.map +1 -1
  190. package/dist/esm/rn-commands/bundle/saveAssets.native.js +87 -89
  191. package/dist/esm/rn-commands/bundle/saveAssets.native.js.map +1 -1
  192. package/dist/esm/rn-commands/bundle/types.mjs +0 -2
  193. package/dist/esm/rn-commands/bundle/types.native.js +0 -2
  194. package/dist/esm/rn-commands/index.mjs +2 -2
  195. package/dist/esm/rn-commands/index.native.js +2 -2
  196. package/dist/esm/transformer/babel-core.mjs +2 -2
  197. package/dist/esm/transformer/babel-core.native.js +2 -2
  198. package/dist/esm/transformer/babel-transformer.mjs +133 -132
  199. package/dist/esm/transformer/babel-transformer.mjs.map +1 -1
  200. package/dist/esm/transformer/babel-transformer.native.js +145 -142
  201. package/dist/esm/transformer/babel-transformer.native.js.map +1 -1
  202. package/dist/esm/transformer/expoVirtualEnv.mjs +67 -0
  203. package/dist/esm/transformer/expoVirtualEnv.mjs.map +1 -0
  204. package/dist/esm/transformer/expoVirtualEnv.native.js +86 -0
  205. package/dist/esm/transformer/expoVirtualEnv.native.js.map +1 -0
  206. package/dist/esm/transformer/loadBabelConfig.mjs +29 -23
  207. package/dist/esm/transformer/loadBabelConfig.mjs.map +1 -1
  208. package/dist/esm/transformer/loadBabelConfig.native.js +33 -27
  209. package/dist/esm/transformer/loadBabelConfig.native.js.map +1 -1
  210. package/dist/esm/transformer/metroNativeWorker.mjs +1393 -1442
  211. package/dist/esm/transformer/metroNativeWorker.mjs.map +1 -1
  212. package/dist/esm/transformer/metroNativeWorker.native.js +2370 -2515
  213. package/dist/esm/transformer/metroNativeWorker.native.js.map +1 -1
  214. package/dist/esm/transformer/transformSync.mjs +33 -38
  215. package/dist/esm/transformer/transformSync.mjs.map +1 -1
  216. package/dist/esm/transformer/transformSync.native.js +35 -40
  217. package/dist/esm/transformer/transformSync.native.js.map +1 -1
  218. package/dist/esm/transformer/types.mjs +0 -2
  219. package/dist/esm/transformer/types.native.js +0 -2
  220. package/dist/esm/utils/exit.mjs +123 -112
  221. package/dist/esm/utils/exit.mjs.map +1 -1
  222. package/dist/esm/utils/exit.native.js +210 -215
  223. package/dist/esm/utils/exit.native.js.map +1 -1
  224. package/dist/esm/utils/getTerminalReporter.mjs +20 -21
  225. package/dist/esm/utils/getTerminalReporter.mjs.map +1 -1
  226. package/dist/esm/utils/getTerminalReporter.native.js +23 -24
  227. package/dist/esm/utils/getTerminalReporter.native.js.map +1 -1
  228. package/dist/esm/utils/metroCacheManager.mjs +73 -82
  229. package/dist/esm/utils/metroCacheManager.mjs.map +1 -1
  230. package/dist/esm/utils/metroCacheManager.native.js +91 -102
  231. package/dist/esm/utils/metroCacheManager.native.js.map +1 -1
  232. package/dist/esm/utils/projectImport.mjs +23 -25
  233. package/dist/esm/utils/projectImport.mjs.map +1 -1
  234. package/dist/esm/utils/projectImport.native.js +24 -33
  235. package/dist/esm/utils/projectImport.native.js.map +1 -1
  236. package/package.json +15 -18
  237. package/src/babel-plugins/import-meta-env-plugin.ts +1 -1
  238. package/src/env/platformEnv.test.ts +44 -0
  239. package/src/env/platformEnv.ts +6 -3
  240. package/src/index.ts +0 -2
  241. package/src/metro-config/getMetroBabelConfigFromViteConfig.test.ts +52 -0
  242. package/src/metro-config/getMetroBabelConfigFromViteConfig.ts +8 -7
  243. package/src/metro-config/getMetroConfigFromViteConfig.test.ts +60 -0
  244. package/src/metro-config/getMetroConfigFromViteConfig.ts +150 -113
  245. package/src/plugins/metroPlugin.ts +3 -6
  246. package/src/transformer/babel-transformer.test.ts +118 -0
  247. package/src/transformer/babel-transformer.ts +82 -15
  248. package/src/transformer/expoVirtualEnv.integration.test.ts +106 -0
  249. package/src/transformer/expoVirtualEnv.test.ts +72 -0
  250. package/src/transformer/expoVirtualEnv.ts +115 -0
  251. package/src/transformer/loadBabelConfig.ts +1 -1
  252. package/src/transformer/metroNativeWorker.test.ts +268 -50
  253. package/src/transformer/metroNativeWorker.ts +53 -71
  254. package/src/transformer/transformSync.test.ts +22 -0
  255. package/src/transformer/transformSync.ts +4 -4
  256. package/src/utils/exit.ts +2 -2
  257. package/src/utils/getTerminalReporter.ts +1 -1
  258. package/src/utils/projectImport.ts +2 -2
  259. package/types/babel-plugins/import-meta-env-plugin.d.ts +1 -1
  260. package/types/babel-plugins/import-meta-env-plugin.d.ts.map +1 -1
  261. package/types/env/platformEnv.d.ts +2 -1
  262. package/types/env/platformEnv.d.ts.map +1 -1
  263. package/types/index.d.ts +0 -2
  264. package/types/index.d.ts.map +1 -1
  265. package/types/metro-config/getMetroBabelConfigFromViteConfig.d.ts +1 -1
  266. package/types/metro-config/getMetroBabelConfigFromViteConfig.d.ts.map +1 -1
  267. package/types/metro-config/getMetroConfigFromViteConfig.d.ts +2 -2
  268. package/types/metro-config/getMetroConfigFromViteConfig.d.ts.map +1 -1
  269. package/types/plugins/metroPlugin.d.ts +2 -4
  270. package/types/plugins/metroPlugin.d.ts.map +1 -1
  271. package/types/rn-commands/bundle/assetPathUtils.d.ts.map +1 -1
  272. package/types/rn-commands/bundle/filterPlatformAssetScales.d.ts.map +1 -1
  273. package/types/rn-commands/bundle/getAssetDestPathAndroid.d.ts.map +1 -1
  274. package/types/rn-commands/bundle/getAssetDestPathIOS.d.ts.map +1 -1
  275. package/types/rn-commands/bundle/saveAssets.d.ts.map +1 -1
  276. package/types/transformer/babel-transformer.d.ts +10 -1
  277. package/types/transformer/babel-transformer.d.ts.map +1 -1
  278. package/types/transformer/expoVirtualEnv.d.ts +8 -0
  279. package/types/transformer/expoVirtualEnv.d.ts.map +1 -0
  280. package/types/transformer/metroNativeWorker.d.ts +7 -8
  281. package/types/transformer/metroNativeWorker.d.ts.map +1 -1
  282. package/types/utils/projectImport.d.ts +2 -2
  283. package/dist/cjs/plugins/expoManifestRequestHandlerPlugin.cjs +0 -71
  284. package/dist/cjs/plugins/expoManifestRequestHandlerPlugin.native.js +0 -82
  285. package/dist/cjs/plugins/expoManifestRequestHandlerPlugin.native.js.map +0 -1
  286. package/dist/cjs/transformer/metroNativeWorker.test.cjs +0 -1054
  287. package/dist/cjs/transformer/metroNativeWorker.test.native.js +0 -1170
  288. package/dist/cjs/transformer/metroNativeWorker.test.native.js.map +0 -1
  289. package/dist/cjs/transformer/transformSync.test.cjs +0 -36
  290. package/dist/cjs/transformer/transformSync.test.native.js +0 -49
  291. package/dist/cjs/transformer/transformSync.test.native.js.map +0 -1
  292. package/dist/cjs/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.cjs +0 -39
  293. package/dist/cjs/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.native.js +0 -42
  294. package/dist/cjs/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.native.js.map +0 -1
  295. package/dist/esm/index.js.map +0 -1
  296. package/dist/esm/index.mjs.map +0 -1
  297. package/dist/esm/index.native.js.map +0 -1
  298. package/dist/esm/metro-config/types.mjs.map +0 -1
  299. package/dist/esm/metro-config/types.native.js.map +0 -1
  300. package/dist/esm/plugins/expoManifestRequestHandlerPlugin.mjs +0 -46
  301. package/dist/esm/plugins/expoManifestRequestHandlerPlugin.mjs.map +0 -1
  302. package/dist/esm/plugins/expoManifestRequestHandlerPlugin.native.js +0 -54
  303. package/dist/esm/plugins/expoManifestRequestHandlerPlugin.native.js.map +0 -1
  304. package/dist/esm/rn-commands/bundle/index.mjs.map +0 -1
  305. package/dist/esm/rn-commands/bundle/index.native.js.map +0 -1
  306. package/dist/esm/rn-commands/bundle/types.mjs.map +0 -1
  307. package/dist/esm/rn-commands/bundle/types.native.js.map +0 -1
  308. package/dist/esm/rn-commands/index.mjs.map +0 -1
  309. package/dist/esm/rn-commands/index.native.js.map +0 -1
  310. package/dist/esm/transformer/babel-core.mjs.map +0 -1
  311. package/dist/esm/transformer/babel-core.native.js.map +0 -1
  312. package/dist/esm/transformer/metroNativeWorker.test.mjs +0 -1010
  313. package/dist/esm/transformer/metroNativeWorker.test.mjs.map +0 -1
  314. package/dist/esm/transformer/metroNativeWorker.test.native.js +0 -1124
  315. package/dist/esm/transformer/metroNativeWorker.test.native.js.map +0 -1
  316. package/dist/esm/transformer/transformSync.test.mjs +0 -37
  317. package/dist/esm/transformer/transformSync.test.mjs.map +0 -1
  318. package/dist/esm/transformer/transformSync.test.native.js +0 -47
  319. package/dist/esm/transformer/transformSync.test.native.js.map +0 -1
  320. package/dist/esm/transformer/types.mjs.map +0 -1
  321. package/dist/esm/transformer/types.native.js.map +0 -1
  322. package/dist/esm/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.mjs +0 -14
  323. package/dist/esm/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.mjs.map +0 -1
  324. package/dist/esm/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.native.js +0 -14
  325. package/dist/esm/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.native.js.map +0 -1
  326. package/src/plugins/expoManifestRequestHandlerPlugin.ts +0 -88
  327. package/src/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.ts +0 -28
  328. package/types/plugins/expoManifestRequestHandlerPlugin.d.ts +0 -14
  329. package/types/plugins/expoManifestRequestHandlerPlugin.d.ts.map +0 -1
  330. package/types/transformer/metroNativeWorker.test.d.ts +0 -2
  331. package/types/transformer/metroNativeWorker.test.d.ts.map +0 -1
  332. package/types/transformer/transformSync.test.d.ts +0 -2
  333. package/types/transformer/transformSync.test.d.ts.map +0 -1
  334. package/types/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.d.ts +0 -5
  335. package/types/utils/patchExpoGoManifestHandlerMiddlewareWithCustomMainModuleName.d.ts.map +0 -1
@@ -6,1526 +6,1477 @@ import { parseSync } from "oxc-parser";
6
6
  import MagicString from "magic-string";
7
7
  import remapping from "@jridgewell/remapping";
8
8
  import { TraceMap, eachMapping } from "@jridgewell/trace-mapping";
9
- import { shouldStripFlow, transformHermesAsync, transformHermesLoops, transformReactNativeCodegen } from "@vxrn/compiler";
9
+ import { shouldStripFlow, stripFlowTypes, transformHermesAsync, transformHermesLoops, transformReactNativeCodegen } from "@vxrn/compiler";
10
+ import { withExpoPublicEnvAliases } from "@vxrn/utils/publicEnv";
11
+ import { substituteExpoVirtualEnvSource } from "./expoVirtualEnv.mjs";
10
12
  import { getPlatformEnv, metroPlatformToViteEnvironment } from "../env/platformEnv.mjs";
13
+
11
14
  function collectModuleLiteralBindings(program) {
12
- const reassigned = /* @__PURE__ */new Set();
13
- const declCount = /* @__PURE__ */new Map();
14
- (function findReassignments(node) {
15
- if (!node || typeof node !== "object") return;
16
- if (Array.isArray(node)) {
17
- for (const child of node) findReassignments(child);
18
- return;
19
- }
20
- if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
21
- reassigned.add(node.left.name);
22
- } else if (node.type === "UpdateExpression" && node.argument?.type === "Identifier") {
23
- reassigned.add(node.argument.name);
24
- }
25
- for (const key in node) {
26
- if (key === "type" || key === "start" || key === "end") continue;
27
- findReassignments(node[key]);
28
- }
29
- })(program);
30
- for (const stmt of program.body || []) {
31
- if (stmt.type !== "VariableDeclaration") continue;
32
- for (const decl of stmt.declarations || []) {
33
- if (decl.id?.type === "Identifier") {
34
- declCount.set(decl.id.name, (declCount.get(decl.id.name) || 0) + 1);
35
- }
36
- }
37
- }
38
- const bindings = /* @__PURE__ */new Map();
39
- for (const stmt of program.body || []) {
40
- if (stmt.type !== "VariableDeclaration") continue;
41
- for (const decl of stmt.declarations || []) {
42
- if (decl.id?.type === "Identifier" && decl.init?.type === "Literal" && !reassigned.has(decl.id.name) && declCount.get(decl.id.name) === 1) {
43
- bindings.set(decl.id.name, decl.init);
44
- }
45
- }
46
- }
47
- return bindings;
15
+ const reassigned = /* @__PURE__ */ new Set();
16
+ const declCount = /* @__PURE__ */ new Map();
17
+ (function findReassignments(node) {
18
+ if (!node || typeof node !== "object") return;
19
+ if (Array.isArray(node)) {
20
+ for (const child of node) findReassignments(child);
21
+ return;
22
+ }
23
+ if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
24
+ reassigned.add(node.left.name);
25
+ } else if (node.type === "UpdateExpression" && node.argument?.type === "Identifier") {
26
+ reassigned.add(node.argument.name);
27
+ }
28
+ for (const key in node) {
29
+ if (key === "type" || key === "start" || key === "end") continue;
30
+ findReassignments(node[key]);
31
+ }
32
+ })(program);
33
+ for (const stmt of program.body || []) {
34
+ if (stmt.type !== "VariableDeclaration") continue;
35
+ for (const decl of stmt.declarations || []) {
36
+ if (decl.id?.type === "Identifier") {
37
+ declCount.set(decl.id.name, (declCount.get(decl.id.name) || 0) + 1);
38
+ }
39
+ }
40
+ }
41
+ const bindings = /* @__PURE__ */ new Map();
42
+ for (const stmt of program.body || []) {
43
+ if (stmt.type !== "VariableDeclaration") continue;
44
+ for (const decl of stmt.declarations || []) {
45
+ if (decl.id?.type === "Identifier" && decl.init?.type === "Literal" && !reassigned.has(decl.id.name) && declCount.get(decl.id.name) === 1) {
46
+ bindings.set(decl.id.name, decl.init);
47
+ }
48
+ }
49
+ }
50
+ return bindings;
48
51
  }
49
52
  const WORKER_CACHE_KEY_VERSION = "5";
50
53
  function langForFilename(filename) {
51
- if (filename.endsWith(".tsx")) return "tsx";
52
- if (filename.endsWith(".ts")) return "ts";
53
- return "jsx";
54
+ if (filename.endsWith(".tsx")) return "tsx";
55
+ if (filename.endsWith(".ts")) return "ts";
56
+ return "jsx";
54
57
  }
55
58
  function getOneRouterMetroOptions(options) {
56
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
57
- if (!Array.isArray(plugins)) return void 0;
58
- for (const plugin of plugins) {
59
- if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("one-router-metro")) {
60
- return plugin[1];
61
- }
62
- }
63
- return void 0;
59
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
60
+ if (!Array.isArray(plugins)) return void 0;
61
+ for (const plugin of plugins) {
62
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("one-router-metro")) {
63
+ return plugin[1];
64
+ }
65
+ }
66
+ return void 0;
64
67
  }
65
68
  function getRemoveServerCodeRouterRoot(options) {
66
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
67
- if (!Array.isArray(plugins)) return void 0;
68
- for (const plugin of plugins) {
69
- if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("remove-server-code")) {
70
- return plugin[1]?.routerRoot ?? "app";
71
- }
72
- }
73
- return void 0;
69
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
70
+ if (!Array.isArray(plugins)) return void 0;
71
+ for (const plugin of plugins) {
72
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("remove-server-code")) {
73
+ return plugin[1]?.routerRoot ?? "app";
74
+ }
75
+ }
76
+ return void 0;
74
77
  }
75
- const importMetaEnvCache = /* @__PURE__ */new WeakMap();
78
+ const importMetaEnvCache = /* @__PURE__ */ new WeakMap();
76
79
  function getImportMetaEnv(options) {
77
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
78
- const platform = options.platform ?? "";
79
- let byPlatform = Array.isArray(plugins) ? importMetaEnvCache.get(plugins) : void 0;
80
- const cached = byPlatform?.get(platform);
81
- if (cached) return cached;
82
- let env = {};
83
- if (Array.isArray(plugins)) {
84
- for (const plugin of plugins) {
85
- if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("import-meta-env-plugin")) {
86
- const found = plugin[1]?.env;
87
- if (found && typeof found === "object") env = found;
88
- }
89
- }
90
- }
91
- const merged = {
92
- ...env,
93
- ...getPlatformEnv(metroPlatformToViteEnvironment(options.platform))
94
- };
95
- if (Array.isArray(plugins)) {
96
- if (!byPlatform) {
97
- byPlatform = /* @__PURE__ */new Map();
98
- importMetaEnvCache.set(plugins, byPlatform);
99
- }
100
- byPlatform.set(platform, merged);
101
- }
102
- return merged;
80
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
81
+ const platform = options.platform ?? "";
82
+ let byPlatform = Array.isArray(plugins) ? importMetaEnvCache.get(plugins) : void 0;
83
+ const cached = byPlatform?.get(platform);
84
+ if (cached) return cached;
85
+ let env = {};
86
+ if (Array.isArray(plugins)) {
87
+ for (const plugin of plugins) {
88
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("import-meta-env-plugin")) {
89
+ const found = plugin[1]?.env;
90
+ if (found && typeof found === "object") env = found;
91
+ }
92
+ }
93
+ }
94
+ const merged = {
95
+ ...env,
96
+ ...getPlatformEnv(metroPlatformToViteEnvironment(options.platform))
97
+ };
98
+ if (Array.isArray(plugins)) {
99
+ if (!byPlatform) {
100
+ byPlatform = /* @__PURE__ */ new Map();
101
+ importMetaEnvCache.set(plugins, byPlatform);
102
+ }
103
+ byPlatform.set(platform, merged);
104
+ }
105
+ return merged;
103
106
  }
104
- const PORTED_BABEL_PLUGINS = ["import-meta-env-plugin", "one-router-metro", "remove-server-code", "module-resolver", "environment-guard", "inline-one-server-url",
105
- // the worklets transform is a native oxc port, so both plugin names it can
106
- // arrive under are covered.
107
- "react-native-worklets/plugin", "react-native-reanimated/plugin", "babel-plugin-react-compiler"];
108
- const unportedPluginCache = /* @__PURE__ */new WeakMap();
109
- const loadedNativeTransforms = /* @__PURE__ */new Map();
107
+ const PORTED_BABEL_PLUGINS = [
108
+ "import-meta-env-plugin",
109
+ "one-router-metro",
110
+ "remove-server-code",
111
+ "module-resolver",
112
+ "environment-guard",
113
+ "inline-one-server-url",
114
+ "react-native-worklets/plugin",
115
+ "react-native-reanimated/plugin",
116
+ "babel-plugin-react-compiler"
117
+ ];
118
+ const unportedPluginCache = /* @__PURE__ */ new WeakMap();
119
+ const loadedNativeTransforms = /* @__PURE__ */ new Map();
110
120
  function getNativeTransforms(options, projectRoot) {
111
- const ids = options.customTransformOptions?.vite?.nativeTransformModules;
112
- if (!Array.isArray(ids) || !ids.length) return [];
113
- const req = createRequire(path.join(projectRoot, "package.json"));
114
- return ids.map(id => {
115
- const cached = loadedNativeTransforms.get(id);
116
- if (cached) return cached;
117
- let mod;
118
- try {
119
- mod = req(id);
120
- } catch (err) {
121
- throw new Error(`[vxrn/metro] Could not load the native transform "${id}" from ${projectRoot}: ${err.message}`);
122
- }
123
- const fn = mod?.default ?? mod;
124
- if (typeof fn !== "function") {
125
- throw new Error(`[vxrn/metro] The native transform "${id}" must default-export a function (code, ctx) => string.`);
126
- }
127
- loadedNativeTransforms.set(id, fn);
128
- return fn;
129
- });
121
+ const ids = options.customTransformOptions?.vite?.nativeTransformModules;
122
+ if (!Array.isArray(ids) || !ids.length) return [];
123
+ const req = createRequire(path.join(projectRoot, "package.json"));
124
+ return ids.map((id) => {
125
+ const cached = loadedNativeTransforms.get(id);
126
+ if (cached) return cached;
127
+ let mod;
128
+ try {
129
+ mod = req(id);
130
+ } catch (err) {
131
+ throw new Error(`[vxrn/metro] Could not load the native transform "${id}" from ${projectRoot}: ${err.message}`);
132
+ }
133
+ const fn = mod?.default ?? mod;
134
+ if (typeof fn !== "function") {
135
+ throw new Error(`[vxrn/metro] The native transform "${id}" must default-export a function (code, ctx) => string.`);
136
+ }
137
+ loadedNativeTransforms.set(id, fn);
138
+ return fn;
139
+ });
130
140
  }
131
141
  function isReactCompilerCandidate(filename) {
132
- if (!/\.tsx?$/.test(filename)) return false;
133
- if (filename.includes("node_modules")) return false;
134
- if (filename.includes("+api.")) return false;
135
- return true;
142
+ if (!/\.tsx?$/.test(filename)) return false;
143
+ if (filename.includes("node_modules")) return false;
144
+ if (filename.includes("+api.")) return false;
145
+ return true;
136
146
  }
137
147
  function hasBabelPlugin(options, id) {
138
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
139
- if (!Array.isArray(plugins)) return false;
140
- return plugins.some(plugin => (Array.isArray(plugin) ? plugin[0] : plugin) === id);
148
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
149
+ if (!Array.isArray(plugins)) return false;
150
+ return plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === id);
141
151
  }
142
152
  function assertNoUnportedBabelPlugins(options) {
143
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
144
- if (!Array.isArray(plugins)) return;
145
- let unported = unportedPluginCache.get(plugins);
146
- if (!unported) {
147
- unported = [];
148
- for (const plugin of plugins) {
149
- const id = Array.isArray(plugin) ? plugin[0] : plugin;
150
- if (typeof id !== "string") {
151
- unported.push("(a function or object plugin, which cannot be ported)");
152
- continue;
153
- }
154
- if (!PORTED_BABEL_PLUGINS.some(ported => id.includes(ported))) {
155
- unported.push(id);
156
- }
157
- }
158
- unportedPluginCache.set(plugins, unported);
159
- }
160
- if (unported.length) {
161
- throw new Error(`[vxrn/metro] the native transform path runs no babel, so these babel plugins would be silently ignored:
162
- ` + unported.map(id => ` - ${id}`).join("\n") + `
153
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
154
+ if (!Array.isArray(plugins)) return;
155
+ let unported = unportedPluginCache.get(plugins);
156
+ if (!unported) {
157
+ unported = [];
158
+ for (const plugin of plugins) {
159
+ const id = Array.isArray(plugin) ? plugin[0] : plugin;
160
+ if (typeof id !== "string") {
161
+ unported.push("(a function or object plugin, which cannot be ported)");
162
+ continue;
163
+ }
164
+ if (!PORTED_BABEL_PLUGINS.some((ported) => id.includes(ported))) {
165
+ unported.push(id);
166
+ }
167
+ }
168
+ unportedPluginCache.set(plugins, unported);
169
+ }
170
+ if (unported.length) {
171
+ throw new Error(`[vxrn/metro] the native transform path runs no babel, so these babel plugins would be silently ignored:
172
+ ` + unported.map((id) => ` - ${id}`).join("\n") + `
163
173
 
164
174
  Port each one to a native transform and list it in bundlerOptions.nativeTransformModules, remove it from bundlerOptions.babelConfigOverrides, or set bundlerOptions.nativeTransforms: false (or ONE_METRO_NATIVE_TRANSFORMS=0) to go back to the babel transformer.`);
165
- }
175
+ }
166
176
  }
167
177
  function getModuleResolverAliases(options) {
168
- const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
169
- if (!Array.isArray(plugins)) return void 0;
170
- for (const plugin of plugins) {
171
- if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("module-resolver")) {
172
- const alias = plugin[1]?.alias;
173
- if (alias && typeof alias === "object") return alias;
174
- }
175
- }
176
- return void 0;
178
+ const plugins = options.customTransformOptions?.vite?.babelConfig?.plugins;
179
+ if (!Array.isArray(plugins)) return void 0;
180
+ for (const plugin of plugins) {
181
+ if (Array.isArray(plugin) && typeof plugin[0] === "string" && plugin[0].includes("module-resolver")) {
182
+ const alias = plugin[1]?.alias;
183
+ if (alias && typeof alias === "object") return alias;
184
+ }
185
+ }
186
+ return void 0;
177
187
  }
178
188
  function resolveAliasSpecifier(specifier, filename, projectRoot, aliases) {
179
- for (const [rawKey, value] of Object.entries(aliases)) {
180
- let target;
181
- if (rawKey.endsWith("$")) {
182
- if (specifier === rawKey.slice(0, -1)) target = value;
183
- } else if (specifier === rawKey || specifier.startsWith(`${rawKey}/`)) {
184
- target = value + specifier.slice(rawKey.length);
185
- }
186
- if (target === void 0) continue;
187
- const abs = path.resolve(projectRoot, target);
188
- let rel = path.relative(path.dirname(filename), abs).split(path.sep).join("/");
189
- if (!rel.startsWith(".")) rel = `./${rel}`;
190
- return rel;
191
- }
192
- return void 0;
189
+ for (const [rawKey, value] of Object.entries(aliases)) {
190
+ let target;
191
+ if (rawKey.endsWith("$")) {
192
+ if (specifier === rawKey.slice(0, -1)) target = value;
193
+ } else if (specifier === rawKey || specifier.startsWith(`${rawKey}/`)) {
194
+ target = value + specifier.slice(rawKey.length);
195
+ }
196
+ if (target === void 0) continue;
197
+ const abs = path.resolve(projectRoot, target);
198
+ let rel = path.relative(path.dirname(filename), abs).split(path.sep).join("/");
199
+ if (!rel.startsWith(".")) rel = `./${rel}`;
200
+ return rel;
201
+ }
202
+ return void 0;
193
203
  }
194
204
  function applyModuleResolverAliases(code, filename, projectRoot, aliases) {
195
- const parsed = parseSync(filename, code, {
196
- lang: langForFilename(filename)
197
- });
198
- if (parsed?.errors?.length) {
199
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for alias resolution: ${parsed.errors[0].message}`);
200
- }
201
- if (!parsed?.program) return code;
202
- const ms = new MagicString(code);
203
- let changed = false;
204
- function rewrite(sourceNode) {
205
- if (sourceNode?.type !== "Literal" || typeof sourceNode.value !== "string") return;
206
- const resolved = resolveAliasSpecifier(sourceNode.value, filename, projectRoot, aliases);
207
- if (resolved === void 0) return;
208
- ms.overwrite(sourceNode.start, sourceNode.end, JSON.stringify(resolved));
209
- changed = true;
210
- }
211
- function walk(node) {
212
- if (!node || typeof node !== "object") return;
213
- if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
214
- rewrite(node.source);
215
- } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
216
- rewrite(node.arguments?.[0]);
217
- }
218
- for (const k of Object.keys(node)) {
219
- if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
220
- const child = node[k];
221
- if (Array.isArray(child)) {
222
- for (const item of child) walk(item);
223
- } else if (child && typeof child === "object") {
224
- walk(child);
225
- }
226
- }
227
- }
228
- walk(parsed.program);
229
- return changed ? ms.toString() : code;
205
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) });
206
+ if (parsed?.errors?.length) {
207
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for alias resolution: ${parsed.errors[0].message}`);
208
+ }
209
+ if (!parsed?.program) return code;
210
+ const ms = new MagicString(code);
211
+ let changed = false;
212
+ function rewrite(sourceNode) {
213
+ if (sourceNode?.type !== "Literal" || typeof sourceNode.value !== "string") return;
214
+ const resolved = resolveAliasSpecifier(sourceNode.value, filename, projectRoot, aliases);
215
+ if (resolved === void 0) return;
216
+ ms.overwrite(sourceNode.start, sourceNode.end, JSON.stringify(resolved));
217
+ changed = true;
218
+ }
219
+ function walk(node) {
220
+ if (!node || typeof node !== "object") return;
221
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ImportExpression") {
222
+ rewrite(node.source);
223
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
224
+ rewrite(node.arguments?.[0]);
225
+ }
226
+ for (const k of Object.keys(node)) {
227
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
228
+ const child = node[k];
229
+ if (Array.isArray(child)) {
230
+ for (const item of child) walk(item);
231
+ } else if (child && typeof child === "object") {
232
+ walk(child);
233
+ }
234
+ }
235
+ }
236
+ walk(parsed.program);
237
+ return changed ? ms.toString() : code;
230
238
  }
231
239
  function applyInlineEnvVars(code, filename, isProduction, env = {}) {
232
- const parsed = parseSync(filename, code, {
233
- lang: langForFilename(filename)
234
- });
235
- if (parsed?.errors?.length) {
236
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for env inlining: ${parsed.errors[0].message}`);
237
- }
238
- if (!parsed?.program) return code;
239
- const ms = new MagicString(code);
240
- let needsEnvImport = false;
241
- const edits = [];
242
- const known = /* @__PURE__ */new Map();
243
- function replace(node, value) {
244
- const text = value === void 0 ? "undefined" : JSON.stringify(value);
245
- edits.push({
246
- start: node.start,
247
- end: node.end,
248
- text
249
- });
250
- known.set(node, value);
251
- }
252
- function keyOf(prop, computed) {
253
- if (!computed && prop?.type === "Identifier") return prop.name;
254
- if (prop?.type === "Literal" && typeof prop.value === "string") return prop.value;
255
- return void 0;
256
- }
257
- function isImportMeta(node) {
258
- return node?.type === "MetaProperty" && node.meta?.name === "import" && node.property?.name === "meta";
259
- }
260
- function walk(node, parent) {
261
- if (!node || typeof node !== "object") return;
262
- if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
263
- const obj = node.object;
264
- const isMember = obj?.type === "MemberExpression" || obj?.type === "OptionalMemberExpression";
265
- const isProcessEnv = isMember && obj.object?.type === "Identifier" && obj.object.name === "process" && keyOf(obj.property, obj.computed) === "env";
266
- const isAssignmentTarget = parent?.type === "AssignmentExpression" && parent.left === node;
267
- const key = keyOf(node.property, node.computed);
268
- if (isProcessEnv && !isAssignmentTarget && key === "ONE_SERVER_URL") {
269
- replace(node, process.env.ONE_SERVER_URL || "");
270
- return;
271
- }
272
- if (isProcessEnv && !isAssignmentTarget && key?.startsWith("EXPO_PUBLIC_")) {
273
- if (isProduction) {
274
- replace(node, process.env[key] ?? void 0);
275
- } else {
276
- edits.push({
277
- start: node.start,
278
- end: node.end,
279
- text: `_$$_EXPO_ENV.${key}`
280
- });
281
- needsEnvImport = true;
282
- }
283
- return;
284
- }
285
- if (!isAssignmentTarget && isMember && isImportMeta(obj.object) && keyOf(obj.property, obj.computed) === "env" && key !== void 0) {
286
- replace(node, env[key]);
287
- return;
288
- }
289
- if (!isAssignmentTarget && isImportMeta(obj) && key === "env") {
290
- edits.push({
291
- start: node.start,
292
- end: node.end,
293
- text: JSON.stringify(env)
294
- });
295
- return;
296
- }
297
- if (isProcessEnv && !isAssignmentTarget && key !== void 0 && key in env) {
298
- replace(node, env[key]);
299
- return;
300
- }
301
- }
302
- for (const k of Object.keys(node)) {
303
- if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
304
- const child = node[k];
305
- if (Array.isArray(child)) {
306
- for (const item of child) walk(item, node);
307
- } else if (child && typeof child === "object") {
308
- walk(child, node);
309
- }
310
- }
311
- }
312
- walk(parsed.program, null);
313
- function testValue(node) {
314
- if (known.has(node)) return !!known.get(node);
315
- if (node?.type === "UnaryExpression" && node.operator === "!") {
316
- const inner = testValue(node.argument);
317
- return inner === void 0 ? void 0 : !inner;
318
- }
319
- if (node?.type === "BinaryExpression" && (node.operator === "===" || node.operator === "!==")) {
320
- const left = known.has(node.left) ? known.get(node.left) : void 0;
321
- const right = node.right?.type === "Literal" ? node.right.value : void 0;
322
- if (!known.has(node.left) || node.right?.type !== "Literal") return void 0;
323
- return node.operator === "===" ? left === right : left !== right;
324
- }
325
- return void 0;
326
- }
327
- const dead = [];
328
- (function foldWalk(node) {
329
- if (!node || typeof node !== "object") return;
330
- if (Array.isArray(node)) {
331
- for (const child of node) foldWalk(child);
332
- return;
333
- }
334
- if (node.type === "IfStatement" || node.type === "ConditionalExpression") {
335
- const value = testValue(node.test);
336
- if (value !== void 0) {
337
- const kept = value ? node.consequent : node.alternate;
338
- if (!kept) {
339
- dead.push({
340
- start: node.start,
341
- end: node.end,
342
- text: ";"
343
- });
344
- return;
345
- }
346
- dead.push({
347
- start: node.start,
348
- end: kept.start,
349
- text: ""
350
- });
351
- if (kept.end < node.end) {
352
- dead.push({
353
- start: kept.end,
354
- end: node.end,
355
- text: ""
356
- });
357
- }
358
- foldWalk(kept);
359
- return;
360
- }
361
- }
362
- for (const k of Object.keys(node)) {
363
- if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
364
- foldWalk(node[k]);
365
- }
366
- })(parsed.program);
367
- for (const range of dead) {
368
- ms.overwrite(range.start, range.end, range.text);
369
- }
370
- for (const edit of edits) {
371
- if (dead.some(d => edit.start >= d.start && edit.end <= d.end)) continue;
372
- ms.overwrite(edit.start, edit.end, edit.text);
373
- }
374
- if (needsEnvImport) {
375
- ms.prepend(`import { env as _$$_EXPO_ENV } from "expo/virtual/env";
376
- `);
377
- }
378
- return ms.hasChanged() ? ms.toString() : code;
240
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) });
241
+ if (parsed?.errors?.length) {
242
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for env inlining: ${parsed.errors[0].message}`);
243
+ }
244
+ if (!parsed?.program) return code;
245
+ const processPublicEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith("ONE_PUBLIC_") || key.startsWith("EXPO_PUBLIC_")));
246
+ const effectiveEnv = withExpoPublicEnvAliases({
247
+ ...processPublicEnv,
248
+ ...env
249
+ });
250
+ const ms = new MagicString(code);
251
+ const edits = [];
252
+ const known = /* @__PURE__ */ new Map();
253
+ function replace(node, value) {
254
+ const text = value === void 0 ? "undefined" : JSON.stringify(value);
255
+ edits.push({
256
+ start: node.start,
257
+ end: node.end,
258
+ text
259
+ });
260
+ known.set(node, value);
261
+ }
262
+ function keyOf(prop, computed) {
263
+ if (!computed && prop?.type === "Identifier") return prop.name;
264
+ if (prop?.type === "Literal" && typeof prop.value === "string") return prop.value;
265
+ return void 0;
266
+ }
267
+ function isImportMeta(node) {
268
+ return node?.type === "MetaProperty" && node.meta?.name === "import" && node.property?.name === "meta";
269
+ }
270
+ function walk(node, parent) {
271
+ if (!node || typeof node !== "object") return;
272
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
273
+ const obj = node.object;
274
+ const isMember = obj?.type === "MemberExpression" || obj?.type === "OptionalMemberExpression";
275
+ const isProcessEnv = isMember && obj.object?.type === "Identifier" && obj.object.name === "process" && keyOf(obj.property, obj.computed) === "env";
276
+ const isAssignmentTarget = parent?.type === "AssignmentExpression" && parent.left === node;
277
+ const key = keyOf(node.property, node.computed);
278
+ if (isProcessEnv && !isAssignmentTarget && key === "ONE_SERVER_URL") {
279
+ replace(node, process.env.ONE_SERVER_URL || "");
280
+ return;
281
+ }
282
+ if (isProcessEnv && !isAssignmentTarget && (key?.startsWith("ONE_PUBLIC_") || key?.startsWith("EXPO_PUBLIC_"))) {
283
+ replace(node, effectiveEnv[key] ?? void 0);
284
+ return;
285
+ }
286
+ if (!isAssignmentTarget && isMember && isImportMeta(obj.object) && keyOf(obj.property, obj.computed) === "env" && key !== void 0) {
287
+ replace(node, effectiveEnv[key]);
288
+ return;
289
+ }
290
+ if (!isAssignmentTarget && isImportMeta(obj) && key === "env") {
291
+ edits.push({
292
+ start: node.start,
293
+ end: node.end,
294
+ text: JSON.stringify(effectiveEnv)
295
+ });
296
+ return;
297
+ }
298
+ if (isProcessEnv && !isAssignmentTarget && key !== void 0 && key in effectiveEnv) {
299
+ replace(node, effectiveEnv[key]);
300
+ return;
301
+ }
302
+ }
303
+ for (const k of Object.keys(node)) {
304
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
305
+ const child = node[k];
306
+ if (Array.isArray(child)) {
307
+ for (const item of child) walk(item, node);
308
+ } else if (child && typeof child === "object") {
309
+ walk(child, node);
310
+ }
311
+ }
312
+ }
313
+ walk(parsed.program, null);
314
+ function testValue(node) {
315
+ if (known.has(node)) return !!known.get(node);
316
+ if (node?.type === "UnaryExpression" && node.operator === "!") {
317
+ const inner = testValue(node.argument);
318
+ return inner === void 0 ? void 0 : !inner;
319
+ }
320
+ if (node?.type === "BinaryExpression" && (node.operator === "===" || node.operator === "!==")) {
321
+ const left = known.has(node.left) ? known.get(node.left) : void 0;
322
+ const right = node.right?.type === "Literal" ? node.right.value : void 0;
323
+ if (!known.has(node.left) || node.right?.type !== "Literal") return void 0;
324
+ return node.operator === "===" ? left === right : left !== right;
325
+ }
326
+ return void 0;
327
+ }
328
+ const dead = [];
329
+ (function foldWalk(node) {
330
+ if (!node || typeof node !== "object") return;
331
+ if (Array.isArray(node)) {
332
+ for (const child of node) foldWalk(child);
333
+ return;
334
+ }
335
+ if (node.type === "IfStatement" || node.type === "ConditionalExpression") {
336
+ const value = testValue(node.test);
337
+ if (value !== void 0) {
338
+ const kept = value ? node.consequent : node.alternate;
339
+ if (!kept) {
340
+ dead.push({
341
+ start: node.start,
342
+ end: node.end,
343
+ text: ";"
344
+ });
345
+ return;
346
+ }
347
+ dead.push({
348
+ start: node.start,
349
+ end: kept.start,
350
+ text: ""
351
+ });
352
+ if (kept.end < node.end) {
353
+ dead.push({
354
+ start: kept.end,
355
+ end: node.end,
356
+ text: ""
357
+ });
358
+ }
359
+ foldWalk(kept);
360
+ return;
361
+ }
362
+ }
363
+ for (const k of Object.keys(node)) {
364
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
365
+ foldWalk(node[k]);
366
+ }
367
+ })(parsed.program);
368
+ for (const range of dead) {
369
+ ms.overwrite(range.start, range.end, range.text);
370
+ }
371
+ for (const edit of edits) {
372
+ if (dead.some((d) => edit.start >= d.start && edit.end <= d.end)) continue;
373
+ ms.overwrite(edit.start, edit.end, edit.text);
374
+ }
375
+ return ms.hasChanged() ? ms.toString() : code;
379
376
  }
380
- const GUARD_SPECIFIERS = /* @__PURE__ */new Set(["server-only", "client-only", "web-only"]);
377
+ const GUARD_SPECIFIERS = /* @__PURE__ */ new Set([
378
+ "server-only",
379
+ "client-only",
380
+ "web-only"
381
+ ]);
381
382
  function applyEnvironmentGuard(code, filename) {
382
- const parsed = parseSync(filename, code, {
383
- lang: langForFilename(filename)
384
- });
385
- if (parsed?.errors?.length) {
386
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for environment guards: ${parsed.errors[0].message}`);
387
- }
388
- const body = parsed?.program?.body;
389
- if (!body) return code;
390
- const ms = new MagicString(code);
391
- let changed = false;
392
- for (const node of body) {
393
- if (node.type !== "ImportDeclaration") continue;
394
- const source = node.source?.value;
395
- if (source === "native-only") {
396
- ms.remove(node.start, node.end);
397
- changed = true;
398
- } else if (GUARD_SPECIFIERS.has(source)) {
399
- ms.overwrite(node.start, node.end, `throw new Error(${JSON.stringify(`${source} cannot be imported in a native environment`)});`);
400
- changed = true;
401
- }
402
- }
403
- return changed ? ms.toString() : code;
383
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) });
384
+ if (parsed?.errors?.length) {
385
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for environment guards: ${parsed.errors[0].message}`);
386
+ }
387
+ const body = parsed?.program?.body;
388
+ if (!body) return code;
389
+ const ms = new MagicString(code);
390
+ let changed = false;
391
+ for (const node of body) {
392
+ if (node.type !== "ImportDeclaration") continue;
393
+ const source = node.source?.value;
394
+ if (source === "native-only") {
395
+ ms.remove(node.start, node.end);
396
+ changed = true;
397
+ } else if (GUARD_SPECIFIERS.has(source)) {
398
+ ms.overwrite(node.start, node.end, `throw new Error(${JSON.stringify(`${source} cannot be imported in a native environment`)});`);
399
+ changed = true;
400
+ }
401
+ }
402
+ return changed ? ms.toString() : code;
404
403
  }
405
404
  function applyOneRouterMetro(code, filename, options) {
406
- const isMetroEntry = filename.endsWith("metro-entry.js");
407
- const isEntryCtx = filename.endsWith("metro-entry-ctx.js");
408
- if (!isMetroEntry && !isEntryCtx) return code;
409
- const parsed = parseSync(filename, code, {
410
- lang: langForFilename(filename)
411
- });
412
- if (parsed?.errors?.length) {
413
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for one-router-metro: ${parsed.errors[0].message}`);
414
- }
415
- if (!parsed?.program) return code;
416
- const ms = new MagicString(code);
417
- let lastImportEnd = -1;
418
- function replacementFor(key) {
419
- if (key.startsWith("ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY")) {
420
- return JSON.stringify(options.ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY);
421
- }
422
- if (key.startsWith("ONE_ROUTER_ROOT_FOLDER_NAME")) {
423
- return JSON.stringify(options.ONE_ROUTER_ROOT_FOLDER_NAME);
424
- }
425
- if (key.startsWith("ONE_ROUTER_REQUIRE_CONTEXT_REGEX")) {
426
- return `/${options.ONE_ROUTER_REQUIRE_CONTEXT_REGEX_STRING}/`;
427
- }
428
- if (key === "ONE_ROUTER_LINKING_CONFIG") {
429
- return isMetroEntry ? JSON.stringify(options.ONE_ROUTER_LINKING_CONFIG ?? null) : void 0;
430
- }
431
- if (key === "ONE_SETUP_FILE_NATIVE") {
432
- return options.ONE_SETUP_FILE_NATIVE ? JSON.stringify(options.ONE_SETUP_FILE_NATIVE) : "undefined";
433
- }
434
- return void 0;
435
- }
436
- function walk(node, parent) {
437
- if (!node || typeof node !== "object") return;
438
- if (node.type === "ImportDeclaration" && parent === parsed.program) {
439
- lastImportEnd = Math.max(lastImportEnd, node.end);
440
- }
441
- if (node.type === "MemberExpression" && node.object?.type === "MemberExpression" && !node.object.computed && node.object.object?.type === "Identifier" && node.object.object.name === "process" && node.object.property?.type === "Identifier" && node.object.property.name === "env") {
442
- const key = node.computed ? node.property?.type === "Literal" && typeof node.property.value === "string" ? node.property.value : void 0 : node.property?.type === "Identifier" ? node.property.name : void 0;
443
- const isAssignTarget = parent?.type === "AssignmentExpression" && parent.left === node;
444
- if (key && !isAssignTarget) {
445
- const replacement = replacementFor(key);
446
- if (replacement !== void 0) {
447
- ms.overwrite(node.start, node.end, replacement);
448
- }
449
- }
450
- }
451
- for (const k of Object.keys(node)) {
452
- if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
453
- const child = node[k];
454
- if (Array.isArray(child)) {
455
- for (const item of child) walk(item, node);
456
- } else if (child && typeof child === "object") {
457
- walk(child, node);
458
- }
459
- }
460
- }
461
- walk(parsed.program, parsed.program);
462
- if (isMetroEntry && options.ONE_SETUP_FILE_NATIVE) {
463
- const stmt = `
405
+ const isMetroEntry = filename.endsWith("metro-entry.js");
406
+ const isEntryCtx = filename.endsWith("metro-entry-ctx.js");
407
+ if (!isMetroEntry && !isEntryCtx) return code;
408
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) });
409
+ if (parsed?.errors?.length) {
410
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for one-router-metro: ${parsed.errors[0].message}`);
411
+ }
412
+ if (!parsed?.program) return code;
413
+ const ms = new MagicString(code);
414
+ let lastImportEnd = -1;
415
+ function replacementFor(key) {
416
+ if (key.startsWith("ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY")) {
417
+ return JSON.stringify(options.ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY);
418
+ }
419
+ if (key.startsWith("ONE_ROUTER_ROOT_FOLDER_NAME")) {
420
+ return JSON.stringify(options.ONE_ROUTER_ROOT_FOLDER_NAME);
421
+ }
422
+ if (key.startsWith("ONE_ROUTER_REQUIRE_CONTEXT_REGEX")) {
423
+ return `/${options.ONE_ROUTER_REQUIRE_CONTEXT_REGEX_STRING}/`;
424
+ }
425
+ if (key === "ONE_ROUTER_LINKING_CONFIG") {
426
+ return isMetroEntry ? JSON.stringify(options.ONE_ROUTER_LINKING_CONFIG ?? null) : void 0;
427
+ }
428
+ if (key === "ONE_SETUP_FILE_NATIVE") {
429
+ return options.ONE_SETUP_FILE_NATIVE ? JSON.stringify(options.ONE_SETUP_FILE_NATIVE) : "undefined";
430
+ }
431
+ return void 0;
432
+ }
433
+ function walk(node, parent) {
434
+ if (!node || typeof node !== "object") return;
435
+ if (node.type === "ImportDeclaration" && parent === parsed.program) {
436
+ lastImportEnd = Math.max(lastImportEnd, node.end);
437
+ }
438
+ if (node.type === "MemberExpression" && node.object?.type === "MemberExpression" && !node.object.computed && node.object.object?.type === "Identifier" && node.object.object.name === "process" && node.object.property?.type === "Identifier" && node.object.property.name === "env") {
439
+ const key = node.computed ? node.property?.type === "Literal" && typeof node.property.value === "string" ? node.property.value : void 0 : node.property?.type === "Identifier" ? node.property.name : void 0;
440
+ const isAssignTarget = parent?.type === "AssignmentExpression" && parent.left === node;
441
+ if (key && !isAssignTarget) {
442
+ const replacement = replacementFor(key);
443
+ if (replacement !== void 0) {
444
+ ms.overwrite(node.start, node.end, replacement);
445
+ }
446
+ }
447
+ }
448
+ for (const k of Object.keys(node)) {
449
+ if (k === "start" || k === "end" || k === "loc" || k === "range" || k === "parent" || k === "comments") continue;
450
+ const child = node[k];
451
+ if (Array.isArray(child)) {
452
+ for (const item of child) walk(item, node);
453
+ } else if (child && typeof child === "object") {
454
+ walk(child, node);
455
+ }
456
+ }
457
+ }
458
+ walk(parsed.program, parsed.program);
459
+ if (isMetroEntry && options.ONE_SETUP_FILE_NATIVE) {
460
+ const stmt = `
464
461
  import ${JSON.stringify(options.ONE_SETUP_FILE_NATIVE)};`;
465
- if (lastImportEnd >= 0) {
466
- ms.appendRight(lastImportEnd, stmt);
467
- } else {
468
- ms.prepend(`${stmt}
462
+ if (lastImportEnd >= 0) {
463
+ ms.appendRight(lastImportEnd, stmt);
464
+ } else {
465
+ ms.prepend(`${stmt}
469
466
  `);
470
- }
471
- }
472
- return ms.toString();
467
+ }
468
+ }
469
+ return ms.toString();
473
470
  }
474
471
  function collectPatternNames(pattern, names) {
475
- if (!pattern) return;
476
- if (pattern.type === "Identifier") {
477
- names.add(pattern.name);
478
- } else if (pattern.type === "AssignmentPattern") {
479
- collectPatternNames(pattern.left, names);
480
- } else if (pattern.type === "ObjectPattern") {
481
- for (const prop of pattern.properties || []) {
482
- if (prop.type === "Property") collectPatternNames(prop.value, names);else if (prop.type === "RestElement") collectPatternNames(prop.argument, names);
483
- }
484
- } else if (pattern.type === "ArrayPattern") {
485
- for (const elem of pattern.elements || []) {
486
- if (elem) collectPatternNames(elem, names);
487
- }
488
- } else if (pattern.type === "RestElement") {
489
- collectPatternNames(pattern.argument, names);
490
- }
472
+ if (!pattern) return;
473
+ if (pattern.type === "Identifier") {
474
+ names.add(pattern.name);
475
+ } else if (pattern.type === "AssignmentPattern") {
476
+ collectPatternNames(pattern.left, names);
477
+ } else if (pattern.type === "ObjectPattern") {
478
+ for (const prop of pattern.properties || []) {
479
+ if (prop.type === "Property") collectPatternNames(prop.value, names);
480
+ else if (prop.type === "RestElement") collectPatternNames(prop.argument, names);
481
+ }
482
+ } else if (pattern.type === "ArrayPattern") {
483
+ for (const elem of pattern.elements || []) {
484
+ if (elem) collectPatternNames(elem, names);
485
+ }
486
+ } else if (pattern.type === "RestElement") {
487
+ collectPatternNames(pattern.argument, names);
488
+ }
491
489
  }
492
490
  function collectHoistedBindings(node, names) {
493
- function traverse(n) {
494
- if (!n || typeof n !== "object") return;
495
- if (n === node) {} else if (n.type === "FunctionDeclaration" || n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression") {
496
- if (n.type === "FunctionDeclaration" && n.id?.name) {
497
- names.add(n.id.name);
498
- }
499
- return;
500
- }
501
- if (n.type === "VariableDeclaration" && n.kind === "var") {
502
- for (const decl of n.declarations || []) {
503
- collectPatternNames(decl.id, names);
504
- }
505
- }
506
- for (const key of Object.keys(n)) {
507
- if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
508
- const child = n[key];
509
- if (Array.isArray(child)) {
510
- for (const item of child) traverse(item);
511
- } else if (child && typeof child === "object") {
512
- traverse(child);
513
- }
514
- }
515
- }
516
- traverse(node);
491
+ function traverse(n) {
492
+ if (!n || typeof n !== "object") return;
493
+ if (n === node) {} else if (n.type === "FunctionDeclaration" || n.type === "FunctionExpression" || n.type === "ArrowFunctionExpression") {
494
+ if (n.type === "FunctionDeclaration" && n.id?.name) {
495
+ names.add(n.id.name);
496
+ }
497
+ return;
498
+ }
499
+ if (n.type === "VariableDeclaration" && n.kind === "var") {
500
+ for (const decl of n.declarations || []) {
501
+ collectPatternNames(decl.id, names);
502
+ }
503
+ }
504
+ for (const key of Object.keys(n)) {
505
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
506
+ const child = n[key];
507
+ if (Array.isArray(child)) {
508
+ for (const item of child) traverse(item);
509
+ } else if (child && typeof child === "object") {
510
+ traverse(child);
511
+ }
512
+ }
513
+ }
514
+ traverse(node);
517
515
  }
518
516
  function collectBlockBindings(statements, names) {
519
- if (!Array.isArray(statements)) return;
520
- for (const stmt of statements) {
521
- if (!stmt) continue;
522
- if (stmt.type === "VariableDeclaration" && stmt.kind !== "var") {
523
- for (const decl of stmt.declarations || []) {
524
- collectPatternNames(decl.id, names);
525
- }
526
- } else if (stmt.type === "ClassDeclaration" && stmt.id?.name) {
527
- names.add(stmt.id.name);
528
- } else if (stmt.type === "FunctionDeclaration" && stmt.id?.name) {
529
- names.add(stmt.id.name);
530
- }
531
- }
532
- }
533
- class ScopeTracker {
534
- stack = [/* @__PURE__ */new Set()];
535
- enter(initialBindings) {
536
- this.stack.push(new Set(initialBindings));
537
- }
538
- exit() {
539
- if (this.stack.length > 1) {
540
- this.stack.pop();
541
- }
542
- }
543
- add(name) {
544
- this.stack[this.stack.length - 1].add(name);
545
- }
546
- currentScope() {
547
- return this.stack[this.stack.length - 1];
548
- }
549
- addPattern(pattern) {
550
- collectPatternNames(pattern, this.currentScope());
551
- }
552
- isShadowed(name) {
553
- for (let i = this.stack.length - 1; i >= 0; i--) {
554
- if (this.stack[i].has(name)) return true;
555
- }
556
- return false;
557
- }
517
+ if (!Array.isArray(statements)) return;
518
+ for (const stmt of statements) {
519
+ if (!stmt) continue;
520
+ if (stmt.type === "VariableDeclaration" && stmt.kind !== "var") {
521
+ for (const decl of stmt.declarations || []) {
522
+ collectPatternNames(decl.id, names);
523
+ }
524
+ } else if (stmt.type === "ClassDeclaration" && stmt.id?.name) {
525
+ names.add(stmt.id.name);
526
+ } else if (stmt.type === "FunctionDeclaration" && stmt.id?.name) {
527
+ names.add(stmt.id.name);
528
+ }
529
+ }
558
530
  }
531
+ var ScopeTracker = class {
532
+ stack = [/* @__PURE__ */ new Set()];
533
+ enter(initialBindings) {
534
+ this.stack.push(new Set(initialBindings));
535
+ }
536
+ exit() {
537
+ if (this.stack.length > 1) {
538
+ this.stack.pop();
539
+ }
540
+ }
541
+ add(name) {
542
+ this.stack[this.stack.length - 1].add(name);
543
+ }
544
+ currentScope() {
545
+ return this.stack[this.stack.length - 1];
546
+ }
547
+ addPattern(pattern) {
548
+ collectPatternNames(pattern, this.currentScope());
549
+ }
550
+ isShadowed(name) {
551
+ for (let i = this.stack.length - 1; i >= 0; i--) {
552
+ if (this.stack[i].has(name)) return true;
553
+ }
554
+ return false;
555
+ }
556
+ };
559
557
  function getCacheKey(config = {}, opts) {
560
- const hash = crypto.createHash("sha256");
561
- hash.update("metroNativeWorker");
562
- hash.update(WORKER_CACHE_KEY_VERSION);
563
- if (config.globalPrefix) {
564
- hash.update(config.globalPrefix);
565
- }
566
- if (config.unstable_dependencyMapReservedName) {
567
- hash.update(config.unstable_dependencyMapReservedName);
568
- }
569
- if (config.minifierPath) {
570
- hash.update(config.minifierPath);
571
- }
572
- if (opts?.projectRoot) {
573
- hash.update(opts.projectRoot);
574
- }
575
- return hash.digest("hex");
558
+ const hash = crypto.createHash("sha256");
559
+ hash.update("metroNativeWorker");
560
+ hash.update(WORKER_CACHE_KEY_VERSION);
561
+ if (config.globalPrefix) {
562
+ hash.update(config.globalPrefix);
563
+ }
564
+ if (config.unstable_dependencyMapReservedName) {
565
+ hash.update(config.unstable_dependencyMapReservedName);
566
+ }
567
+ if (config.minifierPath) {
568
+ hash.update(config.minifierPath);
569
+ }
570
+ if (opts?.projectRoot) {
571
+ hash.update(opts.projectRoot);
572
+ }
573
+ return hash.digest("hex");
576
574
  }
577
575
  function convertSourceMapToMetroRawMappings(composedMap) {
578
- if (!composedMap) return [];
579
- const tracer = new TraceMap(composedMap);
580
- const rawMappings = [];
581
- eachMapping(tracer, m => {
582
- if (m.originalLine == null) {
583
- rawMappings.push([m.generatedLine, m.generatedColumn]);
584
- } else if (m.name == null) {
585
- rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn]);
586
- } else {
587
- rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn, m.name]);
588
- }
589
- });
590
- rawMappings.sort((a, b) => {
591
- if (a[0] !== b[0]) return a[0] - b[0];
592
- return a[1] - b[1];
593
- });
594
- const deduped = [];
595
- for (const mapping of rawMappings) {
596
- const prev = deduped[deduped.length - 1];
597
- if (prev && prev[0] === mapping[0] && prev[1] === mapping[1]) {
598
- continue;
599
- }
600
- deduped.push(mapping);
601
- }
602
- return deduped;
576
+ if (!composedMap) return [];
577
+ const tracer = new TraceMap(composedMap);
578
+ const rawMappings = [];
579
+ eachMapping(tracer, (m) => {
580
+ if (m.originalLine == null) {
581
+ rawMappings.push([m.generatedLine, m.generatedColumn]);
582
+ } else if (m.name == null) {
583
+ rawMappings.push([
584
+ m.generatedLine,
585
+ m.generatedColumn,
586
+ m.originalLine,
587
+ m.originalColumn
588
+ ]);
589
+ } else {
590
+ rawMappings.push([
591
+ m.generatedLine,
592
+ m.generatedColumn,
593
+ m.originalLine,
594
+ m.originalColumn,
595
+ m.name
596
+ ]);
597
+ }
598
+ });
599
+ rawMappings.sort((a, b) => {
600
+ if (a[0] !== b[0]) return a[0] - b[0];
601
+ return a[1] - b[1];
602
+ });
603
+ const deduped = [];
604
+ for (const mapping of rawMappings) {
605
+ const prev = deduped[deduped.length - 1];
606
+ if (prev && prev[0] === mapping[0] && prev[1] === mapping[1]) {
607
+ continue;
608
+ }
609
+ deduped.push(mapping);
610
+ }
611
+ return deduped;
603
612
  }
604
613
  function countLinesAndTerminateMap(code, map = []) {
605
- const NEWLINE = /\r\n?|\n|\u2028|\u2029/g;
606
- let lineCount = 1;
607
- let lastLineStart = 0;
608
- for (const match of code.matchAll(NEWLINE)) {
609
- lineCount++;
610
- lastLineStart = match.index + match[0].length;
611
- }
612
- const lastLineLength = code.length - lastLineStart;
613
- const lastLineIndex1Based = lineCount;
614
- const lastLineNextColumn0Based = lastLineLength;
615
- const lastMapping = map[map.length - 1];
616
- const terminatingMapping = [lastLineIndex1Based, lastLineNextColumn0Based];
617
- if (!lastMapping || lastMapping[0] !== terminatingMapping[0] || lastMapping[1] !== terminatingMapping[1]) {
618
- return {
619
- lineCount,
620
- map: map.concat([terminatingMapping])
621
- };
622
- }
623
- return {
624
- lineCount,
625
- map: [...map]
626
- };
614
+ const NEWLINE = /\r\n?|\n|\u2028|\u2029/g;
615
+ let lineCount = 1;
616
+ let lastLineStart = 0;
617
+ for (const match of code.matchAll(NEWLINE)) {
618
+ lineCount++;
619
+ lastLineStart = match.index + match[0].length;
620
+ }
621
+ const lastLineLength = code.length - lastLineStart;
622
+ const lastLineIndex1Based = lineCount;
623
+ const lastLineNextColumn0Based = lastLineLength;
624
+ const lastMapping = map[map.length - 1];
625
+ const terminatingMapping = [lastLineIndex1Based, lastLineNextColumn0Based];
626
+ if (!lastMapping || lastMapping[0] !== terminatingMapping[0] || lastMapping[1] !== terminatingMapping[1]) {
627
+ return {
628
+ lineCount,
629
+ map: map.concat([terminatingMapping])
630
+ };
631
+ }
632
+ return {
633
+ lineCount,
634
+ map: [...map]
635
+ };
627
636
  }
628
637
  function wrapJson(source, options) {
629
- const globalPrefix = options?.globalPrefix || "";
630
- const factory = ["function (global, require, _importDefaultUnused, _importAllUnused, module, exports, _dependencyMapUnused) {", ` module.exports = ${source};`, "}"].join("\n");
631
- if (options?.moduleId !== void 0) {
632
- const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
633
- return `${globalPrefix}__d(${factory}, ${JSON.stringify(options.moduleId)}, ${depIds});`;
634
- }
635
- return `${globalPrefix}__d(${factory});`;
638
+ const globalPrefix = options?.globalPrefix || "";
639
+ const factory = [
640
+ "function (global, require, _importDefaultUnused, _importAllUnused, module, exports, _dependencyMapUnused) {",
641
+ ` module.exports = ${source};`,
642
+ "}"
643
+ ].join("\n");
644
+ if (options?.moduleId !== void 0) {
645
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
646
+ return `${globalPrefix}__d(${factory}, ${JSON.stringify(options.moduleId)}, ${depIds});`;
647
+ }
648
+ return `${globalPrefix}__d(${factory});`;
636
649
  }
637
650
  function wrapModule(code, options) {
638
- const globalPrefix = options?.globalPrefix || "";
639
- const depMap = options?.dependencyMapName || "_dependencyMap";
640
- const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMap}) {`;
641
- const requireAlias = options?.requireAlias !== false ? "var require = _$$_REQUIRE;\n" : "";
642
- const footer = `}`;
643
- if (options?.moduleId !== void 0) {
644
- const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
645
- return `${globalPrefix}__d(${header}
651
+ const globalPrefix = options?.globalPrefix || "";
652
+ const depMap = options?.dependencyMapName || "_dependencyMap";
653
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMap}) {`;
654
+ const requireAlias = options?.requireAlias !== false ? "var require = _$$_REQUIRE;\n" : "";
655
+ const footer = `}`;
656
+ if (options?.moduleId !== void 0) {
657
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
658
+ return `${globalPrefix}__d(${header}
646
659
  ${requireAlias}${code}
647
660
  ${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`;
648
- }
649
- return `${globalPrefix}__d(${header}
661
+ }
662
+ return `${globalPrefix}__d(${header}
650
663
  ${requireAlias}${code}
651
664
  ${footer});`;
652
665
  }
653
666
  function getDependencyKey(name, isESM, asyncType = null, contextParams) {
654
- let key = `${name}\0${isESM ? "import" : "require"}`;
655
- if (asyncType != null) {
656
- key += `\0${asyncType}`;
657
- }
658
- if (contextParams) {
659
- key += ["", "context", String(contextParams.recursive), String(contextParams.filter.pattern), String(contextParams.filter.flags), contextParams.mode].join("\0");
660
- }
661
- return key;
667
+ let key = `${name}\0${isESM ? "import" : "require"}`;
668
+ if (asyncType != null) {
669
+ key += `\0${asyncType}`;
670
+ }
671
+ if (contextParams) {
672
+ key += [
673
+ "",
674
+ "context",
675
+ String(contextParams.recursive),
676
+ String(contextParams.filter.pattern),
677
+ String(contextParams.filter.flags),
678
+ contextParams.mode
679
+ ].join("\0");
680
+ }
681
+ return key;
662
682
  }
663
683
  function rewriteDependencyCalls(code, dependencies, depMapName = "_dependencyMap", filename = "module.js", asyncRequirePath = "metro-runtime/src/modules/asyncRequire") {
664
- const ms = new MagicString(code);
665
- const emptyResult = {
666
- code,
667
- map: ms.generateMap({
668
- source: filename,
669
- hires: true,
670
- includeContent: true
671
- }),
672
- toString() {
673
- return code;
674
- }
675
- };
676
- if (dependencies.length === 0) return emptyResult;
677
- let parsed;
678
- try {
679
- parsed = parseSync(filename, code, {
680
- lang: langForFilename(filename)
681
- });
682
- } catch (err) {
683
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${err.message || err}`);
684
- }
685
- if (parsed?.errors?.length) {
686
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${parsed.errors[0].message}`);
687
- }
688
- if (!parsed?.program) return emptyResult;
689
- const contextLiteralBindings = collectModuleLiteralBindings(parsed.program);
690
- const scopeTracker = new ScopeTracker();
691
- collectHoistedBindings(parsed.program, scopeTracker.currentScope());
692
- collectBlockBindings(parsed.program.body, scopeTracker.currentScope());
693
- for (const stmt of parsed.program.body || []) {
694
- if (stmt.type === "ImportDeclaration") {
695
- for (const spec of stmt.specifiers || []) {
696
- if (spec.local?.name) {
697
- scopeTracker.add(spec.local.name);
698
- }
699
- }
700
- }
701
- }
702
- function walk(node) {
703
- if (!node || typeof node !== "object") return;
704
- let pushedScope = false;
705
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
706
- scopeTracker.enter();
707
- pushedScope = true;
708
- for (const param of node.params || []) {
709
- scopeTracker.addPattern(param);
710
- }
711
- if (node.type === "FunctionExpression" && node.id?.name) {
712
- scopeTracker.add(node.id.name);
713
- }
714
- if (node.body) {
715
- collectHoistedBindings(node.body, scopeTracker.currentScope());
716
- }
717
- } else if (node.type === "BlockStatement") {
718
- scopeTracker.enter();
719
- pushedScope = true;
720
- collectBlockBindings(node.body, scopeTracker.currentScope());
721
- } else if (node.type === "CatchClause") {
722
- scopeTracker.enter();
723
- pushedScope = true;
724
- if (node.param) {
725
- scopeTracker.addPattern(node.param);
726
- }
727
- } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
728
- const decl = node.type === "ForStatement" ? node.init : node.left;
729
- if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
730
- scopeTracker.enter();
731
- pushedScope = true;
732
- for (const d of decl.declarations || []) {
733
- scopeTracker.addPattern(d.id);
734
- }
735
- }
736
- }
737
- if (node.type === "ImportExpression" && node.source?.type === "Literal" && typeof node.source.value === "string") {
738
- const depName = node.source.value;
739
- const depKey = getDependencyKey(depName, true, "async");
740
- const dep = dependencies.find(d => d.data.key === depKey) || dependencies.find(d => d.name === depName && d.data.asyncType === "async");
741
- const asyncKey = getDependencyKey(asyncRequirePath, false, null);
742
- const asyncDep = dependencies.find(d => d.data.key === asyncKey) || dependencies.find(d => d.name === asyncRequirePath && d.data.asyncType == null);
743
- if (dep && asyncDep) {
744
- const depIndex = dep.data.index ?? dependencies.indexOf(dep);
745
- const asyncIndex = asyncDep.data.index ?? dependencies.indexOf(asyncDep);
746
- ms.overwrite(node.start, node.end, `require(${depMapName}[${asyncIndex}], ${JSON.stringify(asyncRequirePath)})(${depMapName}[${depIndex}], ${depMapName}.paths, ${JSON.stringify(depName)})`);
747
- }
748
- } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
749
- const arg = node.arguments[0];
750
- if (arg.type === "Literal" && typeof arg.value === "string") {
751
- const depKey = getDependencyKey(arg.value, false, null);
752
- const dep = dependencies.find(d => d.data.key === depKey) || dependencies.find(d => d.name === arg.value && d.data.asyncType == null);
753
- if (dep) {
754
- const index = dep.data.index ?? dependencies.indexOf(dep);
755
- ms.overwrite(arg.start, arg.end, `${depMapName}[${index}], ${JSON.stringify(arg.value)}`);
756
- }
757
- }
758
- } else if (
759
- // metro rewrites require.context(dir, ...) down to a plain require of the
760
- // single context module it registered for that directory.
761
- node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
762
- const arg = node.arguments[0]?.type === "Identifier" ? contextLiteralBindings.get(node.arguments[0].name) : node.arguments[0];
763
- if (arg?.type === "Literal" && typeof arg.value === "string") {
764
- const dep = dependencies.find(d => d.name === arg.value && d.data.contextParams != null);
765
- if (dep) {
766
- const index = dep.data.index ?? dependencies.indexOf(dep);
767
- ms.overwrite(node.start, node.end, `require(${depMapName}[${index}], ${JSON.stringify(arg.value)})`);
768
- }
769
- }
770
- }
771
- for (const key of Object.keys(node)) {
772
- if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
773
- const child = node[key];
774
- if (Array.isArray(child)) {
775
- for (const item of child) walk(item);
776
- } else if (child && typeof child === "object") {
777
- walk(child);
778
- }
779
- }
780
- if (pushedScope) {
781
- scopeTracker.exit();
782
- }
783
- }
784
- walk(parsed.program);
785
- const resultString = ms.toString();
786
- const map = ms.generateMap({
787
- source: filename,
788
- hires: true,
789
- includeContent: true
790
- });
791
- return {
792
- code: resultString,
793
- map,
794
- toString() {
795
- return resultString;
796
- }
797
- };
684
+ const ms = new MagicString(code);
685
+ const emptyResult = {
686
+ code,
687
+ map: ms.generateMap({
688
+ source: filename,
689
+ hires: true,
690
+ includeContent: true
691
+ }),
692
+ toString() {
693
+ return code;
694
+ }
695
+ };
696
+ if (dependencies.length === 0) return emptyResult;
697
+ let parsed;
698
+ try {
699
+ parsed = parseSync(filename, code, { lang: langForFilename(filename) });
700
+ } catch (err) {
701
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${err.message || err}`);
702
+ }
703
+ if (parsed?.errors?.length) {
704
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${parsed.errors[0].message}`);
705
+ }
706
+ if (!parsed?.program) return emptyResult;
707
+ const contextLiteralBindings = collectModuleLiteralBindings(parsed.program);
708
+ const scopeTracker = new ScopeTracker();
709
+ collectHoistedBindings(parsed.program, scopeTracker.currentScope());
710
+ collectBlockBindings(parsed.program.body, scopeTracker.currentScope());
711
+ for (const stmt of parsed.program.body || []) {
712
+ if (stmt.type === "ImportDeclaration") {
713
+ for (const spec of stmt.specifiers || []) {
714
+ if (spec.local?.name) {
715
+ scopeTracker.add(spec.local.name);
716
+ }
717
+ }
718
+ }
719
+ }
720
+ function walk(node) {
721
+ if (!node || typeof node !== "object") return;
722
+ let pushedScope = false;
723
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
724
+ scopeTracker.enter();
725
+ pushedScope = true;
726
+ for (const param of node.params || []) {
727
+ scopeTracker.addPattern(param);
728
+ }
729
+ if (node.type === "FunctionExpression" && node.id?.name) {
730
+ scopeTracker.add(node.id.name);
731
+ }
732
+ if (node.body) {
733
+ collectHoistedBindings(node.body, scopeTracker.currentScope());
734
+ }
735
+ } else if (node.type === "BlockStatement") {
736
+ scopeTracker.enter();
737
+ pushedScope = true;
738
+ collectBlockBindings(node.body, scopeTracker.currentScope());
739
+ } else if (node.type === "CatchClause") {
740
+ scopeTracker.enter();
741
+ pushedScope = true;
742
+ if (node.param) {
743
+ scopeTracker.addPattern(node.param);
744
+ }
745
+ } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
746
+ const decl = node.type === "ForStatement" ? node.init : node.left;
747
+ if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
748
+ scopeTracker.enter();
749
+ pushedScope = true;
750
+ for (const d of decl.declarations || []) {
751
+ scopeTracker.addPattern(d.id);
752
+ }
753
+ }
754
+ }
755
+ if (node.type === "ImportExpression" && node.source?.type === "Literal" && typeof node.source.value === "string") {
756
+ const depName = node.source.value;
757
+ const depKey = getDependencyKey(depName, true, "async");
758
+ const dep = dependencies.find((d) => d.data.key === depKey) || dependencies.find((d) => d.name === depName && d.data.asyncType === "async");
759
+ const asyncKey = getDependencyKey(asyncRequirePath, false, null);
760
+ const asyncDep = dependencies.find((d) => d.data.key === asyncKey) || dependencies.find((d) => d.name === asyncRequirePath && d.data.asyncType == null);
761
+ if (dep && asyncDep) {
762
+ const depIndex = dep.data.index ?? dependencies.indexOf(dep);
763
+ const asyncIndex = asyncDep.data.index ?? dependencies.indexOf(asyncDep);
764
+ ms.overwrite(node.start, node.end, `require(${depMapName}[${asyncIndex}], ${JSON.stringify(asyncRequirePath)})(${depMapName}[${depIndex}], ${depMapName}.paths, ${JSON.stringify(depName)})`);
765
+ }
766
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
767
+ const arg = node.arguments[0];
768
+ if (arg.type === "Literal" && typeof arg.value === "string") {
769
+ const depKey = getDependencyKey(arg.value, false, null);
770
+ const dep = dependencies.find((d) => d.data.key === depKey) || dependencies.find((d) => d.name === arg.value && d.data.asyncType == null);
771
+ if (dep) {
772
+ const index = dep.data.index ?? dependencies.indexOf(dep);
773
+ ms.overwrite(arg.start, arg.end, `${depMapName}[${index}], ${JSON.stringify(arg.value)}`);
774
+ }
775
+ }
776
+ } else if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require") && node.arguments?.length >= 1) {
777
+ const arg = node.arguments[0]?.type === "Identifier" ? contextLiteralBindings.get(node.arguments[0].name) : node.arguments[0];
778
+ if (arg?.type === "Literal" && typeof arg.value === "string") {
779
+ const dep = dependencies.find((d) => d.name === arg.value && d.data.contextParams != null);
780
+ if (dep) {
781
+ const index = dep.data.index ?? dependencies.indexOf(dep);
782
+ ms.overwrite(node.start, node.end, `require(${depMapName}[${index}], ${JSON.stringify(arg.value)})`);
783
+ }
784
+ }
785
+ }
786
+ for (const key of Object.keys(node)) {
787
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
788
+ const child = node[key];
789
+ if (Array.isArray(child)) {
790
+ for (const item of child) walk(item);
791
+ } else if (child && typeof child === "object") {
792
+ walk(child);
793
+ }
794
+ }
795
+ if (pushedScope) {
796
+ scopeTracker.exit();
797
+ }
798
+ }
799
+ walk(parsed.program);
800
+ const resultString = ms.toString();
801
+ const map = ms.generateMap({
802
+ source: filename,
803
+ hires: true,
804
+ includeContent: true
805
+ });
806
+ return {
807
+ code: resultString,
808
+ map,
809
+ toString() {
810
+ return resultString;
811
+ }
812
+ };
798
813
  }
799
814
  function extractDependencies(code, filename, options) {
800
- const asyncRequirePath = options?.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
801
- const allowOptionalDependencies = options?.allowOptionalDependencies;
802
- const lineOffsets = [0];
803
- for (let i = 0; i < code.length; i++) {
804
- if (code[i] === "\n") {
805
- lineOffsets.push(i + 1);
806
- }
807
- }
808
- function offsetToLoc(pos) {
809
- let low = 0;
810
- let high = lineOffsets.length - 1;
811
- while (low <= high) {
812
- const mid = low + high >> 1;
813
- if (lineOffsets[mid] <= pos) {
814
- low = mid + 1;
815
- } else {
816
- high = mid - 1;
817
- }
818
- }
819
- const line = high + 1;
820
- const column = pos - lineOffsets[high];
821
- return {
822
- line,
823
- column
824
- };
825
- }
826
- let parseResult;
827
- try {
828
- parseResult = parseSync(filename, code, {
829
- lang: langForFilename(filename)
830
- });
831
- } catch (err) {
832
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${err.message || err}`);
833
- }
834
- if (parseResult?.errors?.length) {
835
- throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${parseResult.errors[0].message}`);
836
- }
837
- if (!parseResult?.program) {
838
- return [];
839
- }
840
- const depMap = /* @__PURE__ */new Map();
841
- function addDep(name, isESM, asyncType, start, end, contextParams, isOptional) {
842
- const key = getDependencyKey(name, isESM, asyncType, contextParams);
843
- let entry = depMap.get(key);
844
- const loc = {
845
- start: offsetToLoc(start),
846
- end: offsetToLoc(end)
847
- };
848
- if (!entry) {
849
- entry = {
850
- name,
851
- data: {
852
- key,
853
- asyncType,
854
- locs: [loc],
855
- isESMImportAtSource: isESM,
856
- isESMImport: isESM,
857
- index: depMap.size,
858
- ...(contextParams ? {
859
- contextParams
860
- } : {}),
861
- ...(isOptional ? {
862
- isOptional: true
863
- } : {})
864
- }
865
- };
866
- depMap.set(key, entry);
867
- } else {
868
- entry.data.locs.push(loc);
869
- }
870
- }
871
- const moduleConsts = collectModuleLiteralBindings(parseResult.program);
872
- function resolveConst(node) {
873
- if (node?.type === "Identifier") return moduleConsts.get(node.name);
874
- return node;
875
- }
876
- const ancestors = [];
877
- function isOptionalHere(name) {
878
- if (!allowOptionalDependencies) return false;
879
- if (Array.isArray(allowOptionalDependencies.exclude)) {
880
- if (allowOptionalDependencies.exclude.includes(name)) return false;
881
- }
882
- let sCount = 0;
883
- for (let i = ancestors.length - 1; i >= 0 && sCount < 3; i--) {
884
- const n = ancestors[i];
885
- const isStatement = /(?:Statement|Declaration)$/.test(n.type);
886
- if (!isStatement) continue;
887
- if (n.type === "BlockStatement") {
888
- const parent = ancestors[i - 1];
889
- return parent?.type === "TryStatement" && parent.block === n;
890
- }
891
- sCount += 1;
892
- }
893
- return false;
894
- }
895
- const scopeTracker = new ScopeTracker();
896
- collectHoistedBindings(parseResult.program, scopeTracker.currentScope());
897
- collectBlockBindings(parseResult.program.body, scopeTracker.currentScope());
898
- for (const stmt of parseResult.program.body || []) {
899
- if (stmt.type === "ImportDeclaration") {
900
- for (const spec of stmt.specifiers || []) {
901
- if (spec.local?.name) {
902
- scopeTracker.add(spec.local.name);
903
- }
904
- }
905
- }
906
- }
907
- function walk(node) {
908
- if (!node || typeof node !== "object") return;
909
- let pushedScope = false;
910
- ancestors.push(node);
911
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
912
- scopeTracker.enter();
913
- pushedScope = true;
914
- for (const param of node.params || []) {
915
- scopeTracker.addPattern(param);
916
- }
917
- if (node.type === "FunctionExpression" && node.id?.name) {
918
- scopeTracker.add(node.id.name);
919
- }
920
- if (node.body) {
921
- collectHoistedBindings(node.body, scopeTracker.currentScope());
922
- }
923
- } else if (node.type === "BlockStatement") {
924
- scopeTracker.enter();
925
- pushedScope = true;
926
- collectBlockBindings(node.body, scopeTracker.currentScope());
927
- } else if (node.type === "CatchClause") {
928
- scopeTracker.enter();
929
- pushedScope = true;
930
- if (node.param) {
931
- scopeTracker.addPattern(node.param);
932
- }
933
- } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
934
- const decl = node.type === "ForStatement" ? node.init : node.left;
935
- if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
936
- scopeTracker.enter();
937
- pushedScope = true;
938
- for (const d of decl.declarations || []) {
939
- scopeTracker.addPattern(d.id);
940
- }
941
- }
942
- }
943
- if (node.type === "ImportDeclaration" && node.source?.value) {
944
- if (node.importKind !== "type") {
945
- const hasValueSpecifier = !node.specifiers?.length || node.specifiers.some(s => s.importKind !== "type");
946
- if (hasValueSpecifier) {
947
- addDep(node.source.value, true, null, node.start, node.end);
948
- }
949
- }
950
- } else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source?.value) {
951
- if (node.exportKind !== "type") {
952
- addDep(node.source.value, true, null, node.start, node.end);
953
- }
954
- } else if (node.type === "ImportExpression") {
955
- if (node.source?.type === "Literal" && typeof node.source.value === "string") {
956
- addDep(node.source.value, true, "async", node.start, node.end);
957
- addDep(asyncRequirePath, false, null, node.start, node.end);
958
- } else {
959
- throw new Error(`[vxrn/metro] Dynamic import with non-string literal is not supported by Metro in ${filename}`);
960
- }
961
- } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require")) {
962
- if (node.arguments?.[0]?.type === "Literal" && typeof node.arguments[0].value === "string") {
963
- addDep(node.arguments[0].value, false, null, node.start, node.end, void 0, node.arguments[0].value !== asyncRequirePath && isOptionalHere(node.arguments[0].value));
964
- }
965
- } else if (
966
- // require.context(dir, recursive?, filter?, mode?) registers a whole
967
- // directory as one dependency. one's router entry uses it for the route
968
- // tree, so dropping it silently omits every route from the bundle.
969
- node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require")) {
970
- const args = node.arguments || [];
971
- const dir = resolveConst(args[0]);
972
- if (dir?.type !== "Literal" || typeof dir.value !== "string") {
973
- throw new Error(`[vxrn/metro] First argument of require.context must be a string literal in ${filename}`);
974
- }
975
- if (args.length > 4) {
976
- throw new Error(`[vxrn/metro] Too many arguments provided to require.context in ${filename}. Expected 4, got: ${args.length}`);
977
- }
978
- let recursive = true;
979
- const recursiveArg = resolveConst(args[1]);
980
- if (recursiveArg) {
981
- if (recursiveArg.type !== "Literal" || typeof recursiveArg.value !== "boolean") {
982
- throw new Error(`[vxrn/metro] Second argument of require.context must be an optional boolean literal in ${filename}`);
983
- }
984
- recursive = recursiveArg.value;
985
- }
986
- let filter = {
987
- pattern: ".*",
988
- flags: ""
989
- };
990
- const filterArg = resolveConst(args[2]);
991
- if (filterArg) {
992
- if (filterArg.type !== "Literal" || !filterArg.regex) {
993
- throw new Error(`[vxrn/metro] Third argument of require.context must be an optional RegExp literal in ${filename}, instead found node of type: ${filterArg.type}`);
994
- }
995
- filter = {
996
- pattern: filterArg.regex.pattern,
997
- flags: filterArg.regex.flags || ""
998
- };
999
- }
1000
- let mode = "sync";
1001
- const modeArg = resolveConst(args[3]);
1002
- if (modeArg) {
1003
- const m = modeArg.type === "Literal" ? modeArg.value : void 0;
1004
- if (m !== "sync" && m !== "eager" && m !== "lazy" && m !== "lazy-once") {
1005
- throw new Error(`[vxrn/metro] require.context mode must be one of sync, eager, lazy, lazy-once in ${filename}`);
1006
- }
1007
- mode = m;
1008
- }
1009
- addDep(dir.value, false, null, node.start, node.end, {
1010
- recursive,
1011
- filter,
1012
- mode
1013
- });
1014
- }
1015
- for (const key of Object.keys(node)) {
1016
- if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
1017
- const child = node[key];
1018
- if (Array.isArray(child)) {
1019
- for (const item of child) walk(item);
1020
- } else if (child && typeof child === "object") {
1021
- walk(child);
1022
- }
1023
- }
1024
- ancestors.pop();
1025
- if (pushedScope) {
1026
- scopeTracker.exit();
1027
- }
1028
- }
1029
- walk(parseResult.program);
1030
- return Array.from(depMap.values());
815
+ const asyncRequirePath = options?.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
816
+ const allowOptionalDependencies = options?.allowOptionalDependencies;
817
+ const lineOffsets = [0];
818
+ for (let i = 0; i < code.length; i++) {
819
+ if (code[i] === "\n") {
820
+ lineOffsets.push(i + 1);
821
+ }
822
+ }
823
+ function offsetToLoc(pos) {
824
+ let low = 0;
825
+ let high = lineOffsets.length - 1;
826
+ while (low <= high) {
827
+ const mid = low + high >> 1;
828
+ if (lineOffsets[mid] <= pos) {
829
+ low = mid + 1;
830
+ } else {
831
+ high = mid - 1;
832
+ }
833
+ }
834
+ const line = high + 1;
835
+ const column = pos - lineOffsets[high];
836
+ return {
837
+ line,
838
+ column
839
+ };
840
+ }
841
+ let parseResult;
842
+ try {
843
+ parseResult = parseSync(filename, code, { lang: langForFilename(filename) });
844
+ } catch (err) {
845
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${err.message || err}`);
846
+ }
847
+ if (parseResult?.errors?.length) {
848
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${parseResult.errors[0].message}`);
849
+ }
850
+ if (!parseResult?.program) {
851
+ return [];
852
+ }
853
+ const depMap = /* @__PURE__ */ new Map();
854
+ function addDep(name, isESM, asyncType, start, end, contextParams, isOptional) {
855
+ const key = getDependencyKey(name, isESM, asyncType, contextParams);
856
+ let entry = depMap.get(key);
857
+ const loc = {
858
+ start: offsetToLoc(start),
859
+ end: offsetToLoc(end)
860
+ };
861
+ if (!entry) {
862
+ entry = {
863
+ name,
864
+ data: {
865
+ key,
866
+ asyncType,
867
+ locs: [loc],
868
+ isESMImportAtSource: isESM,
869
+ isESMImport: isESM,
870
+ index: depMap.size,
871
+ ...contextParams ? { contextParams } : {},
872
+ ...isOptional ? { isOptional: true } : {}
873
+ }
874
+ };
875
+ depMap.set(key, entry);
876
+ } else {
877
+ entry.data.locs.push(loc);
878
+ }
879
+ }
880
+ const moduleConsts = collectModuleLiteralBindings(parseResult.program);
881
+ function resolveConst(node) {
882
+ if (node?.type === "Identifier") return moduleConsts.get(node.name);
883
+ return node;
884
+ }
885
+ const ancestors = [];
886
+ function isOptionalHere(name) {
887
+ if (!allowOptionalDependencies) return false;
888
+ if (Array.isArray(allowOptionalDependencies.exclude)) {
889
+ if (allowOptionalDependencies.exclude.includes(name)) return false;
890
+ }
891
+ let sCount = 0;
892
+ for (let i = ancestors.length - 1; i >= 0 && sCount < 3; i--) {
893
+ const n = ancestors[i];
894
+ const isStatement = /(?:Statement|Declaration)$/.test(n.type);
895
+ if (!isStatement) continue;
896
+ if (n.type === "BlockStatement") {
897
+ const parent = ancestors[i - 1];
898
+ return parent?.type === "TryStatement" && parent.block === n;
899
+ }
900
+ sCount += 1;
901
+ }
902
+ return false;
903
+ }
904
+ const scopeTracker = new ScopeTracker();
905
+ collectHoistedBindings(parseResult.program, scopeTracker.currentScope());
906
+ collectBlockBindings(parseResult.program.body, scopeTracker.currentScope());
907
+ for (const stmt of parseResult.program.body || []) {
908
+ if (stmt.type === "ImportDeclaration") {
909
+ for (const spec of stmt.specifiers || []) {
910
+ if (spec.local?.name) {
911
+ scopeTracker.add(spec.local.name);
912
+ }
913
+ }
914
+ }
915
+ }
916
+ function walk(node) {
917
+ if (!node || typeof node !== "object") return;
918
+ let pushedScope = false;
919
+ ancestors.push(node);
920
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
921
+ scopeTracker.enter();
922
+ pushedScope = true;
923
+ for (const param of node.params || []) {
924
+ scopeTracker.addPattern(param);
925
+ }
926
+ if (node.type === "FunctionExpression" && node.id?.name) {
927
+ scopeTracker.add(node.id.name);
928
+ }
929
+ if (node.body) {
930
+ collectHoistedBindings(node.body, scopeTracker.currentScope());
931
+ }
932
+ } else if (node.type === "BlockStatement") {
933
+ scopeTracker.enter();
934
+ pushedScope = true;
935
+ collectBlockBindings(node.body, scopeTracker.currentScope());
936
+ } else if (node.type === "CatchClause") {
937
+ scopeTracker.enter();
938
+ pushedScope = true;
939
+ if (node.param) {
940
+ scopeTracker.addPattern(node.param);
941
+ }
942
+ } else if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
943
+ const decl = node.type === "ForStatement" ? node.init : node.left;
944
+ if (decl?.type === "VariableDeclaration" && decl.kind !== "var") {
945
+ scopeTracker.enter();
946
+ pushedScope = true;
947
+ for (const d of decl.declarations || []) {
948
+ scopeTracker.addPattern(d.id);
949
+ }
950
+ }
951
+ }
952
+ if (node.type === "ImportDeclaration" && node.source?.value) {
953
+ if (node.importKind !== "type") {
954
+ const hasValueSpecifier = !node.specifiers?.length || node.specifiers.some((s) => s.importKind !== "type");
955
+ if (hasValueSpecifier) {
956
+ addDep(node.source.value, true, null, node.start, node.end);
957
+ }
958
+ }
959
+ } else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source?.value) {
960
+ if (node.exportKind !== "type") {
961
+ addDep(node.source.value, true, null, node.start, node.end);
962
+ }
963
+ } else if (node.type === "ImportExpression") {
964
+ if (node.source?.type === "Literal" && typeof node.source.value === "string") {
965
+ addDep(node.source.value, true, "async", node.start, node.end);
966
+ addDep(asyncRequirePath, false, null, node.start, node.end);
967
+ } else {
968
+ throw new Error(`[vxrn/metro] Dynamic import with non-string literal is not supported by Metro in ${filename}`);
969
+ }
970
+ } else if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && !scopeTracker.isShadowed("require")) {
971
+ if (node.arguments?.[0]?.type === "Literal" && typeof node.arguments[0].value === "string") {
972
+ addDep(node.arguments[0].value, false, null, node.start, node.end, void 0, node.arguments[0].value !== asyncRequirePath && isOptionalHere(node.arguments[0].value));
973
+ }
974
+ } else if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "require" && node.callee.property?.type === "Identifier" && node.callee.property.name === "context" && !scopeTracker.isShadowed("require")) {
975
+ const args = node.arguments || [];
976
+ const dir = resolveConst(args[0]);
977
+ if (dir?.type !== "Literal" || typeof dir.value !== "string") {
978
+ throw new Error(`[vxrn/metro] First argument of require.context must be a string literal in ${filename}`);
979
+ }
980
+ if (args.length > 4) {
981
+ throw new Error(`[vxrn/metro] Too many arguments provided to require.context in ${filename}. Expected 4, got: ${args.length}`);
982
+ }
983
+ let recursive = true;
984
+ const recursiveArg = resolveConst(args[1]);
985
+ if (recursiveArg) {
986
+ if (recursiveArg.type !== "Literal" || typeof recursiveArg.value !== "boolean") {
987
+ throw new Error(`[vxrn/metro] Second argument of require.context must be an optional boolean literal in ${filename}`);
988
+ }
989
+ recursive = recursiveArg.value;
990
+ }
991
+ let filter = {
992
+ pattern: ".*",
993
+ flags: ""
994
+ };
995
+ const filterArg = resolveConst(args[2]);
996
+ if (filterArg) {
997
+ if (filterArg.type !== "Literal" || !filterArg.regex) {
998
+ throw new Error(`[vxrn/metro] Third argument of require.context must be an optional RegExp literal in ${filename}, instead found node of type: ${filterArg.type}`);
999
+ }
1000
+ filter = {
1001
+ pattern: filterArg.regex.pattern,
1002
+ flags: filterArg.regex.flags || ""
1003
+ };
1004
+ }
1005
+ let mode = "sync";
1006
+ const modeArg = resolveConst(args[3]);
1007
+ if (modeArg) {
1008
+ const m = modeArg.type === "Literal" ? modeArg.value : void 0;
1009
+ if (m !== "sync" && m !== "eager" && m !== "lazy" && m !== "lazy-once") {
1010
+ throw new Error(`[vxrn/metro] require.context mode must be one of sync, eager, lazy, lazy-once in ${filename}`);
1011
+ }
1012
+ mode = m;
1013
+ }
1014
+ addDep(dir.value, false, null, node.start, node.end, {
1015
+ recursive,
1016
+ filter,
1017
+ mode
1018
+ });
1019
+ }
1020
+ for (const key of Object.keys(node)) {
1021
+ if (key === "start" || key === "end" || key === "loc" || key === "range" || key === "parent" || key === "comments") continue;
1022
+ const child = node[key];
1023
+ if (Array.isArray(child)) {
1024
+ for (const item of child) walk(item);
1025
+ } else if (child && typeof child === "object") {
1026
+ walk(child);
1027
+ }
1028
+ }
1029
+ ancestors.pop();
1030
+ if (pushedScope) {
1031
+ scopeTracker.exit();
1032
+ }
1033
+ }
1034
+ walk(parseResult.program);
1035
+ return Array.from(depMap.values());
1031
1036
  }
1032
1037
  function checkReservedStrings(sourceCode, config, options) {
1033
- const reservedStrings = [];
1034
- if (options.customTransformOptions?.unstable_staticHermesOptimizedRequire === true) {
1035
- reservedStrings.push("_$$_METRO_MODULE_ID");
1036
- }
1037
- if (config.unstable_dependencyMapReservedName != null) {
1038
- reservedStrings.push(config.unstable_dependencyMapReservedName);
1039
- }
1040
- for (const reservedString of reservedStrings) {
1041
- const position = sourceCode.indexOf(reservedString);
1042
- if (position > -1) {
1043
- throw new SyntaxError("Source code contains the reserved string `" + reservedString + "` at character offset " + position);
1044
- }
1045
- }
1038
+ const reservedStrings = [];
1039
+ if (options.customTransformOptions?.unstable_staticHermesOptimizedRequire === true) {
1040
+ reservedStrings.push("_$$_METRO_MODULE_ID");
1041
+ }
1042
+ if (config.unstable_dependencyMapReservedName != null) {
1043
+ reservedStrings.push(config.unstable_dependencyMapReservedName);
1044
+ }
1045
+ for (const reservedString of reservedStrings) {
1046
+ const position = sourceCode.indexOf(reservedString);
1047
+ if (position > -1) {
1048
+ throw new SyntaxError("Source code contains the reserved string `" + reservedString + "` at character offset " + position);
1049
+ }
1050
+ }
1046
1051
  }
1047
1052
  let workletsConfigured = false;
1048
1053
  let oneNativeTransforms;
1049
1054
  function loadOneNativeTransforms(projectRoot) {
1050
- if (oneNativeTransforms !== void 0) return oneNativeTransforms;
1051
- try {
1052
- const req = createRequire(path.resolve(projectRoot, "package.json"));
1053
- oneNativeTransforms = req("one/native-transforms");
1054
- } catch {
1055
- oneNativeTransforms = null;
1056
- }
1057
- return oneNativeTransforms;
1055
+ if (oneNativeTransforms !== void 0) return oneNativeTransforms;
1056
+ try {
1057
+ const req = createRequire(path.resolve(projectRoot, "package.json"));
1058
+ oneNativeTransforms = req("one/native-transforms");
1059
+ } catch {
1060
+ oneNativeTransforms = null;
1061
+ }
1062
+ return oneNativeTransforms;
1058
1063
  }
1059
1064
  async function configureWorkletsForWorker(projectRoot) {
1060
- if (workletsConfigured) return;
1061
- workletsConfigured = true;
1062
- if (!projectRoot) return;
1063
- const req = createRequire(path.resolve(projectRoot, "package.json"));
1064
- let hasReanimated = false;
1065
- try {
1066
- req.resolve("react-native-reanimated/package.json");
1067
- hasReanimated = true;
1068
- } catch {
1069
- try {
1070
- req.resolve("react-native-worklets/package.json");
1071
- hasReanimated = true;
1072
- } catch {}
1073
- }
1074
- const {
1075
- configureVXRNCompilerPlugin
1076
- } = await import("@vxrn/compiler");
1077
- configureVXRNCompilerPlugin({
1078
- enableReanimated: hasReanimated
1079
- });
1065
+ if (workletsConfigured) return;
1066
+ workletsConfigured = true;
1067
+ if (!projectRoot) return;
1068
+ const req = createRequire(path.resolve(projectRoot, "package.json"));
1069
+ let hasReanimated = false;
1070
+ try {
1071
+ req.resolve("react-native-reanimated/package.json");
1072
+ hasReanimated = true;
1073
+ } catch {
1074
+ try {
1075
+ req.resolve("react-native-worklets/package.json");
1076
+ hasReanimated = true;
1077
+ } catch {}
1078
+ }
1079
+ const { configureVXRNCompilerPlugin } = await import("@vxrn/compiler");
1080
+ configureVXRNCompilerPlugin({ enableReanimated: hasReanimated });
1080
1081
  }
1081
1082
  async function transform(config, projectRoot, filename, data, options) {
1082
- assertNoUnportedBabelPlugins(options);
1083
- let sourceCode = typeof data === "string" ? data : data.toString("utf8");
1084
- const environment = options.customTransformOptions?.environment;
1085
- const isClientEnvironment = environment !== "node" && environment !== "react-server";
1086
- if (isClientEnvironment && /[\\/]expo[\\/]virtual[\\/]env\.js$/.test(filename)) {
1087
- if (options.dev) {
1088
- const rel = path.relative(path.dirname(filename), projectRoot).split(path.sep).join("/");
1089
- sourceCode = `const dotEnvModules = require.context(${JSON.stringify(rel)},false,/^\\.\\/\\.env/);
1090
- export const env = !dotEnvModules.keys().length ? process.env : { ...process.env, ...['.env', '.env.development', '.env.local', '.env.development.local'].reduce((acc, file) => {
1091
- return { ...acc, ...(dotEnvModules(file)?.default ?? {}) };
1092
- }, {}) };`;
1093
- } else {
1094
- sourceCode = `export const env = new Proxy({}, {
1095
- get(target, key) {
1096
- throw new Error(\`Attempting to access internal environment variable "\${String(key)}" is not supported in production bundles.\`);
1097
- },
1098
- });`;
1099
- }
1100
- } else if (/(^|[\\/])\.env(\.(local|(development|production)(\.local)?))?$/.test(filename)) {
1101
- const {
1102
- parseEnvFile
1103
- } = await import("@expo/metro-config/build/transform-worker/dot-env-development");
1104
- sourceCode = `export default ${JSON.stringify(parseEnvFile(sourceCode, isClientEnvironment))};`;
1105
- }
1106
- checkReservedStrings(sourceCode, config, options);
1107
- if (filename.endsWith(".json")) {
1108
- try {
1109
- JSON.parse(sourceCode);
1110
- } catch (err) {
1111
- throw new Error(`[vxrn/metro] JSON parse error in ${filename}: ${err.message || err}`);
1112
- }
1113
- let code2 = config.unstable_disableModuleWrapping === true ? `module.exports = ${sourceCode};` : wrapJson(sourceCode, {
1114
- globalPrefix: config.globalPrefix,
1115
- moduleId: options.moduleId,
1116
- dependencyIds: options.dependencyIds
1117
- });
1118
- if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1119
- try {
1120
- const minifier = require(config.minifierPath);
1121
- const minified = await minifier({
1122
- code: code2,
1123
- config: config.minifierConfig,
1124
- filename
1125
- });
1126
- code2 = minified.code;
1127
- } catch (err) {
1128
- throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1129
- }
1130
- }
1131
- const {
1132
- lineCount: lineCount2,
1133
- map: map2
1134
- } = countLinesAndTerminateMap(code2, []);
1135
- const outputType = options.type === "asset" ? "js/module/asset" : options.type === "script" ? "js/script" : "js/module";
1136
- return {
1137
- dependencies: [],
1138
- output: [{
1139
- data: {
1140
- code: code2,
1141
- lineCount: lineCount2,
1142
- map: map2,
1143
- functionMap: null
1144
- },
1145
- type: outputType
1146
- }]
1147
- };
1148
- }
1149
- if (options.type === "asset") {
1150
- const assetRegistryPath = config.assetRegistryPath || "react-native/Libraries/Image/AssetRegistry";
1151
- let properDescriptor = null;
1152
- const absolutePath = path.resolve(projectRoot, filename);
1153
- if (fs.existsSync(absolutePath)) {
1154
- try {
1155
- let getAssetData;
1156
- try {
1157
- getAssetData = require("metro/private/Assets").getAssetData;
1158
- } catch {
1159
- getAssetData = require("metro/src/Assets").getAssetData;
1160
- }
1161
- if (typeof getAssetData === "function") {
1162
- const rawData = await getAssetData(absolutePath, filename, config.assetPlugins || [], options.platform || "", config.publicPath || "/assets");
1163
- const copied = {
1164
- ...rawData
1165
- };
1166
- delete copied.files;
1167
- delete copied.fileSystemLocation;
1168
- delete copied.path;
1169
- properDescriptor = copied;
1170
- }
1171
- } catch (err) {
1172
- throw new Error(`[vxrn/metro] Asset resolution failed for ${filename}: ${err.message || err}`);
1173
- }
1174
- }
1175
- if (!properDescriptor) {
1176
- const ext = path.extname(filename).slice(1);
1177
- const name = path.basename(filename, "." + ext);
1178
- properDescriptor = {
1179
- __packager_asset: true,
1180
- httpServerLocation: config.publicPath || "/assets",
1181
- width: void 0,
1182
- height: void 0,
1183
- scales: [1],
1184
- hash: crypto.createHash("md5").update(sourceCode).digest("hex"),
1185
- name,
1186
- type: ext
1187
- };
1188
- }
1189
- const assetDepMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1190
- const assetCode = `module.exports = require(${assetDepMapName}[0], ${JSON.stringify(assetRegistryPath)}).registerAsset(${JSON.stringify(properDescriptor)});`;
1191
- let code2 = config.unstable_disableModuleWrapping === true ? assetCode : wrapModule(assetCode, {
1192
- globalPrefix: config.globalPrefix,
1193
- moduleId: options.moduleId,
1194
- dependencyIds: options.dependencyIds,
1195
- dependencyMapName: config.unstable_dependencyMapReservedName
1196
- });
1197
- const dependencies2 = [{
1198
- name: assetRegistryPath,
1199
- data: {
1200
- key: getDependencyKey(assetRegistryPath, false, null),
1201
- asyncType: null,
1202
- locs: [],
1203
- isESMImportAtSource: false,
1204
- isESMImport: false,
1205
- index: 0
1206
- }
1207
- }];
1208
- const {
1209
- lineCount: lineCount2,
1210
- map: map2
1211
- } = countLinesAndTerminateMap(code2, []);
1212
- return {
1213
- dependencies: dependencies2,
1214
- output: [{
1215
- data: {
1216
- code: code2,
1217
- lineCount: lineCount2,
1218
- map: map2,
1219
- functionMap: null
1220
- },
1221
- type: "js/module/asset"
1222
- }]
1223
- };
1224
- }
1225
- let code = sourceCode;
1226
- const intermediateMaps = [];
1227
- for (const nativeTransform of getNativeTransforms(options, projectRoot)) {
1228
- const out = nativeTransform(code, {
1229
- // absolute, unlike metro's own project-relative name. a transform that
1230
- // matches on paths (include/exclude lists, node_modules skips) or stamps
1231
- // a location into the output would otherwise get a different answer here
1232
- // than the babel plugin it replaced, which is handed an absolute path.
1233
- filename: path.isAbsolute(filename) ? filename : path.resolve(projectRoot, filename),
1234
- platform: options.platform,
1235
- dev: options.dev,
1236
- projectRoot
1237
- });
1238
- if (typeof out === "string") code = out;
1239
- }
1240
- const oneRouterOptions = getOneRouterMetroOptions(options);
1241
- if (oneRouterOptions) {
1242
- code = applyOneRouterMetro(code, filename, oneRouterOptions);
1243
- }
1244
- try {
1245
- const codegenRes = transformReactNativeCodegen(code, filename, projectRoot);
1246
- if (codegenRes?.code) {
1247
- code = codegenRes.code;
1248
- if (codegenRes.map) {
1249
- intermediateMaps.push(codegenRes.map);
1250
- }
1251
- }
1252
- } catch (err) {
1253
- throw new Error(`[vxrn/metro] React Native codegen failed for ${filename}: ${err.message || err}`);
1254
- }
1255
- if (shouldStripFlow(filename, code)) {
1256
- try {
1257
- const fft = await import("fast-flow-transform");
1258
- const flowTransform = fft.default || fft;
1259
- const flowResult = await flowTransform({
1260
- filename,
1261
- source: code,
1262
- sourcemap: true,
1263
- dialect: "flow",
1264
- format: "pretty"
1265
- });
1266
- if (flowResult?.code) {
1267
- code = flowResult.code;
1268
- if (flowResult.map) {
1269
- intermediateMaps.push(typeof flowResult.map === "string" ? JSON.parse(flowResult.map) : flowResult.map);
1270
- }
1271
- }
1272
- } catch (err) {
1273
- throw new Error(`[vxrn/metro] Flow transform failed for ${filename}: ${err.message || err}`);
1274
- }
1275
- }
1276
- const asyncRequirePath = config.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
1277
- const aliases = getModuleResolverAliases(options);
1278
- if (aliases && projectRoot) {
1279
- const aliasKeys = Object.keys(aliases);
1280
- if (aliasKeys.some(k => code.includes(k.endsWith("$") ? k.slice(0, -1) : k))) {
1281
- code = applyModuleResolverAliases(code, filename, projectRoot, aliases);
1282
- }
1283
- }
1284
- if (code.includes("process.env") || code.includes("import.meta")) {
1285
- code = applyInlineEnvVars(code, filename, !options.dev, getImportMetaEnv(options));
1286
- }
1287
- if (code.includes("-only")) {
1288
- code = applyEnvironmentGuard(code, filename);
1289
- }
1290
- const serverCodeRouterRoot = getRemoveServerCodeRouterRoot(options);
1291
- if (serverCodeRouterRoot && projectRoot && !filename.includes("node_modules")) {
1292
- const oneNativeTransforms2 = loadOneNativeTransforms(projectRoot);
1293
- if (oneNativeTransforms2) {
1294
- const shaken = await oneNativeTransforms2.transformTreeShakeClient(code, filename, projectRoot, serverCodeRouterRoot);
1295
- if (shaken?.code) {
1296
- code = shaken.code;
1297
- }
1298
- }
1299
- }
1300
- const dependencies = extractDependencies(code, filename, {
1301
- asyncRequireModulePath: asyncRequirePath,
1302
- allowOptionalDependencies: config.allowOptionalDependencies
1303
- });
1304
- await configureWorkletsForWorker(projectRoot);
1305
- let shouldRunWorklets = Boolean(options.customTransformOptions?.worklets);
1306
- if (!shouldRunWorklets) {
1307
- const {
1308
- shouldTransformWorklets
1309
- } = await import("@vxrn/compiler");
1310
- shouldRunWorklets = shouldTransformWorklets({
1311
- id: filename,
1312
- code
1313
- });
1314
- }
1315
- const shouldRunReactCompiler = Boolean(options.customTransformOptions?.reactCompiler) || hasBabelPlugin(options, "babel-plugin-react-compiler") && isReactCompilerCandidate(filename) || code.includes('"use memo"') || code.includes("'use memo'");
1316
- if (shouldRunReactCompiler) {
1317
- try {
1318
- const {
1319
- prepareWorkletsForReactCompiler,
1320
- transformOxcReactCompiler
1321
- } = await import("@vxrn/compiler");
1322
- if (shouldRunWorklets) {
1323
- const prepared = prepareWorkletsForReactCompiler(filename, code, true);
1324
- if (prepared) {
1325
- code = prepared.code;
1326
- if (prepared.map) intermediateMaps.push(prepared.map);
1327
- }
1328
- }
1329
- const compilerRes = await transformOxcReactCompiler(filename, code, "19", true);
1330
- if (compilerRes?.code) {
1331
- code = compilerRes.code;
1332
- if (compilerRes.map) {
1333
- intermediateMaps.push(typeof compilerRes.map === "string" ? JSON.parse(compilerRes.map) : compilerRes.map);
1334
- }
1335
- }
1336
- } catch (err) {
1337
- throw new Error(`[vxrn/metro] React Compiler failed for ${filename}: ${err.message || err}`);
1338
- }
1339
- }
1340
- if (shouldRunWorklets) {
1341
- try {
1342
- const {
1343
- transformWorklets
1344
- } = await import("@vxrn/compiler");
1345
- const workletRes = await transformWorklets(filename, code, true, {
1346
- projectRoot
1347
- });
1348
- if (workletRes?.code) {
1349
- code = workletRes.code;
1350
- if (workletRes.map) {
1351
- intermediateMaps.push(typeof workletRes.map === "string" ? JSON.parse(workletRes.map) : workletRes.map);
1352
- }
1353
- }
1354
- } catch (err) {
1355
- throw new Error(`[vxrn/metro] Worklets transform failed for ${filename}: ${err.message || err}`);
1356
- }
1357
- }
1358
- const lang = langForFilename(filename);
1359
- const {
1360
- transformSync: oxcTransform
1361
- } = await import("oxc-transform");
1362
- let oxcRes;
1363
- try {
1364
- oxcRes = oxcTransform(filename, code, {
1365
- lang,
1366
- target: "es2020",
1367
- assumptions: {
1368
- setPublicClassFields: true
1369
- },
1370
- jsx: {
1371
- runtime: "automatic",
1372
- development: Boolean(options.dev)
1373
- },
1374
- sourcemap: true
1375
- });
1376
- } catch (err) {
1377
- throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${err.message || err}`);
1378
- }
1379
- if (oxcRes.errors?.length) {
1380
- throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${oxcRes.errors[0].message || oxcRes.errors[0]}`);
1381
- }
1382
- code = oxcRes.code || code;
1383
- if (oxcRes.map) {
1384
- intermediateMaps.push(typeof oxcRes.map === "string" ? JSON.parse(oxcRes.map) : oxcRes.map);
1385
- }
1386
- try {
1387
- const esbuildRes = await transformHermesAsync(code, filename, true, options.type === "script" ? void 0 : "cjs");
1388
- if (esbuildRes) {
1389
- code = esbuildRes.code;
1390
- if (esbuildRes.map) {
1391
- intermediateMaps.push(esbuildRes.map);
1392
- }
1393
- }
1394
- } catch (err) {
1395
- throw new Error(`[vxrn/metro] native async/CJS lowering failed for ${filename}: ${err.message || err}`);
1396
- }
1397
- try {
1398
- const loopsRes = transformHermesLoops(code, filename);
1399
- if (loopsRes) {
1400
- code = loopsRes.code;
1401
- for (const map2 of loopsRes.maps) {
1402
- intermediateMaps.push(map2);
1403
- }
1404
- }
1405
- } catch (err) {
1406
- throw new Error(`[vxrn/metro] Hermes loop-binding transform failed for ${filename}: ${err.message || err}`);
1407
- }
1408
- const finalDeps = extractDependencies(code, filename, {
1409
- asyncRequireModulePath: asyncRequirePath,
1410
- allowOptionalDependencies: config.allowOptionalDependencies
1411
- });
1412
- const finalNames = new Set(finalDeps.map(d => d.name));
1413
- const reconciled = dependencies.filter(d => finalNames.has(d.name));
1414
- for (const injected of finalDeps) {
1415
- if (reconciled.some(d => d.name === injected.name)) continue;
1416
- reconciled.push(injected);
1417
- }
1418
- dependencies.length = 0;
1419
- for (const dep of reconciled) {
1420
- dependencies.push({
1421
- ...dep,
1422
- data: {
1423
- ...dep.data,
1424
- index: dependencies.length
1425
- }
1426
- });
1427
- }
1428
- const depMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1429
- if (options.type === "script") {
1430
- const msScript = new MagicString(code);
1431
- msScript.prepend(`(function (global) {
1083
+ assertNoUnportedBabelPlugins(options);
1084
+ let sourceCode = typeof data === "string" ? data : data.toString("utf8");
1085
+ sourceCode = substituteExpoVirtualEnvSource({
1086
+ filename,
1087
+ src: sourceCode,
1088
+ projectRoot,
1089
+ dev: options.dev,
1090
+ environment: options.customTransformOptions?.environment
1091
+ });
1092
+ checkReservedStrings(sourceCode, config, options);
1093
+ if (filename.endsWith(".json")) {
1094
+ try {
1095
+ JSON.parse(sourceCode);
1096
+ } catch (err) {
1097
+ throw new Error(`[vxrn/metro] JSON parse error in ${filename}: ${err.message || err}`);
1098
+ }
1099
+ let code2 = config.unstable_disableModuleWrapping === true ? `module.exports = ${sourceCode};` : wrapJson(sourceCode, {
1100
+ globalPrefix: config.globalPrefix,
1101
+ moduleId: options.moduleId,
1102
+ dependencyIds: options.dependencyIds
1103
+ });
1104
+ if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1105
+ try {
1106
+ const minifier = require(config.minifierPath);
1107
+ const minified = await minifier({
1108
+ code: code2,
1109
+ config: config.minifierConfig,
1110
+ filename
1111
+ });
1112
+ code2 = minified.code;
1113
+ } catch (err) {
1114
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1115
+ }
1116
+ }
1117
+ const { lineCount: lineCount2, map: map2 } = countLinesAndTerminateMap(code2, []);
1118
+ const outputType = options.type === "asset" ? "js/module/asset" : options.type === "script" ? "js/script" : "js/module";
1119
+ return {
1120
+ dependencies: [],
1121
+ output: [{
1122
+ data: {
1123
+ code: code2,
1124
+ lineCount: lineCount2,
1125
+ map: map2,
1126
+ functionMap: null
1127
+ },
1128
+ type: outputType
1129
+ }]
1130
+ };
1131
+ }
1132
+ if (options.type === "asset") {
1133
+ const assetRegistryPath = config.assetRegistryPath || "react-native/asset-registry";
1134
+ let properDescriptor = null;
1135
+ const absolutePath = path.resolve(projectRoot, filename);
1136
+ if (fs.existsSync(absolutePath)) {
1137
+ try {
1138
+ let getAssetData;
1139
+ try {
1140
+ getAssetData = require("metro/private/Assets").getAssetData;
1141
+ } catch {
1142
+ getAssetData = require("metro/src/Assets").getAssetData;
1143
+ }
1144
+ if (typeof getAssetData === "function") {
1145
+ const rawData = await getAssetData(absolutePath, filename, config.assetPlugins || [], options.platform || "", config.publicPath || "/assets");
1146
+ const copied = { ...rawData };
1147
+ delete copied.files;
1148
+ delete copied.fileSystemLocation;
1149
+ delete copied.path;
1150
+ properDescriptor = copied;
1151
+ }
1152
+ } catch (err) {
1153
+ throw new Error(`[vxrn/metro] Asset resolution failed for ${filename}: ${err.message || err}`);
1154
+ }
1155
+ }
1156
+ if (!properDescriptor) {
1157
+ const ext = path.extname(filename).slice(1);
1158
+ const name = path.basename(filename, "." + ext);
1159
+ properDescriptor = {
1160
+ __packager_asset: true,
1161
+ httpServerLocation: config.publicPath || "/assets",
1162
+ width: void 0,
1163
+ height: void 0,
1164
+ scales: [1],
1165
+ hash: crypto.createHash("md5").update(sourceCode).digest("hex"),
1166
+ name,
1167
+ type: ext
1168
+ };
1169
+ }
1170
+ const assetDepMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1171
+ const assetCode = `module.exports = require(${assetDepMapName}[0], ${JSON.stringify(assetRegistryPath)}).registerAsset(${JSON.stringify(properDescriptor)});`;
1172
+ let code2 = config.unstable_disableModuleWrapping === true ? assetCode : wrapModule(assetCode, {
1173
+ globalPrefix: config.globalPrefix,
1174
+ moduleId: options.moduleId,
1175
+ dependencyIds: options.dependencyIds,
1176
+ dependencyMapName: config.unstable_dependencyMapReservedName
1177
+ });
1178
+ const dependencies2 = [{
1179
+ name: assetRegistryPath,
1180
+ data: {
1181
+ key: getDependencyKey(assetRegistryPath, false, null),
1182
+ asyncType: null,
1183
+ locs: [],
1184
+ isESMImportAtSource: false,
1185
+ isESMImport: false,
1186
+ index: 0
1187
+ }
1188
+ }];
1189
+ const { lineCount: lineCount2, map: map2 } = countLinesAndTerminateMap(code2, []);
1190
+ return {
1191
+ dependencies: dependencies2,
1192
+ output: [{
1193
+ data: {
1194
+ code: code2,
1195
+ lineCount: lineCount2,
1196
+ map: map2,
1197
+ functionMap: null
1198
+ },
1199
+ type: "js/module/asset"
1200
+ }]
1201
+ };
1202
+ }
1203
+ let code = sourceCode;
1204
+ const intermediateMaps = [];
1205
+ for (const nativeTransform of getNativeTransforms(options, projectRoot)) {
1206
+ const out = nativeTransform(code, {
1207
+ filename: path.isAbsolute(filename) ? filename : path.resolve(projectRoot, filename),
1208
+ platform: options.platform,
1209
+ dev: options.dev,
1210
+ projectRoot
1211
+ });
1212
+ if (typeof out === "string") code = out;
1213
+ }
1214
+ const oneRouterOptions = getOneRouterMetroOptions(options);
1215
+ if (oneRouterOptions) {
1216
+ code = applyOneRouterMetro(code, filename, oneRouterOptions);
1217
+ }
1218
+ try {
1219
+ const codegenRes = transformReactNativeCodegen(code, filename, projectRoot);
1220
+ if (codegenRes?.code) {
1221
+ code = codegenRes.code;
1222
+ if (codegenRes.map) {
1223
+ intermediateMaps.push(codegenRes.map);
1224
+ }
1225
+ }
1226
+ } catch (err) {
1227
+ throw new Error(`[vxrn/metro] React Native codegen failed for ${filename}: ${err.message || err}`);
1228
+ }
1229
+ if (shouldStripFlow(filename, code)) {
1230
+ try {
1231
+ const flowResult = await stripFlowTypes(filename, code);
1232
+ if (flowResult?.code) {
1233
+ code = flowResult.code;
1234
+ if (flowResult.map) {
1235
+ intermediateMaps.push(typeof flowResult.map === "string" ? JSON.parse(flowResult.map) : flowResult.map);
1236
+ }
1237
+ }
1238
+ } catch (err) {
1239
+ throw new Error(`[vxrn/metro] Flow transform failed for ${filename}: ${err.message || err}`);
1240
+ }
1241
+ }
1242
+ const asyncRequirePath = config.asyncRequireModulePath || "metro-runtime/src/modules/asyncRequire";
1243
+ const aliases = getModuleResolverAliases(options);
1244
+ if (aliases && projectRoot) {
1245
+ const aliasKeys = Object.keys(aliases);
1246
+ if (aliasKeys.some((k) => code.includes(k.endsWith("$") ? k.slice(0, -1) : k))) {
1247
+ code = applyModuleResolverAliases(code, filename, projectRoot, aliases);
1248
+ }
1249
+ }
1250
+ if (code.includes("process.env") || code.includes("import.meta")) {
1251
+ code = applyInlineEnvVars(code, filename, !options.dev, getImportMetaEnv(options));
1252
+ }
1253
+ if (code.includes("-only")) {
1254
+ code = applyEnvironmentGuard(code, filename);
1255
+ }
1256
+ const serverCodeRouterRoot = getRemoveServerCodeRouterRoot(options);
1257
+ if (serverCodeRouterRoot && projectRoot && !filename.includes("node_modules")) {
1258
+ const oneNativeTransforms2 = loadOneNativeTransforms(projectRoot);
1259
+ if (oneNativeTransforms2) {
1260
+ const shaken = await oneNativeTransforms2.transformTreeShakeClient(code, filename, projectRoot, serverCodeRouterRoot);
1261
+ if (shaken?.code) {
1262
+ code = shaken.code;
1263
+ }
1264
+ }
1265
+ }
1266
+ const dependencies = extractDependencies(code, filename, {
1267
+ asyncRequireModulePath: asyncRequirePath,
1268
+ allowOptionalDependencies: config.allowOptionalDependencies
1269
+ });
1270
+ await configureWorkletsForWorker(projectRoot);
1271
+ let shouldRunWorklets = Boolean(options.customTransformOptions?.worklets);
1272
+ if (!shouldRunWorklets) {
1273
+ const { shouldTransformWorklets } = await import("@vxrn/compiler");
1274
+ shouldRunWorklets = shouldTransformWorklets({
1275
+ id: filename,
1276
+ code
1277
+ });
1278
+ }
1279
+ const shouldRunReactCompiler = Boolean(options.customTransformOptions?.reactCompiler) || hasBabelPlugin(options, "babel-plugin-react-compiler") && isReactCompilerCandidate(filename) || code.includes("\"use memo\"") || code.includes("'use memo'");
1280
+ if (shouldRunReactCompiler) {
1281
+ try {
1282
+ const { prepareWorkletsForReactCompiler, transformOxcReactCompiler } = await import("@vxrn/compiler");
1283
+ if (shouldRunWorklets) {
1284
+ const prepared = prepareWorkletsForReactCompiler(filename, code, true);
1285
+ if (prepared) {
1286
+ code = prepared.code;
1287
+ if (prepared.map) intermediateMaps.push(prepared.map);
1288
+ }
1289
+ }
1290
+ const compilerRes = await transformOxcReactCompiler(filename, code, "19", true);
1291
+ if (compilerRes?.code) {
1292
+ code = compilerRes.code;
1293
+ if (compilerRes.map) {
1294
+ intermediateMaps.push(typeof compilerRes.map === "string" ? JSON.parse(compilerRes.map) : compilerRes.map);
1295
+ }
1296
+ }
1297
+ } catch (err) {
1298
+ throw new Error(`[vxrn/metro] React Compiler failed for ${filename}: ${err.message || err}`);
1299
+ }
1300
+ }
1301
+ if (shouldRunWorklets) {
1302
+ try {
1303
+ const { transformWorklets } = await import("@vxrn/compiler");
1304
+ const workletRes = await transformWorklets(filename, code, true, { projectRoot });
1305
+ if (workletRes?.code) {
1306
+ code = workletRes.code;
1307
+ if (workletRes.map) {
1308
+ intermediateMaps.push(typeof workletRes.map === "string" ? JSON.parse(workletRes.map) : workletRes.map);
1309
+ }
1310
+ }
1311
+ } catch (err) {
1312
+ throw new Error(`[vxrn/metro] Worklets transform failed for ${filename}: ${err.message || err}`);
1313
+ }
1314
+ }
1315
+ const lang = langForFilename(filename);
1316
+ const { transformSync: oxcTransform } = await import("oxc-transform");
1317
+ let oxcRes;
1318
+ try {
1319
+ oxcRes = oxcTransform(filename, code, {
1320
+ lang,
1321
+ target: "es2020",
1322
+ assumptions: { setPublicClassFields: true },
1323
+ jsx: {
1324
+ runtime: "automatic",
1325
+ development: Boolean(options.dev)
1326
+ },
1327
+ sourcemap: true
1328
+ });
1329
+ } catch (err) {
1330
+ throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${err.message || err}`);
1331
+ }
1332
+ if (oxcRes.errors?.length) {
1333
+ throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${oxcRes.errors[0].message || oxcRes.errors[0]}`);
1334
+ }
1335
+ code = oxcRes.code || code;
1336
+ if (oxcRes.map) {
1337
+ intermediateMaps.push(typeof oxcRes.map === "string" ? JSON.parse(oxcRes.map) : oxcRes.map);
1338
+ }
1339
+ try {
1340
+ const esbuildRes = await transformHermesAsync(code, filename, true, options.type === "script" ? void 0 : "cjs");
1341
+ if (esbuildRes) {
1342
+ code = esbuildRes.code;
1343
+ if (esbuildRes.map) {
1344
+ intermediateMaps.push(esbuildRes.map);
1345
+ }
1346
+ }
1347
+ } catch (err) {
1348
+ throw new Error(`[vxrn/metro] native async/CJS lowering failed for ${filename}: ${err.message || err}`);
1349
+ }
1350
+ try {
1351
+ const loopsRes = transformHermesLoops(code, filename);
1352
+ if (loopsRes) {
1353
+ code = loopsRes.code;
1354
+ for (const map2 of loopsRes.maps) {
1355
+ intermediateMaps.push(map2);
1356
+ }
1357
+ }
1358
+ } catch (err) {
1359
+ throw new Error(`[vxrn/metro] Hermes loop-binding transform failed for ${filename}: ${err.message || err}`);
1360
+ }
1361
+ const finalDeps = extractDependencies(code, filename, {
1362
+ asyncRequireModulePath: asyncRequirePath,
1363
+ allowOptionalDependencies: config.allowOptionalDependencies
1364
+ });
1365
+ const finalNames = new Set(finalDeps.map((d) => d.name));
1366
+ const reconciled = dependencies.filter((d) => finalNames.has(d.name));
1367
+ for (const injected of finalDeps) {
1368
+ if (reconciled.some((d) => d.name === injected.name)) continue;
1369
+ reconciled.push(injected);
1370
+ }
1371
+ dependencies.length = 0;
1372
+ for (const dep of reconciled) {
1373
+ dependencies.push({
1374
+ ...dep,
1375
+ data: {
1376
+ ...dep.data,
1377
+ index: dependencies.length
1378
+ }
1379
+ });
1380
+ }
1381
+ const depMapName = config.unstable_dependencyMapReservedName || "_dependencyMap";
1382
+ if (options.type === "script") {
1383
+ const msScript = new MagicString(code);
1384
+ msScript.prepend(`(function (global) {
1432
1385
  `);
1433
- msScript.append(`
1386
+ msScript.append(`
1434
1387
  })(typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this);`);
1435
- code = msScript.toString();
1436
- intermediateMaps.push(msScript.generateMap({
1437
- source: filename,
1438
- hires: true,
1439
- includeContent: true
1440
- }));
1441
- } else if (config.unstable_disableModuleWrapping === true) {
1442
- const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1443
- code = rewriteRes.code;
1444
- if (rewriteRes.map) {
1445
- intermediateMaps.push(rewriteRes.map);
1446
- }
1447
- } else {
1448
- const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1449
- if (rewriteRes.map) {
1450
- intermediateMaps.push(rewriteRes.map);
1451
- }
1452
- const msWrap = new MagicString(rewriteRes.code);
1453
- const globalPrefix = config.globalPrefix || "";
1454
- const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMapName}) {
1388
+ code = msScript.toString();
1389
+ intermediateMaps.push(msScript.generateMap({
1390
+ source: filename,
1391
+ hires: true,
1392
+ includeContent: true
1393
+ }));
1394
+ } else if (config.unstable_disableModuleWrapping === true) {
1395
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1396
+ code = rewriteRes.code;
1397
+ if (rewriteRes.map) {
1398
+ intermediateMaps.push(rewriteRes.map);
1399
+ }
1400
+ } else {
1401
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath);
1402
+ if (rewriteRes.map) {
1403
+ intermediateMaps.push(rewriteRes.map);
1404
+ }
1405
+ const msWrap = new MagicString(rewriteRes.code);
1406
+ const globalPrefix = config.globalPrefix || "";
1407
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMapName}) {
1455
1408
  var require = _$$_REQUIRE;
1456
1409
  `;
1457
- const footer = `
1410
+ const footer = `
1458
1411
  }`;
1459
- msWrap.prepend(`${globalPrefix}__d(${header}`);
1460
- if (options.moduleId !== void 0) {
1461
- const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
1462
- msWrap.append(`${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`);
1463
- } else {
1464
- msWrap.append(`${footer});`);
1465
- }
1466
- code = msWrap.toString();
1467
- intermediateMaps.push(msWrap.generateMap({
1468
- source: filename,
1469
- hires: true,
1470
- includeContent: true
1471
- }));
1472
- }
1473
- if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1474
- try {
1475
- const minifier = require(config.minifierPath);
1476
- const minified = await minifier({
1477
- code,
1478
- config: config.minifierConfig,
1479
- filename,
1480
- map: new MagicString(code).generateMap({
1481
- source: filename,
1482
- hires: true,
1483
- includeContent: true
1484
- })
1485
- });
1486
- code = minified.code;
1487
- if (minified.map) {
1488
- intermediateMaps.push(typeof minified.map === "string" ? JSON.parse(minified.map) : minified.map);
1489
- } else {
1490
- intermediateMaps.length = 0;
1491
- }
1492
- } catch (err) {
1493
- throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1494
- }
1495
- }
1496
- let rawMappings = [];
1497
- if (intermediateMaps.length > 0) {
1498
- const cleanMaps = intermediateMaps.map(m => typeof m === "string" ? JSON.parse(m) : m).filter(Boolean);
1499
- if (cleanMaps.length > 0) {
1500
- const composed = cleanMaps.length === 1 ? cleanMaps[0] : remapping(cleanMaps.slice().reverse(), () => null);
1501
- rawMappings = convertSourceMapToMetroRawMappings(composed);
1502
- }
1503
- }
1504
- const {
1505
- lineCount,
1506
- map
1507
- } = countLinesAndTerminateMap(code, rawMappings);
1508
- return {
1509
- dependencies,
1510
- output: [{
1511
- data: {
1512
- code,
1513
- lineCount,
1514
- map,
1515
- functionMap: null
1516
- },
1517
- type: options.type === "script" ? "js/script" : "js/module"
1518
- }]
1519
- };
1412
+ msWrap.prepend(`${globalPrefix}__d(${header}`);
1413
+ if (options.moduleId !== void 0) {
1414
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : "[]";
1415
+ msWrap.append(`${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`);
1416
+ } else {
1417
+ msWrap.append(`${footer});`);
1418
+ }
1419
+ code = msWrap.toString();
1420
+ intermediateMaps.push(msWrap.generateMap({
1421
+ source: filename,
1422
+ hires: true,
1423
+ includeContent: true
1424
+ }));
1425
+ }
1426
+ if (options.minify && options.unstable_transformProfile !== "hermes-canary" && options.unstable_transformProfile !== "hermes-stable" && config.minifierPath) {
1427
+ try {
1428
+ const minifier = require(config.minifierPath);
1429
+ const minified = await minifier({
1430
+ code,
1431
+ config: config.minifierConfig,
1432
+ filename,
1433
+ map: new MagicString(code).generateMap({
1434
+ source: filename,
1435
+ hires: true,
1436
+ includeContent: true
1437
+ })
1438
+ });
1439
+ code = minified.code;
1440
+ if (minified.map) {
1441
+ intermediateMaps.push(typeof minified.map === "string" ? JSON.parse(minified.map) : minified.map);
1442
+ } else {
1443
+ intermediateMaps.length = 0;
1444
+ }
1445
+ } catch (err) {
1446
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`);
1447
+ }
1448
+ }
1449
+ let rawMappings = [];
1450
+ if (intermediateMaps.length > 0) {
1451
+ const cleanMaps = intermediateMaps.map((m) => typeof m === "string" ? JSON.parse(m) : m).filter(Boolean);
1452
+ if (cleanMaps.length > 0) {
1453
+ const composed = cleanMaps.length === 1 ? cleanMaps[0] : remapping(cleanMaps.slice().reverse(), () => null);
1454
+ rawMappings = convertSourceMapToMetroRawMappings(composed);
1455
+ }
1456
+ }
1457
+ const { lineCount, map } = countLinesAndTerminateMap(code, rawMappings);
1458
+ return {
1459
+ dependencies,
1460
+ output: [{
1461
+ data: {
1462
+ code,
1463
+ lineCount,
1464
+ map,
1465
+ functionMap: null
1466
+ },
1467
+ type: options.type === "script" ? "js/script" : "js/module"
1468
+ }]
1469
+ };
1520
1470
  }
1521
1471
  var metroNativeWorker_default = {
1522
- transform,
1523
- getCacheKey,
1524
- wrapModule,
1525
- wrapJson,
1526
- extractDependencies,
1527
- rewriteDependencyCalls,
1528
- convertSourceMapToMetroRawMappings
1472
+ transform,
1473
+ getCacheKey,
1474
+ wrapModule,
1475
+ wrapJson,
1476
+ extractDependencies,
1477
+ rewriteDependencyCalls,
1478
+ convertSourceMapToMetroRawMappings
1529
1479
  };
1480
+
1530
1481
  export { ScopeTracker, applyEnvironmentGuard, applyInlineEnvVars, applyModuleResolverAliases, applyOneRouterMetro, assertNoUnportedBabelPlugins, collectBlockBindings, collectHoistedBindings, collectPatternNames, convertSourceMapToMetroRawMappings, countLinesAndTerminateMap, metroNativeWorker_default as default, extractDependencies, getCacheKey, getDependencyKey, getImportMetaEnv, getModuleResolverAliases, getOneRouterMetroOptions, getRemoveServerCodeRouterRoot, resolveAliasSpecifier, rewriteDependencyCalls, transform, wrapJson, wrapModule };
1531
1482
  //# sourceMappingURL=metroNativeWorker.mjs.map