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