vitest 4.0.7 → 4.0.8

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 (63) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/browser.d.ts +2 -2
  3. package/dist/browser.js +2 -2
  4. package/dist/chunks/{base.D3GxgUMI.js → base.BgTO2qAg.js} +71 -36
  5. package/dist/chunks/{benchmark.DHKMYAts.js → benchmark.B3N2zMcH.js} +9 -4
  6. package/dist/chunks/{browser.d.-LKfRopd.d.ts → browser.d.DTTM2PTh.d.ts} +1 -1
  7. package/dist/chunks/{cac.G9DAn-c7.js → cac.CfkWq8Qy.js} +115 -42
  8. package/dist/chunks/{cli-api.Csks4as1.js → cli-api.BQ-bjcRi.js} +1857 -839
  9. package/dist/chunks/console.Cf-YriPC.js +146 -0
  10. package/dist/chunks/{coverage.C2LA1DSL.js → coverage.NVjCOln1.js} +273 -103
  11. package/dist/chunks/{creator.cqqifzG7.js → creator.fzVyoMf3.js} +74 -30
  12. package/dist/chunks/{date.-jtEtIeV.js → date.Bq6ZW5rf.js} +17 -6
  13. package/dist/chunks/{git.BFNcloKD.js → git.Bm2pzPAa.js} +3 -3
  14. package/dist/chunks/{global.d.DxtanrNO.d.ts → global.d.DVdCfKp5.d.ts} +1 -1
  15. package/dist/chunks/{globals.BGT_RUsD.js → globals.DOh96BiR.js} +5 -5
  16. package/dist/chunks/{index.DEPqWSIZ.js → index.BY4-tcno.js} +33 -16
  17. package/dist/chunks/{index.Bgo3tNWt.js → index.DAL392Ss.js} +40 -15
  18. package/dist/chunks/{index.RwjEGCQ0.js → index.DIFZf73e.js} +2 -2
  19. package/dist/chunks/{index.CWIFvlX5.js → index.DfKyPFVi.js} +159 -54
  20. package/dist/chunks/{index.CVpyv-Zg.js → index.kotH7DY7.js} +832 -373
  21. package/dist/chunks/{index.jMQYiEWE.js → index.op2Re5rn.js} +22 -12
  22. package/dist/chunks/{init-forks.IU-xQ2_X.js → init-forks.2hx7cf78.js} +14 -4
  23. package/dist/chunks/{init-threads.C_NWvZkU.js → init-threads.Cm4OCIWA.js} +1 -1
  24. package/dist/chunks/{init.fmH9J833.js → init.DMDG-idf.js} +53 -30
  25. package/dist/chunks/{inspector.DLZxSeU3.js → inspector.CvyFGlXm.js} +25 -10
  26. package/dist/chunks/{moduleRunner.d.DEkTotCv.d.ts → moduleRunner.d.CzOZ_4wC.d.ts} +1 -1
  27. package/dist/chunks/{node.BwAWWjHZ.js → node.Ce0vMQM7.js} +1 -1
  28. package/dist/chunks/{plugin.d.Cpes8Bt6.d.ts → plugin.d.D4RrtywJ.d.ts} +1 -1
  29. package/dist/chunks/{reporters.d.CSNcMDxF.d.ts → reporters.d.Da1D1VbQ.d.ts} +6 -5
  30. package/dist/chunks/{rpc.D38ahn14.js → rpc.BUV7uWKJ.js} +20 -7
  31. package/dist/chunks/{setup-common.DR1sucx6.js → setup-common.LGjNSzXp.js} +20 -8
  32. package/dist/chunks/{startModuleRunner.Cn7hCL7D.js → startModuleRunner.BOmUtLIO.js} +206 -83
  33. package/dist/chunks/{test.B6aJd6T3.js → test.ClrAtjMv.js} +48 -22
  34. package/dist/chunks/{utils.CG9h5ccR.js → utils.DvEY5TfP.js} +14 -5
  35. package/dist/chunks/{vi.BZvkKVkM.js → vi.Bgcdy3bQ.js} +261 -111
  36. package/dist/chunks/{vm.BL7_zzOr.js → vm.BIkCDs68.js} +177 -71
  37. package/dist/chunks/{worker.d.D25zYZ7N.d.ts → worker.d.DadbA89M.d.ts} +30 -2
  38. package/dist/cli.js +2 -2
  39. package/dist/config.d.ts +5 -5
  40. package/dist/coverage.d.ts +3 -3
  41. package/dist/coverage.js +1 -1
  42. package/dist/environments.js +1 -1
  43. package/dist/index.d.ts +5 -5
  44. package/dist/index.js +5 -5
  45. package/dist/module-evaluator.d.ts +2 -2
  46. package/dist/module-evaluator.js +85 -35
  47. package/dist/module-runner.js +2 -2
  48. package/dist/node.d.ts +7 -7
  49. package/dist/node.js +16 -12
  50. package/dist/reporters.d.ts +3 -3
  51. package/dist/reporters.js +2 -2
  52. package/dist/runners.js +7 -7
  53. package/dist/snapshot.js +2 -2
  54. package/dist/suite.js +2 -2
  55. package/dist/worker.d.ts +1 -1
  56. package/dist/worker.js +15 -15
  57. package/dist/workers/forks.js +16 -16
  58. package/dist/workers/runVmTests.js +41 -22
  59. package/dist/workers/threads.js +16 -16
  60. package/dist/workers/vmForks.js +11 -11
  61. package/dist/workers/vmThreads.js +11 -11
  62. package/package.json +20 -20
  63. package/dist/chunks/console.CTJL2nuH.js +0 -115
@@ -43,7 +43,8 @@ test('renders name', async () => {
43
43
  await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
44
44
  })
45
45
  `
46
- }, vueExample = {
46
+ };
47
+ const vueExample = {
47
48
  name: "HelloWorld.vue",
48
49
  js: `
49
50
  <script setup>
@@ -83,7 +84,8 @@ test('renders name', async () => {
83
84
  await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
84
85
  })
85
86
  `
86
- }, svelteExample = {
87
+ };
88
+ const svelteExample = {
87
89
  name: "HelloWorld.svelte",
88
90
  js: `
89
91
  <script>
@@ -109,7 +111,8 @@ test('renders name', async () => {
109
111
  await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
110
112
  })
111
113
  `
112
- }, markoExample = {
114
+ };
115
+ const markoExample = {
113
116
  name: "HelloWorld.marko",
114
117
  js: `
115
118
  class {
@@ -138,7 +141,8 @@ test('renders name', async () => {
138
141
  expect(element).toBeInTheDocument()
139
142
  })
140
143
  `
141
- }, litExample = {
144
+ };
145
+ const litExample = {
142
146
  name: "HelloWorld.js",
143
147
  js: `
144
148
  import { html, LitElement } from 'lit'
@@ -192,7 +196,8 @@ test('renders name', async () => {
192
196
  await expect.element(element).toBeInTheDocument()
193
197
  })
194
198
  `
195
- }, qwikExample = {
199
+ };
200
+ const qwikExample = {
196
201
  name: "HelloWorld.jsx",
197
202
  js: `
198
203
  import { component$ } from '@builder.io/qwik'
@@ -226,7 +231,8 @@ test('renders name', async () => {
226
231
  await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
227
232
  })
228
233
  `
229
- }, vanillaExample = {
234
+ };
235
+ const vanillaExample = {
230
236
  name: "HelloWorld.js",
231
237
  js: `
232
238
  export default function HelloWorld({ name }) {
@@ -286,14 +292,18 @@ function getExampleTest(framework) {
286
292
  async function generateExampleFiles(framework, lang) {
287
293
  const example = getExampleTest(framework);
288
294
  let fileName = example.name;
289
- const folder = resolve(process.cwd(), "vitest-example"), fileContent = example[lang];
295
+ const folder = resolve(process.cwd(), "vitest-example");
296
+ const fileContent = example[lang];
290
297
  if (!existsSync(folder)) await mkdir(folder, { recursive: true });
291
298
  const isJSX = fileName.endsWith(".jsx");
292
299
  if (isJSX && lang === "ts") fileName = fileName.replace(".jsx", ".tsx");
293
300
  else if (fileName.endsWith(".js") && lang === "ts") fileName = fileName.replace(".js", ".ts");
294
301
  example.test = example.test.replace("<EXT>", lang);
295
- const filePath = resolve(folder, fileName), testPath = resolve(folder, `HelloWorld.test.${isJSX ? `${lang}x` : lang}`);
296
- return writeFileSync(filePath, fileContent.trimStart(), "utf-8"), writeFileSync(testPath, example.test.trimStart(), "utf-8"), testPath;
302
+ const filePath = resolve(folder, fileName);
303
+ const testPath = resolve(folder, `HelloWorld.test.${isJSX ? `${lang}x` : lang}`);
304
+ writeFileSync(filePath, fileContent.trimStart(), "utf-8");
305
+ writeFileSync(testPath, example.test.trimStart(), "utf-8");
306
+ return testPath;
297
307
  }
298
308
 
299
309
  // eslint-disable-next-line no-console
@@ -422,7 +432,10 @@ async function installPackages(pkgManager, packages) {
422
432
  log(c.green("✔"), c.bold("All packages are already installed."));
423
433
  return;
424
434
  }
425
- log(c.cyan("◼"), c.bold("Installing packages...")), log(c.cyan("◼"), packages.join(", ")), log(), await installPackage(packages, {
435
+ log(c.cyan("◼"), c.bold("Installing packages..."));
436
+ log(c.cyan("◼"), packages.join(", "));
437
+ log();
438
+ await installPackage(packages, {
426
439
  dev: true,
427
440
  packageManager: pkgManager ?? void 0
428
441
  });
@@ -433,19 +446,27 @@ function readPkgJson(path) {
433
446
  return JSON.parse(content);
434
447
  }
435
448
  function getPossibleDefaults(dependencies) {
436
- const provider = getPossibleProvider(dependencies), framework = getPossibleFramework(dependencies);
437
449
  return {
438
450
  lang: "ts",
439
- provider,
440
- framework
451
+ provider: getPossibleProvider(dependencies),
452
+ framework: getPossibleFramework(dependencies)
441
453
  };
442
454
  }
443
455
  function getPossibleFramework(dependencies) {
444
- return dependencies.vue || dependencies["vue-tsc"] || dependencies["@vue/reactivity"] ? "vue" : dependencies.react || dependencies["react-dom"] ? "react" : dependencies.svelte || dependencies["@sveltejs/kit"] ? "svelte" : dependencies.lit || dependencies["lit-html"] ? "lit" : dependencies.preact ? "preact" : dependencies["solid-js"] || dependencies["@solidjs/start"] ? "solid" : dependencies.marko ? "marko" : dependencies["@builder.io/qwik"] || dependencies["@qwik.dev/core"] ? "qwik" : "vanilla";
456
+ if (dependencies.vue || dependencies["vue-tsc"] || dependencies["@vue/reactivity"]) return "vue";
457
+ if (dependencies.react || dependencies["react-dom"]) return "react";
458
+ if (dependencies.svelte || dependencies["@sveltejs/kit"]) return "svelte";
459
+ if (dependencies.lit || dependencies["lit-html"]) return "lit";
460
+ if (dependencies.preact) return "preact";
461
+ if (dependencies["solid-js"] || dependencies["@solidjs/start"]) return "solid";
462
+ if (dependencies.marko) return "marko";
463
+ if (dependencies["@builder.io/qwik"] || dependencies["@qwik.dev/core"]) return "qwik";
464
+ return "vanilla";
445
465
  }
446
466
  function getPossibleProvider(dependencies) {
467
+ if (dependencies.webdriverio || dependencies["@wdio/cli"] || dependencies["@wdio/config"]) return "webdriverio";
447
468
  // playwright is the default recommendation
448
- return dependencies.webdriverio || dependencies["@wdio/cli"] || dependencies["@wdio/config"] ? "webdriverio" : "playwright";
469
+ return "playwright";
449
470
  }
450
471
  function getProviderDocsLink(provider) {
451
472
  switch (provider) {
@@ -455,7 +476,8 @@ function getProviderDocsLink(provider) {
455
476
  }
456
477
  function sort(choices, value) {
457
478
  const index = choices.findIndex((i) => i.value === value);
458
- return index === -1 ? choices : [choices.splice(index, 1)[0], ...choices];
479
+ if (index === -1) return choices;
480
+ return [choices.splice(index, 1)[0], ...choices];
459
481
  }
460
482
  function fail() {
461
483
  process.exitCode = 1;
@@ -477,7 +499,9 @@ function getFrameworkImportInfo(framework) {
477
499
  }
478
500
  }
479
501
  async function generateFrameworkConfigFile(options) {
480
- const { importName, isNamedExport } = getFrameworkImportInfo(options.framework), frameworkImport = isNamedExport ? `import { ${importName} } from '${options.frameworkPlugin}'` : `import ${importName} from '${options.frameworkPlugin}'`, configContent = [
502
+ const { importName, isNamedExport } = getFrameworkImportInfo(options.framework);
503
+ const frameworkImport = isNamedExport ? `import { ${importName} } from '${options.frameworkPlugin}'` : `import ${importName} from '${options.frameworkPlugin}'`;
504
+ const configContent = [
481
505
  `import { defineConfig } from 'vitest/config'`,
482
506
  `import { ${options.provider} } from '@vitest/browser-${options.provider}'`,
483
507
  options.frameworkPlugin ? frameworkImport : null,
@@ -505,7 +529,9 @@ async function updatePkgJsonScripts(pkgJsonPath, vitestScript) {
505
529
  await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf-8");
506
530
  } else {
507
531
  const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
508
- pkg.scripts = pkg.scripts || {}, pkg.scripts["test:browser"] = vitestScript, await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf-8");
532
+ pkg.scripts = pkg.scripts || {};
533
+ pkg.scripts["test:browser"] = vitestScript;
534
+ await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf-8");
509
535
  }
510
536
  log(c.green("✔"), "Added \"test:browser\" script to your package.json.");
511
537
  }
@@ -531,10 +557,14 @@ function getPlaywrightRunArgs(pkgManager) {
531
557
  }
532
558
  async function create() {
533
559
  log(c.cyan("◼"), "This utility will help you set up a browser testing environment.\n");
534
- const pkgJsonPath = resolve(process.cwd(), "package.json"), pkg = readPkgJson(pkgJsonPath) || {}, dependencies = {
560
+ const pkgJsonPath = resolve(process.cwd(), "package.json");
561
+ const pkg = readPkgJson(pkgJsonPath) || {};
562
+ const dependencies = {
535
563
  ...pkg.dependencies,
536
564
  ...pkg.devDependencies
537
- }, defaults = getPossibleDefaults(dependencies), { lang } = await prompt({
565
+ };
566
+ const defaults = getPossibleDefaults(dependencies);
567
+ const { lang } = await prompt({
538
568
  type: "select",
539
569
  name: "lang",
540
570
  message: "Choose a language for your tests",
@@ -572,23 +602,28 @@ async function create() {
572
602
  message: `Install Playwright browsers (can be done manually via 'pnpm exec playwright install')?`
573
603
  }));
574
604
  if (installPlaywright == null) return fail();
575
- const dependenciesToInstall = [`@vitest/browser-${provider}`], frameworkPackage = getFrameworkTestPackage(framework);
605
+ const dependenciesToInstall = [`@vitest/browser-${provider}`];
606
+ const frameworkPackage = getFrameworkTestPackage(framework);
576
607
  if (frameworkPackage) dependenciesToInstall.push(frameworkPackage);
577
608
  const frameworkPlugin = getFrameworkPluginPackage(framework);
578
609
  if (frameworkPlugin) dependenciesToInstall.push(frameworkPlugin);
579
610
  const pkgManager = await detectPackageManager();
580
- log(), await installPackages(pkgManager, dependenciesToInstall.filter((pkg) => !dependencies[pkg]));
611
+ log();
612
+ await installPackages(pkgManager, dependenciesToInstall.filter((pkg) => !dependencies[pkg]));
581
613
  const rootConfig = any(configFiles, { cwd: process.cwd() });
582
614
  let scriptCommand = "vitest";
583
- if (log(), rootConfig) {
615
+ log();
616
+ if (rootConfig) {
584
617
  const configPath = resolve(dirname(rootConfig), `vitest.browser.config.${lang}`);
585
- scriptCommand = `vitest --config=${relative(process.cwd(), configPath)}`, await generateFrameworkConfigFile({
618
+ scriptCommand = `vitest --config=${relative(process.cwd(), configPath)}`;
619
+ await generateFrameworkConfigFile({
586
620
  configPath,
587
621
  framework,
588
622
  frameworkPlugin,
589
623
  provider,
590
624
  browsers
591
- }), log(
625
+ });
626
+ log(
592
627
  c.green("✔"),
593
628
  "Created a new config file for browser tests:",
594
629
  c.bold(relative(process.cwd(), configPath)),
@@ -605,17 +640,23 @@ async function create() {
605
640
  frameworkPlugin,
606
641
  provider,
607
642
  browsers
608
- }), log(c.green("✔"), "Created a config file for browser tests:", c.bold(relative(process.cwd(), configPath)));
643
+ });
644
+ log(c.green("✔"), "Created a config file for browser tests:", c.bold(relative(process.cwd(), configPath)));
609
645
  }
610
- if (log(), await updatePkgJsonScripts(pkgJsonPath, scriptCommand), installPlaywright) {
646
+ log();
647
+ await updatePkgJsonScripts(pkgJsonPath, scriptCommand);
648
+ if (installPlaywright) {
611
649
  log();
612
- const [command, ...args] = getPlaywrightRunArgs(pkgManager), allArgs = [
650
+ const [command, ...args] = getPlaywrightRunArgs(pkgManager);
651
+ const allArgs = [
613
652
  ...args,
614
653
  "playwright",
615
654
  "install",
616
655
  "--with-deps"
617
656
  ];
618
- log(c.cyan("◼"), `Installing Playwright dependencies with \`${c.bold(command)} ${c.bold(allArgs.join(" "))}\`...`), log(), await x(command, allArgs, { nodeOptions: { stdio: [
657
+ log(c.cyan("◼"), `Installing Playwright dependencies with \`${c.bold(command)} ${c.bold(allArgs.join(" "))}\`...`);
658
+ log();
659
+ await x(command, allArgs, { nodeOptions: { stdio: [
619
660
  "pipe",
620
661
  "inherit",
621
662
  "inherit"
@@ -623,7 +664,10 @@ async function create() {
623
664
  }
624
665
  log();
625
666
  const exampleTestFile = await generateExampleFiles(framework, lang);
626
- log(c.green("✔"), "Created example test file in", c.bold(relative(process.cwd(), exampleTestFile))), log(c.dim(" You can safely delete this file once you have written your own tests.")), log(), log(c.cyan("◼"), "All done! Run your tests with", c.bold(getRunScript(pkgManager)));
667
+ log(c.green("✔"), "Created example test file in", c.bold(relative(process.cwd(), exampleTestFile)));
668
+ log(c.dim(" You can safely delete this file once you have written your own tests."));
669
+ log();
670
+ log(c.cyan("◼"), "All done! Run your tests with", c.bold(getRunScript(pkgManager)));
627
671
  }
628
672
 
629
673
  export { create };
@@ -37,23 +37,34 @@ class MockDate extends RealDate {
37
37
  date = new RealDate(y);
38
38
  break;
39
39
  default:
40
- d = typeof d === "undefined" ? 1 : d, h = h || 0, M = M || 0, s = s || 0, ms = ms || 0, date = new RealDate(y, m, d, h, M, s, ms);
40
+ d = typeof d === "undefined" ? 1 : d;
41
+ h = h || 0;
42
+ M = M || 0;
43
+ s = s || 0;
44
+ ms = ms || 0;
45
+ date = new RealDate(y, m, d, h, M, s, ms);
41
46
  break;
42
47
  }
43
- return Object.setPrototypeOf(date, MockDate.prototype), date;
48
+ Object.setPrototypeOf(date, MockDate.prototype);
49
+ return date;
44
50
  }
45
51
  }
46
- MockDate.UTC = RealDate.UTC, MockDate.now = function() {
52
+ MockDate.UTC = RealDate.UTC;
53
+ MockDate.now = function() {
47
54
  return new MockDate().valueOf();
48
- }, MockDate.parse = function(dateString) {
55
+ };
56
+ MockDate.parse = function(dateString) {
49
57
  return RealDate.parse(dateString);
50
- }, MockDate.toString = function() {
58
+ };
59
+ MockDate.toString = function() {
51
60
  return RealDate.toString();
52
61
  };
53
62
  function mockDate(date) {
54
63
  const dateObj = new RealDate(date.valueOf());
55
64
  if (Number.isNaN(dateObj.getTime())) throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
56
- globalThis.Date = MockDate, now = dateObj.valueOf();
65
+ // @ts-expect-error global
66
+ globalThis.Date = MockDate;
67
+ now = dateObj.valueOf();
57
68
  }
58
69
  function resetDate() {
59
70
  globalThis.Date = RealDate;
@@ -11,7 +11,8 @@ class VitestGit {
11
11
  try {
12
12
  result = await x("git", args, { nodeOptions: { cwd: this.root } });
13
13
  } catch (e) {
14
- throw e.message = e.stderr, e;
14
+ e.message = e.stderr;
15
+ throw e;
15
16
  }
16
17
  return result.stdout.split("\n").filter((s) => s !== "").map((changedPath) => resolve(this.root, changedPath));
17
18
  }
@@ -60,8 +61,7 @@ class VitestGit {
60
61
  async getRoot(cwd) {
61
62
  const args = ["rev-parse", "--show-cdup"];
62
63
  try {
63
- const result = await x("git", args, { nodeOptions: { cwd } });
64
- return resolve(cwd, result.stdout.trim());
64
+ return resolve(cwd, (await x("git", args, { nodeOptions: { cwd } })).stdout.trim());
65
65
  } catch {
66
66
  return null;
67
67
  }
@@ -2,7 +2,7 @@ import { PromisifyAssertion, Tester, ExpectStatic } from '@vitest/expect';
2
2
  import { Plugin } from '@vitest/pretty-format';
3
3
  import { SnapshotState } from '@vitest/snapshot';
4
4
  import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
5
- import { U as UserConsoleLog } from './worker.d.D25zYZ7N.js';
5
+ import { U as UserConsoleLog } from './worker.d.DadbA89M.js';
6
6
 
7
7
  interface SnapshotMatcher<T> {
8
8
  <U extends { [P in keyof T] : any }>(snapshot: Partial<U>, hint?: string): void;
@@ -1,10 +1,10 @@
1
1
  import { g as globalApis } from './constants.D_Q9UYh-.js';
2
- import { i as index } from './index.RwjEGCQ0.js';
3
- import './vi.BZvkKVkM.js';
2
+ import { i as index } from './index.DIFZf73e.js';
3
+ import './vi.Bgcdy3bQ.js';
4
4
  import '@vitest/expect';
5
5
  import '@vitest/runner';
6
6
  import '@vitest/runner/utils';
7
- import './utils.CG9h5ccR.js';
7
+ import './utils.DvEY5TfP.js';
8
8
  import '@vitest/utils/timers';
9
9
  import '@vitest/snapshot';
10
10
  import '@vitest/utils/error';
@@ -13,8 +13,8 @@ import '@vitest/spy';
13
13
  import '@vitest/utils/offset';
14
14
  import '@vitest/utils/source-map';
15
15
  import './_commonjsHelpers.BFTU3MAI.js';
16
- import './date.-jtEtIeV.js';
17
- import './benchmark.DHKMYAts.js';
16
+ import './date.Bq6ZW5rf.js';
17
+ import './benchmark.B3N2zMcH.js';
18
18
  import './evaluatedModules.Dg1zASAC.js';
19
19
  import 'pathe';
20
20
  import 'vite/module-runner';
@@ -1,8 +1,8 @@
1
1
  import { chai } from '@vitest/expect';
2
- import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.DR1sucx6.js';
3
- import { r as rpc } from './rpc.D38ahn14.js';
4
- import { g as getWorkerState } from './utils.CG9h5ccR.js';
5
- import { V as VitestTestRunner, N as NodeBenchmarkRunner } from './test.B6aJd6T3.js';
2
+ import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.LGjNSzXp.js';
3
+ import { r as rpc } from './rpc.BUV7uWKJ.js';
4
+ import { g as getWorkerState } from './utils.DvEY5TfP.js';
5
+ import { V as VitestTestRunner, N as NodeBenchmarkRunner } from './test.ClrAtjMv.js';
6
6
 
7
7
  function setupChaiConfig(config) {
8
8
  Object.assign(chai.config, config);
@@ -10,7 +10,7 @@ function setupChaiConfig(config) {
10
10
 
11
11
  async function resolveSnapshotEnvironment(config, executor) {
12
12
  if (!config.snapshotEnvironment) {
13
- const { VitestNodeSnapshotEnvironment } = await import('./node.BwAWWjHZ.js');
13
+ const { VitestNodeSnapshotEnvironment } = await import('./node.Ce0vMQM7.js');
14
14
  return new VitestNodeSnapshotEnvironment();
15
15
  }
16
16
  const mod = await executor.import(config.snapshotEnvironment);
@@ -26,11 +26,13 @@ async function getTestRunnerConstructor(config, moduleRunner) {
26
26
  }
27
27
  async function resolveTestRunner(config, moduleRunner) {
28
28
  const testRunner = new (await (getTestRunnerConstructor(config, moduleRunner)))(config);
29
- if (Object.defineProperty(testRunner, "moduleRunner", {
29
+ // inject private executor to every runner
30
+ Object.defineProperty(testRunner, "moduleRunner", {
30
31
  value: moduleRunner,
31
32
  enumerable: false,
32
33
  configurable: false
33
- }), !testRunner.config) testRunner.config = config;
34
+ });
35
+ if (!testRunner.config) testRunner.config = config;
34
36
  if (!testRunner.importFile) throw new Error("Runner must implement \"importFile\" method.");
35
37
  const [diffOptions] = await Promise.all([loadDiffConfig(config, moduleRunner), loadSnapshotSerializers(config, moduleRunner)]);
36
38
  testRunner.config.diffOptions = diffOptions;
@@ -38,28 +40,39 @@ async function resolveTestRunner(config, moduleRunner) {
38
40
  const originalOnTaskUpdate = testRunner.onTaskUpdate;
39
41
  testRunner.onTaskUpdate = async (task, events) => {
40
42
  const p = rpc().onTaskUpdate(task, events);
41
- return await originalOnTaskUpdate?.call(testRunner, task, events), p;
43
+ await originalOnTaskUpdate?.call(testRunner, task, events);
44
+ return p;
42
45
  };
43
46
  // patch some methods, so custom runners don't need to call RPC
44
47
  const originalOnTestAnnotate = testRunner.onTestAnnotate;
45
48
  testRunner.onTestAnnotate = async (test, annotation) => {
46
- const p = rpc().onTaskAnnotate(test.id, annotation), overriddenResult = await originalOnTestAnnotate?.call(testRunner, test, annotation), vitestResult = await p;
49
+ const p = rpc().onTaskAnnotate(test.id, annotation);
50
+ const overriddenResult = await originalOnTestAnnotate?.call(testRunner, test, annotation);
51
+ const vitestResult = await p;
47
52
  return overriddenResult || vitestResult;
48
53
  };
49
54
  const originalOnCollectStart = testRunner.onCollectStart;
50
55
  testRunner.onCollectStart = async (file) => {
51
- await rpc().onQueued(file), await originalOnCollectStart?.call(testRunner, file);
56
+ await rpc().onQueued(file);
57
+ await originalOnCollectStart?.call(testRunner, file);
52
58
  };
53
59
  const originalOnCollected = testRunner.onCollected;
54
60
  testRunner.onCollected = async (files) => {
55
61
  const state = getWorkerState();
56
62
  files.forEach((file) => {
57
- file.prepareDuration = state.durations.prepare, file.environmentLoad = state.durations.environment, state.durations.prepare = 0, state.durations.environment = 0;
58
- }), rpc().onCollected(files), await originalOnCollected?.call(testRunner, files);
63
+ file.prepareDuration = state.durations.prepare;
64
+ file.environmentLoad = state.durations.environment;
65
+ // should be collected only for a single test file in a batch
66
+ state.durations.prepare = 0;
67
+ state.durations.environment = 0;
68
+ });
69
+ rpc().onCollected(files);
70
+ await originalOnCollected?.call(testRunner, files);
59
71
  };
60
72
  const originalOnAfterRun = testRunner.onAfterRunFiles;
61
73
  testRunner.onAfterRunFiles = async (files) => {
62
- const state = getWorkerState(), coverage = await takeCoverageInsideWorker(config.coverage, moduleRunner);
74
+ const state = getWorkerState();
75
+ const coverage = await takeCoverageInsideWorker(config.coverage, moduleRunner);
63
76
  if (coverage) rpc().onAfterSuiteRun({
64
77
  coverage,
65
78
  testFiles: files.map((file) => file.name).sort(),
@@ -69,12 +82,16 @@ async function resolveTestRunner(config, moduleRunner) {
69
82
  await originalOnAfterRun?.call(testRunner, files);
70
83
  };
71
84
  const originalOnAfterRunTask = testRunner.onAfterRunTask;
72
- return testRunner.onAfterRunTask = async (test) => {
85
+ testRunner.onAfterRunTask = async (test) => {
73
86
  if (config.bail && test.result?.state === "fail") {
74
- if (1 + await rpc().getCountOfFailedTests() >= config.bail) rpc().onCancel("test-failure"), testRunner.cancel?.("test-failure");
87
+ if (1 + await rpc().getCountOfFailedTests() >= config.bail) {
88
+ rpc().onCancel("test-failure");
89
+ testRunner.cancel?.("test-failure");
90
+ }
75
91
  }
76
92
  await originalOnAfterRunTask?.call(testRunner, test);
77
- }, testRunner;
93
+ };
94
+ return testRunner;
78
95
  }
79
96
 
80
97
  export { resolveSnapshotEnvironment as a, resolveTestRunner as r, setupChaiConfig as s };
@@ -21,7 +21,7 @@ function createBirpc(functions, options) {
21
21
  timeout = DEFAULT_TIMEOUT
22
22
  } = options;
23
23
  const rpcPromiseMap = /* @__PURE__ */ new Map();
24
- let _promise;
24
+ let _promiseInit;
25
25
  let closed = false;
26
26
  const rpc = new Proxy({}, {
27
27
  get(_, method) {
@@ -36,8 +36,8 @@ function createBirpc(functions, options) {
36
36
  return closed;
37
37
  if (method === "then" && !eventNames.includes("then") && !("then" in functions))
38
38
  return void 0;
39
- const sendEvent = (...args) => {
40
- post(serialize({ m: method, a: args, t: TYPE_REQUEST }));
39
+ const sendEvent = async (...args) => {
40
+ await post(serialize({ m: method, a: args, t: TYPE_REQUEST }));
41
41
  };
42
42
  if (eventNames.includes(method)) {
43
43
  sendEvent.asEvent = sendEvent;
@@ -46,16 +46,18 @@ function createBirpc(functions, options) {
46
46
  const sendCall = async (...args) => {
47
47
  if (closed)
48
48
  throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
49
- if (_promise) {
49
+ if (_promiseInit) {
50
50
  try {
51
- await _promise;
51
+ await _promiseInit;
52
52
  } finally {
53
- _promise = void 0;
53
+ _promiseInit = void 0;
54
54
  }
55
55
  }
56
- return new Promise((resolve, reject) => {
57
- const id = nanoid();
58
- let timeoutId;
56
+ let { promise, resolve, reject } = createPromiseWithResolvers();
57
+ const id = nanoid();
58
+ let timeoutId;
59
+ const _req = { m: method, a: args, i: id, t: TYPE_REQUEST };
60
+ async function handler(req = _req) {
59
61
  if (timeout >= 0) {
60
62
  timeoutId = setTimeout(() => {
61
63
  try {
@@ -71,8 +73,22 @@ function createBirpc(functions, options) {
71
73
  timeoutId = timeoutId.unref?.();
72
74
  }
73
75
  rpcPromiseMap.set(id, { resolve, reject, timeoutId, method });
74
- post(serialize({ m: method, a: args, i: id, t: "q" }));
75
- });
76
+ await post(serialize(req));
77
+ return promise;
78
+ }
79
+ try {
80
+ if (options.onRequest)
81
+ await options.onRequest(_req, handler, resolve);
82
+ else
83
+ await handler();
84
+ } catch (e) {
85
+ clearTimeout(timeoutId);
86
+ rpcPromiseMap.delete(id);
87
+ if (options.onGeneralError?.(e) !== true)
88
+ throw e;
89
+ return;
90
+ }
91
+ return promise;
76
92
  };
77
93
  sendCall.asEvent = sendEvent;
78
94
  return sendCall;
@@ -114,7 +130,7 @@ function createBirpc(functions, options) {
114
130
  if (msg.t === TYPE_REQUEST) {
115
131
  const { m: method, a: args } = msg;
116
132
  let result, error;
117
- const fn = resolver ? resolver(method, functions[method]) : functions[method];
133
+ const fn = await (resolver ? resolver(method, functions[method]) : functions[method]);
118
134
  if (!fn) {
119
135
  error = new Error(`[birpc] function "${method}" not found`);
120
136
  } else {
@@ -133,7 +149,7 @@ function createBirpc(functions, options) {
133
149
  }
134
150
  if (!error) {
135
151
  try {
136
- post(serialize({ t: TYPE_RESPONSE, i: msg.i, r: result }), ...extra);
152
+ await post(serialize({ t: TYPE_RESPONSE, i: msg.i, r: result }), ...extra);
137
153
  return;
138
154
  } catch (e) {
139
155
  error = e;
@@ -142,7 +158,7 @@ function createBirpc(functions, options) {
142
158
  }
143
159
  }
144
160
  try {
145
- post(serialize({ t: TYPE_RESPONSE, i: msg.i, e: error }), ...extra);
161
+ await post(serialize({ t: TYPE_RESPONSE, i: msg.i, e: error }), ...extra);
146
162
  } catch (e) {
147
163
  if (options.onGeneralError?.(e, method, args) !== true)
148
164
  throw e;
@@ -161,9 +177,18 @@ function createBirpc(functions, options) {
161
177
  rpcPromiseMap.delete(ack);
162
178
  }
163
179
  }
164
- _promise = on(onMessage);
180
+ _promiseInit = on(onMessage);
165
181
  return rpc;
166
182
  }
183
+ function createPromiseWithResolvers() {
184
+ let resolve;
185
+ let reject;
186
+ const promise = new Promise((res, rej) => {
187
+ resolve = res;
188
+ reject = rej;
189
+ });
190
+ return { promise, resolve, reject };
191
+ }
167
192
  const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
168
193
  function nanoid(size = 21) {
169
194
  let id = "";
@@ -1,5 +1,5 @@
1
- import { b as assert, c as createExpect, g as globalExpect, i as inject, s as should, v as vi, d as vitest } from './vi.BZvkKVkM.js';
2
- import { b as bench } from './benchmark.DHKMYAts.js';
1
+ import { b as assert, c as createExpect, g as globalExpect, i as inject, s as should, v as vi, d as vitest } from './vi.Bgcdy3bQ.js';
2
+ import { b as bench } from './benchmark.B3N2zMcH.js';
3
3
  import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
4
4
  import { expectTypeOf } from 'expect-type';
5
5
  import { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';