@vxrn/vite-plugin-metro 1.25.16 → 1.26.0

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