vitest-native 0.4.1 → 0.5.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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-OJm5IWuL.mjs";
2
- import { t as presets_exports } from "./presets-DOGXQzYT.mjs";
2
+ import { t as presets_exports } from "./presets-C9SvIaG-.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import path from "node:path";
@@ -49,6 +49,34 @@ const KNOWN_OPTIONS = [
49
49
  "transform",
50
50
  "hotRuntime"
51
51
  ];
52
+ const KNOWN_HOT_RUNTIME_OPTIONS = [
53
+ "recycleAfterFiles",
54
+ "memoryLimit",
55
+ "preserveGlobals"
56
+ ];
57
+ function assertStringArray(value, option) {
58
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new TypeError(`[vitest-native] "${option}" must be an array of non-empty strings.`);
59
+ }
60
+ function assertNonNegativeInteger(value, option) {
61
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
62
+ }
63
+ function validateOptions(options) {
64
+ if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new TypeError(`[vitest-native] "engine" must be "auto", "mock", or "native".`);
65
+ if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
66
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
67
+ if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
68
+ if (options.transform !== void 0) assertStringArray(options.transform, "transform");
69
+ if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
70
+ if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new TypeError(`[vitest-native] "mocks" must be a plain object.`);
71
+ const hotRuntime = options.hotRuntime;
72
+ if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
73
+ if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
74
+ const hotOptions = hotRuntime;
75
+ for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
76
+ if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
77
+ if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
78
+ if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
79
+ }
52
80
  function satisfiesMinimum(version, minimum) {
53
81
  const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
54
82
  const [aMaj, aMin = 0, aPat = 0] = parse(version);
@@ -57,11 +85,14 @@ function satisfiesMinimum(version, minimum) {
57
85
  if (aMin !== bMin) return aMin > bMin;
58
86
  return aPat >= bPat;
59
87
  }
60
- function validatePeerDependency(pkgName, minimumVersion, projectRoot) {
88
+ function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
61
89
  const req = createRequire(path.join(projectRoot, "package.json"));
62
90
  try {
63
91
  const { version } = req(req.resolve(`${pkgName}/package.json`));
64
- if (!satisfiesMinimum(version, minimumVersion)) return `vitest-native requires ${pkgName} >= ${minimumVersion}, but found ${version}. Please upgrade.`;
92
+ const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
93
+ const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
94
+ if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
95
+ if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
65
96
  return null;
66
97
  } catch {
67
98
  return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
@@ -106,29 +137,19 @@ function levenshtein(a, b) {
106
137
  function escapeRe(s) {
107
138
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
108
139
  }
109
- function nativeEngineConfig(setupFilePath, env, transformPkgs = [], hot) {
140
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
110
141
  const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
111
142
  const fullEnv = { ...env };
112
143
  if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
113
144
  return {
114
- esbuild: { jsx: "automatic" },
145
+ ...jsxTransform,
115
146
  resolve: {
116
147
  conditions: ["react-native"],
117
- extensions: [
118
- ".ios.tsx",
119
- ".ios.ts",
120
- ".ios.js",
121
- ".native.tsx",
122
- ".native.ts",
123
- ".native.js",
124
- ".tsx",
125
- ".ts",
126
- ".jsx",
127
- ".js"
128
- ],
148
+ extensions,
129
149
  dedupe: [
130
150
  "react",
131
151
  "react-test-renderer",
152
+ "test-renderer",
132
153
  "react-is"
133
154
  ]
134
155
  },
@@ -220,6 +241,7 @@ function stripFsPrefix(id) {
220
241
  }
221
242
  async function autoDetectPresets(diagnostics, projectRoot) {
222
243
  const detected = [];
244
+ const enabled = /* @__PURE__ */ new Set();
223
245
  const presetFactories = await import("./presets.mjs");
224
246
  const req = createRequire(path.join(projectRoot, "package.json"));
225
247
  for (const [pkgName, exportName] of Object.entries(AUTO_DETECT_PRESETS)) {
@@ -229,15 +251,39 @@ async function autoDetectPresets(diagnostics, projectRoot) {
229
251
  installed = true;
230
252
  } catch {}
231
253
  if (installed) {
254
+ if (enabled.has(exportName)) continue;
232
255
  const factory = presetFactories[exportName];
233
256
  if (typeof factory === "function") {
234
257
  detected.push(factory());
258
+ enabled.add(exportName);
235
259
  if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
236
260
  }
237
261
  } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
238
262
  }
239
263
  return detected;
240
264
  }
265
+ function resolvePackageVersion(packageName, projectRoot) {
266
+ const req = createRequire(path.join(projectRoot, "package.json"));
267
+ try {
268
+ return req(`${packageName}/package.json`).version ?? null;
269
+ } catch {
270
+ return null;
271
+ }
272
+ }
273
+ function getJsxTransformConfig(projectRoot) {
274
+ const viteVersion = resolvePackageVersion("vite", projectRoot);
275
+ return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
276
+ }
277
+ /**
278
+ * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
279
+ * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
280
+ * version check above guarantees that only the matching shape is returned,
281
+ * but a build against any single Vite major cannot type the other major's
282
+ * valid config. Keep that unavoidable assertion at this compatibility edge.
283
+ */
284
+ function asCompatibleViteConfig(config) {
285
+ return config;
286
+ }
241
287
  /**
242
288
  * Synchronously resolve the export-names of presets whose package is installed.
243
289
  * Used by the native-engine config path (which can't await the factory imports)
@@ -379,8 +425,11 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
379
425
  * React Native code in a Node/JSDOM environment.
380
426
  */
381
427
  function reactNative(options) {
428
+ if (options) {
429
+ validateOptions(options);
430
+ warnUnknownOptions(options);
431
+ }
382
432
  if (options?.mocks && containsFunctions(options.mocks)) throw new Error("[vitest-native] The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
383
- if (options) warnUnknownOptions(options);
384
433
  let resolved;
385
434
  const presetModules = /* @__PURE__ */ new Map();
386
435
  const presetExportNames = /* @__PURE__ */ new Map();
@@ -410,6 +459,7 @@ function reactNative(options) {
410
459
  enforce: "pre",
411
460
  async config(userConfig, _env) {
412
461
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
462
+ const jsxTransform = getJsxTransformConfig(resolvedRoot);
413
463
  const decision = detectEngine(requestedEngine, resolvedRoot);
414
464
  engine = decision.engine;
415
465
  if (decision.notice) console.log(decision.notice);
@@ -418,29 +468,35 @@ function reactNative(options) {
418
468
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
419
469
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
420
470
  };
471
+ const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
472
+ if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
473
+ if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
421
474
  if (engine === "native") {
475
+ if (options?.mocks && Object.keys(options.mocks).length > 0) throw new Error("[vitest-native] The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
422
476
  const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
423
477
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
424
- return nativeEngineConfig(nativeSetupPath, env, transformPkgs, hotRuntime ? {
425
- pool: (await import("./pool-oPTZiSXU.mjs")).nativePool({
478
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
479
+ pool: (await import("./pool-B7LBfcMQ.mjs")).nativePool({
426
480
  workerEntry: nativeWorkerPath,
427
481
  recycleAfterFiles: hotRecycle.recycleAfterFiles,
428
- memoryLimit: hotRecycle.memoryLimit
482
+ memoryLimit: hotRecycle.memoryLimit,
483
+ diagnostics
429
484
  }),
430
485
  runnerPath: nativeRunnerPath
431
- } : void 0);
486
+ } : void 0, jsxTransform));
432
487
  }
433
488
  if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
434
489
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
435
490
  if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
436
- return {
437
- esbuild: { jsx: "automatic" },
491
+ return asCompatibleViteConfig({
492
+ ...jsxTransform,
438
493
  resolve: {
439
494
  extensions,
440
495
  conditions: ["react-native"],
441
496
  dedupe: [
442
497
  "react",
443
498
  "react-test-renderer",
499
+ "test-renderer",
444
500
  "react-is"
445
501
  ]
446
502
  },
@@ -448,27 +504,37 @@ function reactNative(options) {
448
504
  setupFiles: [setupFilePath],
449
505
  env
450
506
  }
451
- };
507
+ });
452
508
  },
453
509
  async configResolved(config) {
454
- for (const { name, range } of [
510
+ const peers = [
455
511
  {
456
512
  name: "vitest",
457
- range: "4.0.0"
513
+ minimum: "4.0.0",
514
+ maximumMajor: 5
458
515
  },
459
516
  {
460
517
  name: "vite",
461
- range: "5.0.0"
518
+ minimum: "6.4.2",
519
+ maximumMajor: 9,
520
+ minimumByMajor: {
521
+ 6: "6.4.2",
522
+ 7: "7.3.2",
523
+ 8: "8.0.5"
524
+ }
462
525
  },
463
526
  {
464
527
  name: "react",
465
- range: "18.0.0"
528
+ minimum: "18.0.0"
466
529
  }
467
- ]) {
468
- const error = validatePeerDependency(name, range, config.root);
469
- if (error) console.error(`[vitest-native] ${error}`);
530
+ ];
531
+ const peerErrors = [];
532
+ for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
533
+ const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
534
+ if (error) peerErrors.push(error);
470
535
  }
471
- const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root);
536
+ if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
537
+ const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
472
538
  if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
473
539
  resolved = await resolveOptions(options, config.root);
474
540
  resolved.engine = engine;
@@ -523,6 +589,8 @@ function reactNative(options) {
523
589
  virtualCodeCache.set(id, code);
524
590
  return code;
525
591
  }
592
+ const fsPath = stripFsPrefix(id);
593
+ if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
526
594
  if (engine === "native") return void 0;
527
595
  if (id === "\0virtual:react-native") return "export default {};";
528
596
  if (id.startsWith("\0virtual:rn-subpath:")) {
@@ -537,8 +605,6 @@ function reactNative(options) {
537
605
  }
538
606
  return code;
539
607
  }
540
- const fsPath = stripFsPrefix(id);
541
- if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
542
608
  },
543
609
  transform(code, id) {
544
610
  if (engine === "native") return void 0;
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
3
  let magic_string = require("magic-string");
4
- magic_string = require_chunk.__toESM(magic_string);
4
+ magic_string = require_chunk.__toESM(magic_string, 1);
5
5
  //#region src/jest-compat/transform.ts
6
6
  const HOISTABLE = new Set([
7
7
  "mock",
@@ -3,27 +3,52 @@
3
3
  // expressed as CJS source strings so both transform hooks (loader + require) can
4
4
  // serve them identically. Mirrors react-native/jest/setup.js's mock set.
5
5
 
6
- const DEVICE_CONSTANTS = JSON.stringify({
7
- PlatformConstants: {
8
- forceTouchAvailable: false,
9
- reactNativeVersion: { major: 0, minor: 84, patch: 1 },
10
- osVersion: "17.0",
11
- systemName: "iOS",
12
- interfaceIdiom: "phone",
13
- isTesting: true,
14
- },
15
- DeviceInfo: {
16
- Dimensions: {
17
- window: { width: 390, height: 844, scale: 3, fontScale: 1 },
18
- screen: { width: 390, height: 844, scale: 3, fontScale: 1 },
6
+ function parseVersion(version) {
7
+ const [major = 0, minor = 0, patch = 0] = String(version || "0.0.0")
8
+ .split(/[.-]/)
9
+ .map((part) => Number.parseInt(part, 10) || 0);
10
+ return { major, minor, patch };
11
+ }
12
+
13
+ function deviceConstants(platform, reactNativeVersion) {
14
+ const platformConstants =
15
+ platform === "android"
16
+ ? {
17
+ isTesting: true,
18
+ reactNativeVersion,
19
+ Version: 34,
20
+ Release: "14",
21
+ Serial: "unknown",
22
+ Fingerprint: "vitest-native",
23
+ Model: "vitest-native",
24
+ uiMode: "normal",
25
+ Brand: "generic",
26
+ Manufacturer: "generic",
27
+ }
28
+ : {
29
+ forceTouchAvailable: false,
30
+ reactNativeVersion,
31
+ osVersion: "17.0",
32
+ systemName: "iOS",
33
+ interfaceIdiom: "phone",
34
+ isTesting: true,
35
+ };
36
+
37
+ return {
38
+ PlatformConstants: platformConstants,
39
+ DeviceInfo: {
40
+ Dimensions: {
41
+ window: { width: 390, height: 844, scale: 3, fontScale: 1 },
42
+ screen: { width: 390, height: 844, scale: 3, fontScale: 1 },
43
+ },
44
+ },
45
+ I18nManager: {
46
+ isRTL: false,
47
+ doLeftAndRightSwapInRTL: true,
48
+ localeIdentifier: "en_US",
19
49
  },
20
- },
21
- I18nManager: {
22
- isRTL: false,
23
- doLeftAndRightSwapInRTL: true,
24
- localeIdentifier: "en_US",
25
- },
26
- });
50
+ };
51
+ }
27
52
 
28
53
  // A reusable mock-native-component factory, inlined into each source string that needs it.
29
54
  //
@@ -71,8 +96,18 @@ const MOCK_NATIVE_COMPONENT = `
71
96
  };
72
97
  `;
73
98
 
74
- const TURBO_STUB = `
75
- const __C = ${DEVICE_CONSTANTS};
99
+ function turboStubSource(platform, version) {
100
+ const constants = JSON.stringify(deviceConstants(platform, parseVersion(version)));
101
+ return `
102
+ const __C = ${constants};
103
+ const __moduleMocks = () => globalThis.__vitest_native_module_mocks || {};
104
+ const __boundaryState =
105
+ globalThis.__vitest_native_boundary_state ||
106
+ (globalThis.__vitest_native_boundary_state = Object.create(null));
107
+ const getBoundaryState = (name) =>
108
+ __boundaryState[name] || (__boundaryState[name] = Object.create(null));
109
+ const getModuleMock = (name) =>
110
+ Object.prototype.hasOwnProperty.call(__moduleMocks(), name) ? __moduleMocks()[name] : null;
76
111
  // Native methods that return a Promise on the device (no callback arg). Without
77
112
  // this, real RN code doing \`NativeModule.canOpenURL(url).then(...)\` would crash
78
113
  // on \`undefined\`. Values are the no-native defaults.
@@ -94,7 +129,15 @@ const TURBO_STUB = `
94
129
  const turboStub = (name) => new Proxy({}, {
95
130
  get: (_t, p) => {
96
131
  if (p === "getConstants") return () => (__C[name] || {});
97
- if (p === "getColorScheme") return () => "light"; // NativeAppearance
132
+ if (p === "getColorScheme") {
133
+ return () => getBoundaryState(name).colorScheme ?? "light";
134
+ }
135
+ if (p === "setColorScheme") {
136
+ return (colorScheme) => {
137
+ getBoundaryState(name).colorScheme =
138
+ colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
139
+ };
140
+ }
98
141
  if (p === "addListener") return () => ({ remove: () => {} });
99
142
  if (p === "removeListeners") return () => {};
100
143
  return (...args) => {
@@ -114,17 +157,21 @@ const TURBO_STUB = `
114
157
  },
115
158
  });
116
159
  `;
160
+ }
117
161
 
118
162
  export const BOUNDARY_SOURCES = {
119
- "Libraries/TurboModule/TurboModuleRegistry.js": `
120
- ${TURBO_STUB}
121
- exports.get = (n) => turboStub(n);
122
- exports.getEnforcing = (n) => turboStub(n);
163
+ "Libraries/TurboModule/TurboModuleRegistry.js": (platform, version) => `
164
+ ${turboStubSource(platform, version)}
165
+ exports.get = (n) => getModuleMock(n) || turboStub(n);
166
+ exports.getEnforcing = (n) => getModuleMock(n) || turboStub(n);
123
167
  `,
124
- "Libraries/BatchedBridge/NativeModules.js": `
125
- ${TURBO_STUB}
168
+ "Libraries/BatchedBridge/NativeModules.js": (platform, version) => `
169
+ ${turboStubSource(platform, version)}
126
170
  module.exports = { __esModule: true, default: new Proxy({}, {
127
- get: (_t, n) => (typeof n === "string" ? turboStub(n) : undefined),
171
+ get: (_t, n) => {
172
+ if (typeof n !== "string") return undefined;
173
+ return getModuleMock(n) || turboStub(n);
174
+ },
128
175
  }) };
129
176
  `,
130
177
  "Libraries/NativeComponent/NativeComponentRegistry.js": `
@@ -217,9 +264,12 @@ export function isBoundary(normPath) {
217
264
  }
218
265
 
219
266
  /** Returns the CJS source for a boundary module, or null if not a boundary. */
220
- export function boundarySourceFor(normPath) {
267
+ export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0") {
221
268
  for (const s of SUFFIXES) {
222
- if (normPath.endsWith("/react-native/" + s)) return BOUNDARY_SOURCES[s];
269
+ if (normPath.endsWith("/react-native/" + s)) {
270
+ const source = BOUNDARY_SOURCES[s];
271
+ return typeof source === "function" ? source(platform, version) : source;
272
+ }
223
273
  }
224
274
  return null;
225
275
  }
@@ -21,6 +21,7 @@ export function installGlobals() {
21
21
  g.IS_REACT_ACT_ENVIRONMENT = true;
22
22
  g.IS_REACT_NATIVE_TEST_ENVIRONMENT = true;
23
23
  g.__fbBatchedBridgeConfig = { remoteModuleConfig: [], localModulesConfig: [] };
24
+ g.__vitest_native_module_mocks = g.__vitest_native_module_mocks || {};
24
25
 
25
26
  installExpoGlobal(g);
26
27
  }
@@ -14,7 +14,12 @@ const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
14
14
  // can be evaluated twice in one worker (once by the worker entry through Node's
15
15
  // loader, once through Vitest's module runner when the setup file is inlined),
16
16
  // and the hooks must still install exactly once per worker.
17
- export function installRequireHooks(projectRoot, transformPkgs = []) {
17
+ export function installRequireHooks(
18
+ projectRoot,
19
+ transformPkgs = [],
20
+ platform = "ios",
21
+ reactNativeVersion = "0.0.0",
22
+ ) {
18
23
  if (globalThis.__vitest_native_require_hooks_installed) return;
19
24
  globalThis.__vitest_native_require_hooks_installed = true;
20
25
 
@@ -42,11 +47,14 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
42
47
  if (
43
48
  parent &&
44
49
  parent.filename &&
45
- RN_PATH.test(parent.filename) &&
50
+ (RN_PATH.test(parent.filename) || isExtra(parent.filename)) &&
46
51
  request.startsWith(".") &&
47
52
  !path.extname(request)
48
53
  ) {
49
- const hit = resolvePlatformFile(path.resolve(path.dirname(parent.filename), request));
54
+ const hit = resolvePlatformFile(
55
+ path.resolve(path.dirname(parent.filename), request),
56
+ platform,
57
+ );
50
58
  if (hit) return hit;
51
59
  }
52
60
  return origResolve.call(this, request, parent, ...rest);
@@ -55,16 +63,17 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
55
63
  const origJs = Module._extensions[".js"];
56
64
  Module._extensions[".js"] = function (mod, filename) {
57
65
  const norm = filename.replace(/\\/g, "/");
58
- const boundary = boundarySourceFor(norm);
66
+ const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
59
67
  if (boundary != null) return mod._compile(boundary, filename);
60
68
  if (RN_PATH.test(norm)) {
61
69
  const src = fs.readFileSync(filename, "utf8");
62
- if (isFlow(src)) return mod._compile(transformRN(filename, src, projectRoot), filename);
70
+ if (isFlow(src))
71
+ return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
63
72
  } else if (isExtra(norm)) {
64
73
  // Configured third-party packages: transform unconditionally — TS `import
65
74
  // type`/JSX aren't caught by isFlow, and babel passes plain JS through.
66
75
  const src = fs.readFileSync(filename, "utf8");
67
- return mod._compile(transformRN(filename, src, projectRoot), filename);
76
+ return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
68
77
  }
69
78
  return origJs(mod, filename);
70
79
  };
@@ -79,7 +88,7 @@ export function installRequireHooks(projectRoot, transformPkgs = []) {
79
88
  if (Module._extensions[ext]) continue;
80
89
  Module._extensions[ext] = function (mod, filename) {
81
90
  const src = fs.readFileSync(filename, "utf8");
82
- return mod._compile(transformRN(filename, src, projectRoot), filename);
91
+ return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
83
92
  };
84
93
  }
85
94
  }
@@ -34,12 +34,16 @@ function resolveExtensionless(base) {
34
34
  // Synthetic URL scheme for preset mocks served to the ESM graph (see below).
35
35
  const PRESET_SCHEME = "vitest-native-preset:";
36
36
  let PROJECT_ROOT = process.cwd();
37
+ let PLATFORM = "ios";
38
+ let REACT_NATIVE_VERSION = "0.0.0";
37
39
  let isExtra = () => false;
38
40
  // Preset package name → its mock's named-export list (from the preset definition).
39
41
  let presetExports = {};
40
42
 
41
43
  export async function initialize(data) {
42
44
  if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
45
+ if (data && data.platform === "android") PLATFORM = "android";
46
+ if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
43
47
  if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
44
48
  if (data && data.presetExports) presetExports = data.presetExports;
45
49
  }
@@ -57,8 +61,13 @@ export async function resolve(specifier, context, nextResolve) {
57
61
  context.parentURL && context.parentURL.startsWith("file:")
58
62
  ? fileURLToPath(context.parentURL)
59
63
  : null;
60
- if (parent && RN_PATH.test(parent) && specifier.startsWith(".") && !path.extname(specifier)) {
61
- const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier));
64
+ if (
65
+ parent &&
66
+ (RN_PATH.test(parent) || isExtra(parent)) &&
67
+ specifier.startsWith(".") &&
68
+ !path.extname(specifier)
69
+ ) {
70
+ const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier), PLATFORM);
62
71
  if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
63
72
  }
64
73
 
@@ -100,14 +109,14 @@ export async function load(url, context, nextLoad) {
100
109
  if (!isRN && !isExtra(norm)) return nextLoad(url, context);
101
110
 
102
111
  if (isRN) {
103
- const boundary = boundarySourceFor(norm);
112
+ const boundary = boundarySourceFor(norm, PLATFORM, REACT_NATIVE_VERSION);
104
113
  if (boundary != null) return { format: "commonjs", source: boundary, shortCircuit: true };
105
114
  if (norm.endsWith(".js")) {
106
115
  const src = fs.readFileSync(file, "utf8");
107
116
  if (isFlow(src))
108
117
  return {
109
118
  format: "commonjs",
110
- source: transformRN(file, src, PROJECT_ROOT),
119
+ source: transformRN(file, src, PROJECT_ROOT, PLATFORM),
111
120
  shortCircuit: true,
112
121
  };
113
122
  }
@@ -117,7 +126,11 @@ export async function load(url, context, nextLoad) {
117
126
  // Configured third-party package: transform any JS/TS/JSX source to CJS.
118
127
  if (TRANSFORMABLE.test(norm)) {
119
128
  const src = fs.readFileSync(file, "utf8");
120
- return { format: "commonjs", source: transformRN(file, src, PROJECT_ROOT), shortCircuit: true };
129
+ return {
130
+ format: "commonjs",
131
+ source: transformRN(file, src, PROJECT_ROOT, PLATFORM),
132
+ shortCircuit: true,
133
+ };
121
134
  }
122
135
  return nextLoad(url, context);
123
136
  }