@vxrn/vite-plugin-metro 1.25.13 → 1.25.16-1788753284749

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 (49) hide show
  1. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.cjs +20 -0
  2. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  3. package/dist/cjs/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  4. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.cjs +2 -1
  5. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  6. package/dist/cjs/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  7. package/dist/cjs/plugins/metroPlugin.native.js.map +1 -1
  8. package/dist/cjs/transformer/metroNativeWorker.cjs +1594 -0
  9. package/dist/cjs/transformer/metroNativeWorker.native.js +2678 -0
  10. package/dist/cjs/transformer/metroNativeWorker.native.js.map +1 -0
  11. package/dist/cjs/transformer/metroNativeWorker.test.cjs +813 -0
  12. package/dist/cjs/transformer/metroNativeWorker.test.native.js +920 -0
  13. package/dist/cjs/transformer/metroNativeWorker.test.native.js.map +1 -0
  14. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs +20 -0
  15. package/dist/esm/metro-config/getMetroConfigFromViteConfig.mjs.map +1 -1
  16. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js +20 -0
  17. package/dist/esm/metro-config/getMetroConfigFromViteConfig.native.js.map +1 -1
  18. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs +2 -1
  19. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.mjs.map +1 -1
  20. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js +2 -1
  21. package/dist/esm/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.native.js.map +1 -1
  22. package/dist/esm/plugins/metroPlugin.mjs.map +1 -1
  23. package/dist/esm/plugins/metroPlugin.native.js.map +1 -1
  24. package/dist/esm/transformer/metroNativeWorker.mjs +1535 -0
  25. package/dist/esm/transformer/metroNativeWorker.mjs.map +1 -0
  26. package/dist/esm/transformer/metroNativeWorker.native.js +2616 -0
  27. package/dist/esm/transformer/metroNativeWorker.native.js.map +1 -0
  28. package/dist/esm/transformer/metroNativeWorker.test.mjs +777 -0
  29. package/dist/esm/transformer/metroNativeWorker.test.mjs.map +1 -0
  30. package/dist/esm/transformer/metroNativeWorker.test.native.js +882 -0
  31. package/dist/esm/transformer/metroNativeWorker.test.native.js.map +1 -0
  32. package/package.json +22 -3
  33. package/src/metro-config/getMetroConfigFromViteConfig.ts +42 -0
  34. package/src/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.ts +1 -0
  35. package/src/plugins/metroPlugin.ts +22 -0
  36. package/src/transformer/__fixtures__/exampleNativeTransform.cjs +17 -0
  37. package/src/transformer/metroNativeWorker.test.ts +1138 -0
  38. package/src/transformer/metroNativeWorker.ts +2385 -0
  39. package/src/transformer/types.ts +21 -0
  40. package/types/metro-config/getMetroConfigFromViteConfig.d.ts.map +1 -1
  41. package/types/metro-config/patchMetroServerWithViteConfigAndMetroPluginOptions.d.ts.map +1 -1
  42. package/types/plugins/metroPlugin.d.ts +22 -0
  43. package/types/plugins/metroPlugin.d.ts.map +1 -1
  44. package/types/transformer/metroNativeWorker.d.ts +251 -0
  45. package/types/transformer/metroNativeWorker.d.ts.map +1 -0
  46. package/types/transformer/metroNativeWorker.test.d.ts +2 -0
  47. package/types/transformer/metroNativeWorker.test.d.ts.map +1 -0
  48. package/types/transformer/types.d.ts +17 -0
  49. package/types/transformer/types.d.ts.map +1 -1
@@ -0,0 +1,2385 @@
1
+ import crypto from 'node:crypto'
2
+ import { createRequire } from 'node:module'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { parseSync } from 'oxc-parser'
6
+ import MagicString from 'magic-string'
7
+ import remapping from '@jridgewell/remapping'
8
+ import { TraceMap, eachMapping } from '@jridgewell/trace-mapping'
9
+ import { transformHermesLoops, transformReactNativeCodegen } from '@vxrn/compiler'
10
+ import { getPlatformEnv, metroPlatformToViteEnvironment } from '../env/platformEnv'
11
+
12
+ // `async function*`, the `async *name()` method shorthand, and `for await (`.
13
+ // Hermes rejects all three at parse time with "async generators are unsupported".
14
+ // the shorthand arm can also match `async * x` multiplication, which only costs
15
+ // that module a lower transform target.
16
+ const HERMES_UNSUPPORTED_ASYNC_RE =
17
+ /\basync\s+function\s*\*|\basync\s*\*\s*[\w$[]|\bfor\s+await\s*\(/
18
+
19
+ /**
20
+ * Module-scope bindings initialized to a literal and never reassigned, so a
21
+ * `require.context` argument held in a variable resolves to its value. Metro
22
+ * evaluates those arguments rather than demanding literals, and one's router
23
+ * entry keeps its route root in exactly such a binding.
24
+ *
25
+ * The declaration kind is deliberately ignored. The Hermes loop-binding pass
26
+ * rewrites every `const` to `var`, so matching on the keyword would stop
27
+ * resolving the router root and drop every route from the bundle. Not being
28
+ * reassigned is the property that actually matters.
29
+ */
30
+ function collectModuleLiteralBindings(program: any): Map<string, any> {
31
+ const reassigned = new Set<string>()
32
+ const declCount = new Map<string, number>()
33
+
34
+ ;(function findReassignments(node: any) {
35
+ if (!node || typeof node !== 'object') return
36
+ if (Array.isArray(node)) {
37
+ for (const child of node) findReassignments(child)
38
+ return
39
+ }
40
+ if (node.type === 'AssignmentExpression' && node.left?.type === 'Identifier') {
41
+ reassigned.add(node.left.name)
42
+ } else if (node.type === 'UpdateExpression' && node.argument?.type === 'Identifier') {
43
+ reassigned.add(node.argument.name)
44
+ }
45
+ for (const key in node) {
46
+ if (key === 'type' || key === 'start' || key === 'end') continue
47
+ findReassignments(node[key])
48
+ }
49
+ })(program)
50
+
51
+ for (const stmt of program.body || []) {
52
+ if (stmt.type !== 'VariableDeclaration') continue
53
+ for (const decl of stmt.declarations || []) {
54
+ if (decl.id?.type === 'Identifier') {
55
+ declCount.set(decl.id.name, (declCount.get(decl.id.name) || 0) + 1)
56
+ }
57
+ }
58
+ }
59
+
60
+ const bindings = new Map<string, any>()
61
+ for (const stmt of program.body || []) {
62
+ if (stmt.type !== 'VariableDeclaration') continue
63
+ for (const decl of stmt.declarations || []) {
64
+ if (
65
+ decl.id?.type === 'Identifier' &&
66
+ decl.init?.type === 'Literal' &&
67
+ !reassigned.has(decl.id.name) &&
68
+ declCount.get(decl.id.name) === 1
69
+ ) {
70
+ bindings.set(decl.id.name, decl.init)
71
+ }
72
+ }
73
+ }
74
+ return bindings
75
+ }
76
+
77
+ export type MetroContextParams = {
78
+ recursive: boolean
79
+ filter: { pattern: string; flags: string }
80
+ mode: 'sync' | 'eager' | 'lazy' | 'lazy-once'
81
+ }
82
+
83
+ export type MetroDependencyData = {
84
+ key?: string
85
+ asyncType?: 'async' | 'weak' | 'maybeSync' | null
86
+ contextParams?: MetroContextParams
87
+ locs: Array<{ start: { line: number; column: number }; end: { line: number; column: number } }>
88
+ isOptional?: boolean
89
+ isESMImportAtSource?: boolean
90
+ isESMImport?: boolean
91
+ index?: number
92
+ }
93
+
94
+ export type MetroDependency = {
95
+ name: string
96
+ data: MetroDependencyData
97
+ }
98
+
99
+ export type MetroOutputData = {
100
+ code: string
101
+ lineCount: number
102
+ map: any[]
103
+ functionMap?: any
104
+ }
105
+
106
+ export type MetroOutput = {
107
+ data: MetroOutputData
108
+ type: 'js/module' | 'js/script' | 'js/module/asset'
109
+ }
110
+
111
+ export type MetroWorkerResult = {
112
+ dependencies: MetroDependency[]
113
+ output: MetroOutput[]
114
+ }
115
+
116
+ export type MetroWorkerConfig = {
117
+ assetRegistryPath?: string
118
+ assetPlugins?: string[]
119
+ asyncRequireModulePath?: string
120
+ globalPrefix?: string
121
+ unstable_dependencyMapReservedName?: string
122
+ unstable_disableModuleWrapping?: boolean
123
+ minifierPath?: string
124
+ minifierConfig?: any
125
+ publicPath?: string
126
+ allowOptionalDependencies?: any
127
+ dynamicDepsInPackages?: string
128
+ }
129
+
130
+ export type MetroWorkerOptions = {
131
+ dev?: boolean
132
+ minify?: boolean
133
+ platform?: 'ios' | 'android' | 'web' | string
134
+ type?: 'module' | 'script' | 'asset'
135
+ customTransformOptions?: Record<string, any>
136
+ unstable_transformProfile?: string
137
+ moduleId?: number | string
138
+ dependencyIds?: Array<number | string>
139
+ }
140
+
141
+ export type WrapModuleOptions = {
142
+ globalPrefix?: string
143
+ moduleId?: number | string
144
+ dependencyIds?: Array<number | string>
145
+ dependencyMapName?: string
146
+ requireAlias?: boolean
147
+ }
148
+
149
+ // bump whenever this worker's output changes, or metro serves cached modules
150
+ // transformed by the previous version. '3' adds import.meta.env inlining.
151
+ const WORKER_CACHE_KEY_VERSION = '3'
152
+
153
+ const FLOW_FILE_PATTERN = /node_modules[\\/](?:react-native|@react-native)[\\/].*\.js$/
154
+
155
+ /**
156
+ * react-native ships jsx inside plain .js files, and oxc disables jsx for .js
157
+ * unless told otherwise. parsing those as 'js' fails on the first JSX element,
158
+ * so every non-typescript file is parsed as jsx.
159
+ */
160
+ function langForFilename(filename: string): 'ts' | 'tsx' | 'jsx' {
161
+ if (filename.endsWith('.tsx')) return 'tsx'
162
+ if (filename.endsWith('.ts')) return 'ts'
163
+ return 'jsx'
164
+ }
165
+
166
+ export type OneRouterMetroOptions = {
167
+ ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY?: string
168
+ ONE_ROUTER_LINKING_CONFIG?: unknown
169
+ ONE_ROUTER_ROOT_FOLDER_NAME?: string
170
+ ONE_ROUTER_REQUIRE_CONTEXT_REGEX_STRING?: string
171
+ ONE_SETUP_FILE_NATIVE?: string
172
+ }
173
+
174
+ /**
175
+ * one's router options reach the transformer on the same channel the babel
176
+ * transformer reads them from, as the options of its `one-router-metro` plugin
177
+ * entry.
178
+ */
179
+ export function getOneRouterMetroOptions(options: MetroWorkerOptions): OneRouterMetroOptions | undefined {
180
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
181
+ if (!Array.isArray(plugins)) return undefined
182
+ for (const plugin of plugins) {
183
+ if (Array.isArray(plugin) && typeof plugin[0] === 'string' && plugin[0].includes('one-router-metro')) {
184
+ return plugin[1] as OneRouterMetroOptions
185
+ }
186
+ }
187
+ return undefined
188
+ }
189
+
190
+ /**
191
+ * Reads the router root one's babel preset hands to
192
+ * `babel-plugin-remove-server-code`. Its absence means one did not ask for
193
+ * server-code removal, so the step is skipped rather than guessed at.
194
+ */
195
+ export function getRemoveServerCodeRouterRoot(
196
+ options: MetroWorkerOptions
197
+ ): string | undefined {
198
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
199
+ if (!Array.isArray(plugins)) return undefined
200
+ for (const plugin of plugins) {
201
+ if (
202
+ Array.isArray(plugin) &&
203
+ typeof plugin[0] === 'string' &&
204
+ plugin[0].includes('remove-server-code')
205
+ ) {
206
+ return plugin[1]?.routerRoot ?? 'app'
207
+ }
208
+ }
209
+ return undefined
210
+ }
211
+
212
+ // the merged map is the same for every file in a bundle, so it is built once
213
+ // per (plugins array, platform) rather than per file.
214
+ const importMetaEnvCache = new WeakMap<
215
+ object,
216
+ Map<string, Record<string, string | boolean | undefined>>
217
+ >()
218
+
219
+ /**
220
+ * Reads the env map one hands to its `import-meta-env-plugin`, with the
221
+ * platform's own values layered on top exactly as that plugin does. Without it
222
+ * every `import.meta.env.X` read compiles to a property of the empty
223
+ * `var import_meta = {}` oxc emits when it lowers ESM to CJS, so the whole map
224
+ * silently reads `undefined` on native.
225
+ */
226
+ export function getImportMetaEnv(
227
+ options: MetroWorkerOptions
228
+ ): Record<string, string | boolean | undefined> {
229
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
230
+ const platform = options.platform ?? ''
231
+
232
+ let byPlatform = Array.isArray(plugins) ? importMetaEnvCache.get(plugins) : undefined
233
+ const cached = byPlatform?.get(platform)
234
+ if (cached) return cached
235
+
236
+ let env: Record<string, string | boolean | undefined> = {}
237
+ if (Array.isArray(plugins)) {
238
+ for (const plugin of plugins) {
239
+ if (
240
+ Array.isArray(plugin) &&
241
+ typeof plugin[0] === 'string' &&
242
+ plugin[0].includes('import-meta-env-plugin')
243
+ ) {
244
+ const found = plugin[1]?.env
245
+ if (found && typeof found === 'object') env = found
246
+ }
247
+ }
248
+ }
249
+
250
+ const merged = {
251
+ ...env,
252
+ ...getPlatformEnv(metroPlatformToViteEnvironment(options.platform)),
253
+ }
254
+
255
+ if (Array.isArray(plugins)) {
256
+ if (!byPlatform) {
257
+ byPlatform = new Map()
258
+ importMetaEnvCache.set(plugins, byPlatform)
259
+ }
260
+ byPlatform.set(platform, merged)
261
+ }
262
+ return merged
263
+ }
264
+
265
+ // every babel plugin id this worker has a native port of. the worker runs no
266
+ // babel at all, so a plugin outside this list has no effect whatsoever.
267
+ const PORTED_BABEL_PLUGINS = [
268
+ 'import-meta-env-plugin',
269
+ 'one-router-metro',
270
+ 'remove-server-code',
271
+ 'module-resolver',
272
+ 'environment-guard',
273
+ 'inline-one-server-url',
274
+ // the worklets transform is a native oxc port, so both plugin names it can
275
+ // arrive under are covered.
276
+ 'react-native-worklets/plugin',
277
+ 'react-native-reanimated/plugin',
278
+ 'babel-plugin-react-compiler',
279
+ ]
280
+
281
+ // keyed on the plugins array so the scan happens once per bundle rather than
282
+ // once per file, while every file still fails.
283
+ const unportedPluginCache = new WeakMap<object, string[]>()
284
+
285
+ const loadedNativeTransforms = new Map<string, (code: string, ctx: any) => unknown>()
286
+
287
+ /**
288
+ * Loads the user's own native transforms — the thing a babel plugin becomes
289
+ * when there is no babel. Each module default-exports `(code, ctx) => string`.
290
+ * Resolved from the project root, since they are the app's dependencies rather
291
+ * than this package's.
292
+ */
293
+ function getNativeTransforms(
294
+ options: MetroWorkerOptions,
295
+ projectRoot: string
296
+ ): ((code: string, ctx: any) => unknown)[] {
297
+ const ids = (options.customTransformOptions as any)?.vite?.nativeTransformModules
298
+ if (!Array.isArray(ids) || !ids.length) return []
299
+
300
+ const req = createRequire(path.join(projectRoot, 'package.json'))
301
+ return ids.map((id: string) => {
302
+ const cached = loadedNativeTransforms.get(id)
303
+ if (cached) return cached
304
+
305
+ let mod: any
306
+ try {
307
+ mod = req(id)
308
+ } catch (err: any) {
309
+ throw new Error(
310
+ `[vxrn/metro] Could not load the native transform "${id}" from ${projectRoot}: ${err.message}`
311
+ )
312
+ }
313
+ const fn = mod?.default ?? mod
314
+ if (typeof fn !== 'function') {
315
+ throw new Error(
316
+ `[vxrn/metro] The native transform "${id}" must default-export a function (code, ctx) => string.`
317
+ )
318
+ }
319
+ loadedNativeTransforms.set(id, fn)
320
+ return fn
321
+ })
322
+ }
323
+
324
+ /**
325
+ * The same files @vxrn/compiler's `applyDefaultFilters` runs the react compiler
326
+ * on for the vite path: app typescript only. node_modules is excluded because
327
+ * react-native's own sources are flow, which the oxc react compiler rejects
328
+ * outright, and the app never asked for its dependencies to be memoized.
329
+ */
330
+ function isReactCompilerCandidate(filename: string): boolean {
331
+ if (!/\.tsx?$/.test(filename)) return false
332
+ if (filename.includes('node_modules')) return false
333
+ if (filename.includes('+api.')) return false
334
+ return true
335
+ }
336
+
337
+ /**
338
+ * Whether the babel plugin list one handed metro names `id`. The list is the
339
+ * only channel one has to say "the app turned this on", so the ported
340
+ * transforms read their own gate out of it.
341
+ */
342
+ function hasBabelPlugin(options: MetroWorkerOptions, id: string): boolean {
343
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
344
+ if (!Array.isArray(plugins)) return false
345
+ return plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === id)
346
+ }
347
+
348
+ /**
349
+ * A babel plugin the user added through `bundlerOptions.babelConfigOverrides`
350
+ * would silently do nothing here, because this worker replaced babel outright.
351
+ * Silently dropping someone's OTA or instrumentation plugin is worse than
352
+ * refusing to build, so it is named and thrown.
353
+ */
354
+ export function assertNoUnportedBabelPlugins(options: MetroWorkerOptions): void {
355
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
356
+ if (!Array.isArray(plugins)) return
357
+
358
+ let unported = unportedPluginCache.get(plugins)
359
+ if (!unported) {
360
+ unported = []
361
+ for (const plugin of plugins) {
362
+ const id = Array.isArray(plugin) ? plugin[0] : plugin
363
+ if (typeof id !== 'string') {
364
+ unported.push('(a function or object plugin, which cannot be ported)')
365
+ continue
366
+ }
367
+ if (!PORTED_BABEL_PLUGINS.some((ported) => id.includes(ported))) {
368
+ unported.push(id)
369
+ }
370
+ }
371
+ unportedPluginCache.set(plugins, unported)
372
+ }
373
+
374
+ if (unported.length) {
375
+ throw new Error(
376
+ `[vxrn/metro] the native transform path runs no babel, so these babel plugins would be silently ignored:\n` +
377
+ unported.map((id) => ` - ${id}`).join('\n') +
378
+ `\n\nPort each one to a native transform and list it in bundlerOptions.nativeTransformModules, ` +
379
+ `remove it from bundlerOptions.babelConfigOverrides, or set ` +
380
+ `bundlerOptions.nativeTransforms: false (or ONE_METRO_NATIVE_TRANSFORMS=0) ` +
381
+ `to go back to the babel transformer.`
382
+ )
383
+ }
384
+ }
385
+
386
+ /**
387
+ * Reads the alias map one's babel preset hands to `babel-plugin-module-resolver`
388
+ * (its "vite-tsconfig-paths for Metro"). Keys ending in `$` are exact matches,
389
+ * the rest are prefixes.
390
+ */
391
+ export function getModuleResolverAliases(
392
+ options: MetroWorkerOptions
393
+ ): Record<string, string> | undefined {
394
+ const plugins = (options.customTransformOptions as any)?.vite?.babelConfig?.plugins
395
+ if (!Array.isArray(plugins)) return undefined
396
+ for (const plugin of plugins) {
397
+ if (
398
+ Array.isArray(plugin) &&
399
+ typeof plugin[0] === 'string' &&
400
+ plugin[0].includes('module-resolver')
401
+ ) {
402
+ const alias = plugin[1]?.alias
403
+ if (alias && typeof alias === 'object') return alias
404
+ }
405
+ }
406
+ return undefined
407
+ }
408
+
409
+ /**
410
+ * Resolves one tsconfig-path alias to a specifier relative to the importing
411
+ * file. The native worker replaces the babel transformer, so without this every
412
+ * aliased import fails to resolve.
413
+ */
414
+ export function resolveAliasSpecifier(
415
+ specifier: string,
416
+ filename: string,
417
+ projectRoot: string,
418
+ aliases: Record<string, string>
419
+ ): string | undefined {
420
+ for (const [rawKey, value] of Object.entries(aliases)) {
421
+ let target: string | undefined
422
+ if (rawKey.endsWith('$')) {
423
+ if (specifier === rawKey.slice(0, -1)) target = value
424
+ } else if (specifier === rawKey || specifier.startsWith(`${rawKey}/`)) {
425
+ target = value + specifier.slice(rawKey.length)
426
+ }
427
+ if (target === undefined) continue
428
+
429
+ const abs = path.resolve(projectRoot, target)
430
+ let rel = path.relative(path.dirname(filename), abs).split(path.sep).join('/')
431
+ if (!rel.startsWith('.')) rel = `./${rel}`
432
+ return rel
433
+ }
434
+ return undefined
435
+ }
436
+
437
+ /**
438
+ * Rewrites aliased import/export/require specifiers in place.
439
+ */
440
+ export function applyModuleResolverAliases(
441
+ code: string,
442
+ filename: string,
443
+ projectRoot: string,
444
+ aliases: Record<string, string>
445
+ ): string {
446
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) })
447
+ if (parsed?.errors?.length) {
448
+ throw new Error(
449
+ `[vxrn/metro] Failed to parse ${filename} for alias resolution: ${parsed.errors[0].message}`
450
+ )
451
+ }
452
+ if (!parsed?.program) return code
453
+
454
+ const ms = new MagicString(code)
455
+ let changed = false
456
+
457
+ function rewrite(sourceNode: any) {
458
+ if (sourceNode?.type !== 'Literal' || typeof sourceNode.value !== 'string') return
459
+ const resolved = resolveAliasSpecifier(sourceNode.value, filename, projectRoot, aliases)
460
+ if (resolved === undefined) return
461
+ ms.overwrite(sourceNode.start, sourceNode.end, JSON.stringify(resolved))
462
+ changed = true
463
+ }
464
+
465
+ function walk(node: any) {
466
+ if (!node || typeof node !== 'object') return
467
+
468
+ if (
469
+ node.type === 'ImportDeclaration' ||
470
+ node.type === 'ExportNamedDeclaration' ||
471
+ node.type === 'ExportAllDeclaration' ||
472
+ node.type === 'ImportExpression'
473
+ ) {
474
+ rewrite(node.source)
475
+ } else if (
476
+ node.type === 'CallExpression' &&
477
+ node.callee?.type === 'Identifier' &&
478
+ node.callee.name === 'require'
479
+ ) {
480
+ rewrite(node.arguments?.[0])
481
+ }
482
+
483
+ for (const k of Object.keys(node)) {
484
+ if (k === 'start' || k === 'end' || k === 'loc' || k === 'range' || k === 'parent' || k === 'comments') continue
485
+ const child = node[k]
486
+ if (Array.isArray(child)) {
487
+ for (const item of child) walk(item)
488
+ } else if (child && typeof child === 'object') {
489
+ walk(child)
490
+ }
491
+ }
492
+ }
493
+
494
+ walk(parsed.program)
495
+ return changed ? ms.toString() : code
496
+ }
497
+
498
+ /**
499
+ * Native port of babel-preset-expo's `expo-inline-or-reference-env-vars` and
500
+ * one's `babel-plugin-inline-one-server-url`. In production every
501
+ * `process.env.EXPO_PUBLIC_*` read is inlined as a literal; in development each
502
+ * one is routed through the `expo/virtual/env` module so edits to .env take
503
+ * effect without a full rebuild. Without this the reads survive into the bundle
504
+ * and every EXPO_PUBLIC_ value is undefined at runtime.
505
+ *
506
+ * `process.env.ONE_SERVER_URL` is inlined in both modes, matching one's plugin:
507
+ * it is how a native bundle knows where to fetch loader data from, and a native
508
+ * runtime has no `process.env` to read it back out of.
509
+ *
510
+ * Both live in one pass because they are the same rewrite over the same walk,
511
+ * and a second parse of every file is the cost this transformer exists to avoid.
512
+ */
513
+ export function applyInlineEnvVars(
514
+ code: string,
515
+ filename: string,
516
+ isProduction: boolean,
517
+ env: Record<string, string | boolean | undefined> = {}
518
+ ): string {
519
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) })
520
+ if (parsed?.errors?.length) {
521
+ throw new Error(
522
+ `[vxrn/metro] Failed to parse ${filename} for env inlining: ${parsed.errors[0].message}`
523
+ )
524
+ }
525
+ if (!parsed?.program) return code
526
+
527
+ const ms = new MagicString(code)
528
+ let needsEnvImport = false
529
+
530
+ // edits are collected rather than written straight through, because a folded
531
+ // dead branch swallows the range an inner edit sits in and MagicString throws
532
+ // on overlapping overwrites.
533
+ const edits: { start: number; end: number; text: string }[] = []
534
+ // nodes whose value is known after inlining, so `if (import.meta.env.SSR)`
535
+ // can be resolved instead of left for metro to resolve imports inside.
536
+ const known = new Map<any, unknown>()
537
+
538
+ function replace(node: any, value: unknown) {
539
+ const text = value === undefined ? 'undefined' : JSON.stringify(value)
540
+ edits.push({ start: node.start, end: node.end, text })
541
+ known.set(node, value)
542
+ }
543
+
544
+ function keyOf(prop: any, computed: boolean): string | undefined {
545
+ if (!computed && prop?.type === 'Identifier') return prop.name
546
+ if (prop?.type === 'Literal' && typeof prop.value === 'string') return prop.value
547
+ return undefined
548
+ }
549
+
550
+ function isImportMeta(node: any): boolean {
551
+ return node?.type === 'MetaProperty' && node.meta?.name === 'import' && node.property?.name === 'meta'
552
+ }
553
+
554
+ function walk(node: any, parent: any) {
555
+ if (!node || typeof node !== 'object') return
556
+
557
+ if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
558
+ const obj = node.object
559
+ const isMember = obj?.type === 'MemberExpression' || obj?.type === 'OptionalMemberExpression'
560
+ const isProcessEnv =
561
+ isMember &&
562
+ obj.object?.type === 'Identifier' &&
563
+ obj.object.name === 'process' &&
564
+ keyOf(obj.property, obj.computed) === 'env'
565
+ // an assignment target is left alone, matching the babel plugin: rewriting
566
+ // it would produce a write to the virtual module.
567
+ const isAssignmentTarget =
568
+ parent?.type === 'AssignmentExpression' && parent.left === node
569
+ const key = keyOf(node.property, node.computed)
570
+
571
+ if (isProcessEnv && !isAssignmentTarget && key === 'ONE_SERVER_URL') {
572
+ replace(node, process.env.ONE_SERVER_URL || '')
573
+ return
574
+ }
575
+
576
+ if (isProcessEnv && !isAssignmentTarget && key?.startsWith('EXPO_PUBLIC_')) {
577
+ if (isProduction) {
578
+ replace(node, process.env[key] ?? undefined)
579
+ } else {
580
+ edits.push({ start: node.start, end: node.end, text: `_$$_EXPO_ENV.${key}` })
581
+ needsEnvImport = true
582
+ }
583
+ return
584
+ }
585
+
586
+ // `import.meta.env.X`. the walk is top-down, so this outer node is reached
587
+ // before the `import.meta.env` inside it and the shorter form never fires.
588
+ if (
589
+ !isAssignmentTarget &&
590
+ isMember &&
591
+ isImportMeta(obj.object) &&
592
+ keyOf(obj.property, obj.computed) === 'env' &&
593
+ key !== undefined
594
+ ) {
595
+ replace(node, env[key])
596
+ return
597
+ }
598
+
599
+ // bare `import.meta.env`, spread or passed around whole.
600
+ if (!isAssignmentTarget && isImportMeta(obj) && key === 'env') {
601
+ edits.push({ start: node.start, end: node.end, text: JSON.stringify(env) })
602
+ return
603
+ }
604
+
605
+ // `process.env.X` for anything the vite env map defines. runs after the
606
+ // two branches above so ONE_SERVER_URL and EXPO_PUBLIC_ keep their own
607
+ // handling.
608
+ if (isProcessEnv && !isAssignmentTarget && key !== undefined && key in env) {
609
+ replace(node, env[key])
610
+ return
611
+ }
612
+ }
613
+
614
+ for (const k of Object.keys(node)) {
615
+ if (k === 'start' || k === 'end' || k === 'loc' || k === 'range' || k === 'parent' || k === 'comments') continue
616
+ const child = node[k]
617
+ if (Array.isArray(child)) {
618
+ for (const item of child) walk(item, node)
619
+ } else if (child && typeof child === 'object') {
620
+ walk(child, node)
621
+ }
622
+ }
623
+ }
624
+
625
+ walk(parsed.program, null)
626
+
627
+ // resolves a test expression to a boolean when inlining made it constant.
628
+ function testValue(node: any): boolean | undefined {
629
+ if (known.has(node)) return !!known.get(node)
630
+ if (node?.type === 'UnaryExpression' && node.operator === '!') {
631
+ const inner = testValue(node.argument)
632
+ return inner === undefined ? undefined : !inner
633
+ }
634
+ if (node?.type === 'BinaryExpression' && (node.operator === '===' || node.operator === '!==')) {
635
+ const left = known.has(node.left) ? known.get(node.left) : undefined
636
+ const right = node.right?.type === 'Literal' ? node.right.value : undefined
637
+ if (!known.has(node.left) || node.right?.type !== 'Literal') return undefined
638
+ return node.operator === '===' ? left === right : left !== right
639
+ }
640
+ return undefined
641
+ }
642
+
643
+ // fold constant branches so metro never tries to resolve the imports inside a
644
+ // dead one. only the dead ranges are cut, never the kept branch, so env reads
645
+ // inside the surviving branch still get their own inlining.
646
+ const dead: { start: number; end: number; text: string }[] = []
647
+ ;(function foldWalk(node: any) {
648
+ if (!node || typeof node !== 'object') return
649
+ if (Array.isArray(node)) {
650
+ for (const child of node) foldWalk(child)
651
+ return
652
+ }
653
+ if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
654
+ const value = testValue(node.test)
655
+ if (value !== undefined) {
656
+ const kept = value ? node.consequent : node.alternate
657
+ if (!kept) {
658
+ // `if (false) {...}` with no else: the whole statement is dead.
659
+ dead.push({ start: node.start, end: node.end, text: ';' })
660
+ return
661
+ }
662
+ // cutting `if (test)` off leaves the consequent as a bare statement or
663
+ // block, and cutting `test ?` leaves the branch as a bare expression.
664
+ dead.push({ start: node.start, end: kept.start, text: '' })
665
+ if (kept.end < node.end) {
666
+ dead.push({ start: kept.end, end: node.end, text: '' })
667
+ }
668
+ foldWalk(kept)
669
+ return
670
+ }
671
+ }
672
+ for (const k of Object.keys(node)) {
673
+ if (k === 'start' || k === 'end' || k === 'loc' || k === 'range' || k === 'parent' || k === 'comments') continue
674
+ foldWalk(node[k])
675
+ }
676
+ })(parsed.program)
677
+
678
+ for (const range of dead) {
679
+ ms.overwrite(range.start, range.end, range.text)
680
+ }
681
+ for (const edit of edits) {
682
+ if (dead.some((d) => edit.start >= d.start && edit.end <= d.end)) continue
683
+ ms.overwrite(edit.start, edit.end, edit.text)
684
+ }
685
+
686
+ if (needsEnvImport) {
687
+ ms.prepend(`import { env as _$$_EXPO_ENV } from "expo/virtual/env";\n`)
688
+ }
689
+ return ms.hasChanged() ? ms.toString() : code
690
+ }
691
+
692
+ // `native-only` is a side-effect guard that is satisfied simply by being in a
693
+ // native build, so the import is dropped. the other three assert the file is
694
+ // NOT in one, and a native bundle that keeps them silently ships web or server
695
+ // code, so the import becomes the throw it was standing in for.
696
+ const GUARD_SPECIFIERS = new Set(['server-only', 'client-only', 'web-only'])
697
+
698
+ /**
699
+ * Native port of one's `babel-plugin-environment-guard`.
700
+ */
701
+ export function applyEnvironmentGuard(code: string, filename: string): string {
702
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) })
703
+ if (parsed?.errors?.length) {
704
+ throw new Error(
705
+ `[vxrn/metro] Failed to parse ${filename} for environment guards: ${parsed.errors[0].message}`
706
+ )
707
+ }
708
+ const body = parsed?.program?.body
709
+ if (!body) return code
710
+
711
+ const ms = new MagicString(code)
712
+ let changed = false
713
+
714
+ for (const node of body) {
715
+ if (node.type !== 'ImportDeclaration') continue
716
+ const source = node.source?.value
717
+ if (source === 'native-only') {
718
+ ms.remove(node.start, node.end)
719
+ changed = true
720
+ } else if (GUARD_SPECIFIERS.has(source)) {
721
+ ms.overwrite(
722
+ node.start,
723
+ node.end,
724
+ `throw new Error(${JSON.stringify(`${source} cannot be imported in a native environment`)});`
725
+ )
726
+ changed = true
727
+ }
728
+ }
729
+
730
+ return changed ? ms.toString() : code
731
+ }
732
+
733
+ /**
734
+ * Native port of one's `babel-plugin-one-router-metro`. The native worker
735
+ * replaces the babel transformer wholesale, so without this the router entry
736
+ * keeps `process.env.ONE_ROUTER_*` reads that never resolve: `require.context`
737
+ * gets a non-literal regex and metro drops the entire route tree, and the
738
+ * configured setup file is never imported.
739
+ */
740
+ export function applyOneRouterMetro(
741
+ code: string,
742
+ filename: string,
743
+ options: OneRouterMetroOptions
744
+ ): string {
745
+ const isMetroEntry = filename.endsWith('metro-entry.js')
746
+ const isEntryCtx = filename.endsWith('metro-entry-ctx.js')
747
+ if (!isMetroEntry && !isEntryCtx) return code
748
+
749
+ const parsed = parseSync(filename, code, { lang: langForFilename(filename) })
750
+ if (parsed?.errors?.length) {
751
+ throw new Error(
752
+ `[vxrn/metro] Failed to parse ${filename} for one-router-metro: ${parsed.errors[0].message}`
753
+ )
754
+ }
755
+ if (!parsed?.program) return code
756
+
757
+ const ms = new MagicString(code)
758
+ let lastImportEnd = -1
759
+
760
+ function replacementFor(key: string): string | undefined {
761
+ if (key.startsWith('ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY')) {
762
+ return JSON.stringify(options.ONE_ROUTER_APP_ROOT_RELATIVE_TO_ENTRY)
763
+ }
764
+ if (key.startsWith('ONE_ROUTER_ROOT_FOLDER_NAME')) {
765
+ return JSON.stringify(options.ONE_ROUTER_ROOT_FOLDER_NAME)
766
+ }
767
+ if (key.startsWith('ONE_ROUTER_REQUIRE_CONTEXT_REGEX')) {
768
+ // must become a real regex literal: metro rejects any other node type as
769
+ // the third argument of require.context.
770
+ return `/${options.ONE_ROUTER_REQUIRE_CONTEXT_REGEX_STRING}/`
771
+ }
772
+ if (key === 'ONE_ROUTER_LINKING_CONFIG') {
773
+ // gated to the entry so a user module reading this name is left alone
774
+ return isMetroEntry ? JSON.stringify(options.ONE_ROUTER_LINKING_CONFIG ?? null) : undefined
775
+ }
776
+ if (key === 'ONE_SETUP_FILE_NATIVE') {
777
+ return options.ONE_SETUP_FILE_NATIVE
778
+ ? JSON.stringify(options.ONE_SETUP_FILE_NATIVE)
779
+ : 'undefined'
780
+ }
781
+ return undefined
782
+ }
783
+
784
+ function walk(node: any, parent: any) {
785
+ if (!node || typeof node !== 'object') return
786
+
787
+ if (node.type === 'ImportDeclaration' && parent === parsed.program) {
788
+ lastImportEnd = Math.max(lastImportEnd, node.end)
789
+ }
790
+
791
+ if (
792
+ node.type === 'MemberExpression' &&
793
+ node.object?.type === 'MemberExpression' &&
794
+ !node.object.computed &&
795
+ node.object.object?.type === 'Identifier' &&
796
+ node.object.object.name === 'process' &&
797
+ node.object.property?.type === 'Identifier' &&
798
+ node.object.property.name === 'env'
799
+ ) {
800
+ const key = node.computed
801
+ ? node.property?.type === 'Literal' && typeof node.property.value === 'string'
802
+ ? node.property.value
803
+ : undefined
804
+ : node.property?.type === 'Identifier'
805
+ ? node.property.name
806
+ : undefined
807
+ const isAssignTarget =
808
+ parent?.type === 'AssignmentExpression' && parent.left === node
809
+ if (key && !isAssignTarget) {
810
+ const replacement = replacementFor(key)
811
+ if (replacement !== undefined) {
812
+ ms.overwrite(node.start, node.end, replacement)
813
+ }
814
+ }
815
+ }
816
+
817
+ for (const k of Object.keys(node)) {
818
+ if (k === 'start' || k === 'end' || k === 'loc' || k === 'range' || k === 'parent' || k === 'comments') continue
819
+ const child = node[k]
820
+ if (Array.isArray(child)) {
821
+ for (const item of child) walk(item, node)
822
+ } else if (child && typeof child === 'object') {
823
+ walk(child, node)
824
+ }
825
+ }
826
+ }
827
+
828
+ walk(parsed.program, parsed.program)
829
+
830
+ // the setup file goes after the existing imports so react-native is
831
+ // initialized before it runs, matching the babel plugin's ordering.
832
+ if (isMetroEntry && options.ONE_SETUP_FILE_NATIVE) {
833
+ const stmt = `\nimport ${JSON.stringify(options.ONE_SETUP_FILE_NATIVE)};`
834
+ if (lastImportEnd >= 0) {
835
+ ms.appendRight(lastImportEnd, stmt)
836
+ } else {
837
+ ms.prepend(`${stmt}\n`)
838
+ }
839
+ }
840
+
841
+ return ms.toString()
842
+ }
843
+
844
+ /**
845
+ * Recursively collects identifier names from patterns (bindings).
846
+ */
847
+ export function collectPatternNames(pattern: any, names: Set<string>) {
848
+ if (!pattern) return
849
+ if (pattern.type === 'Identifier') {
850
+ names.add(pattern.name)
851
+ } else if (pattern.type === 'AssignmentPattern') {
852
+ collectPatternNames(pattern.left, names)
853
+ } else if (pattern.type === 'ObjectPattern') {
854
+ for (const prop of pattern.properties || []) {
855
+ if (prop.type === 'Property') collectPatternNames(prop.value, names)
856
+ else if (prop.type === 'RestElement') collectPatternNames(prop.argument, names)
857
+ }
858
+ } else if (pattern.type === 'ArrayPattern') {
859
+ for (const elem of pattern.elements || []) {
860
+ if (elem) collectPatternNames(elem, names)
861
+ }
862
+ } else if (pattern.type === 'RestElement') {
863
+ collectPatternNames(pattern.argument, names)
864
+ }
865
+ }
866
+
867
+ /**
868
+ * Recursively collects all hoisted `var` declarations and `FunctionDeclaration` names
869
+ * within a function body or program, stopping traversal at nested function boundaries.
870
+ */
871
+ export function collectHoistedBindings(node: any, names: Set<string>) {
872
+ function traverse(n: any) {
873
+ if (!n || typeof n !== 'object') return
874
+ if (n === node) {
875
+ // Root of traversal
876
+ } else if (
877
+ n.type === 'FunctionDeclaration' ||
878
+ n.type === 'FunctionExpression' ||
879
+ n.type === 'ArrowFunctionExpression'
880
+ ) {
881
+ if (n.type === 'FunctionDeclaration' && n.id?.name) {
882
+ names.add(n.id.name)
883
+ }
884
+ return
885
+ }
886
+
887
+ if (n.type === 'VariableDeclaration' && n.kind === 'var') {
888
+ for (const decl of n.declarations || []) {
889
+ collectPatternNames(decl.id, names)
890
+ }
891
+ }
892
+
893
+ for (const key of Object.keys(n)) {
894
+ if (key === 'start' || key === 'end' || key === 'loc' || key === 'range' || key === 'parent' || key === 'comments') continue
895
+ const child = n[key]
896
+ if (Array.isArray(child)) {
897
+ for (const item of child) traverse(item)
898
+ } else if (child && typeof child === 'object') {
899
+ traverse(child)
900
+ }
901
+ }
902
+ }
903
+
904
+ traverse(node)
905
+ }
906
+
907
+ /**
908
+ * Collects block-scoped declarations (let, const, class, and block-level function declarations)
909
+ * directly declared in this block (not inside nested blocks).
910
+ */
911
+ export function collectBlockBindings(statements: any[], names: Set<string>) {
912
+ if (!Array.isArray(statements)) return
913
+ for (const stmt of statements) {
914
+ if (!stmt) continue
915
+ if (stmt.type === 'VariableDeclaration' && stmt.kind !== 'var') {
916
+ for (const decl of stmt.declarations || []) {
917
+ collectPatternNames(decl.id, names)
918
+ }
919
+ } else if (stmt.type === 'ClassDeclaration' && stmt.id?.name) {
920
+ names.add(stmt.id.name)
921
+ } else if (stmt.type === 'FunctionDeclaration' && stmt.id?.name) {
922
+ names.add(stmt.id.name)
923
+ }
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Lexical scope tracker for identifier shadowing analysis.
929
+ */
930
+ export class ScopeTracker {
931
+ private stack: Array<Set<string>> = [new Set()]
932
+
933
+ enter(initialBindings?: Iterable<string>) {
934
+ this.stack.push(new Set(initialBindings))
935
+ }
936
+
937
+ exit() {
938
+ if (this.stack.length > 1) {
939
+ this.stack.pop()
940
+ }
941
+ }
942
+
943
+ add(name: string) {
944
+ this.stack[this.stack.length - 1].add(name)
945
+ }
946
+
947
+ currentScope(): Set<string> {
948
+ return this.stack[this.stack.length - 1]
949
+ }
950
+
951
+ addPattern(pattern: any) {
952
+ collectPatternNames(pattern, this.currentScope())
953
+ }
954
+
955
+ isShadowed(name: string): boolean {
956
+ for (let i = this.stack.length - 1; i >= 0; i--) {
957
+ if (this.stack[i].has(name)) return true
958
+ }
959
+ return false
960
+ }
961
+ }
962
+
963
+ /**
964
+ * Cache key generation without any Babel references.
965
+ */
966
+ export function getCacheKey(config: MetroWorkerConfig = {}, opts?: any): string {
967
+ const hash = crypto.createHash('sha256')
968
+ hash.update('metroNativeWorker')
969
+ hash.update(WORKER_CACHE_KEY_VERSION)
970
+ if (config.globalPrefix) {
971
+ hash.update(config.globalPrefix)
972
+ }
973
+ if (config.unstable_dependencyMapReservedName) {
974
+ hash.update(config.unstable_dependencyMapReservedName)
975
+ }
976
+ if (config.minifierPath) {
977
+ hash.update(config.minifierPath)
978
+ }
979
+ if (opts?.projectRoot) {
980
+ hash.update(opts.projectRoot)
981
+ }
982
+ return hash.digest('hex')
983
+ }
984
+
985
+ /**
986
+ * Converts a standard SourceMap V3 object into Metro's raw mapping segment tuples.
987
+ * Metro expects an array of tuples: [line, column] or [line, column, origLine, origCol, name?]
988
+ * Mappings must be strictly sorted by generatedLine ascending, then generatedColumn ascending.
989
+ */
990
+ export function convertSourceMapToMetroRawMappings(
991
+ composedMap: any
992
+ ): Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> {
993
+ if (!composedMap) return []
994
+ const tracer = new TraceMap(composedMap)
995
+ const rawMappings: Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> = []
996
+
997
+ eachMapping(tracer, (m) => {
998
+ if (m.originalLine == null) {
999
+ rawMappings.push([m.generatedLine, m.generatedColumn])
1000
+ } else if (m.name == null) {
1001
+ rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn])
1002
+ } else {
1003
+ rawMappings.push([m.generatedLine, m.generatedColumn, m.originalLine, m.originalColumn, m.name])
1004
+ }
1005
+ })
1006
+
1007
+ // Mappings MUST be strictly sorted by generatedLine ascending, then generatedColumn ascending
1008
+ rawMappings.sort((a, b) => {
1009
+ if (a[0] !== b[0]) return a[0] - b[0]
1010
+ return a[1] - b[1]
1011
+ })
1012
+
1013
+ // Deduplicate consecutive identical (generatedLine, generatedColumn) tuples
1014
+ const deduped: Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> = []
1015
+ for (const mapping of rawMappings) {
1016
+ const prev = deduped[deduped.length - 1]
1017
+ if (prev && prev[0] === mapping[0] && prev[1] === mapping[1]) {
1018
+ continue
1019
+ }
1020
+ deduped.push(mapping)
1021
+ }
1022
+
1023
+ return deduped
1024
+ }
1025
+
1026
+ /**
1027
+ * Counts lines and ensures map terminates per Metro contract.
1028
+ */
1029
+ export function countLinesAndTerminateMap(
1030
+ code: string,
1031
+ map: Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> = []
1032
+ ): { lineCount: number; map: Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> } {
1033
+ const NEWLINE = /\r\n?|\n|\u2028|\u2029/g
1034
+ let lineCount = 1
1035
+ let lastLineStart = 0
1036
+ for (const match of code.matchAll(NEWLINE)) {
1037
+ lineCount++
1038
+ lastLineStart = match.index! + match[0].length
1039
+ }
1040
+ const lastLineLength = code.length - lastLineStart
1041
+ const lastLineIndex1Based = lineCount
1042
+ const lastLineNextColumn0Based = lastLineLength
1043
+ const lastMapping = map[map.length - 1]
1044
+ const terminatingMapping: [number, number] = [lastLineIndex1Based, lastLineNextColumn0Based]
1045
+ if (
1046
+ !lastMapping ||
1047
+ lastMapping[0] !== terminatingMapping[0] ||
1048
+ lastMapping[1] !== terminatingMapping[1]
1049
+ ) {
1050
+ return {
1051
+ lineCount,
1052
+ map: map.concat([terminatingMapping]),
1053
+ }
1054
+ }
1055
+ return {
1056
+ lineCount,
1057
+ map: [...map],
1058
+ }
1059
+ }
1060
+
1061
+ /**
1062
+ * Wraps JSON in CommonJS via module.exports and Metro's module wrapper.
1063
+ */
1064
+ export function wrapJson(
1065
+ source: string,
1066
+ options?: {
1067
+ globalPrefix?: string
1068
+ moduleId?: number | string
1069
+ dependencyIds?: Array<number | string>
1070
+ }
1071
+ ): string {
1072
+ const globalPrefix = options?.globalPrefix || ''
1073
+ const factory = [
1074
+ 'function (global, require, _importDefaultUnused, _importAllUnused, module, exports, _dependencyMapUnused) {',
1075
+ ` module.exports = ${source};`,
1076
+ '}',
1077
+ ].join('\n')
1078
+
1079
+ if (options?.moduleId !== undefined) {
1080
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : '[]'
1081
+ return `${globalPrefix}__d(${factory}, ${JSON.stringify(options.moduleId)}, ${depIds});`
1082
+ }
1083
+
1084
+ return `${globalPrefix}__d(${factory});`
1085
+ }
1086
+
1087
+ /**
1088
+ * Wraps CommonJS code in Metro's standard define wrapper:
1089
+ * __d(function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) { ... }, moduleId, [dependencyIds])
1090
+ */
1091
+ export function wrapModule(
1092
+ code: string,
1093
+ options?: WrapModuleOptions
1094
+ ): string {
1095
+ const globalPrefix = options?.globalPrefix || ''
1096
+ const depMap = options?.dependencyMapName || '_dependencyMap'
1097
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMap}) {`
1098
+ const requireAlias = options?.requireAlias !== false ? 'var require = _$$_REQUIRE;\n' : ''
1099
+ const footer = `}`
1100
+
1101
+ if (options?.moduleId !== undefined) {
1102
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : '[]'
1103
+ return `${globalPrefix}__d(${header}\n${requireAlias}${code}\n${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`
1104
+ }
1105
+
1106
+ return `${globalPrefix}__d(${header}\n${requireAlias}${code}\n${footer});`
1107
+ }
1108
+
1109
+ /**
1110
+ * Metro canonical dependency qualifier key format.
1111
+ */
1112
+ export function getDependencyKey(
1113
+ name: string,
1114
+ isESM: boolean,
1115
+ asyncType: 'async' | 'weak' | 'maybeSync' | null = null,
1116
+ contextParams?: MetroContextParams
1117
+ ): string {
1118
+ let key = `${name}\0${isESM ? 'import' : 'require'}`
1119
+ if (asyncType != null) {
1120
+ key += `\0${asyncType}`
1121
+ }
1122
+ // mirrors metro's getKeyForDependency so a require.context dependency keys the
1123
+ // same way metro's own collectDependencies would key it.
1124
+ if (contextParams) {
1125
+ key += [
1126
+ '',
1127
+ 'context',
1128
+ String(contextParams.recursive),
1129
+ String(contextParams.filter.pattern),
1130
+ String(contextParams.filter.flags),
1131
+ contextParams.mode,
1132
+ ].join('\0')
1133
+ }
1134
+ return key
1135
+ }
1136
+
1137
+ /**
1138
+ * Rewrites require("dep") calls to Metro's dependency ABI:
1139
+ * require(_dependencyMap[index], "dep")
1140
+ * Respects lexical scope shadowing (does NOT rewrite local parameters or variables named require).
1141
+ */
1142
+ export type RewriteDependencyCallsResult = {
1143
+ code: string
1144
+ map: any
1145
+ toString(): string
1146
+ }
1147
+
1148
+ /**
1149
+ * Rewrites require("dep") calls and import("dep") expressions to Metro's dependency ABI:
1150
+ * require(_dependencyMap[index], "dep")
1151
+ * require(_dependencyMap[asyncIndex], "metro-runtime/src/modules/asyncRequire")(_dependencyMap[depIndex], _dependencyMap.paths, "dep")
1152
+ * Respects lexical scope shadowing and JS hoisting rules.
1153
+ * Returns { code, map, toString() } preserving source maps for the rewrite stage.
1154
+ */
1155
+ export function rewriteDependencyCalls(
1156
+ code: string,
1157
+ dependencies: MetroDependency[],
1158
+ depMapName = '_dependencyMap',
1159
+ filename = 'module.js',
1160
+ asyncRequirePath = 'metro-runtime/src/modules/asyncRequire'
1161
+ ): RewriteDependencyCallsResult {
1162
+ const ms = new MagicString(code)
1163
+
1164
+ const emptyResult: RewriteDependencyCallsResult = {
1165
+ code,
1166
+ map: ms.generateMap({ source: filename, hires: true, includeContent: true }),
1167
+ toString() {
1168
+ return code
1169
+ },
1170
+ }
1171
+
1172
+ if (dependencies.length === 0) return emptyResult
1173
+
1174
+ let parsed: any
1175
+ try {
1176
+ parsed = parseSync(filename, code, { lang: langForFilename(filename) })
1177
+ } catch (err: any) {
1178
+ throw new Error(
1179
+ `[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${err.message || err}`
1180
+ )
1181
+ }
1182
+
1183
+ // a silent bail here leaves raw require("./dep") calls that metro never
1184
+ // registered, so the module is absent from the bundle and throws at runtime.
1185
+ if (parsed?.errors?.length) {
1186
+ throw new Error(
1187
+ `[vxrn/metro] Failed to parse ${filename} for dependency rewriting: ${parsed.errors[0].message}`
1188
+ )
1189
+ }
1190
+
1191
+ if (!parsed?.program) return emptyResult
1192
+
1193
+ const contextLiteralBindings = collectModuleLiteralBindings(parsed.program)
1194
+
1195
+ const scopeTracker = new ScopeTracker()
1196
+ collectHoistedBindings(parsed.program, scopeTracker.currentScope())
1197
+ collectBlockBindings(parsed.program.body, scopeTracker.currentScope())
1198
+ for (const stmt of parsed.program.body || []) {
1199
+ if (stmt.type === 'ImportDeclaration') {
1200
+ for (const spec of stmt.specifiers || []) {
1201
+ if (spec.local?.name) {
1202
+ scopeTracker.add(spec.local.name)
1203
+ }
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ function walk(node: any) {
1209
+ if (!node || typeof node !== 'object') return
1210
+
1211
+ let pushedScope = false
1212
+
1213
+ if (
1214
+ node.type === 'FunctionDeclaration' ||
1215
+ node.type === 'FunctionExpression' ||
1216
+ node.type === 'ArrowFunctionExpression'
1217
+ ) {
1218
+ scopeTracker.enter()
1219
+ pushedScope = true
1220
+ for (const param of node.params || []) {
1221
+ scopeTracker.addPattern(param)
1222
+ }
1223
+ if (node.type === 'FunctionExpression' && node.id?.name) {
1224
+ scopeTracker.add(node.id.name)
1225
+ }
1226
+ if (node.body) {
1227
+ collectHoistedBindings(node.body, scopeTracker.currentScope())
1228
+ }
1229
+ } else if (node.type === 'BlockStatement') {
1230
+ scopeTracker.enter()
1231
+ pushedScope = true
1232
+ collectBlockBindings(node.body, scopeTracker.currentScope())
1233
+ } else if (node.type === 'CatchClause') {
1234
+ scopeTracker.enter()
1235
+ pushedScope = true
1236
+ if (node.param) {
1237
+ scopeTracker.addPattern(node.param)
1238
+ }
1239
+ } else if (
1240
+ node.type === 'ForStatement' ||
1241
+ node.type === 'ForInStatement' ||
1242
+ node.type === 'ForOfStatement'
1243
+ ) {
1244
+ const decl = node.type === 'ForStatement' ? node.init : node.left
1245
+ if (decl?.type === 'VariableDeclaration' && decl.kind !== 'var') {
1246
+ scopeTracker.enter()
1247
+ pushedScope = true
1248
+ for (const d of decl.declarations || []) {
1249
+ scopeTracker.addPattern(d.id)
1250
+ }
1251
+ }
1252
+ }
1253
+
1254
+ if (
1255
+ node.type === 'ImportExpression' &&
1256
+ node.source?.type === 'Literal' &&
1257
+ typeof node.source.value === 'string'
1258
+ ) {
1259
+ const depName = node.source.value
1260
+ const depKey = getDependencyKey(depName, true, 'async')
1261
+ const dep =
1262
+ dependencies.find((d) => d.data.key === depKey) ||
1263
+ dependencies.find((d) => d.name === depName && d.data.asyncType === 'async')
1264
+
1265
+ const asyncKey = getDependencyKey(asyncRequirePath, false, null)
1266
+ const asyncDep =
1267
+ dependencies.find((d) => d.data.key === asyncKey) ||
1268
+ dependencies.find((d) => d.name === asyncRequirePath && d.data.asyncType == null)
1269
+
1270
+ if (dep && asyncDep) {
1271
+ const depIndex = dep.data.index ?? dependencies.indexOf(dep)
1272
+ const asyncIndex = asyncDep.data.index ?? dependencies.indexOf(asyncDep)
1273
+ ms.overwrite(
1274
+ node.start,
1275
+ node.end,
1276
+ `require(${depMapName}[${asyncIndex}], ${JSON.stringify(asyncRequirePath)})(${depMapName}[${depIndex}], ${depMapName}.paths, ${JSON.stringify(depName)})`
1277
+ )
1278
+ }
1279
+ } else if (
1280
+ node.type === 'CallExpression' &&
1281
+ node.callee?.type === 'Identifier' &&
1282
+ node.callee.name === 'require' &&
1283
+ !scopeTracker.isShadowed('require') &&
1284
+ node.arguments?.length >= 1
1285
+ ) {
1286
+ const arg = node.arguments[0]
1287
+ if (arg.type === 'Literal' && typeof arg.value === 'string') {
1288
+ const depKey = getDependencyKey(arg.value, false, null)
1289
+ const dep =
1290
+ dependencies.find((d) => d.data.key === depKey) ||
1291
+ dependencies.find((d) => d.name === arg.value && d.data.asyncType == null)
1292
+ if (dep) {
1293
+ const index = dep.data.index ?? dependencies.indexOf(dep)
1294
+ ms.overwrite(arg.start, arg.end, `${depMapName}[${index}], ${JSON.stringify(arg.value)}`)
1295
+ }
1296
+ }
1297
+ } else if (
1298
+ // metro rewrites require.context(dir, ...) down to a plain require of the
1299
+ // single context module it registered for that directory.
1300
+ node.type === 'CallExpression' &&
1301
+ node.callee?.type === 'MemberExpression' &&
1302
+ !node.callee.computed &&
1303
+ node.callee.object?.type === 'Identifier' &&
1304
+ node.callee.object.name === 'require' &&
1305
+ node.callee.property?.type === 'Identifier' &&
1306
+ node.callee.property.name === 'context' &&
1307
+ !scopeTracker.isShadowed('require') &&
1308
+ node.arguments?.length >= 1
1309
+ ) {
1310
+ // resolved the same way dependency extraction resolved it. matching only
1311
+ // a direct Literal here left a variable-held directory registered as a
1312
+ // dependency but never rewritten, so the call reached metro's
1313
+ // fallbackRequireContext at runtime and threw.
1314
+ const arg =
1315
+ node.arguments[0]?.type === 'Identifier'
1316
+ ? contextLiteralBindings.get(node.arguments[0].name)
1317
+ : node.arguments[0]
1318
+ if (arg?.type === 'Literal' && typeof arg.value === 'string') {
1319
+ const dep = dependencies.find(
1320
+ (d) => d.name === arg.value && d.data.contextParams != null
1321
+ )
1322
+ if (dep) {
1323
+ const index = dep.data.index ?? dependencies.indexOf(dep)
1324
+ ms.overwrite(
1325
+ node.start,
1326
+ node.end,
1327
+ `require(${depMapName}[${index}], ${JSON.stringify(arg.value)})`
1328
+ )
1329
+ }
1330
+ }
1331
+ }
1332
+
1333
+ for (const key of Object.keys(node)) {
1334
+ if (key === 'start' || key === 'end' || key === 'loc' || key === 'range' || key === 'parent' || key === 'comments') continue
1335
+ const child = node[key]
1336
+ if (Array.isArray(child)) {
1337
+ for (const item of child) walk(item)
1338
+ } else if (child && typeof child === 'object') {
1339
+ walk(child)
1340
+ }
1341
+ }
1342
+
1343
+ if (pushedScope) {
1344
+ scopeTracker.exit()
1345
+ }
1346
+ }
1347
+
1348
+ walk(parsed.program)
1349
+ const resultString = ms.toString()
1350
+ const map = ms.generateMap({ source: filename, hires: true, includeContent: true })
1351
+ return {
1352
+ code: resultString,
1353
+ map,
1354
+ toString() {
1355
+ return resultString
1356
+ },
1357
+ }
1358
+ }
1359
+
1360
+ /**
1361
+ * Extracts dependencies using oxc-parser (zero Babel).
1362
+ * Respects lexical scope shadowing and JS hoisting rules.
1363
+ */
1364
+ export function extractDependencies(
1365
+ code: string,
1366
+ filename: string,
1367
+ options?: {
1368
+ asyncRequireModulePath?: string
1369
+ allowOptionalDependencies?: any
1370
+ }
1371
+ ): MetroDependency[] {
1372
+ const asyncRequirePath =
1373
+ options?.asyncRequireModulePath || 'metro-runtime/src/modules/asyncRequire'
1374
+ const allowOptionalDependencies = options?.allowOptionalDependencies
1375
+ const lineOffsets = [0]
1376
+ for (let i = 0; i < code.length; i++) {
1377
+ if (code[i] === '\n') {
1378
+ lineOffsets.push(i + 1)
1379
+ }
1380
+ }
1381
+
1382
+ function offsetToLoc(pos: number): { line: number; column: number } {
1383
+ let low = 0
1384
+ let high = lineOffsets.length - 1
1385
+ while (low <= high) {
1386
+ const mid = (low + high) >> 1
1387
+ if (lineOffsets[mid] <= pos) {
1388
+ low = mid + 1
1389
+ } else {
1390
+ high = mid - 1
1391
+ }
1392
+ }
1393
+ const line = high + 1
1394
+ const column = pos - lineOffsets[high]
1395
+ return { line, column }
1396
+ }
1397
+
1398
+ let parseResult: any
1399
+ try {
1400
+ parseResult = parseSync(filename, code, { lang: langForFilename(filename) })
1401
+ } catch (err: any) {
1402
+ throw new Error(`[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${err.message || err}`)
1403
+ }
1404
+
1405
+ // oxc reports syntax errors on the result rather than throwing. ignoring them
1406
+ // yields zero dependencies, which metro turns into a bundle that is missing
1407
+ // modules and only fails at runtime, so surface it here instead.
1408
+ if (parseResult?.errors?.length) {
1409
+ throw new Error(
1410
+ `[vxrn/metro] Failed to parse ${filename} for dependency extraction: ${parseResult.errors[0].message}`
1411
+ )
1412
+ }
1413
+
1414
+ if (!parseResult?.program) {
1415
+ return []
1416
+ }
1417
+
1418
+ const depMap = new Map<string, MetroDependency>()
1419
+
1420
+ function addDep(
1421
+ name: string,
1422
+ isESM: boolean,
1423
+ asyncType: 'async' | 'weak' | 'maybeSync' | null,
1424
+ start: number,
1425
+ end: number,
1426
+ contextParams?: MetroContextParams,
1427
+ isOptional?: boolean
1428
+ ) {
1429
+ const key = getDependencyKey(name, isESM, asyncType, contextParams)
1430
+ let entry = depMap.get(key)
1431
+ // metro reads loc.start.line / loc.end.line when it formats an
1432
+ // unable-to-resolve error. a flat {line, column} makes that error path throw
1433
+ // instead, which hides the real resolution failure behind a crash.
1434
+ const loc = { start: offsetToLoc(start), end: offsetToLoc(end) }
1435
+ if (!entry) {
1436
+ entry = {
1437
+ name,
1438
+ data: {
1439
+ key,
1440
+ asyncType,
1441
+ locs: [loc],
1442
+ isESMImportAtSource: isESM,
1443
+ isESMImport: isESM,
1444
+ index: depMap.size,
1445
+ ...(contextParams ? { contextParams } : {}),
1446
+ ...(isOptional ? { isOptional: true } : {}),
1447
+ },
1448
+ }
1449
+ depMap.set(key, entry)
1450
+ } else {
1451
+ entry.data.locs.push(loc)
1452
+ }
1453
+ }
1454
+
1455
+ // metro evaluates require.context arguments instead of demanding literals, so
1456
+ // a module-scope const holding the value works there. this covers that one
1457
+ // case rather than reimplementing babel's full constant evaluation.
1458
+ const moduleConsts = collectModuleLiteralBindings(parseResult.program)
1459
+
1460
+ function resolveConst(node: any): any {
1461
+ if (node?.type === 'Identifier') return moduleConsts.get(node.name)
1462
+ return node
1463
+ }
1464
+
1465
+ // mirrors metro's isOptionalDependency: a require within three statement
1466
+ // levels of a try block is allowed to fail resolution. optional native modules
1467
+ // like react-native-worklets-core are required exactly this way, and treating
1468
+ // them as required fails the whole build.
1469
+ const ancestors: any[] = []
1470
+ function isOptionalHere(name: string): boolean {
1471
+ if (!allowOptionalDependencies) return false
1472
+ if (Array.isArray(allowOptionalDependencies.exclude)) {
1473
+ if (allowOptionalDependencies.exclude.includes(name)) return false
1474
+ }
1475
+ let sCount = 0
1476
+ for (let i = ancestors.length - 1; i >= 0 && sCount < 3; i--) {
1477
+ const n = ancestors[i]
1478
+ const isStatement = /(?:Statement|Declaration)$/.test(n.type)
1479
+ if (!isStatement) continue
1480
+ if (n.type === 'BlockStatement') {
1481
+ const parent = ancestors[i - 1]
1482
+ return parent?.type === 'TryStatement' && parent.block === n
1483
+ }
1484
+ sCount += 1
1485
+ }
1486
+ return false
1487
+ }
1488
+
1489
+ const scopeTracker = new ScopeTracker()
1490
+ collectHoistedBindings(parseResult.program, scopeTracker.currentScope())
1491
+ collectBlockBindings(parseResult.program.body, scopeTracker.currentScope())
1492
+ for (const stmt of parseResult.program.body || []) {
1493
+ if (stmt.type === 'ImportDeclaration') {
1494
+ for (const spec of stmt.specifiers || []) {
1495
+ if (spec.local?.name) {
1496
+ scopeTracker.add(spec.local.name)
1497
+ }
1498
+ }
1499
+ }
1500
+ }
1501
+
1502
+ function walk(node: any) {
1503
+ if (!node || typeof node !== 'object') return
1504
+
1505
+ let pushedScope = false
1506
+ ancestors.push(node)
1507
+
1508
+ if (
1509
+ node.type === 'FunctionDeclaration' ||
1510
+ node.type === 'FunctionExpression' ||
1511
+ node.type === 'ArrowFunctionExpression'
1512
+ ) {
1513
+ scopeTracker.enter()
1514
+ pushedScope = true
1515
+ for (const param of node.params || []) {
1516
+ scopeTracker.addPattern(param)
1517
+ }
1518
+ if (node.type === 'FunctionExpression' && node.id?.name) {
1519
+ scopeTracker.add(node.id.name)
1520
+ }
1521
+ if (node.body) {
1522
+ collectHoistedBindings(node.body, scopeTracker.currentScope())
1523
+ }
1524
+ } else if (node.type === 'BlockStatement') {
1525
+ scopeTracker.enter()
1526
+ pushedScope = true
1527
+ collectBlockBindings(node.body, scopeTracker.currentScope())
1528
+ } else if (node.type === 'CatchClause') {
1529
+ scopeTracker.enter()
1530
+ pushedScope = true
1531
+ if (node.param) {
1532
+ scopeTracker.addPattern(node.param)
1533
+ }
1534
+ } else if (
1535
+ node.type === 'ForStatement' ||
1536
+ node.type === 'ForInStatement' ||
1537
+ node.type === 'ForOfStatement'
1538
+ ) {
1539
+ const decl = node.type === 'ForStatement' ? node.init : node.left
1540
+ if (decl?.type === 'VariableDeclaration' && decl.kind !== 'var') {
1541
+ scopeTracker.enter()
1542
+ pushedScope = true
1543
+ for (const d of decl.declarations || []) {
1544
+ scopeTracker.addPattern(d.id)
1545
+ }
1546
+ }
1547
+ }
1548
+
1549
+ if (node.type === 'ImportDeclaration' && node.source?.value) {
1550
+ if (node.importKind !== 'type') {
1551
+ const hasValueSpecifier =
1552
+ !node.specifiers?.length ||
1553
+ node.specifiers.some((s: any) => s.importKind !== 'type')
1554
+ if (hasValueSpecifier) {
1555
+ addDep(node.source.value, true, null, node.start, node.end)
1556
+ }
1557
+ }
1558
+ } else if (
1559
+ (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') &&
1560
+ node.source?.value
1561
+ ) {
1562
+ if (node.exportKind !== 'type') {
1563
+ addDep(node.source.value, true, null, node.start, node.end)
1564
+ }
1565
+ } else if (node.type === 'ImportExpression') {
1566
+ if (node.source?.type === 'Literal' && typeof node.source.value === 'string') {
1567
+ addDep(node.source.value, true, 'async', node.start, node.end)
1568
+ addDep(asyncRequirePath, false, null, node.start, node.end)
1569
+ } else {
1570
+ throw new Error(`[vxrn/metro] Dynamic import with non-string literal is not supported by Metro in ${filename}`)
1571
+ }
1572
+ } else if (
1573
+ node.type === 'CallExpression' &&
1574
+ node.callee?.type === 'Identifier' &&
1575
+ node.callee.name === 'require' &&
1576
+ !scopeTracker.isShadowed('require')
1577
+ ) {
1578
+ if (
1579
+ node.arguments?.[0]?.type === 'Literal' &&
1580
+ typeof node.arguments[0].value === 'string'
1581
+ ) {
1582
+ addDep(
1583
+ node.arguments[0].value,
1584
+ false,
1585
+ null,
1586
+ node.start,
1587
+ node.end,
1588
+ undefined,
1589
+ node.arguments[0].value !== asyncRequirePath && isOptionalHere(node.arguments[0].value)
1590
+ )
1591
+ }
1592
+ } else if (
1593
+ // require.context(dir, recursive?, filter?, mode?) registers a whole
1594
+ // directory as one dependency. one's router entry uses it for the route
1595
+ // tree, so dropping it silently omits every route from the bundle.
1596
+ node.type === 'CallExpression' &&
1597
+ node.callee?.type === 'MemberExpression' &&
1598
+ !node.callee.computed &&
1599
+ node.callee.object?.type === 'Identifier' &&
1600
+ node.callee.object.name === 'require' &&
1601
+ node.callee.property?.type === 'Identifier' &&
1602
+ node.callee.property.name === 'context' &&
1603
+ !scopeTracker.isShadowed('require')
1604
+ ) {
1605
+ const args = node.arguments || []
1606
+ // metro evaluates these arguments rather than requiring literals, so a
1607
+ // module-scope const holding the string is valid. one's router entry reads
1608
+ // its route root through exactly such a const.
1609
+ const dir = resolveConst(args[0])
1610
+ if (dir?.type !== 'Literal' || typeof dir.value !== 'string') {
1611
+ throw new Error(
1612
+ `[vxrn/metro] First argument of require.context must be a string literal in ${filename}`
1613
+ )
1614
+ }
1615
+ if (args.length > 4) {
1616
+ throw new Error(
1617
+ `[vxrn/metro] Too many arguments provided to require.context in ${filename}. Expected 4, got: ${args.length}`
1618
+ )
1619
+ }
1620
+
1621
+ let recursive = true
1622
+ const recursiveArg = resolveConst(args[1])
1623
+ if (recursiveArg) {
1624
+ if (recursiveArg.type !== 'Literal' || typeof recursiveArg.value !== 'boolean') {
1625
+ throw new Error(
1626
+ `[vxrn/metro] Second argument of require.context must be an optional boolean literal in ${filename}`
1627
+ )
1628
+ }
1629
+ recursive = recursiveArg.value
1630
+ }
1631
+
1632
+ let filter = { pattern: '.*', flags: '' }
1633
+ const filterArg = resolveConst(args[2])
1634
+ if (filterArg) {
1635
+ // oxc reports regex literals as Literal nodes carrying a `regex` field.
1636
+ if (filterArg.type !== 'Literal' || !filterArg.regex) {
1637
+ throw new Error(
1638
+ `[vxrn/metro] Third argument of require.context must be an optional RegExp literal in ${filename}, instead found node of type: ${filterArg.type}`
1639
+ )
1640
+ }
1641
+ filter = { pattern: filterArg.regex.pattern, flags: filterArg.regex.flags || '' }
1642
+ }
1643
+
1644
+ let mode: MetroContextParams['mode'] = 'sync'
1645
+ const modeArg = resolveConst(args[3])
1646
+ if (modeArg) {
1647
+ const m = modeArg.type === 'Literal' ? modeArg.value : undefined
1648
+ if (m !== 'sync' && m !== 'eager' && m !== 'lazy' && m !== 'lazy-once') {
1649
+ throw new Error(
1650
+ `[vxrn/metro] require.context mode must be one of sync, eager, lazy, lazy-once in ${filename}`
1651
+ )
1652
+ }
1653
+ mode = m
1654
+ }
1655
+
1656
+ addDep(dir.value, false, null, node.start, node.end, { recursive, filter, mode })
1657
+ }
1658
+
1659
+ for (const key of Object.keys(node)) {
1660
+ if (key === 'start' || key === 'end' || key === 'loc' || key === 'range' || key === 'parent' || key === 'comments') continue
1661
+ const child = node[key]
1662
+ if (Array.isArray(child)) {
1663
+ for (const item of child) walk(item)
1664
+ } else if (child && typeof child === 'object') {
1665
+ walk(child)
1666
+ }
1667
+ }
1668
+
1669
+ ancestors.pop()
1670
+ if (pushedScope) {
1671
+ scopeTracker.exit()
1672
+ }
1673
+ }
1674
+
1675
+ walk(parseResult.program)
1676
+ return Array.from(depMap.values())
1677
+ }
1678
+
1679
+ function checkReservedStrings(sourceCode: string, config: MetroWorkerConfig, options: MetroWorkerOptions) {
1680
+ const reservedStrings: string[] = []
1681
+ if (
1682
+ options.customTransformOptions?.unstable_staticHermesOptimizedRequire === true
1683
+ ) {
1684
+ reservedStrings.push('_$$_METRO_MODULE_ID')
1685
+ }
1686
+ if (config.unstable_dependencyMapReservedName != null) {
1687
+ reservedStrings.push(config.unstable_dependencyMapReservedName)
1688
+ }
1689
+ for (const reservedString of reservedStrings) {
1690
+ const position = sourceCode.indexOf(reservedString)
1691
+ if (position > -1) {
1692
+ throw new SyntaxError(
1693
+ 'Source code contains the reserved string `' +
1694
+ reservedString +
1695
+ '` at character offset ' +
1696
+ position
1697
+ )
1698
+ }
1699
+ }
1700
+ }
1701
+
1702
+ /**
1703
+ * Main transform entry point conforming to Metro's worker contract with ZERO Babel.
1704
+ */
1705
+ let workletsConfigured = false
1706
+
1707
+ /**
1708
+ * Turns on @vxrn/compiler's reanimated transform inside this metro worker
1709
+ * process when the project actually depends on reanimated.
1710
+ */
1711
+ type OneNativeTransforms = typeof import('one/native-transforms')
1712
+
1713
+ let oneNativeTransforms: OneNativeTransforms | null | undefined
1714
+
1715
+ /**
1716
+ * Resolves `one/native-transforms` from the user's project. Returns null once
1717
+ * and stays null when one isn't installed, so a bare vite-plugin-metro app
1718
+ * doesn't pay a failed resolve per file.
1719
+ */
1720
+ function loadOneNativeTransforms(projectRoot: string) {
1721
+ if (oneNativeTransforms !== undefined) return oneNativeTransforms
1722
+ try {
1723
+ // require, not import: this worker runs as cjs, so `resolve` lands on one's
1724
+ // cjs build, whose named exports an `import()` namespace would not carry.
1725
+ const req = createRequire(path.resolve(projectRoot, 'package.json'))
1726
+ oneNativeTransforms = req('one/native-transforms') as OneNativeTransforms
1727
+ } catch {
1728
+ oneNativeTransforms = null
1729
+ }
1730
+ return oneNativeTransforms
1731
+ }
1732
+
1733
+ async function configureWorkletsForWorker(projectRoot: string | undefined) {
1734
+ if (workletsConfigured) return
1735
+ workletsConfigured = true
1736
+ if (!projectRoot) return
1737
+
1738
+ const req = createRequire(path.resolve(projectRoot, 'package.json'))
1739
+ let hasReanimated = false
1740
+ try {
1741
+ req.resolve('react-native-reanimated/package.json')
1742
+ hasReanimated = true
1743
+ } catch {
1744
+ try {
1745
+ req.resolve('react-native-worklets/package.json')
1746
+ hasReanimated = true
1747
+ } catch {}
1748
+ }
1749
+
1750
+ const { configureVXRNCompilerPlugin } = await import('@vxrn/compiler')
1751
+ configureVXRNCompilerPlugin({ enableReanimated: hasReanimated })
1752
+ }
1753
+
1754
+ export async function transform(
1755
+ config: MetroWorkerConfig,
1756
+ projectRoot: string,
1757
+ filename: string,
1758
+ data: Buffer | string,
1759
+ options: MetroWorkerOptions
1760
+ ): Promise<MetroWorkerResult> {
1761
+ assertNoUnportedBabelPlugins(options)
1762
+
1763
+ let sourceCode = typeof data === 'string' ? data : data.toString('utf8')
1764
+
1765
+ // expo's own transform worker substitutes the source of two virtual files
1766
+ // before transforming them. this worker replaces that worker outright, so
1767
+ // without the same substitution `expo/virtual/env` stays a bare
1768
+ // `process.env` re-export and no .env file ever reaches the bundle.
1769
+ const environment = options.customTransformOptions?.environment
1770
+ const isClientEnvironment = environment !== 'node' && environment !== 'react-server'
1771
+
1772
+ if (isClientEnvironment && /[\\/]expo[\\/]virtual[\\/]env\.js$/.test(filename)) {
1773
+ if (options.dev) {
1774
+ const rel = path.relative(path.dirname(filename), projectRoot).split(path.sep).join('/')
1775
+ sourceCode = `const dotEnvModules = require.context(${JSON.stringify(rel)},false,/^\\.\\/\\.env/);
1776
+ export const env = !dotEnvModules.keys().length ? process.env : { ...process.env, ...['.env', '.env.development', '.env.local', '.env.development.local'].reduce((acc, file) => {
1777
+ return { ...acc, ...(dotEnvModules(file)?.default ?? {}) };
1778
+ }, {}) };`
1779
+ } else {
1780
+ // production inlines every value at its use site, so reaching this module
1781
+ // at all is a bug worth naming rather than silently returning undefined.
1782
+ sourceCode = `export const env = new Proxy({}, {
1783
+ get(target, key) {
1784
+ throw new Error(\`Attempting to access internal environment variable "\${String(key)}" is not supported in production bundles.\`);
1785
+ },
1786
+ });`
1787
+ }
1788
+ } else if (/(^|[\\/])\.env(\.(local|(development|production)(\.local)?))?$/.test(filename)) {
1789
+ const { parseEnvFile } = await import(
1790
+ '@expo/metro-config/build/transform-worker/dot-env-development'
1791
+ )
1792
+ sourceCode = `export default ${JSON.stringify(parseEnvFile(sourceCode, isClientEnvironment))};`
1793
+ }
1794
+
1795
+ checkReservedStrings(sourceCode, config, options)
1796
+
1797
+ // 1. JSON files
1798
+ if (filename.endsWith('.json')) {
1799
+ try {
1800
+ JSON.parse(sourceCode)
1801
+ } catch (err: any) {
1802
+ throw new Error(`[vxrn/metro] JSON parse error in ${filename}: ${err.message || err}`)
1803
+ }
1804
+
1805
+ let code =
1806
+ config.unstable_disableModuleWrapping === true
1807
+ ? `module.exports = ${sourceCode};`
1808
+ : wrapJson(sourceCode, {
1809
+ globalPrefix: config.globalPrefix,
1810
+ moduleId: options.moduleId,
1811
+ dependencyIds: options.dependencyIds,
1812
+ })
1813
+
1814
+ if (
1815
+ options.minify &&
1816
+ options.unstable_transformProfile !== 'hermes-canary' &&
1817
+ options.unstable_transformProfile !== 'hermes-stable' &&
1818
+ config.minifierPath
1819
+ ) {
1820
+ try {
1821
+ const minifier = require(config.minifierPath)
1822
+ const minified = await minifier({
1823
+ code,
1824
+ config: config.minifierConfig,
1825
+ filename,
1826
+ map: [],
1827
+ })
1828
+ code = minified.code
1829
+ } catch (err: any) {
1830
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`)
1831
+ }
1832
+ }
1833
+
1834
+ const { lineCount, map } = countLinesAndTerminateMap(code, [])
1835
+ const outputType: MetroOutput['type'] =
1836
+ options.type === 'asset'
1837
+ ? 'js/module/asset'
1838
+ : options.type === 'script'
1839
+ ? 'js/script'
1840
+ : 'js/module'
1841
+
1842
+ return {
1843
+ dependencies: [],
1844
+ output: [
1845
+ {
1846
+ data: {
1847
+ code,
1848
+ lineCount,
1849
+ map,
1850
+ functionMap: null,
1851
+ },
1852
+ type: outputType,
1853
+ },
1854
+ ],
1855
+ }
1856
+ }
1857
+
1858
+ // 2. Asset files
1859
+ if (options.type === 'asset') {
1860
+ const assetRegistryPath =
1861
+ config.assetRegistryPath || 'react-native/Libraries/Image/AssetRegistry'
1862
+ let properDescriptor: any = null
1863
+
1864
+ const absolutePath = path.resolve(projectRoot, filename)
1865
+ if (fs.existsSync(absolutePath)) {
1866
+ try {
1867
+ let getAssetData: any
1868
+ try {
1869
+ getAssetData = require('metro/private/Assets').getAssetData
1870
+ } catch {
1871
+ getAssetData = require('metro/src/Assets').getAssetData
1872
+ }
1873
+
1874
+ if (typeof getAssetData === 'function') {
1875
+ const rawData = await getAssetData(
1876
+ absolutePath,
1877
+ filename,
1878
+ config.assetPlugins || [],
1879
+ options.platform || '',
1880
+ config.publicPath || '/assets'
1881
+ )
1882
+ const copied = { ...rawData }
1883
+ delete copied.files
1884
+ delete copied.fileSystemLocation
1885
+ delete copied.path
1886
+ properDescriptor = copied
1887
+ }
1888
+ } catch (err: any) {
1889
+ throw new Error(`[vxrn/metro] Asset resolution failed for ${filename}: ${err.message || err}`)
1890
+ }
1891
+ }
1892
+
1893
+ if (!properDescriptor) {
1894
+ const ext = path.extname(filename).slice(1)
1895
+ const name = path.basename(filename, '.' + ext)
1896
+ properDescriptor = {
1897
+ __packager_asset: true,
1898
+ httpServerLocation: config.publicPath || '/assets',
1899
+ width: undefined,
1900
+ height: undefined,
1901
+ scales: [1],
1902
+ hash: crypto.createHash('md5').update(sourceCode).digest('hex'),
1903
+ name,
1904
+ type: ext,
1905
+ }
1906
+ }
1907
+
1908
+ // the registry is dependency 0 below, and metro's runtime require takes a
1909
+ // module id from the dependency map. emitting the bare specifier here leaves
1910
+ // a require metro cannot resolve, so every asset throws when it renders.
1911
+ const assetDepMapName = config.unstable_dependencyMapReservedName || '_dependencyMap'
1912
+ const assetCode = `module.exports = require(${assetDepMapName}[0], ${JSON.stringify(assetRegistryPath)}).registerAsset(${JSON.stringify(properDescriptor)});`
1913
+ let code =
1914
+ config.unstable_disableModuleWrapping === true
1915
+ ? assetCode
1916
+ : wrapModule(assetCode, {
1917
+ globalPrefix: config.globalPrefix,
1918
+ moduleId: options.moduleId,
1919
+ dependencyIds: options.dependencyIds,
1920
+ dependencyMapName: config.unstable_dependencyMapReservedName,
1921
+ })
1922
+
1923
+ const dependencies: MetroDependency[] = [
1924
+ {
1925
+ name: assetRegistryPath,
1926
+ data: {
1927
+ key: getDependencyKey(assetRegistryPath, false, null),
1928
+ asyncType: null,
1929
+ locs: [],
1930
+ isESMImportAtSource: false,
1931
+ isESMImport: false,
1932
+ index: 0,
1933
+ },
1934
+ },
1935
+ ]
1936
+
1937
+ const { lineCount, map } = countLinesAndTerminateMap(code, [])
1938
+ return {
1939
+ dependencies,
1940
+ output: [
1941
+ {
1942
+ data: {
1943
+ code,
1944
+ lineCount,
1945
+ map,
1946
+ functionMap: null,
1947
+ },
1948
+ type: 'js/module/asset',
1949
+ },
1950
+ ],
1951
+ }
1952
+ }
1953
+
1954
+ // 3. JS / TS files
1955
+ let code = sourceCode
1956
+ const intermediateMaps: any[] = []
1957
+
1958
+ // Step A00: the user's own native transforms, each standing in for a babel
1959
+ // plugin. they run on the file exactly as it came off disk, because in the
1960
+ // babel path every plugin visits one AST parsed from that source, so a plugin
1961
+ // that reads positions (jump-to-source stamps file:line:column) sees original
1962
+ // line numbers. one's ports below are sequential string rewrites that shift
1963
+ // lines, so running these after them would report a location the editor
1964
+ // cannot jump to.
1965
+ for (const nativeTransform of getNativeTransforms(options, projectRoot)) {
1966
+ const out = nativeTransform(code, {
1967
+ // absolute, unlike metro's own project-relative name. a transform that
1968
+ // matches on paths (include/exclude lists, node_modules skips) or stamps
1969
+ // a location into the output would otherwise get a different answer here
1970
+ // than the babel plugin it replaced, which is handed an absolute path.
1971
+ filename: path.isAbsolute(filename) ? filename : path.resolve(projectRoot, filename),
1972
+ platform: options.platform,
1973
+ dev: options.dev,
1974
+ projectRoot,
1975
+ })
1976
+ if (typeof out === 'string') code = out
1977
+ }
1978
+
1979
+ // Step A0: one's router entry rewrites. must run before dependency extraction
1980
+ // so the injected setup import and the inlined require.context regex are both
1981
+ // visible to it.
1982
+ const oneRouterOptions = getOneRouterMetroOptions(options)
1983
+ if (oneRouterOptions) {
1984
+ code = applyOneRouterMetro(code, filename, oneRouterOptions)
1985
+ }
1986
+
1987
+
1988
+ // Step A0b: React Native codegen. `codegenNativeComponent('RNSScreen')` is a
1989
+ // spec that has to become a real view config registration; without it the
1990
+ // component has no view config and the screen never mounts. Metro's default
1991
+ // pipeline gets this from @react-native/babel-plugin-codegen inside
1992
+ // @react-native/babel-preset, which this transformer replaces.
1993
+ //
1994
+ // This runs before Flow stripping because codegen reads the component's props
1995
+ // out of the type argument to codegenNativeComponent. Once Step A removes the
1996
+ // types there is nothing left to generate from, and react-native's own parser
1997
+ // rejects the file with "Could not find component config".
1998
+ try {
1999
+ const codegenRes = transformReactNativeCodegen(code, filename, projectRoot)
2000
+ if (codegenRes?.code) {
2001
+ code = codegenRes.code
2002
+ if (codegenRes.map) {
2003
+ intermediateMaps.push(codegenRes.map)
2004
+ }
2005
+ }
2006
+ } catch (err: any) {
2007
+ throw new Error(
2008
+ `[vxrn/metro] React Native codegen failed for ${filename}: ${err.message || err}`
2009
+ )
2010
+ }
2011
+
2012
+ // Step A: Flow stripping
2013
+ const hasFlowPragma = code.includes('@flow')
2014
+ const isFlowCandidate =
2015
+ (filename.endsWith('.js') || filename.endsWith('.jsx')) &&
2016
+ (hasFlowPragma || FLOW_FILE_PATTERN.test(filename) || code.includes('import type'))
2017
+
2018
+ if (isFlowCandidate) {
2019
+ try {
2020
+ const fft = await import('fast-flow-transform')
2021
+ const flowTransform = fft.default || fft
2022
+ const flowResult = await flowTransform({
2023
+ filename,
2024
+ source: code,
2025
+ sourcemap: true,
2026
+ dialect: 'flow',
2027
+ format: 'pretty',
2028
+ })
2029
+ if (flowResult?.code) {
2030
+ code = flowResult.code
2031
+ if (flowResult.map) {
2032
+ intermediateMaps.push(
2033
+ typeof flowResult.map === 'string' ? JSON.parse(flowResult.map) : flowResult.map
2034
+ )
2035
+ }
2036
+ }
2037
+ } catch (err: any) {
2038
+ throw new Error(`[vxrn/metro] Flow transform failed for ${filename}: ${err.message || err}`)
2039
+ }
2040
+ }
2041
+
2042
+ const asyncRequirePath =
2043
+ config.asyncRequireModulePath || 'metro-runtime/src/modules/asyncRequire'
2044
+
2045
+ // Step A1: tsconfig path aliases. runs after flow stripping so the parse can
2046
+ // succeed, and before dependency extraction so metro only ever sees
2047
+ // specifiers it can resolve. the substring guard keeps the extra parse off
2048
+ // the files that have no aliased import at all.
2049
+ const aliases = getModuleResolverAliases(options)
2050
+ if (aliases && projectRoot) {
2051
+ const aliasKeys = Object.keys(aliases)
2052
+ if (aliasKeys.some((k) => code.includes(k.endsWith('$') ? k.slice(0, -1) : k))) {
2053
+ code = applyModuleResolverAliases(code, filename, projectRoot, aliases)
2054
+ }
2055
+ }
2056
+
2057
+ // Step A2: expo public env vars, one's server url, and `import.meta.env`.
2058
+ // after flow stripping so the parse succeeds, before extraction so both the
2059
+ // injected `expo/virtual/env` import and any folded-away dead branch are seen.
2060
+ // the substring guards keep the extra parse off files with no such read at all.
2061
+ if (code.includes('process.env') || code.includes('import.meta')) {
2062
+ code = applyInlineEnvVars(code, filename, !options.dev, getImportMetaEnv(options))
2063
+ }
2064
+
2065
+ // Step A3: one's environment guards. `import 'server-only'` in a native
2066
+ // bundle has to become a throw, and it has to happen before extraction or
2067
+ // metro tries to resolve a module that only exists to be rejected.
2068
+ if (code.includes('-only')) {
2069
+ code = applyEnvironmentGuard(code, filename)
2070
+ }
2071
+
2072
+ // Step A4: one's server-only route exports. a route's `loader` runs on the
2073
+ // server, and leaving it in drags everything it imports — database clients,
2074
+ // secrets — into the app bundle. this reuses one's own oxc tree-shaker rather
2075
+ // than reimplementing its dead-code elimination here; it is resolved out of
2076
+ // the user's `one` install because one depends on this package, not the
2077
+ // reverse.
2078
+ const serverCodeRouterRoot = getRemoveServerCodeRouterRoot(options)
2079
+ if (serverCodeRouterRoot && projectRoot && !filename.includes('node_modules')) {
2080
+ const oneNativeTransforms = loadOneNativeTransforms(projectRoot)
2081
+ if (oneNativeTransforms) {
2082
+ const shaken = await oneNativeTransforms.transformTreeShakeClient(
2083
+ code,
2084
+ filename,
2085
+ projectRoot,
2086
+ serverCodeRouterRoot
2087
+ )
2088
+ if (shaken?.code) {
2089
+ code = shaken.code
2090
+ }
2091
+ }
2092
+ }
2093
+
2094
+ // Step B: Extract dependencies using oxc-parser (zero Babel, lexical scope aware)
2095
+ const dependencies = extractDependencies(code, filename, {
2096
+ asyncRequireModulePath: asyncRequirePath,
2097
+ allowOptionalDependencies: config.allowOptionalDependencies,
2098
+ })
2099
+
2100
+ // Step C: React Compiler (via @vxrn/compiler / oxc-transform-react)
2101
+ //
2102
+ // `react: { compiler: true }` in one's config reaches metro as
2103
+ // babel-plugin-react-compiler in the babel plugin list, not as expo's
2104
+ // customTransformOptions.reactCompiler (which only ever comes from a
2105
+ // `transform.reactCompiler` query param on the bundle url). the babel
2106
+ // transformer read the plugin list, so this one has to as well or the app
2107
+ // asked for the compiler and silently got nothing.
2108
+ const shouldRunReactCompiler =
2109
+ Boolean(options.customTransformOptions?.reactCompiler) ||
2110
+ (hasBabelPlugin(options, 'babel-plugin-react-compiler') && isReactCompilerCandidate(filename)) ||
2111
+ code.includes('"use memo"') ||
2112
+ code.includes("'use memo'")
2113
+
2114
+ if (shouldRunReactCompiler) {
2115
+ try {
2116
+ const { transformOxcReactCompiler } = await import('@vxrn/compiler')
2117
+ const compilerRes = await transformOxcReactCompiler(filename, code, '19')
2118
+ if (compilerRes?.code) {
2119
+ code = compilerRes.code
2120
+ if (compilerRes.map) {
2121
+ intermediateMaps.push(
2122
+ typeof compilerRes.map === 'string' ? JSON.parse(compilerRes.map) : compilerRes.map
2123
+ )
2124
+ }
2125
+ }
2126
+ } catch (err: any) {
2127
+ throw new Error(`[vxrn/metro] React Compiler failed for ${filename}: ${err.message || err}`)
2128
+ }
2129
+ }
2130
+
2131
+ // Step D: Native Worklets (via @vxrn/compiler)
2132
+ //
2133
+ // @vxrn/compiler's reanimated gate is process-global state set by one's vite
2134
+ // plugin. metro runs its transformer in separate worker processes that never
2135
+ // see that call, so the gate reads false there and every worklet in the app
2136
+ // silently ships untransformed. configure it once per worker from the same
2137
+ // fact the vite side derives it from: does the project have reanimated.
2138
+ await configureWorkletsForWorker(projectRoot)
2139
+
2140
+ let shouldRunWorklets = Boolean(options.customTransformOptions?.worklets)
2141
+ if (!shouldRunWorklets) {
2142
+ const { shouldTransformWorklets } = await import('@vxrn/compiler')
2143
+ shouldRunWorklets = shouldTransformWorklets({ id: filename, code })
2144
+ }
2145
+
2146
+ if (shouldRunWorklets) {
2147
+ try {
2148
+ const { transformWorklets } = await import('@vxrn/compiler')
2149
+ // no pluginVersion here: the compiler reads it from the worklets package
2150
+ // the app actually installed, and worklets throws at runtime when the
2151
+ // stamped version is not exactly its own.
2152
+ const workletRes = await transformWorklets(filename, code, true, {
2153
+ projectRoot,
2154
+ })
2155
+ if (workletRes?.code) {
2156
+ code = workletRes.code
2157
+ if (workletRes.map) {
2158
+ intermediateMaps.push(
2159
+ typeof workletRes.map === 'string' ? JSON.parse(workletRes.map) : workletRes.map
2160
+ )
2161
+ }
2162
+ }
2163
+ } catch (err: any) {
2164
+ throw new Error(`[vxrn/metro] Worklets transform failed for ${filename}: ${err.message || err}`)
2165
+ }
2166
+ }
2167
+
2168
+ // Step E: Hermes lowering + CommonJS + TS/JSX via oxc + esbuild (zero Babel, zero SWC)
2169
+ const lang = langForFilename(filename)
2170
+
2171
+ const { transformSync: oxcTransform } = await import('oxc-transform')
2172
+ let oxcRes: any
2173
+ try {
2174
+ oxcRes = oxcTransform(filename, code, {
2175
+ lang,
2176
+ // Hermes supports BigInt but not async generators or for-await-of, and no
2177
+ // single oxc target expresses that: es2020 keeps BigInt and leaves async
2178
+ // generators in, es2017 lowers them but rejects BigInt literals. oxc's
2179
+ // `hermes*` targets claim async generators are supported, which the device
2180
+ // disproves. So the level is chosen per module. A module using both is
2181
+ // vanishingly rare and fails loudly here rather than at runtime.
2182
+ target: HERMES_UNSUPPORTED_ASYNC_RE.test(code) ? 'es2017' : 'es2020',
2183
+ assumptions: {
2184
+ setPublicClassFields: true,
2185
+ },
2186
+ jsx: {
2187
+ runtime: 'automatic',
2188
+ development: Boolean(options.dev),
2189
+ },
2190
+ sourcemap: true,
2191
+ })
2192
+ } catch (err: any) {
2193
+ throw new Error(`[vxrn/metro] Oxc transform failed for ${filename}: ${err.message || err}`)
2194
+ }
2195
+
2196
+ // oxc reports errors on the result rather than throwing. falling back to the
2197
+ // untransformed source here leaves jsx and typescript in place, which only
2198
+ // fails later in esbuild with a misleading message about the wrong step.
2199
+ if (oxcRes.errors?.length) {
2200
+ throw new Error(
2201
+ `[vxrn/metro] Oxc transform failed for ${filename}: ${oxcRes.errors[0].message || oxcRes.errors[0]}`
2202
+ )
2203
+ }
2204
+
2205
+ code = oxcRes.code || code
2206
+ if (oxcRes.map) {
2207
+ intermediateMaps.push(
2208
+ typeof oxcRes.map === 'string' ? JSON.parse(oxcRes.map) : oxcRes.map
2209
+ )
2210
+ }
2211
+
2212
+ if (options.type !== 'script') {
2213
+ try {
2214
+ const esbuild = await import('esbuild')
2215
+ const esbuildRes = esbuild.transformSync(code, {
2216
+ loader: 'js',
2217
+ format: 'cjs',
2218
+ target: 'es2020',
2219
+ sourcemap: true,
2220
+ sourcefile: filename,
2221
+ })
2222
+ code = esbuildRes.code
2223
+ if (esbuildRes.map) {
2224
+ intermediateMaps.push(
2225
+ typeof esbuildRes.map === 'string' ? JSON.parse(esbuildRes.map) : esbuildRes.map
2226
+ )
2227
+ }
2228
+ } catch (err: any) {
2229
+ throw new Error(`[vxrn/metro] esbuild CJS lowering failed for ${filename}: ${err.message || err}`)
2230
+ }
2231
+ }
2232
+
2233
+ // Step E2: per-iteration loop bindings for Hermes.
2234
+ //
2235
+ // Runs after esbuild because esbuild's own __copyProps interop helper is built
2236
+ // on `for (let key of ...)` with a closure in the body, which under Hermes
2237
+ // makes every named export of a module resolve to its last one. See
2238
+ // transformHermesLoops for the engine detail and the bytecode evidence.
2239
+ try {
2240
+ const loopsRes = transformHermesLoops(code, filename)
2241
+ if (loopsRes) {
2242
+ code = loopsRes.code
2243
+ for (const map of loopsRes.maps) {
2244
+ intermediateMaps.push(map)
2245
+ }
2246
+ }
2247
+ } catch (err: any) {
2248
+ throw new Error(
2249
+ `[vxrn/metro] Hermes loop-binding transform failed for ${filename}: ${err.message || err}`
2250
+ )
2251
+ }
2252
+
2253
+ // step B read the original source, but steps C through E both add and remove
2254
+ // imports: they inject the jsx runtime, react/compiler-runtime, oxc's
2255
+ // @oxc-project/runtime helpers and the asset registry, and oxc elides
2256
+ // type-only imports typescript never emits. metro resolves and bundles exactly
2257
+ // this list, so an extra entry is an unresolvable module that fails the build
2258
+ // and a missing one is a module absent from the bundle. reconcile against what
2259
+ // the final code actually requires.
2260
+ const finalDeps = extractDependencies(code, filename, {
2261
+ asyncRequireModulePath: asyncRequirePath,
2262
+ allowOptionalDependencies: config.allowOptionalDependencies,
2263
+ })
2264
+ const finalNames = new Set(finalDeps.map((d) => d.name))
2265
+ // keep the original entries, which carry the source's ESM metadata that the
2266
+ // cjs-lowered code no longer shows, then append whatever was injected.
2267
+ const reconciled = dependencies.filter((d) => finalNames.has(d.name))
2268
+ for (const injected of finalDeps) {
2269
+ if (reconciled.some((d) => d.name === injected.name)) continue
2270
+ reconciled.push(injected)
2271
+ }
2272
+ dependencies.length = 0
2273
+ for (const dep of reconciled) {
2274
+ dependencies.push({ ...dep, data: { ...dep.data, index: dependencies.length } })
2275
+ }
2276
+
2277
+ // Step F: Module Wrapping & Dependency ABI Rewriting with full sourcemap tracking
2278
+ const depMapName = config.unstable_dependencyMapReservedName || '_dependencyMap'
2279
+
2280
+ if (options.type === 'script') {
2281
+ const msScript = new MagicString(code)
2282
+ msScript.prepend(`(function (global) {\n`)
2283
+ msScript.append(
2284
+ `\n})(typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this);`
2285
+ )
2286
+ code = msScript.toString()
2287
+ intermediateMaps.push(msScript.generateMap({ source: filename, hires: true, includeContent: true }))
2288
+ } else if (config.unstable_disableModuleWrapping === true) {
2289
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath)
2290
+ code = rewriteRes.code
2291
+ if (rewriteRes.map) {
2292
+ intermediateMaps.push(rewriteRes.map)
2293
+ }
2294
+ } else {
2295
+ const rewriteRes = rewriteDependencyCalls(code, dependencies, depMapName, filename, asyncRequirePath)
2296
+ if (rewriteRes.map) {
2297
+ intermediateMaps.push(rewriteRes.map)
2298
+ }
2299
+ const msWrap = new MagicString(rewriteRes.code)
2300
+ const globalPrefix = config.globalPrefix || ''
2301
+ const header = `function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, ${depMapName}) {\nvar require = _$$_REQUIRE;\n`
2302
+ const footer = `\n}`
2303
+
2304
+ msWrap.prepend(`${globalPrefix}__d(${header}`)
2305
+ if (options.moduleId !== undefined) {
2306
+ const depIds = options.dependencyIds ? JSON.stringify(options.dependencyIds) : '[]'
2307
+ msWrap.append(`${footer}, ${JSON.stringify(options.moduleId)}, ${depIds});`)
2308
+ } else {
2309
+ msWrap.append(`${footer});`)
2310
+ }
2311
+
2312
+ code = msWrap.toString()
2313
+ intermediateMaps.push(msWrap.generateMap({ source: filename, hires: true, includeContent: true }))
2314
+ }
2315
+
2316
+ // Step G: Minification
2317
+ if (
2318
+ options.minify &&
2319
+ options.unstable_transformProfile !== 'hermes-canary' &&
2320
+ options.unstable_transformProfile !== 'hermes-stable' &&
2321
+ config.minifierPath
2322
+ ) {
2323
+ try {
2324
+ const minifier = require(config.minifierPath)
2325
+ const minified = await minifier({
2326
+ code,
2327
+ config: config.minifierConfig,
2328
+ filename,
2329
+ map: [],
2330
+ })
2331
+ code = minified.code
2332
+ if (minified.map) {
2333
+ intermediateMaps.push(
2334
+ typeof minified.map === 'string' ? JSON.parse(minified.map) : minified.map
2335
+ )
2336
+ }
2337
+ } catch (err: any) {
2338
+ throw new Error(`[vxrn/metro] Minifier failed for ${filename}: ${err.message || err}`)
2339
+ }
2340
+ }
2341
+
2342
+ // Step H: Compose all pipeline maps and convert to Metro raw mapping segment tuples
2343
+ let rawMappings: Array<[number, number] | [number, number, number, number] | [number, number, number, number, string]> = []
2344
+
2345
+ if (intermediateMaps.length > 0) {
2346
+ const cleanMaps = intermediateMaps
2347
+ .map((m) => (typeof m === 'string' ? JSON.parse(m) : m))
2348
+ .filter(Boolean)
2349
+
2350
+ if (cleanMaps.length > 0) {
2351
+ const composed =
2352
+ cleanMaps.length === 1
2353
+ ? cleanMaps[0]
2354
+ : remapping(cleanMaps.slice().reverse(), () => null)
2355
+ rawMappings = convertSourceMapToMetroRawMappings(composed)
2356
+ }
2357
+ }
2358
+
2359
+ const { lineCount, map } = countLinesAndTerminateMap(code, rawMappings)
2360
+
2361
+ return {
2362
+ dependencies,
2363
+ output: [
2364
+ {
2365
+ data: {
2366
+ code,
2367
+ lineCount,
2368
+ map,
2369
+ functionMap: null,
2370
+ },
2371
+ type: options.type === 'script' ? 'js/script' : 'js/module',
2372
+ },
2373
+ ],
2374
+ }
2375
+ }
2376
+
2377
+ export default {
2378
+ transform,
2379
+ getCacheKey,
2380
+ wrapModule,
2381
+ wrapJson,
2382
+ extractDependencies,
2383
+ rewriteDependencyCalls,
2384
+ convertSourceMapToMetroRawMappings,
2385
+ }