vitest-native 0.9.0 → 0.11.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 (64) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/README.md +33 -1
  3. package/dist/cli.cjs +185 -31
  4. package/dist/cli.mjs +182 -28
  5. package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
  6. package/dist/ecosystem-C4qT_vl3.mjs +506 -0
  7. package/dist/errors-B3lJK46O.cjs +75 -0
  8. package/dist/errors-CxoBUfVJ.mjs +64 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
  16. package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
  17. package/dist/index.d.mts +8 -7
  18. package/dist/index.mjs +307 -91
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/jest-compat.cjs +4 -4
  22. package/dist/jest-compat.d.cts +0 -1
  23. package/dist/jest-compat.d.mts +0 -1
  24. package/dist/jest-compat.mjs +2 -2
  25. package/dist/matchers.cjs +16 -7
  26. package/dist/matchers.mjs +16 -7
  27. package/dist/native/hooks.mjs +152 -13
  28. package/dist/native/loader.mjs +36 -11
  29. package/dist/native/match.d.mts +33 -0
  30. package/dist/native/match.mjs +94 -22
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +110 -13
  33. package/dist/native/resolve.d.mts +22 -0
  34. package/dist/native/resolve.mjs +21 -13
  35. package/dist/native/runner.mjs +21 -0
  36. package/dist/native/setup.mjs +4 -2
  37. package/dist/native/transform.mjs +108 -3
  38. package/dist/native/worker.mjs +59 -16
  39. package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
  40. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
  41. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
  42. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
  43. package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
  44. package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
  45. package/dist/presets.d.mts +2 -2
  46. package/dist/presets.mjs +2 -2
  47. package/dist/rntl-matchers.d.ts +35 -0
  48. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  49. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  50. package/dist/serializer.cjs +34 -4
  51. package/dist/serializer.mjs +34 -4
  52. package/dist/setup.d.mts +1 -1
  53. package/dist/setup.mjs +237 -74
  54. package/docs/release-readiness.md +22 -5
  55. package/docs/versioning.md +133 -0
  56. package/package.json +38 -46
  57. package/dist/ecosystem-BIWaVwYL.cjs +0 -294
  58. package/dist/ecosystem-EFtHnKS9.mjs +0 -256
  59. package/dist/index.cjs +0 -788
  60. package/dist/index.d.cts +0 -14
  61. package/dist/presets.cjs +0 -18
  62. package/dist/presets.d.cts +0 -2
  63. package/dist/setup.cjs +0 -2702
  64. package/dist/setup.d.cts +0 -1
package/dist/index.cjs DELETED
@@ -1,788 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
- const require_ecosystem = require("./ecosystem-BIWaVwYL.cjs");
4
- const require_preset_map = require("./preset-map-CG4FMtsl.cjs");
5
- const require_presets = require("./presets-C4faM3ds.cjs");
6
- let node_url = require("node:url");
7
- let node_path = require("node:path");
8
- node_path = require_chunk.__toESM(node_path, 1);
9
- let node_fs = require("node:fs");
10
- node_fs = require_chunk.__toESM(node_fs, 1);
11
- let node_module = require("node:module");
12
- let flow_remove_types = require("flow-remove-types");
13
- flow_remove_types = require_chunk.__toESM(flow_remove_types, 1);
14
- //#region src/resolve.ts
15
- const PLATFORM_EXTENSIONS_IOS = [
16
- ".ios.tsx",
17
- ".ios.ts",
18
- ".ios.jsx",
19
- ".ios.js",
20
- ".native.tsx",
21
- ".native.ts",
22
- ".native.jsx",
23
- ".native.js",
24
- ".tsx",
25
- ".ts",
26
- ".jsx",
27
- ".js"
28
- ];
29
- const PLATFORM_EXTENSIONS_ANDROID = [
30
- ".android.tsx",
31
- ".android.ts",
32
- ".android.jsx",
33
- ".android.js",
34
- ".native.tsx",
35
- ".native.ts",
36
- ".native.jsx",
37
- ".native.js",
38
- ".tsx",
39
- ".ts",
40
- ".jsx",
41
- ".js"
42
- ];
43
- function getPlatformExtensions(platform) {
44
- return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
45
- }
46
- //#endregion
47
- //#region src/native/apply.ts
48
- /**
49
- * Vite/Vitest config fragment for the native engine. RN is externalized so it
50
- * loads through Node's single CJS graph, where the native setup file's hooks
51
- * Flow-strip it and mock the native boundary.
52
- */
53
- /** Escape a package name for use inside a RegExp character-delimited path match. */
54
- function escapeRe(s) {
55
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
56
- }
57
- /**
58
- * The on-disk directory a package resolves to, or null. Used alongside the
59
- * node_modules-anchored patterns so workspace and `file:` dependencies — which
60
- * resolve to a real path with no node_modules segment — are matched too.
61
- */
62
- function resolvePackageDir(name, projectRoot) {
63
- try {
64
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
65
- return node_path.default.dirname(req.resolve(`${name}/package.json`));
66
- } catch {
67
- return null;
68
- }
69
- }
70
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd()) {
71
- const extraExternal = transformPkgs.flatMap((p) => {
72
- const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
73
- const dir = resolvePackageDir(p, projectRoot);
74
- if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
75
- return patterns;
76
- });
77
- const ecosystemInline = inlinePkgs.flatMap((p) => {
78
- const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
79
- const dir = resolvePackageDir(p, projectRoot);
80
- if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
81
- return patterns;
82
- });
83
- const fullEnv = { ...env };
84
- if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
85
- return {
86
- ...jsxTransform,
87
- ssr: { resolve: {
88
- conditions: ["react-native"],
89
- mainFields: [
90
- "react-native",
91
- "module",
92
- "jsnext:main",
93
- "jsnext"
94
- ]
95
- } },
96
- resolve: {
97
- conditions: ["react-native"],
98
- mainFields: [
99
- "react-native",
100
- "module",
101
- "jsnext:main",
102
- "jsnext"
103
- ],
104
- extensions,
105
- dedupe: [
106
- "react",
107
- "react-test-renderer",
108
- "test-renderer",
109
- "react-is"
110
- ]
111
- },
112
- test: {
113
- setupFiles: [setupFilePath],
114
- env: fullEnv,
115
- ...hot ? {
116
- pool: hot.pool,
117
- isolate: false,
118
- runner: hot.runnerPath
119
- } : { pool: userPool ?? "threads" },
120
- server: { deps: {
121
- external: [
122
- /[\\/]node_modules[\\/]react-native[\\/]/,
123
- /[\\/]node_modules[\\/]@react-native[\\/]/,
124
- ...extraExternal
125
- ],
126
- ...ecosystemInline.length > 0 ? { inline: ecosystemInline } : {}
127
- } }
128
- }
129
- };
130
- }
131
- //#endregion
132
- //#region src/plugin.ts
133
- const DEFAULT_ASSET_EXTS = [
134
- "png",
135
- "jpg",
136
- "jpeg",
137
- "gif",
138
- "bmp",
139
- "webp",
140
- "svg",
141
- "tiff",
142
- "heic",
143
- "heif",
144
- "mp4",
145
- "mp3",
146
- "wav",
147
- "aac",
148
- "m4a",
149
- "mov",
150
- "webm",
151
- "ttf",
152
- "otf",
153
- "woff",
154
- "woff2"
155
- ];
156
- /** Strip Vite's /@fs/ prefix to get a real filesystem path. */
157
- function stripFsPrefix(id) {
158
- return id.startsWith("/@fs/") ? id.slice(4) : id;
159
- }
160
- async function autoDetectPresets(diagnostics, projectRoot) {
161
- const detected = [];
162
- const enabled = /* @__PURE__ */ new Set();
163
- const presetFactories = await Promise.resolve().then(() => require("./presets.cjs"));
164
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
165
- for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
166
- let installed = false;
167
- try {
168
- req.resolve(pkgName);
169
- installed = true;
170
- } catch {}
171
- if (installed) {
172
- if (enabled.has(exportName)) continue;
173
- const factory = presetFactories[exportName];
174
- if (typeof factory === "function") {
175
- detected.push(factory());
176
- enabled.add(exportName);
177
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
178
- }
179
- } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
180
- }
181
- return detected;
182
- }
183
- function resolvePackageVersion(packageName, projectRoot) {
184
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
185
- try {
186
- return req(`${packageName}/package.json`).version ?? null;
187
- } catch {
188
- return null;
189
- }
190
- }
191
- /**
192
- * One line, once per process, stating which engine this run actually uses.
193
- * Tests pass either way; a team that believes it's exercising real React Native
194
- * while running the mock (or vice versa) must be able to see it in every log.
195
- * Guarded via globalThis (like the require-hook install) so workspace setups
196
- * that call config() per project print it once.
197
- *
198
- * Written to stderr: this is the plugin's only unconditional output, and stdout
199
- * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
200
- */
201
- function printEngineBanner(engine, platform, projectRoot) {
202
- const g = globalThis;
203
- if (g.__vitest_native_banner_printed) return;
204
- g.__vitest_native_banner_printed = true;
205
- if (engine === "native") {
206
- const rn = resolvePackageVersion("react-native", projectRoot);
207
- console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform})`);
208
- } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
209
- }
210
- function getJsxTransformConfig(projectRoot) {
211
- const viteVersion = resolvePackageVersion("vite", projectRoot);
212
- return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
213
- }
214
- /**
215
- * The names React Native's index exports.
216
- *
217
- * They cannot be read with a normal import: the index is Flow source, and its
218
- * exports are lazy getters that neither a bundler nor cjs-module-lexer can see.
219
- * They also cannot be read by requiring the module here — that would execute React
220
- * Native inside the Vite process, before any of the engine's globals exist.
221
- *
222
- * So they are parsed out of the `module.exports = { … }` object literal, whose
223
- * members sit at one indentation level. React Native uses three member shapes
224
- * there: lazy getters (`get View() {`), method shorthand
225
- * (`unstable_batchedUpdates<T>(fn) {`), and plain properties (`Systrace: …`).
226
- * A name missed here surfaces immediately as "does not provide an export named X"
227
- * rather than silently, and the facade's export surface is asserted against the
228
- * real module in the native suite, across every React Native version in CI.
229
- */
230
- function parseReactNativeExports(indexSource) {
231
- const start = indexSource.indexOf("module.exports = {");
232
- if (start === -1) return [];
233
- const body = indexSource.slice(start);
234
- const names = /* @__PURE__ */ new Set();
235
- for (const match of body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)) {
236
- const name = match[1];
237
- if (name !== "default" && name !== "__esModule" && name !== "get") names.add(name);
238
- }
239
- return [...names];
240
- }
241
- /**
242
- * Build (or reuse) the precompiled React Native registry for a project.
243
- *
244
- * The builder ships as runtime `.mjs` next to this file (it is also imported by the
245
- * native setup file, which Node loads directly), so it is reached through a computed
246
- * dynamic import rather than a static one — a static specifier would bundle a second
247
- * copy into the plugin entry. Returns the registry path, or null when one could not
248
- * be produced, in which case the engine keeps loading RN file by file.
249
- */
250
- async function buildRegistryFor(options) {
251
- try {
252
- const dir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
253
- return (await import((0, node_url.pathToFileURL)(node_path.default.resolve(dir, "native/registry.mjs")).href)).buildRegistry(options);
254
- } catch (error) {
255
- if (options.diagnostics) console.warn(`[vitest-native] could not precompile the React Native registry (${error?.message}); using per-file module loading.`);
256
- return null;
257
- }
258
- }
259
- /**
260
- * Compile one inlined ecosystem file with the project's React Native Babel preset.
261
- *
262
- * The transformer ships as runtime `.mjs` (Node's loader hooks use it too), so it is
263
- * loaded through a computed path rather than a static import, and synchronously —
264
- * Vite's transform hook may be sync and the module is already resident by the time
265
- * any file reaches this point.
266
- */
267
- let ecosystemTransformer = null;
268
- function transformEcosystem(file, code, projectRoot, platform) {
269
- if (!ecosystemTransformer) {
270
- const dir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
271
- ecosystemTransformer = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)(node_path.default.resolve(dir, "native/transform.mjs")).transformRN;
272
- }
273
- return ecosystemTransformer(file, code, projectRoot, platform);
274
- }
275
- /**
276
- * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
277
- * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
278
- * version check above guarantees that only the matching shape is returned,
279
- * but a build against any single Vite major cannot type the other major's
280
- * valid config. Keep that unavoidable assertion at this compatibility edge.
281
- */
282
- function asCompatibleViteConfig(config) {
283
- return config;
284
- }
285
- /**
286
- * Synchronously resolve the export-names of presets whose package is installed.
287
- * Used by the native-engine config path (which can't await the factory imports)
288
- * to tell the native setup file which preset mocks to build. Returns deduped
289
- * preset names (e.g. ["reanimated", "navigation"]).
290
- */
291
- function autoDetectPresetNames(projectRoot, diagnostics) {
292
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
293
- const names = /* @__PURE__ */ new Set();
294
- for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
295
- req.resolve(pkgName);
296
- names.add(exportName);
297
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
298
- } catch {
299
- if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
300
- }
301
- return [...names];
302
- }
303
- async function resolveOptions(options = {}, projectRoot) {
304
- const platform = options.platform ?? "ios";
305
- const diagnostics = options.diagnostics ?? false;
306
- const engine = options.engine === "native" ? "native" : "mock";
307
- const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
308
- let presets;
309
- if (options.presets) presets = options.presets;
310
- else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
311
- return {
312
- platform,
313
- engine,
314
- diagnostics,
315
- extensions: getPlatformExtensions(platform),
316
- presets,
317
- mocks: options.mocks ?? {},
318
- assetExts: [...DEFAULT_ASSET_EXTS, ...userExts]
319
- };
320
- }
321
- /**
322
- * All named exports from the react-native mock that virtual subpath
323
- * modules should re-export. Kept in sync with registry.ts.
324
- */
325
- const RN_EXPORT_NAMES = [
326
- "View",
327
- "Text",
328
- "Image",
329
- "TextInput",
330
- "ScrollView",
331
- "FlatList",
332
- "SectionList",
333
- "Modal",
334
- "Pressable",
335
- "TouchableOpacity",
336
- "TouchableHighlight",
337
- "TouchableWithoutFeedback",
338
- "TouchableNativeFeedback",
339
- "ActivityIndicator",
340
- "Button",
341
- "Switch",
342
- "RefreshControl",
343
- "StatusBar",
344
- "SafeAreaView",
345
- "KeyboardAvoidingView",
346
- "ImageBackground",
347
- "VirtualizedList",
348
- "InputAccessoryView",
349
- "DrawerLayoutAndroid",
350
- "Platform",
351
- "Dimensions",
352
- "StyleSheet",
353
- "Animated",
354
- "Alert",
355
- "Linking",
356
- "AppState",
357
- "Keyboard",
358
- "BackHandler",
359
- "Vibration",
360
- "PermissionsAndroid",
361
- "Appearance",
362
- "PixelRatio",
363
- "LayoutAnimation",
364
- "Clipboard",
365
- "Share",
366
- "AccessibilityInfo",
367
- "InteractionManager",
368
- "PanResponder",
369
- "ToastAndroid",
370
- "ActionSheetIOS",
371
- "LogBox",
372
- "Easing",
373
- "I18nManager",
374
- "DeviceEventEmitter",
375
- "useColorScheme",
376
- "useWindowDimensions",
377
- "NativeModules",
378
- "TurboModuleRegistry",
379
- "UIManager",
380
- "NativeEventEmitter",
381
- "NativeAppEventEmitter",
382
- "EventEmitter",
383
- "NativeComponentRegistry",
384
- "requireNativeComponent",
385
- "AppRegistry",
386
- "VirtualizedSectionList",
387
- "Touchable",
388
- "processColor",
389
- "findNodeHandle",
390
- "PlatformColor",
391
- "DynamicColorIOS",
392
- "Settings",
393
- "DeviceInfo",
394
- "useAnimatedValue",
395
- "useAnimatedValueXY",
396
- "useAnimatedColor",
397
- "RootTagContext",
398
- "ReactNativeVersion",
399
- "Systrace",
400
- "DevSettings",
401
- "Networking",
402
- "unstable_batchedUpdates",
403
- "registerCallableModule",
404
- "codegenNativeCommands",
405
- "codegenNativeComponent",
406
- "UTFSequence",
407
- "ProgressBarAndroid",
408
- "PushNotificationIOS",
409
- "NativeDialogManagerAndroid",
410
- "usePressability"
411
- ];
412
- /**
413
- * A file inside a React Native ecosystem package under node_modules — one whose
414
- * package NAME begins with `react-native` (with or without a scope, so
415
- * `@shopify/react-native-skia` counts), or whose scope begins with `@react-native`.
416
- *
417
- * The name must BEGIN with it, which is what separates this from the substring test
418
- * it replaced: `eslint-plugin-react-native` and a project directory called
419
- * `react-native-app` both contain the words without being React Native packages.
420
- */
421
- const RN_ECOSYSTEM_PATH = /[\\/]node_modules[\\/](?:@react-native[^\\/]*[\\/][^\\/]+|(?:@[^\\/]+[\\/])?react-native[^\\/]*)[\\/]/;
422
- /** Fast membership check for leaf-name lookups on subpath imports. */
423
- const RN_EXPORT_NAME_SET = new Set(RN_EXPORT_NAMES);
424
- /**
425
- * The bare package name of an import specifier ("@scope/pkg/sub" → "@scope/pkg",
426
- * "pkg/sub" → "pkg"). Mirrors native/match.mjs for the Vite-graph side.
427
- */
428
- function packageNameOf(specifier) {
429
- if (specifier.startsWith("@")) {
430
- const [scope, name] = specifier.split("/");
431
- return name ? `${scope}/${name}` : specifier;
432
- }
433
- return specifier.split("/")[0];
434
- }
435
- /**
436
- * The leaf module name a subpath import points at ("pkg/lib/Swipeable" or
437
- * "react-native/Libraries/Utilities/Platform.ios.js" → "Platform"), used to pick
438
- * the matching export off the mock. Mirrors native/match.mjs.
439
- */
440
- function subpathLeafOf(specifier) {
441
- const base = specifier.split("/").pop();
442
- if (!base) return null;
443
- return base.split(".")[0] || null;
444
- }
445
- /**
446
- * Deep entries of preset packages that are deliberately Node-safe and must NOT
447
- * be shadowed (test utilities and tooling entry points). Mirrors
448
- * native/match.mjs.
449
- */
450
- const UTILITY_SUBPATH_LEAVES = new Set([
451
- "jest-utils",
452
- "jestSetup",
453
- "mock",
454
- "plugin"
455
- ]);
456
- function isUtilitySubpath(specifier) {
457
- const leaf = subpathLeafOf(specifier);
458
- return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf);
459
- }
460
- /** Check if a value (or any nested value) contains functions. */
461
- function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
462
- if (typeof value === "function") return true;
463
- if (value === null || typeof value !== "object") return false;
464
- if (visited.has(value)) return false;
465
- visited.add(value);
466
- for (const v of Object.values(value)) if (containsFunctions(v, visited)) return true;
467
- return false;
468
- }
469
- /**
470
- * Vitest plugin for React Native.
471
- *
472
- * Handles platform-specific module resolution, asset stubs, preset virtual
473
- * modules, and automatic setup-file injection so tests can run against
474
- * React Native code in a Node/JSDOM environment.
475
- */
476
- function reactNative(options) {
477
- if (options) {
478
- require_ecosystem.validateOptions(options);
479
- require_ecosystem.warnUnknownOptions(options);
480
- }
481
- 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 });");
482
- let resolved;
483
- const presetModules = /* @__PURE__ */ new Map();
484
- const presetExportNames = /* @__PURE__ */ new Map();
485
- let assetPattern;
486
- let realRnPackageJson;
487
- let rnFacadeExports = null;
488
- let rnFacadeRoot = "";
489
- let ecosystemPattern = null;
490
- let ecosystemRoot = "";
491
- const resolveCache = /* @__PURE__ */ new Map();
492
- const virtualCodeCache = /* @__PURE__ */ new Map();
493
- const thisDir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
494
- let setupFilePath = node_path.default.resolve(thisDir, "setup.mjs");
495
- if (!node_fs.default.existsSync(setupFilePath)) {
496
- const srcPath = node_path.default.resolve(thisDir, "setup.ts");
497
- if (node_fs.default.existsSync(srcPath)) setupFilePath = srcPath;
498
- }
499
- const nativeSetupPath = node_path.default.resolve(thisDir, "native/setup.mjs");
500
- const nativeWorkerPath = node_path.default.resolve(thisDir, "native/worker.mjs");
501
- const nativeRunnerPath = node_path.default.resolve(thisDir, "native/runner.mjs");
502
- const platform = options?.platform ?? "ios";
503
- const diagnostics = options?.diagnostics ?? false;
504
- const requestedEngine = options?.engine ?? "auto";
505
- const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
506
- const hotRuntimeOpt = options?.hotRuntime ?? false;
507
- const hotRuntime = hotRuntimeOpt !== false;
508
- const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
509
- let engine = requestedEngine === "native" ? "native" : "mock";
510
- const extensions = getPlatformExtensions(platform);
511
- const resolvePresetId = (source) => {
512
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
513
- if (!assetPattern) return void 0;
514
- if (source.endsWith(".json") || assetPattern.test(source) || isUtilitySubpath(source)) return;
515
- const pkg = packageNameOf(source);
516
- if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
517
- };
518
- return {
519
- name: "vitest-native",
520
- enforce: "pre",
521
- async config(userConfig, _env) {
522
- const resolvedRoot = userConfig.root ? node_path.default.resolve(userConfig.root) : process.cwd();
523
- const jsxTransform = getJsxTransformConfig(resolvedRoot);
524
- const decision = require_ecosystem.detectEngine(requestedEngine, resolvedRoot);
525
- engine = decision.engine;
526
- if (engine === "native" && !decision.nativeAvailable) throw new Error(`[vitest-native] engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
527
- if (decision.notice) console.warn(decision.notice);
528
- printEngineBanner(engine, platform, resolvedRoot);
529
- const env = {
530
- VITEST_NATIVE_PLATFORM: platform,
531
- VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
532
- VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
533
- };
534
- const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
535
- if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
536
- const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
537
- env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
538
- if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
539
- if (engine === "native") {
540
- 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'.");
541
- const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
542
- if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
543
- if (options?.presets) {
544
- const presetConfig = {};
545
- for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
546
- if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
547
- }
548
- const ecosystem = require_ecosystem.detectEcosystemPackages(resolvedRoot, transformPkgs);
549
- if (ecosystem.length > 0) {
550
- ecosystemRoot = resolvedRoot;
551
- ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
552
- if (diagnostics) console.log(`[vitest-native] inlining React Native packages: ${ecosystem.join(", ")}`);
553
- }
554
- const registryFile = await buildRegistryFor({
555
- projectRoot: resolvedRoot,
556
- platform,
557
- reactNativeVersion: reactNativeVersion ?? "0.0.0",
558
- assetExts: assetExtList,
559
- diagnostics
560
- });
561
- if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
562
- let hot;
563
- if (hotRuntime) {
564
- const { nativePool, defaultHotMemoryLimit } = await Promise.resolve().then(() => require("./pool-DzsEo9vv.cjs"));
565
- const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
566
- hot = {
567
- pool: nativePool({
568
- workerEntry: nativeWorkerPath,
569
- projectRoot: resolvedRoot,
570
- recycleAfterFiles: hotRecycle.recycleAfterFiles,
571
- memoryLimit,
572
- diagnostics
573
- }),
574
- runnerPath: nativeRunnerPath
575
- };
576
- }
577
- const userPool = userConfig.test?.pool;
578
- if (userPool === "vmThreads" || userPool === "vmForks") throw new Error(`[vitest-native] engine:'native' cannot run on the '${userPool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
579
- if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
580
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot));
581
- }
582
- if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
583
- if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
584
- if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
585
- return asCompatibleViteConfig({
586
- ...jsxTransform,
587
- ssr: { resolve: {
588
- conditions: ["react-native"],
589
- mainFields: [
590
- "react-native",
591
- "module",
592
- "jsnext:main",
593
- "jsnext"
594
- ]
595
- } },
596
- resolve: {
597
- extensions,
598
- conditions: ["react-native"],
599
- mainFields: [
600
- "react-native",
601
- "module",
602
- "jsnext:main",
603
- "jsnext"
604
- ],
605
- dedupe: [
606
- "react",
607
- "react-test-renderer",
608
- "test-renderer",
609
- "react-is"
610
- ]
611
- },
612
- test: {
613
- setupFiles: [setupFilePath],
614
- env
615
- }
616
- });
617
- },
618
- async configResolved(config) {
619
- const peerErrors = [];
620
- for (const { name, minimum, maximumMajor, minimumByMajor } of require_ecosystem.PEER_REQUIREMENTS) {
621
- const error = require_ecosystem.validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
622
- if (error) peerErrors.push(error);
623
- }
624
- if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
625
- const rntlError = require_ecosystem.validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
626
- if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
627
- resolved = await resolveOptions(options, config.root);
628
- try {
629
- realRnPackageJson = (0, node_module.createRequire)(node_path.default.join(config.root, "package.json")).resolve("react-native/package.json");
630
- } catch {}
631
- resolved.engine = engine;
632
- for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
633
- presetModules.set(moduleName, presetModule.factory);
634
- presetExportNames.set(moduleName, presetModule.exports);
635
- }
636
- if (engine === "native") {
637
- rnFacadeRoot = config.root;
638
- try {
639
- const indexPath = (0, node_module.createRequire)(node_path.default.join(config.root, "package.json")).resolve("react-native");
640
- const names = parseReactNativeExports(node_fs.default.readFileSync(indexPath, "utf8"));
641
- rnFacadeExports = names.length > 0 ? names : null;
642
- } catch {
643
- rnFacadeExports = null;
644
- }
645
- }
646
- const escaped = resolved.assetExts.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
647
- assetPattern = new RegExp(`\\.(${escaped.join("|")})$`, "i");
648
- },
649
- resolveId(source, importer) {
650
- if (engine === "native") {
651
- if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
652
- return resolvePresetId(source);
653
- }
654
- if (source === "react-native") return "\0virtual:react-native";
655
- if (source.startsWith("react-native/")) {
656
- if (source === "react-native/package.json" && realRnPackageJson) return realRnPackageJson;
657
- return `\0virtual:rn-subpath:${source}`;
658
- }
659
- const presetId = resolvePresetId(source);
660
- if (presetId) return presetId;
661
- if (importer && importer.includes("node_modules") && source.startsWith(".") && !node_path.default.extname(source)) {
662
- const cacheKey = `${importer}\0${source}`;
663
- const cached = resolveCache.get(cacheKey);
664
- if (cached !== void 0) return cached;
665
- const importerDir = node_path.default.dirname(importer);
666
- const absolute = node_path.default.resolve(importerDir, source);
667
- for (const ext of extensions) {
668
- const candidate = absolute + ext;
669
- if (node_fs.default.existsSync(candidate)) {
670
- resolveCache.set(cacheKey, candidate);
671
- return candidate;
672
- }
673
- }
674
- for (const ext of extensions) {
675
- const candidate = node_path.default.join(absolute, `index${ext}`);
676
- if (node_fs.default.existsSync(candidate)) {
677
- resolveCache.set(cacheKey, candidate);
678
- return candidate;
679
- }
680
- }
681
- resolveCache.set(cacheKey, void 0);
682
- }
683
- },
684
- load(id) {
685
- if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
686
- const cached = virtualCodeCache.get(id);
687
- if (cached) return cached;
688
- const code = [
689
- `import { createRequire } from "node:module";`,
690
- `const _rn = createRequire(${JSON.stringify(node_path.default.join(rnFacadeRoot, "package.json"))})("react-native");`,
691
- ...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
692
- `export default _rn;`
693
- ].join("\n");
694
- virtualCodeCache.set(id, code);
695
- return code;
696
- }
697
- if (id.startsWith("\0virtual:preset:")) {
698
- const cached = virtualCodeCache.get(id);
699
- if (cached) return cached;
700
- const specifier = id.slice(16);
701
- const pkg = packageNameOf(specifier);
702
- const exportNames = presetExportNames.get(pkg) || [];
703
- const leaf = specifier === pkg ? null : subpathLeafOf(specifier);
704
- const fallback = `('default' in _m ? _m['default'] : _m)`;
705
- const code = [
706
- `const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
707
- ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
708
- ...leaf ? [
709
- `const _hit = ${JSON.stringify(leaf)} in _m;`,
710
- `if (!_hit && process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(${JSON.stringify(`[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`)});`,
711
- `export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`
712
- ] : [`export default ${fallback};`]
713
- ].join("\n");
714
- virtualCodeCache.set(id, code);
715
- return code;
716
- }
717
- const fsPath = stripFsPrefix(id);
718
- if (assetPattern.test(fsPath)) {
719
- const basename = fsPath.split("/").pop() ?? fsPath;
720
- return `export default ${JSON.stringify(basename)};`;
721
- }
722
- if (engine === "native") return void 0;
723
- if (id === "\0virtual:react-native") {
724
- const cacheKey = "\0rn-root";
725
- let code = virtualCodeCache.get(cacheKey);
726
- if (!code) {
727
- code = [
728
- `const _rn = globalThis.__vitest_native_mock || {};`,
729
- ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
730
- `export default _rn;`
731
- ].join("\n");
732
- virtualCodeCache.set(cacheKey, code);
733
- }
734
- return code;
735
- }
736
- if (id.startsWith("\0virtual:rn-subpath:")) {
737
- const leaf = subpathLeafOf(id.slice(20));
738
- const known = leaf && RN_EXPORT_NAME_SET.has(leaf) ? leaf : null;
739
- const cacheKey = `\0rn-subpath:${known ?? ""}`;
740
- let code = virtualCodeCache.get(cacheKey);
741
- if (!code) {
742
- code = [
743
- `const _rn = globalThis.__vitest_native_mock || {};`,
744
- ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
745
- known ? `export default _rn[${JSON.stringify(known)}];` : `export default _rn;`
746
- ].join("\n");
747
- virtualCodeCache.set(cacheKey, code);
748
- }
749
- return code;
750
- }
751
- },
752
- transform(code, id) {
753
- if (engine === "native") {
754
- if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
755
- if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
756
- try {
757
- return {
758
- code: transformEcosystem(id, code, ecosystemRoot, platform),
759
- map: null
760
- };
761
- } catch (error) {
762
- if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
763
- return;
764
- }
765
- }
766
- if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
767
- if (!code.includes("@flow")) return void 0;
768
- try {
769
- const stripped = (0, flow_remove_types.default)(code, { all: true });
770
- return {
771
- code: stripped.toString(),
772
- map: stripped.generateMap()
773
- };
774
- } catch (e) {
775
- console.warn(`[vitest-native] Flow strip skipped for ${id} (parse failed: ${e?.message}); serving the file untouched.`);
776
- return;
777
- }
778
- }
779
- };
780
- }
781
- //#endregion
782
- Object.defineProperty(exports, "presets", {
783
- enumerable: true,
784
- get: function() {
785
- return require_presets.presets_exports;
786
- }
787
- });
788
- exports.reactNative = reactNative;