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