vitest-native 0.8.0 → 0.10.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 (65) hide show
  1. package/CHANGELOG.md +1063 -0
  2. package/README.md +47 -2
  3. package/dist/cli.cjs +642 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +638 -0
  7. package/dist/ecosystem-CO5vqExO.mjs +318 -0
  8. package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
  9. package/dist/errors-Dm5yLNTF.mjs +64 -0
  10. package/dist/errors-flXDIeWk.cjs +75 -0
  11. package/dist/errors.d.mts +46 -0
  12. package/dist/errors.mjs +78 -0
  13. package/dist/helpers.cjs +6 -23
  14. package/dist/helpers.d.cts +0 -6
  15. package/dist/helpers.d.mts +0 -6
  16. package/dist/helpers.mjs +6 -23
  17. package/dist/{index-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
  18. package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
  19. package/dist/index.d.mts +8 -6
  20. package/dist/index.mjs +563 -232
  21. package/dist/jest-compat/interop.mjs +15 -0
  22. package/dist/jest-compat/setup.mjs +164 -5
  23. package/dist/matchers.cjs +16 -7
  24. package/dist/matchers.mjs +16 -7
  25. package/dist/native/boundary.mjs +108 -30
  26. package/dist/native/compile-cache.mjs +10 -5
  27. package/dist/native/explain.mjs +69 -0
  28. package/dist/native/hooks.mjs +151 -4
  29. package/dist/native/loader.mjs +61 -12
  30. package/dist/native/match.mjs +107 -8
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +540 -0
  33. package/dist/native/reset.mjs +18 -12
  34. package/dist/native/resolve.d.mts +22 -0
  35. package/dist/native/resolve.mjs +21 -13
  36. package/dist/native/runner.mjs +34 -7
  37. package/dist/native/setup.mjs +19 -3
  38. package/dist/native/transform.mjs +195 -21
  39. package/dist/native/worker.mjs +69 -17
  40. package/dist/pool-Bcxp4Qrg.mjs +118 -0
  41. package/dist/pool-CFND7plG.cjs +122 -0
  42. package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
  43. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
  44. package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
  45. package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
  46. package/dist/presets.d.mts +2 -2
  47. package/dist/presets.mjs +2 -2
  48. package/dist/rntl-matchers.d.ts +35 -0
  49. package/dist/serializer.cjs +33 -3
  50. package/dist/serializer.mjs +33 -3
  51. package/dist/setup.mjs +544 -193
  52. package/docs/hot-default-design.md +129 -0
  53. package/docs/migrating-from-jest.md +43 -7
  54. package/docs/migrating-from-vitest-react-native.md +1 -1
  55. package/docs/release-readiness.md +24 -6
  56. package/docs/versioning.md +133 -0
  57. package/package.json +40 -38
  58. package/dist/index.cjs +0 -643
  59. package/dist/index.d.cts +0 -14
  60. package/dist/pool-B7LBfcMQ.mjs +0 -67
  61. package/dist/pool-p54QV1dQ.cjs +0 -69
  62. package/dist/presets.cjs +0 -17
  63. package/dist/presets.d.cts +0 -2
  64. package/dist/setup.cjs +0 -2514
  65. package/dist/setup.d.cts +0 -1
package/dist/index.cjs DELETED
@@ -1,643 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
3
- const require_preset_map = require("./preset-map-BY9zk9Pj.cjs");
4
- const require_presets = require("./presets-7eMfp7o2.cjs");
5
- let node_url = require("node:url");
6
- let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
8
- let node_fs = require("node:fs");
9
- node_fs = require_chunk.__toESM(node_fs, 1);
10
- let node_module = require("node:module");
11
- let flow_remove_types = require("flow-remove-types");
12
- flow_remove_types = require_chunk.__toESM(flow_remove_types, 1);
13
- //#region src/resolve.ts
14
- const PLATFORM_EXTENSIONS_IOS = [
15
- ".ios.tsx",
16
- ".ios.ts",
17
- ".ios.jsx",
18
- ".ios.js",
19
- ".native.tsx",
20
- ".native.ts",
21
- ".native.jsx",
22
- ".native.js",
23
- ".tsx",
24
- ".ts",
25
- ".jsx",
26
- ".js"
27
- ];
28
- const PLATFORM_EXTENSIONS_ANDROID = [
29
- ".android.tsx",
30
- ".android.ts",
31
- ".android.jsx",
32
- ".android.js",
33
- ".native.tsx",
34
- ".native.ts",
35
- ".native.jsx",
36
- ".native.js",
37
- ".tsx",
38
- ".ts",
39
- ".jsx",
40
- ".js"
41
- ];
42
- function getPlatformExtensions(platform) {
43
- return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
44
- }
45
- //#endregion
46
- //#region src/validate.ts
47
- const KNOWN_OPTIONS = [
48
- "platform",
49
- "presets",
50
- "mocks",
51
- "diagnostics",
52
- "assetExts",
53
- "engine",
54
- "transform",
55
- "hotRuntime"
56
- ];
57
- const KNOWN_HOT_RUNTIME_OPTIONS = [
58
- "recycleAfterFiles",
59
- "memoryLimit",
60
- "preserveGlobals"
61
- ];
62
- function assertStringArray(value, option) {
63
- 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.`);
64
- }
65
- function assertNonNegativeInteger(value, option) {
66
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
67
- }
68
- function validateOptions(options) {
69
- 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".`);
70
- if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
71
- if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
72
- if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
73
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
74
- if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
75
- 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.`);
76
- const hotRuntime = options.hotRuntime;
77
- if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
78
- if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
79
- const hotOptions = hotRuntime;
80
- for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
81
- if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
82
- if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
83
- if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
84
- }
85
- function satisfiesMinimum(version, minimum) {
86
- const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
87
- const [aMaj, aMin = 0, aPat = 0] = parse(version);
88
- const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
89
- if (aMaj !== bMaj) return aMaj > bMaj;
90
- if (aMin !== bMin) return aMin > bMin;
91
- return aPat >= bPat;
92
- }
93
- function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
94
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
95
- try {
96
- const { version } = req(req.resolve(`${pkgName}/package.json`));
97
- const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
98
- const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
99
- if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
100
- if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
101
- return null;
102
- } catch {
103
- return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
104
- }
105
- }
106
- function warnUnknownOptions(options) {
107
- for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
108
- const suggestion = findClosest(key, KNOWN_OPTIONS);
109
- const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
110
- console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
111
- }
112
- }
113
- function findClosest(input, candidates) {
114
- let best = null;
115
- let bestDist = Infinity;
116
- for (const c of candidates) {
117
- const d = levenshtein(input.toLowerCase(), c.toLowerCase());
118
- if (d < bestDist && d <= 3) {
119
- bestDist = d;
120
- best = c;
121
- }
122
- }
123
- return best;
124
- }
125
- function levenshtein(a, b) {
126
- const m = a.length;
127
- const n = b.length;
128
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
129
- for (let i = 0; i <= m; i++) dp[i][0] = i;
130
- for (let j = 0; j <= n; j++) dp[0][j] = j;
131
- for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
132
- return dp[m][n];
133
- }
134
- //#endregion
135
- //#region src/native/apply.ts
136
- /**
137
- * Vite/Vitest config fragment for the native engine. RN is externalized so it
138
- * loads through Node's single CJS graph, where the native setup file's hooks
139
- * Flow-strip it and mock the native boundary.
140
- */
141
- /** Escape a package name for use inside a RegExp character-delimited path match. */
142
- function escapeRe(s) {
143
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
144
- }
145
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
146
- const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
147
- const fullEnv = { ...env };
148
- if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
149
- return {
150
- ...jsxTransform,
151
- resolve: {
152
- conditions: ["react-native"],
153
- extensions,
154
- dedupe: [
155
- "react",
156
- "react-test-renderer",
157
- "test-renderer",
158
- "react-is"
159
- ]
160
- },
161
- test: {
162
- setupFiles: [setupFilePath],
163
- env: fullEnv,
164
- ...hot ? {
165
- pool: hot.pool,
166
- isolate: false,
167
- runner: hot.runnerPath
168
- } : { pool: "threads" },
169
- server: { deps: { external: [
170
- /[\\/]node_modules[\\/]react-native[\\/]/,
171
- /[\\/]node_modules[\\/]@react-native[\\/]/,
172
- ...extraExternal
173
- ] } }
174
- }
175
- };
176
- }
177
- /** Can this project run the native engine? (Both transform deps resolvable.) */
178
- function isNativeCapable(projectRoot) {
179
- try {
180
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
181
- req.resolve("@react-native/babel-preset");
182
- req.resolve("@babel/core");
183
- return true;
184
- } catch {
185
- return false;
186
- }
187
- }
188
- /** Resolve the concrete engine for a run. Pure; never throws. */
189
- function detectEngine(requested, projectRoot, opts) {
190
- const nativeAvailable = isNativeCapable(projectRoot);
191
- if (requested === "native") return {
192
- engine: "native",
193
- nativeAvailable,
194
- notice: null
195
- };
196
- if (requested === "mock") return {
197
- engine: "mock",
198
- nativeAvailable,
199
- notice: null
200
- };
201
- const prefersNative = opts?.autoPrefersNative ?? true;
202
- if (prefersNative && nativeAvailable) return {
203
- engine: "native",
204
- nativeAvailable,
205
- notice: null
206
- };
207
- if (prefersNative) return {
208
- engine: "mock",
209
- nativeAvailable: false,
210
- notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
211
- };
212
- return {
213
- engine: "mock",
214
- nativeAvailable,
215
- notice: null
216
- };
217
- }
218
- //#endregion
219
- //#region src/plugin.ts
220
- const DEFAULT_ASSET_EXTS = [
221
- "png",
222
- "jpg",
223
- "jpeg",
224
- "gif",
225
- "bmp",
226
- "webp",
227
- "svg",
228
- "tiff",
229
- "heic",
230
- "heif",
231
- "mp4",
232
- "mp3",
233
- "wav",
234
- "aac",
235
- "m4a",
236
- "mov",
237
- "webm",
238
- "ttf",
239
- "otf",
240
- "woff",
241
- "woff2"
242
- ];
243
- /** Strip Vite's /@fs/ prefix to get a real filesystem path. */
244
- function stripFsPrefix(id) {
245
- return id.startsWith("/@fs/") ? id.slice(4) : id;
246
- }
247
- async function autoDetectPresets(diagnostics, projectRoot) {
248
- const detected = [];
249
- const enabled = /* @__PURE__ */ new Set();
250
- const presetFactories = await Promise.resolve().then(() => require("./presets.cjs"));
251
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
252
- for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
253
- let installed = false;
254
- try {
255
- req.resolve(pkgName);
256
- installed = true;
257
- } catch {}
258
- if (installed) {
259
- if (enabled.has(exportName)) continue;
260
- const factory = presetFactories[exportName];
261
- if (typeof factory === "function") {
262
- detected.push(factory());
263
- enabled.add(exportName);
264
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
265
- }
266
- } else if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
267
- }
268
- return detected;
269
- }
270
- function resolvePackageVersion(packageName, projectRoot) {
271
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
272
- try {
273
- return req(`${packageName}/package.json`).version ?? null;
274
- } catch {
275
- return null;
276
- }
277
- }
278
- function getJsxTransformConfig(projectRoot) {
279
- const viteVersion = resolvePackageVersion("vite", projectRoot);
280
- return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
281
- }
282
- /**
283
- * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
284
- * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
285
- * version check above guarantees that only the matching shape is returned,
286
- * but a build against any single Vite major cannot type the other major's
287
- * valid config. Keep that unavoidable assertion at this compatibility edge.
288
- */
289
- function asCompatibleViteConfig(config) {
290
- return config;
291
- }
292
- /**
293
- * Synchronously resolve the export-names of presets whose package is installed.
294
- * Used by the native-engine config path (which can't await the factory imports)
295
- * to tell the native setup file which preset mocks to build. Returns deduped
296
- * preset names (e.g. ["reanimated", "navigation"]).
297
- */
298
- function autoDetectPresetNames(projectRoot, diagnostics) {
299
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
300
- const names = /* @__PURE__ */ new Set();
301
- for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
302
- req.resolve(pkgName);
303
- names.add(exportName);
304
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
305
- } catch {
306
- if (diagnostics) console.log(`[vitest-native] Checked for ${pkgName}: not found, skipping preset`);
307
- }
308
- return [...names];
309
- }
310
- async function resolveOptions(options = {}, projectRoot) {
311
- const platform = options.platform ?? "ios";
312
- const diagnostics = options.diagnostics ?? false;
313
- const engine = options.engine === "native" ? "native" : "mock";
314
- const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
315
- let presets;
316
- if (options.presets) presets = options.presets;
317
- else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
318
- return {
319
- platform,
320
- engine,
321
- diagnostics,
322
- extensions: getPlatformExtensions(platform),
323
- presets,
324
- mocks: options.mocks ?? {},
325
- assetExts: [...DEFAULT_ASSET_EXTS, ...userExts]
326
- };
327
- }
328
- /**
329
- * All named exports from the react-native mock that virtual subpath
330
- * modules should re-export. Kept in sync with registry.ts.
331
- */
332
- const RN_EXPORT_NAMES = [
333
- "View",
334
- "Text",
335
- "Image",
336
- "TextInput",
337
- "ScrollView",
338
- "FlatList",
339
- "SectionList",
340
- "Modal",
341
- "Pressable",
342
- "TouchableOpacity",
343
- "TouchableHighlight",
344
- "TouchableWithoutFeedback",
345
- "TouchableNativeFeedback",
346
- "ActivityIndicator",
347
- "Button",
348
- "Switch",
349
- "RefreshControl",
350
- "StatusBar",
351
- "SafeAreaView",
352
- "KeyboardAvoidingView",
353
- "ImageBackground",
354
- "VirtualizedList",
355
- "InputAccessoryView",
356
- "DrawerLayoutAndroid",
357
- "Platform",
358
- "Dimensions",
359
- "StyleSheet",
360
- "Animated",
361
- "Alert",
362
- "Linking",
363
- "AppState",
364
- "Keyboard",
365
- "BackHandler",
366
- "Vibration",
367
- "PermissionsAndroid",
368
- "Appearance",
369
- "PixelRatio",
370
- "LayoutAnimation",
371
- "Clipboard",
372
- "Share",
373
- "AccessibilityInfo",
374
- "InteractionManager",
375
- "PanResponder",
376
- "ToastAndroid",
377
- "ActionSheetIOS",
378
- "LogBox",
379
- "Easing",
380
- "I18nManager",
381
- "DeviceEventEmitter",
382
- "useColorScheme",
383
- "useWindowDimensions",
384
- "NativeModules",
385
- "TurboModuleRegistry",
386
- "UIManager",
387
- "NativeEventEmitter",
388
- "NativeAppEventEmitter",
389
- "EventEmitter",
390
- "NativeComponentRegistry",
391
- "requireNativeComponent",
392
- "AppRegistry",
393
- "VirtualizedSectionList",
394
- "Touchable",
395
- "processColor",
396
- "findNodeHandle",
397
- "PlatformColor",
398
- "DynamicColorIOS",
399
- "Settings",
400
- "DeviceInfo",
401
- "useAnimatedValue",
402
- "useAnimatedValueXY",
403
- "useAnimatedColor",
404
- "RootTagContext",
405
- "ReactNativeVersion",
406
- "Systrace",
407
- "DevSettings",
408
- "Networking",
409
- "unstable_batchedUpdates",
410
- "registerCallableModule",
411
- "codegenNativeCommands",
412
- "codegenNativeComponent",
413
- "UTFSequence",
414
- "ProgressBarAndroid",
415
- "PushNotificationIOS",
416
- "NativeDialogManagerAndroid",
417
- "usePressability"
418
- ];
419
- /** Check if a value (or any nested value) contains functions. */
420
- function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
421
- if (typeof value === "function") return true;
422
- if (value === null || typeof value !== "object") return false;
423
- if (visited.has(value)) return false;
424
- visited.add(value);
425
- for (const v of Object.values(value)) if (containsFunctions(v, visited)) return true;
426
- return false;
427
- }
428
- /**
429
- * Vitest plugin for React Native.
430
- *
431
- * Handles platform-specific module resolution, asset stubs, preset virtual
432
- * modules, and automatic setup-file injection so tests can run against
433
- * React Native code in a Node/JSDOM environment.
434
- */
435
- function reactNative(options) {
436
- if (options) {
437
- validateOptions(options);
438
- warnUnknownOptions(options);
439
- }
440
- 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 });");
441
- let resolved;
442
- const presetModules = /* @__PURE__ */ new Map();
443
- const presetExportNames = /* @__PURE__ */ new Map();
444
- let assetPattern;
445
- const resolveCache = /* @__PURE__ */ new Map();
446
- const virtualCodeCache = /* @__PURE__ */ new Map();
447
- const thisDir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
448
- let setupFilePath = node_path.default.resolve(thisDir, "setup.mjs");
449
- if (!node_fs.default.existsSync(setupFilePath)) {
450
- const srcPath = node_path.default.resolve(thisDir, "setup.ts");
451
- if (node_fs.default.existsSync(srcPath)) setupFilePath = srcPath;
452
- }
453
- const nativeSetupPath = node_path.default.resolve(thisDir, "native/setup.mjs");
454
- const nativeWorkerPath = node_path.default.resolve(thisDir, "native/worker.mjs");
455
- const nativeRunnerPath = node_path.default.resolve(thisDir, "native/runner.mjs");
456
- const platform = options?.platform ?? "ios";
457
- const diagnostics = options?.diagnostics ?? false;
458
- const requestedEngine = options?.engine ?? "auto";
459
- const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
460
- const hotRuntimeOpt = options?.hotRuntime ?? false;
461
- const hotRuntime = hotRuntimeOpt !== false;
462
- const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
463
- let engine = requestedEngine === "native" ? "native" : "mock";
464
- const extensions = getPlatformExtensions(platform);
465
- return {
466
- name: "vitest-native",
467
- enforce: "pre",
468
- async config(userConfig, _env) {
469
- const resolvedRoot = userConfig.root ? node_path.default.resolve(userConfig.root) : process.cwd();
470
- const jsxTransform = getJsxTransformConfig(resolvedRoot);
471
- const decision = detectEngine(requestedEngine, resolvedRoot);
472
- engine = decision.engine;
473
- if (decision.notice) console.log(decision.notice);
474
- const env = {
475
- VITEST_NATIVE_PLATFORM: platform,
476
- VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
477
- VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
478
- };
479
- const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
480
- if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
481
- env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify([...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))]);
482
- if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
483
- if (engine === "native") {
484
- 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'.");
485
- const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
486
- if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
487
- if (options?.presets) {
488
- const presetConfig = {};
489
- for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
490
- if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
491
- }
492
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
493
- pool: (await Promise.resolve().then(() => require("./pool-p54QV1dQ.cjs"))).nativePool({
494
- workerEntry: nativeWorkerPath,
495
- recycleAfterFiles: hotRecycle.recycleAfterFiles,
496
- memoryLimit: hotRecycle.memoryLimit,
497
- diagnostics
498
- }),
499
- runnerPath: nativeRunnerPath
500
- } : void 0, jsxTransform));
501
- }
502
- if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
503
- if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
504
- if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
505
- return asCompatibleViteConfig({
506
- ...jsxTransform,
507
- resolve: {
508
- extensions,
509
- conditions: ["react-native"],
510
- dedupe: [
511
- "react",
512
- "react-test-renderer",
513
- "test-renderer",
514
- "react-is"
515
- ]
516
- },
517
- test: {
518
- setupFiles: [setupFilePath],
519
- env
520
- }
521
- });
522
- },
523
- async configResolved(config) {
524
- const peers = [
525
- {
526
- name: "vitest",
527
- minimum: "4.0.0",
528
- maximumMajor: 5
529
- },
530
- {
531
- name: "vite",
532
- minimum: "6.4.2",
533
- maximumMajor: 9,
534
- minimumByMajor: {
535
- 6: "6.4.2",
536
- 7: "7.3.2",
537
- 8: "8.0.5"
538
- }
539
- },
540
- {
541
- name: "react",
542
- minimum: "18.0.0"
543
- }
544
- ];
545
- const peerErrors = [];
546
- for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
547
- const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
548
- if (error) peerErrors.push(error);
549
- }
550
- if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
551
- const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
552
- if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
553
- resolved = await resolveOptions(options, config.root);
554
- resolved.engine = engine;
555
- for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
556
- presetModules.set(moduleName, presetModule.factory);
557
- presetExportNames.set(moduleName, presetModule.exports);
558
- }
559
- assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
560
- },
561
- resolveId(source, importer) {
562
- if (engine === "native") {
563
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
564
- return;
565
- }
566
- if (source === "react-native") return "\0virtual:react-native";
567
- if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
568
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
569
- if (importer && importer.includes("node_modules") && source.startsWith(".") && !node_path.default.extname(source)) {
570
- const cacheKey = `${importer}\0${source}`;
571
- const cached = resolveCache.get(cacheKey);
572
- if (cached !== void 0) return cached;
573
- const importerDir = node_path.default.dirname(importer);
574
- const absolute = node_path.default.resolve(importerDir, source);
575
- for (const ext of extensions) {
576
- const candidate = absolute + ext;
577
- if (node_fs.default.existsSync(candidate)) {
578
- resolveCache.set(cacheKey, candidate);
579
- return candidate;
580
- }
581
- }
582
- for (const ext of extensions) {
583
- const candidate = node_path.default.join(absolute, `index${ext}`);
584
- if (node_fs.default.existsSync(candidate)) {
585
- resolveCache.set(cacheKey, candidate);
586
- return candidate;
587
- }
588
- }
589
- resolveCache.set(cacheKey, void 0);
590
- }
591
- },
592
- load(id) {
593
- if (id.startsWith("\0virtual:preset:")) {
594
- const cached = virtualCodeCache.get(id);
595
- if (cached) return cached;
596
- const moduleName = id.slice(16);
597
- const exportNames = presetExportNames.get(moduleName) || [];
598
- const code = [
599
- `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
600
- ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
601
- `export default ('default' in _m ? _m['default'] : _m);`
602
- ].join("\n");
603
- virtualCodeCache.set(id, code);
604
- return code;
605
- }
606
- const fsPath = stripFsPrefix(id);
607
- if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
608
- if (engine === "native") return void 0;
609
- if (id === "\0virtual:react-native") return "export default {};";
610
- if (id.startsWith("\0virtual:rn-subpath:")) {
611
- let code = virtualCodeCache.get("\0rn-subpath");
612
- if (!code) {
613
- code = [
614
- `const _rn = globalThis.__vitest_native_mock || {};`,
615
- ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
616
- `export default _rn;`
617
- ].join("\n");
618
- virtualCodeCache.set("\0rn-subpath", code);
619
- }
620
- return code;
621
- }
622
- },
623
- transform(code, id) {
624
- if (engine === "native") return void 0;
625
- if (!id.includes("node_modules")) return void 0;
626
- if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
627
- if (!code.includes("@flow")) return void 0;
628
- const stripped = (0, flow_remove_types.default)(code, { all: true });
629
- return {
630
- code: stripped.toString(),
631
- map: stripped.generateMap()
632
- };
633
- }
634
- };
635
- }
636
- //#endregion
637
- Object.defineProperty(exports, "presets", {
638
- enumerable: true,
639
- get: function() {
640
- return require_presets.presets_exports;
641
- }
642
- });
643
- exports.reactNative = reactNative;
package/dist/index.d.cts DELETED
@@ -1,14 +0,0 @@
1
- import { _ as Preset, t as index_d_exports, v as ReactNativeMock, y as VitestNativeOptions } from "./index-YjjYELG7.cjs";
2
- import { Plugin } from "vite";
3
-
4
- //#region src/plugin.d.ts
5
- /**
6
- * Vitest plugin for React Native.
7
- *
8
- * Handles platform-specific module resolution, asset stubs, preset virtual
9
- * modules, and automatic setup-file injection so tests can run against
10
- * React Native code in a Node/JSDOM environment.
11
- */
12
- declare function reactNative(options?: VitestNativeOptions): Plugin;
13
- //#endregion
14
- export { type Preset, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets, reactNative };