vitest 2.0.5 → 2.1.0-beta.2

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 (54) hide show
  1. package/dist/browser.d.ts +3 -3
  2. package/dist/browser.js +1 -1
  3. package/dist/chunks/RandomSequencer.B4M2ux5b.js +952 -0
  4. package/dist/chunks/{base.DSsbfkDg.js → base.BH-FAiX7.js} +1 -1
  5. package/dist/chunks/{base.CC5R_kgU.js → base.BYvKfYzm.js} +2 -2
  6. package/dist/chunks/{benchmark.DDmpNjj-.js → benchmark.C8CRJYG4.js} +1 -1
  7. package/dist/chunks/{cac.DGgmCKmU.js → cac.B6BJeWgz.js} +9 -8
  8. package/dist/chunks/{cli-api.OKfd3qJ0.js → cli-api.de6RCgV0.js} +221 -4329
  9. package/dist/chunks/{config.DCnyCTbs.d.ts → config.CHuotKvS.d.ts} +3 -0
  10. package/dist/chunks/{console.Bgn7_A1x.js → console.DI3gHgtH.js} +1 -1
  11. package/dist/chunks/{creator.a3OfuIEW.js → creator.GreKbaUc.js} +2 -3
  12. package/dist/chunks/{env.BU041cs9.js → env.CmHVDJnw.js} +1 -1
  13. package/dist/chunks/{execute.Cjlr2CRw.js → execute.DT9BA6zp.js} +7 -7
  14. package/dist/chunks/{globals.BliuJFNR.js → globals.DRPLtPOv.js} +6 -6
  15. package/dist/chunks/{index.BfeNhc0N.js → index.CNZXZ9PJ.js} +2 -2
  16. package/dist/chunks/{index.DYufA6CZ.js → index.CxRxs566.js} +1 -1
  17. package/dist/chunks/{index.R1VjssW9.js → index.CxWPpGJz.js} +2 -2
  18. package/dist/chunks/{index.JbiJutJ_.js → index.YuPJueCg.js} +25 -965
  19. package/dist/chunks/{node.DS3zEPa7.js → node.Bx4JZjMG.js} +1 -1
  20. package/dist/chunks/{reporters.C_zwCd4j.d.ts → reporters.DRZ7ndzr.d.ts} +14 -1
  21. package/dist/chunks/resolveConfig.CGobt8AB.js +8120 -0
  22. package/dist/chunks/{runBaseTests.CyvqmuC9.js → runBaseTests.BAhL8UH_.js} +9 -9
  23. package/dist/chunks/{setup-common.CNzatKMx.js → setup-common.KBrCO5LJ.js} +1 -1
  24. package/dist/chunks/{utils.DpP_sDwr.js → utils.DO38lwfj.js} +1 -1
  25. package/dist/chunks/{vi.fiQ7lMRF.js → vi.B6QZ938s.js} +2 -2
  26. package/dist/chunks/{vm.DcSuuaHr.js → vm.kl9T_5ai.js} +3 -3
  27. package/dist/chunks/{worker.C5iHKIaJ.d.ts → worker.BANO5ak1.d.ts} +1 -1
  28. package/dist/chunks/{worker.DKkAC4Qw.d.ts → worker.Cx2xE71X.d.ts} +1 -1
  29. package/dist/cli.js +2 -2
  30. package/dist/config.d.ts +2 -2
  31. package/dist/coverage.d.ts +2 -2
  32. package/dist/coverage.js +34 -14
  33. package/dist/execute.d.ts +2 -2
  34. package/dist/execute.js +2 -2
  35. package/dist/index.d.ts +6 -6
  36. package/dist/index.js +7 -7
  37. package/dist/node.d.ts +5 -5
  38. package/dist/node.js +19 -18
  39. package/dist/reporters.d.ts +2 -2
  40. package/dist/reporters.js +10 -9
  41. package/dist/runners.d.ts +9 -2
  42. package/dist/runners.js +5 -5
  43. package/dist/snapshot.js +2 -2
  44. package/dist/suite.js +3 -3
  45. package/dist/worker.js +1 -1
  46. package/dist/workers/forks.js +3 -3
  47. package/dist/workers/runVmTests.js +8 -8
  48. package/dist/workers/threads.js +3 -3
  49. package/dist/workers/vmForks.js +5 -5
  50. package/dist/workers/vmThreads.js +5 -5
  51. package/dist/workers.d.ts +4 -4
  52. package/dist/workers.js +6 -6
  53. package/package.json +14 -15
  54. package/dist/chunks/index.BMmMjLIQ.js +0 -3975
@@ -1,29 +1,29 @@
1
- import fs$8, { existsSync, promises as promises$1, statSync as statSync$1, realpathSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { join, resolve, isAbsolute, relative, dirname, normalize, basename, toNamespacedPath } from 'pathe';
1
+ import { existsSync, promises, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { relative, dirname, join, resolve, basename, toNamespacedPath, isAbsolute, normalize } from 'pathe';
3
3
  import { g as getCoverageProvider, C as CoverageProviderMap } from './coverage.CqfT4xaf.js';
4
4
  import { searchForWorkspaceRoot, version, createServer, mergeConfig } from 'vite';
5
5
  import { f as findUp, p as prompt } from './index.CM5UI-4O.js';
6
- import { A as API_PATH, e as extraInlineDeps, d as defaultPort, a as defaultBrowserPort, b as defaultInspectPort, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.CaAN7icJ.js';
7
- import { MessageChannel, isMainThread } from 'node:worker_threads';
6
+ import { A as API_PATH, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles, d as defaultPort } from './constants.CaAN7icJ.js';
7
+ import { isMainThread } from 'node:worker_threads';
8
8
  import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers.BFTU3MAI.js';
9
9
  import require$$0 from 'os';
10
10
  import p from 'path';
11
11
  import require$$0$1 from 'util';
12
- import { b as braces_1, p as picomatch$1, u as utils$d, m as mm } from './index.BMmMjLIQ.js';
12
+ import { d as braces_1, p as picomatch$1, u as utils$d, V as VitestCache, e as configDefaults, m as mm, a as resolveConfig, i as isBrowserEnabled, f as isPackageExists, h as createPool, r as resolveApiServerConfig, j as coverageConfigDefaults } from './resolveConfig.CGobt8AB.js';
13
13
  import require$$0$2 from 'stream';
14
14
  import require$$0$4 from 'events';
15
15
  import require$$0$3 from 'fs';
16
16
  import { ViteNodeRunner } from 'vite-node/client';
17
17
  import { SnapshotManager } from '@vitest/snapshot/manager';
18
18
  import { ViteNodeServer } from 'vite-node/server';
19
- import { v as version$1 } from './cac.DGgmCKmU.js';
20
- import { hasFailed, createFileTask, getTasks, getTests, getNames } from '@vitest/runner/utils';
21
- import { n as noop$1, b as isPrimitive, c as groupBy, A as AggregateErrorPonyfill, a as slash$1, t as toArray, d as deepMerge, e as nanoid, w as wildcardPatternToRegExp, f as stdout } from './base.DSsbfkDg.js';
22
- import { createDefer, toArray as toArray$1, notNullish } from '@vitest/utils';
23
- import { b as isWindows } from './env.BU041cs9.js';
24
- import { rootDir, distDir } from '../path.js';
19
+ import { v as version$1 } from './cac.B6BJeWgz.js';
20
+ import { createFileTask, getTasks, hasFailed, getTests, getNames } from '@vitest/runner/utils';
21
+ import { n as noop$1, c as isPrimitive, t as toArray, d as deepMerge, e as nanoid, w as wildcardPatternToRegExp, a as slash$1, f as stdout } from './base.BH-FAiX7.js';
22
+ import { toArray as toArray$1, notNullish, createDefer } from '@vitest/utils';
23
+ import { i as isWindows } from './env.CmHVDJnw.js';
24
+ import { distDir, rootDir } from '../path.js';
25
25
  import { c as createBirpc } from './index.BpSiYbpB.js';
26
- import { s as stringify, p as parse$3, w as wrapSerializableConfig, j as Typechecker, R as ReportersMap, g as BenchmarkReportsMap, e as TestFile, f as TestSuite, d as TestCase, k as RandomSequencer, h as BaseSequencer, l as findNodeAround, m as generateCodeFrame, n as highlightCode, i as TestProject, L as Logger, o as BlobReporter, r as readBlobs } from './index.JbiJutJ_.js';
26
+ import { s as stringify, p as parse$3, R as ReportersMap, g as BenchmarkReportsMap, e as TestFile, f as TestSuite, d as TestCase, i as generateCodeFrame, j as highlightCode, h as TestProject, L as Logger, k as BlobReporter, r as readBlobs } from './index.YuPJueCg.js';
27
27
  import require$$0$5 from 'zlib';
28
28
  import require$$0$6 from 'buffer';
29
29
  import require$$1 from 'crypto';
@@ -33,27 +33,20 @@ import require$$3 from 'net';
33
33
  import require$$4 from 'tls';
34
34
  import require$$7 from 'url';
35
35
  import { parseErrorStacktrace } from '@vitest/utils/source-map';
36
- import v8 from 'node:v8';
37
- import * as nodeos from 'node:os';
38
- import nodeos__default, { tmpdir } from 'node:os';
39
- import EventEmitter$2 from 'node:events';
40
- import Tinypool$1, { Tinypool } from 'tinypool';
41
- import crypto, { createHash as createHash$2 } from 'node:crypto';
42
- import { mkdir, writeFile, rm } from 'node:fs/promises';
43
- import path$8, { win32 } from 'node:path';
44
- import process$1 from 'node:process';
45
- import { builtinModules, createRequire } from 'node:module';
46
- import url, { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$2 } from 'node:url';
47
- import assert from 'node:assert';
48
- import { format as format$2, inspect } from 'node:util';
49
- import c from 'tinyrainbow';
50
- import { isCI, provider as provider$1 } from 'std-env';
36
+ import { tmpdir } from 'node:os';
37
+ import { rm } from 'node:fs/promises';
38
+ import { createHash as createHash$2 } from 'node:crypto';
51
39
  import { normalizeRequestId, cleanUrl } from 'vite-node/utils';
52
40
  import MagicString from 'magic-string';
41
+ import { f as findNodeAround } from './RandomSequencer.B4M2ux5b.js';
53
42
  import { esmWalker } from '@vitest/utils/ast';
54
- import { a as removeUndefinedValues } from './index.DYufA6CZ.js';
43
+ import url from 'node:url';
44
+ import { createRequire } from 'node:module';
45
+ import c from 'tinyrainbow';
46
+ import { isCI } from 'std-env';
47
+ import { a as removeUndefinedValues } from './index.CxRxs566.js';
55
48
  import readline from 'node:readline';
56
- import { s as stripAnsi } from './utils.DpP_sDwr.js';
49
+ import { s as stripAnsi } from './utils.DO38lwfj.js';
57
50
 
58
51
  async function getModuleGraph(ctx, projectName, id, browser = false) {
59
52
  const graph = {};
@@ -1446,7 +1439,7 @@ var async$2 = {};
1446
1439
 
1447
1440
  Object.defineProperty(async$2, "__esModule", { value: true });
1448
1441
  async$2.read = void 0;
1449
- function read$4(path, settings, callback) {
1442
+ function read$3(path, settings, callback) {
1450
1443
  settings.fs.lstat(path, (lstatError, lstat) => {
1451
1444
  if (lstatError !== null) {
1452
1445
  callFailureCallback$2(callback, lstatError);
@@ -1472,7 +1465,7 @@ function read$4(path, settings, callback) {
1472
1465
  });
1473
1466
  });
1474
1467
  }
1475
- async$2.read = read$4;
1468
+ async$2.read = read$3;
1476
1469
  function callFailureCallback$2(callback, error) {
1477
1470
  callback(error);
1478
1471
  }
@@ -1484,7 +1477,7 @@ var sync$7 = {};
1484
1477
 
1485
1478
  Object.defineProperty(sync$7, "__esModule", { value: true });
1486
1479
  sync$7.read = void 0;
1487
- function read$3(path, settings) {
1480
+ function read$2(path, settings) {
1488
1481
  const lstat = settings.fs.lstatSync(path);
1489
1482
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
1490
1483
  return lstat;
@@ -1503,7 +1496,7 @@ function read$3(path, settings) {
1503
1496
  throw error;
1504
1497
  }
1505
1498
  }
1506
- sync$7.read = read$3;
1499
+ sync$7.read = read$2;
1507
1500
 
1508
1501
  var settings$3 = {};
1509
1502
 
@@ -1703,14 +1696,14 @@ const rpl = runParallel_1;
1703
1696
  const constants_1$1 = constants$1;
1704
1697
  const utils$8 = utils$9;
1705
1698
  const common$5 = common$6;
1706
- function read$2(directory, settings, callback) {
1699
+ function read$1(directory, settings, callback) {
1707
1700
  if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
1708
1701
  readdirWithFileTypes$1(directory, settings, callback);
1709
1702
  return;
1710
1703
  }
1711
1704
  readdir$1(directory, settings, callback);
1712
1705
  }
1713
- async$3.read = read$2;
1706
+ async$3.read = read$1;
1714
1707
  function readdirWithFileTypes$1(directory, settings, callback) {
1715
1708
  settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
1716
1709
  if (readdirError !== null) {
@@ -1808,13 +1801,13 @@ const fsStat$4 = out$1;
1808
1801
  const constants_1 = constants$1;
1809
1802
  const utils$7 = utils$9;
1810
1803
  const common$4 = common$6;
1811
- function read$1(directory, settings) {
1804
+ function read(directory, settings) {
1812
1805
  if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
1813
1806
  return readdirWithFileTypes(directory, settings);
1814
1807
  }
1815
1808
  return readdir(directory, settings);
1816
1809
  }
1817
- sync$5.read = read$1;
1810
+ sync$5.read = read;
1818
1811
  function readdirWithFileTypes(directory, settings) {
1819
1812
  const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
1820
1813
  return dirents.map((dirent) => {
@@ -8050,7 +8043,7 @@ function setup(ctx, _server) {
8050
8043
  if (!ctx.state.filesMap.has(id) || !existsSync(id)) {
8051
8044
  return null;
8052
8045
  }
8053
- return promises$1.readFile(id, "utf-8");
8046
+ return promises.readFile(id, "utf-8");
8054
8047
  },
8055
8048
  async saveTestFile(id, content) {
8056
8049
  if (!ctx.state.filesMap.has(id) || !existsSync(id)) {
@@ -8058,7 +8051,7 @@ function setup(ctx, _server) {
8058
8051
  `Test file "${id}" was not registered, so it cannot be updated using the API.`
8059
8052
  );
8060
8053
  }
8061
- return promises$1.writeFile(id, content, "utf-8");
8054
+ return promises.writeFile(id, content, "utf-8");
8062
8055
  },
8063
8056
  async rerun(files) {
8064
8057
  await ctx.rerunFiles(files);
@@ -8071,7 +8064,7 @@ function setup(ctx, _server) {
8071
8064
  const result = browser ? await project.browser.vite.transformRequest(id) : await project.vitenode.transformRequest(id);
8072
8065
  if (result) {
8073
8066
  try {
8074
- result.source = result.source || await promises$1.readFile(id, "utf-8");
8067
+ result.source = result.source || await promises.readFile(id, "utf-8");
8075
8068
  } catch {
8076
8069
  }
8077
8070
  return result;
@@ -8189,4343 +8182,239 @@ var setup$1 = /*#__PURE__*/Object.freeze({
8189
8182
  setup: setup
8190
8183
  });
8191
8184
 
8192
- const envsOrder = ["node", "jsdom", "happy-dom", "edge-runtime"];
8193
- function getTransformMode(patterns, filename) {
8194
- if (patterns.web && mm.isMatch(filename, patterns.web)) {
8195
- return "web";
8196
- }
8197
- if (patterns.ssr && mm.isMatch(filename, patterns.ssr)) {
8198
- return "ssr";
8199
- }
8200
- return void 0;
8201
- }
8202
- async function groupFilesByEnv(files) {
8203
- const filesWithEnv = await Promise.all(
8204
- files.map(async ([project, file]) => {
8205
- const code = await promises$1.readFile(file, "utf-8");
8206
- let env = code.match(/@(?:vitest|jest)-environment\s+([\w-]+)\b/)?.[1];
8207
- if (!env) {
8208
- for (const [glob, target] of project.config.environmentMatchGlobs || []) {
8209
- if (mm.isMatch(file, glob, { cwd: project.config.root })) {
8210
- env = target;
8211
- break;
8212
- }
8213
- }
8214
- }
8215
- env ||= project.config.environment || "node";
8216
- const transformMode = getTransformMode(
8217
- project.config.testTransformMode,
8218
- file
8219
- );
8220
- let envOptionsJson = code.match(/@(?:vitest|jest)-environment-options\s+(.+)/)?.[1];
8221
- if (envOptionsJson?.endsWith("*/")) {
8222
- envOptionsJson = envOptionsJson.slice(0, -2);
8223
- }
8224
- const envOptions = JSON.parse(envOptionsJson || "null");
8225
- const envKey = env === "happy-dom" ? "happyDOM" : env;
8226
- const environment = {
8227
- name: env,
8228
- transformMode,
8229
- options: envOptions ? { [envKey]: envOptions } : null
8230
- };
8231
- return {
8232
- file,
8233
- project,
8234
- environment
8235
- };
8236
- })
8237
- );
8238
- return groupBy(filesWithEnv, ({ environment }) => environment.name);
8239
- }
8240
-
8241
- const created = /* @__PURE__ */ new Set();
8242
- const promises = /* @__PURE__ */ new Map();
8243
- function createMethodsRPC(project, options = {}) {
8244
- const ctx = project.ctx;
8245
- const cacheFs = options.cacheFs ?? false;
8246
- return {
8247
- snapshotSaved(snapshot) {
8248
- ctx.snapshot.add(snapshot);
8249
- },
8250
- resolveSnapshotPath(testPath) {
8251
- return ctx.snapshot.resolvePath(testPath);
8252
- },
8253
- async getSourceMap(id, force) {
8254
- if (force) {
8255
- const mod = project.server.moduleGraph.getModuleById(id);
8256
- if (mod) {
8257
- project.server.moduleGraph.invalidateModule(mod);
8258
- }
8259
- }
8260
- const r = await project.vitenode.transformRequest(id);
8261
- return r?.map;
8262
- },
8263
- async fetch(id, transformMode) {
8264
- const result = await project.vitenode.fetchResult(id, transformMode);
8265
- const code = result.code;
8266
- if (!cacheFs || result.externalize) {
8267
- return result;
8268
- }
8269
- if ("id" in result && typeof result.id === "string") {
8270
- return { id: result.id };
8271
- }
8272
- if (code == null) {
8273
- throw new Error(`Failed to fetch module ${id}`);
8274
- }
8275
- const dir = join(project.tmpDir, transformMode);
8276
- const name = createHash$2("sha1").update(id).digest("hex");
8277
- const tmp = join(dir, name);
8278
- if (promises.has(tmp)) {
8279
- await promises.get(tmp);
8280
- return { id: tmp };
8281
- }
8282
- if (!created.has(dir)) {
8283
- await mkdir(dir, { recursive: true });
8284
- created.add(dir);
8285
- }
8286
- promises.set(
8287
- tmp,
8288
- writeFile(tmp, code, "utf-8").finally(() => promises.delete(tmp))
8289
- );
8290
- await promises.get(tmp);
8291
- Object.assign(result, { id: tmp });
8292
- return { id: tmp };
8293
- },
8294
- resolveId(id, importer, transformMode) {
8295
- return project.vitenode.resolveId(id, importer, transformMode);
8296
- },
8297
- transform(id, environment) {
8298
- return project.vitenode.transformModule(id, environment);
8299
- },
8300
- onPathsCollected(paths) {
8301
- ctx.state.collectPaths(paths);
8302
- return ctx.report("onPathsCollected", paths);
8303
- },
8304
- onCollected(files) {
8305
- ctx.state.collectFiles(project, files);
8306
- return ctx.report("onCollected", files);
8307
- },
8308
- onAfterSuiteRun(meta) {
8309
- ctx.coverageProvider?.onAfterSuiteRun(meta);
8310
- },
8311
- onTaskUpdate(packs) {
8312
- ctx.state.updateTasks(packs);
8313
- return ctx.report("onTaskUpdate", packs);
8314
- },
8315
- onUserConsoleLog(log) {
8316
- ctx.state.updateUserLog(log);
8317
- ctx.report("onUserConsoleLog", log);
8318
- },
8319
- onUnhandledError(err, type) {
8320
- ctx.state.catchError(err, type);
8321
- },
8322
- onFinished(files) {
8323
- return ctx.report("onFinished", files, ctx.state.getUnhandledErrors());
8324
- },
8325
- onCancel(reason) {
8326
- ctx.cancelCurrentRun(reason);
8327
- },
8328
- getCountOfFailedTests() {
8329
- return ctx.state.getCountOfFailedTests();
8330
- }
8331
- };
8185
+ async function loadCustomReporterModule(path, runner) {
8186
+ let customReporterModule;
8187
+ try {
8188
+ customReporterModule = await runner.executeId(path);
8189
+ } catch (customReporterModuleError) {
8190
+ throw new Error(`Failed to load custom Reporter from ${path}`, {
8191
+ cause: customReporterModuleError
8192
+ });
8193
+ }
8194
+ if (customReporterModule.default === null || customReporterModule.default === void 0) {
8195
+ throw new Error(
8196
+ `Custom reporter loaded from ${path} was not the default export`
8197
+ );
8198
+ }
8199
+ return customReporterModule.default;
8332
8200
  }
8333
-
8334
- function createChildProcessChannel$1(project) {
8335
- const emitter = new EventEmitter$2();
8336
- const cleanup = () => emitter.removeAllListeners();
8337
- const events = { message: "message", response: "response" };
8338
- const channel = {
8339
- onMessage: (callback) => emitter.on(events.message, callback),
8340
- postMessage: (message) => emitter.emit(events.response, message)
8341
- };
8342
- const rpc = createBirpc(createMethodsRPC(project, { cacheFs: true }), {
8343
- eventNames: ["onCancel"],
8344
- serialize: v8.serialize,
8345
- deserialize: (v) => v8.deserialize(Buffer.from(v)),
8346
- post(v) {
8347
- emitter.emit(events.message, v);
8348
- },
8349
- on(fn) {
8350
- emitter.on(events.response, fn);
8351
- },
8352
- onTimeoutError(functionName) {
8353
- throw new Error(`[vitest-pool]: Timeout calling "${functionName}"`);
8354
- }
8355
- });
8356
- project.ctx.onCancel((reason) => rpc.onCancel(reason));
8357
- return { channel, cleanup };
8358
- }
8359
- function createForksPool(ctx, { execArgv, env }) {
8360
- const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
8361
- const threadsCount = ctx.config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
8362
- const poolOptions = ctx.config.poolOptions?.forks ?? {};
8363
- const maxThreads = poolOptions.maxForks ?? ctx.config.maxWorkers ?? threadsCount;
8364
- const minThreads = poolOptions.minForks ?? ctx.config.minWorkers ?? threadsCount;
8365
- const worker = resolve(ctx.distPath, "workers/forks.js");
8366
- const options = {
8367
- runtime: "child_process",
8368
- filename: resolve(ctx.distPath, "worker.js"),
8369
- maxThreads,
8370
- minThreads,
8371
- env,
8372
- execArgv: [...poolOptions.execArgv ?? [], ...execArgv],
8373
- terminateTimeout: ctx.config.teardownTimeout,
8374
- concurrentTasksPerWorker: 1
8375
- };
8376
- const isolated = poolOptions.isolate ?? true;
8377
- if (isolated) {
8378
- options.isolateWorkers = true;
8379
- }
8380
- if (poolOptions.singleFork || !ctx.config.fileParallelism) {
8381
- options.maxThreads = 1;
8382
- options.minThreads = 1;
8383
- }
8384
- const pool = new Tinypool(options);
8385
- const runWithFiles = (name) => {
8386
- let id = 0;
8387
- async function runFiles(project, config, files, environment, invalidates = []) {
8388
- ctx.state.clearFiles(project, files);
8389
- const { channel, cleanup } = createChildProcessChannel$1(project);
8390
- const workerId = ++id;
8391
- const data = {
8392
- pool: "forks",
8393
- worker,
8394
- config,
8395
- files,
8396
- invalidates,
8397
- environment,
8398
- workerId,
8399
- projectName: project.getName(),
8400
- providedContext: project.getProvidedContext()
8401
- };
8402
- try {
8403
- await pool.run(data, { name, channel });
8404
- } catch (error) {
8405
- if (error instanceof Error && /Failed to terminate worker/.test(error.message)) {
8406
- ctx.state.addProcessTimeoutCause(
8407
- `Failed to terminate worker while running ${files.join(", ")}.`
8408
- );
8409
- } else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message)) {
8410
- ctx.state.cancelFiles(files, project);
8411
- } else {
8412
- throw error;
8413
- }
8414
- } finally {
8415
- cleanup();
8416
- }
8417
- }
8418
- return async (specs, invalidates) => {
8419
- ctx.onCancel(() => pool.cancelPendingTasks());
8420
- const configs = /* @__PURE__ */ new Map();
8421
- const getConfig = (project) => {
8422
- if (configs.has(project)) {
8423
- return configs.get(project);
8424
- }
8425
- const _config = project.getSerializableConfig();
8426
- const config = wrapSerializableConfig(_config);
8427
- configs.set(project, config);
8428
- return config;
8429
- };
8430
- const workspaceMap = /* @__PURE__ */ new Map();
8431
- for (const [project, file] of specs) {
8432
- const workspaceFiles = workspaceMap.get(file) ?? [];
8433
- workspaceFiles.push(project);
8434
- workspaceMap.set(file, workspaceFiles);
8435
- }
8436
- const singleFork = specs.filter(
8437
- ([project]) => project.config.poolOptions?.forks?.singleFork
8438
- );
8439
- const multipleForks = specs.filter(
8440
- ([project]) => !project.config.poolOptions?.forks?.singleFork
8441
- );
8442
- if (multipleForks.length) {
8443
- const filesByEnv = await groupFilesByEnv(multipleForks);
8444
- const files = Object.values(filesByEnv).flat();
8445
- const results = [];
8446
- if (isolated) {
8447
- results.push(
8448
- ...await Promise.allSettled(
8449
- files.map(
8450
- ({ file, environment, project }) => runFiles(
8451
- project,
8452
- getConfig(project),
8453
- [file],
8454
- environment,
8455
- invalidates
8456
- )
8457
- )
8458
- )
8201
+ function createReporters(reporterReferences, ctx) {
8202
+ const runner = ctx.runner;
8203
+ const promisedReporters = reporterReferences.map(
8204
+ async (referenceOrInstance) => {
8205
+ if (Array.isArray(referenceOrInstance)) {
8206
+ const [reporterName, reporterOptions] = referenceOrInstance;
8207
+ if (reporterName === "html") {
8208
+ await ctx.packageInstaller.ensureInstalled("@vitest/ui", runner.root);
8209
+ const CustomReporter = await loadCustomReporterModule(
8210
+ "@vitest/ui/reporter",
8211
+ runner
8459
8212
  );
8213
+ return new CustomReporter(reporterOptions);
8214
+ } else if (reporterName in ReportersMap) {
8215
+ const BuiltinReporter = ReportersMap[reporterName];
8216
+ return new BuiltinReporter(reporterOptions);
8460
8217
  } else {
8461
- const grouped = groupBy(
8462
- files,
8463
- ({ project, environment }) => project.getName() + environment.name + JSON.stringify(environment.options)
8464
- );
8465
- for (const group of Object.values(grouped)) {
8466
- results.push(
8467
- ...await Promise.allSettled(
8468
- group.map(
8469
- ({ file, environment, project }) => runFiles(
8470
- project,
8471
- getConfig(project),
8472
- [file],
8473
- environment,
8474
- invalidates
8475
- )
8476
- )
8477
- )
8478
- );
8479
- await new Promise(
8480
- (resolve2) => pool.queueSize === 0 ? resolve2() : pool.once("drain", resolve2)
8481
- );
8482
- await pool.recycleWorkers();
8483
- }
8484
- }
8485
- const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
8486
- if (errors.length > 0) {
8487
- throw new AggregateError(
8488
- errors,
8489
- "Errors occurred while running tests. For more information, see serialized error."
8490
- );
8491
- }
8492
- }
8493
- if (singleFork.length) {
8494
- const filesByEnv = await groupFilesByEnv(singleFork);
8495
- const envs = envsOrder.concat(
8496
- Object.keys(filesByEnv).filter((env2) => !envsOrder.includes(env2))
8497
- );
8498
- for (const env2 of envs) {
8499
- const files = filesByEnv[env2];
8500
- if (!files?.length) {
8501
- continue;
8502
- }
8503
- const filesByOptions = groupBy(
8504
- files,
8505
- ({ project, environment }) => project.getName() + JSON.stringify(environment.options)
8506
- );
8507
- for (const files2 of Object.values(filesByOptions)) {
8508
- await pool.recycleWorkers();
8509
- const filenames = files2.map((f) => f.file);
8510
- await runFiles(
8511
- files2[0].project,
8512
- getConfig(files2[0].project),
8513
- filenames,
8514
- files2[0].environment,
8515
- invalidates
8516
- );
8517
- }
8518
- }
8519
- }
8520
- };
8521
- };
8522
- return {
8523
- name: "forks",
8524
- runTests: runWithFiles("run"),
8525
- collectTests: runWithFiles("collect"),
8526
- close: () => pool.destroy()
8527
- };
8528
- }
8529
-
8530
- function createWorkerChannel$1(project) {
8531
- const channel = new MessageChannel();
8532
- const port = channel.port2;
8533
- const workerPort = channel.port1;
8534
- const rpc = createBirpc(createMethodsRPC(project), {
8535
- eventNames: ["onCancel"],
8536
- post(v) {
8537
- port.postMessage(v);
8538
- },
8539
- on(fn) {
8540
- port.on("message", fn);
8541
- },
8542
- onTimeoutError(functionName) {
8543
- throw new Error(`[vitest-pool]: Timeout calling "${functionName}"`);
8544
- }
8545
- });
8546
- project.ctx.onCancel((reason) => rpc.onCancel(reason));
8547
- return { workerPort, port };
8548
- }
8549
- function createThreadsPool(ctx, { execArgv, env }) {
8550
- const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
8551
- const threadsCount = ctx.config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
8552
- const poolOptions = ctx.config.poolOptions?.threads ?? {};
8553
- const maxThreads = poolOptions.maxThreads ?? ctx.config.maxWorkers ?? threadsCount;
8554
- const minThreads = poolOptions.minThreads ?? ctx.config.minWorkers ?? threadsCount;
8555
- const worker = resolve(ctx.distPath, "workers/threads.js");
8556
- const options = {
8557
- filename: resolve(ctx.distPath, "worker.js"),
8558
- // TODO: investigate further
8559
- // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
8560
- useAtomics: poolOptions.useAtomics ?? false,
8561
- maxThreads,
8562
- minThreads,
8563
- env,
8564
- execArgv: [...poolOptions.execArgv ?? [], ...execArgv],
8565
- terminateTimeout: ctx.config.teardownTimeout,
8566
- concurrentTasksPerWorker: 1
8567
- };
8568
- const isolated = poolOptions.isolate ?? true;
8569
- if (isolated) {
8570
- options.isolateWorkers = true;
8571
- }
8572
- if (poolOptions.singleThread || !ctx.config.fileParallelism) {
8573
- options.maxThreads = 1;
8574
- options.minThreads = 1;
8575
- }
8576
- const pool = new Tinypool$1(options);
8577
- const runWithFiles = (name) => {
8578
- let id = 0;
8579
- async function runFiles(project, config, files, environment, invalidates = []) {
8580
- ctx.state.clearFiles(project, files);
8581
- const { workerPort, port } = createWorkerChannel$1(project);
8582
- const workerId = ++id;
8583
- const data = {
8584
- pool: "threads",
8585
- worker,
8586
- port: workerPort,
8587
- config,
8588
- files,
8589
- invalidates,
8590
- environment,
8591
- workerId,
8592
- projectName: project.getName(),
8593
- providedContext: project.getProvidedContext()
8594
- };
8595
- try {
8596
- await pool.run(data, { transferList: [workerPort], name });
8597
- } catch (error) {
8598
- if (error instanceof Error && /Failed to terminate worker/.test(error.message)) {
8599
- ctx.state.addProcessTimeoutCause(
8600
- `Failed to terminate worker while running ${files.join(
8601
- ", "
8602
- )}.
8603
- See https://vitest.dev/guide/common-errors.html#failed-to-terminate-worker for troubleshooting.`
8218
+ const CustomReporter = await loadCustomReporterModule(
8219
+ reporterName,
8220
+ runner
8604
8221
  );
8605
- } else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message)) {
8606
- ctx.state.cancelFiles(files, project);
8607
- } else {
8608
- throw error;
8222
+ return new CustomReporter(reporterOptions);
8609
8223
  }
8610
- } finally {
8611
- port.close();
8612
- workerPort.close();
8613
8224
  }
8225
+ return referenceOrInstance;
8614
8226
  }
8615
- return async (specs, invalidates) => {
8616
- ctx.onCancel(() => pool.cancelPendingTasks());
8617
- const configs = /* @__PURE__ */ new Map();
8618
- const getConfig = (project) => {
8619
- if (configs.has(project)) {
8620
- return configs.get(project);
8621
- }
8622
- const config = project.getSerializableConfig();
8623
- configs.set(project, config);
8624
- return config;
8625
- };
8626
- const workspaceMap = /* @__PURE__ */ new Map();
8627
- for (const [project, file] of specs) {
8628
- const workspaceFiles = workspaceMap.get(file) ?? [];
8629
- workspaceFiles.push(project);
8630
- workspaceMap.set(file, workspaceFiles);
8631
- }
8632
- const singleThreads = specs.filter(
8633
- ([project]) => project.config.poolOptions?.threads?.singleThread
8634
- );
8635
- const multipleThreads = specs.filter(
8636
- ([project]) => !project.config.poolOptions?.threads?.singleThread
8637
- );
8638
- if (multipleThreads.length) {
8639
- const filesByEnv = await groupFilesByEnv(multipleThreads);
8640
- const files = Object.values(filesByEnv).flat();
8641
- const results = [];
8642
- if (isolated) {
8643
- results.push(
8644
- ...await Promise.allSettled(
8645
- files.map(
8646
- ({ file, environment, project }) => runFiles(
8647
- project,
8648
- getConfig(project),
8649
- [file],
8650
- environment,
8651
- invalidates
8652
- )
8653
- )
8654
- )
8655
- );
8227
+ );
8228
+ return Promise.all(promisedReporters);
8229
+ }
8230
+ function createBenchmarkReporters(reporterReferences, runner) {
8231
+ const promisedReporters = reporterReferences.map(
8232
+ async (referenceOrInstance) => {
8233
+ if (typeof referenceOrInstance === "string") {
8234
+ if (referenceOrInstance in BenchmarkReportsMap) {
8235
+ const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance];
8236
+ return new BuiltinReporter();
8656
8237
  } else {
8657
- const grouped = groupBy(
8658
- files,
8659
- ({ project, environment }) => project.getName() + environment.name + JSON.stringify(environment.options)
8660
- );
8661
- for (const group of Object.values(grouped)) {
8662
- results.push(
8663
- ...await Promise.allSettled(
8664
- group.map(
8665
- ({ file, environment, project }) => runFiles(
8666
- project,
8667
- getConfig(project),
8668
- [file],
8669
- environment,
8670
- invalidates
8671
- )
8672
- )
8673
- )
8674
- );
8675
- await new Promise(
8676
- (resolve2) => pool.queueSize === 0 ? resolve2() : pool.once("drain", resolve2)
8677
- );
8678
- await pool.recycleWorkers();
8679
- }
8680
- }
8681
- const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
8682
- if (errors.length > 0) {
8683
- throw new AggregateErrorPonyfill(
8684
- errors,
8685
- "Errors occurred while running tests. For more information, see serialized error."
8686
- );
8687
- }
8688
- }
8689
- if (singleThreads.length) {
8690
- const filesByEnv = await groupFilesByEnv(singleThreads);
8691
- const envs = envsOrder.concat(
8692
- Object.keys(filesByEnv).filter((env2) => !envsOrder.includes(env2))
8693
- );
8694
- for (const env2 of envs) {
8695
- const files = filesByEnv[env2];
8696
- if (!files?.length) {
8697
- continue;
8698
- }
8699
- const filesByOptions = groupBy(
8700
- files,
8701
- ({ project, environment }) => project.getName() + JSON.stringify(environment.options)
8238
+ const CustomReporter = await loadCustomReporterModule(
8239
+ referenceOrInstance,
8240
+ runner
8702
8241
  );
8703
- for (const files2 of Object.values(filesByOptions)) {
8704
- await pool.recycleWorkers();
8705
- const filenames = files2.map((f) => f.file);
8706
- await runFiles(
8707
- files2[0].project,
8708
- getConfig(files2[0].project),
8709
- filenames,
8710
- files2[0].environment,
8711
- invalidates
8712
- );
8713
- }
8242
+ return new CustomReporter();
8714
8243
  }
8715
8244
  }
8716
- };
8717
- };
8718
- return {
8719
- name: "threads",
8720
- runTests: runWithFiles("run"),
8721
- collectTests: runWithFiles("collect"),
8722
- close: () => pool.destroy()
8723
- };
8245
+ return referenceOrInstance;
8246
+ }
8247
+ );
8248
+ return Promise.all(promisedReporters);
8724
8249
  }
8725
8250
 
8726
- function getDefaultThreadsCount(config) {
8727
- const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
8728
- return config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
8729
- }
8730
- function getWorkerMemoryLimit(config) {
8731
- const memoryLimit = config.poolOptions?.vmThreads?.memoryLimit;
8732
- if (memoryLimit) {
8733
- return memoryLimit;
8734
- }
8735
- return 1 / (config.poolOptions?.vmThreads?.maxThreads ?? getDefaultThreadsCount(config));
8736
- }
8737
- function stringToBytes(input, percentageReference) {
8738
- if (input === null || input === void 0) {
8739
- return input;
8740
- }
8741
- if (typeof input === "string") {
8742
- if (Number.isNaN(Number.parseFloat(input.slice(-1)))) {
8743
- let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/) || [];
8744
- if (trailingChars && numericString) {
8745
- const numericValue = Number.parseFloat(numericString);
8746
- trailingChars = trailingChars.toLowerCase();
8747
- switch (trailingChars) {
8748
- case "%":
8749
- input = numericValue / 100;
8750
- break;
8751
- case "kb":
8752
- case "k":
8753
- return numericValue * 1e3;
8754
- case "kib":
8755
- return numericValue * 1024;
8756
- case "mb":
8757
- case "m":
8758
- return numericValue * 1e3 * 1e3;
8759
- case "mib":
8760
- return numericValue * 1024 * 1024;
8761
- case "gb":
8762
- case "g":
8763
- return numericValue * 1e3 * 1e3 * 1e3;
8764
- case "gib":
8765
- return numericValue * 1024 * 1024 * 1024;
8766
- }
8767
- }
8768
- } else {
8769
- input = Number.parseFloat(input);
8770
- }
8771
- }
8772
- if (typeof input === "number") {
8773
- if (input <= 1 && input > 0) {
8774
- if (percentageReference) {
8775
- return Math.floor(input * percentageReference);
8776
- } else {
8777
- throw new Error(
8778
- "For a percentage based memory limit a percentageReference must be supplied"
8779
- );
8780
- }
8781
- } else if (input > 1) {
8782
- return Math.floor(input);
8783
- } else {
8784
- throw new Error('Unexpected numerical input for "memoryLimit"');
8785
- }
8251
+ function isAggregateError(err) {
8252
+ if (typeof AggregateError !== "undefined" && err instanceof AggregateError) {
8253
+ return true;
8786
8254
  }
8787
- return null;
8255
+ return err instanceof Error && "errors" in err;
8788
8256
  }
8789
-
8790
- const suppressWarningsPath$1 = resolve(rootDir, "./suppress-warnings.cjs");
8791
- function createWorkerChannel(project) {
8792
- const channel = new MessageChannel();
8793
- const port = channel.port2;
8794
- const workerPort = channel.port1;
8795
- const rpc = createBirpc(createMethodsRPC(project), {
8796
- eventNames: ["onCancel"],
8797
- post(v) {
8798
- port.postMessage(v);
8799
- },
8800
- on(fn) {
8801
- port.on("message", fn);
8802
- },
8803
- onTimeoutError(functionName) {
8804
- throw new Error(`[vitest-pool]: Timeout calling "${functionName}"`);
8257
+ class StateManager {
8258
+ filesMap = /* @__PURE__ */ new Map();
8259
+ pathsSet = /* @__PURE__ */ new Set();
8260
+ idMap = /* @__PURE__ */ new Map();
8261
+ taskFileMap = /* @__PURE__ */ new WeakMap();
8262
+ errorsSet = /* @__PURE__ */ new Set();
8263
+ processTimeoutCauses = /* @__PURE__ */ new Set();
8264
+ reportedTasksMap = /* @__PURE__ */ new WeakMap();
8265
+ catchError(err, type) {
8266
+ if (isAggregateError(err)) {
8267
+ return err.errors.forEach((error) => this.catchError(error, type));
8805
8268
  }
8806
- });
8807
- project.ctx.onCancel((reason) => rpc.onCancel(reason));
8808
- return { workerPort, port };
8809
- }
8810
- function createVmThreadsPool(ctx, { execArgv, env }) {
8811
- const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
8812
- const threadsCount = ctx.config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
8813
- const poolOptions = ctx.config.poolOptions?.vmThreads ?? {};
8814
- const maxThreads = poolOptions.maxThreads ?? ctx.config.maxWorkers ?? threadsCount;
8815
- const minThreads = poolOptions.minThreads ?? ctx.config.minWorkers ?? threadsCount;
8816
- const worker = resolve(ctx.distPath, "workers/vmThreads.js");
8817
- const options = {
8818
- filename: resolve(ctx.distPath, "worker.js"),
8819
- // TODO: investigate further
8820
- // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
8821
- useAtomics: poolOptions.useAtomics ?? false,
8822
- maxThreads,
8823
- minThreads,
8824
- env,
8825
- execArgv: [
8826
- "--experimental-import-meta-resolve",
8827
- "--experimental-vm-modules",
8828
- "--require",
8829
- suppressWarningsPath$1,
8830
- ...poolOptions.execArgv ?? [],
8831
- ...execArgv
8832
- ],
8833
- terminateTimeout: ctx.config.teardownTimeout,
8834
- concurrentTasksPerWorker: 1,
8835
- maxMemoryLimitBeforeRecycle: getMemoryLimit$1(ctx.config) || void 0
8836
- };
8837
- if (poolOptions.singleThread || !ctx.config.fileParallelism) {
8838
- options.maxThreads = 1;
8839
- options.minThreads = 1;
8840
- }
8841
- const pool = new Tinypool$1(options);
8842
- const runWithFiles = (name) => {
8843
- let id = 0;
8844
- async function runFiles(project, config, files, environment, invalidates = []) {
8845
- ctx.state.clearFiles(project, files);
8846
- const { workerPort, port } = createWorkerChannel(project);
8847
- const workerId = ++id;
8848
- const data = {
8849
- pool: "vmThreads",
8850
- worker,
8851
- port: workerPort,
8852
- config,
8853
- files,
8854
- invalidates,
8855
- environment,
8856
- workerId,
8857
- projectName: project.getName(),
8858
- providedContext: project.getProvidedContext()
8859
- };
8860
- try {
8861
- await pool.run(data, { transferList: [workerPort], name });
8862
- } catch (error) {
8863
- if (error instanceof Error && /Failed to terminate worker/.test(error.message)) {
8864
- ctx.state.addProcessTimeoutCause(
8865
- `Failed to terminate worker while running ${files.join(
8866
- ", "
8867
- )}.
8868
- See https://vitest.dev/guide/common-errors.html#failed-to-terminate-worker for troubleshooting.`
8869
- );
8870
- } else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message)) {
8871
- ctx.state.cancelFiles(files, project);
8872
- } else {
8873
- throw error;
8874
- }
8875
- } finally {
8876
- port.close();
8877
- workerPort.close();
8878
- }
8269
+ if (err === Object(err)) {
8270
+ err.type = type;
8271
+ } else {
8272
+ err = { type, message: err };
8879
8273
  }
8880
- return async (specs, invalidates) => {
8881
- ctx.onCancel(() => pool.cancelPendingTasks());
8882
- const configs = /* @__PURE__ */ new Map();
8883
- const getConfig = (project) => {
8884
- if (configs.has(project)) {
8885
- return configs.get(project);
8886
- }
8887
- const config = project.getSerializableConfig();
8888
- configs.set(project, config);
8889
- return config;
8890
- };
8891
- const filesByEnv = await groupFilesByEnv(specs);
8892
- const promises = Object.values(filesByEnv).flat();
8893
- const results = await Promise.allSettled(
8894
- promises.map(
8895
- ({ file, environment, project }) => runFiles(
8896
- project,
8897
- getConfig(project),
8898
- [file],
8899
- environment,
8900
- invalidates
8901
- )
8902
- )
8903
- );
8904
- const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
8905
- if (errors.length > 0) {
8906
- throw new AggregateErrorPonyfill(
8907
- errors,
8908
- "Errors occurred while running tests. For more information, see serialized error."
8909
- );
8274
+ const _err = err;
8275
+ if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
8276
+ const task = this.idMap.get(_err.taskId);
8277
+ if (task) {
8278
+ task.mode = "skip";
8279
+ task.result ??= { state: "skip" };
8280
+ task.result.state = "skip";
8910
8281
  }
8911
- };
8912
- };
8913
- return {
8914
- name: "vmThreads",
8915
- runTests: runWithFiles("run"),
8916
- collectTests: runWithFiles("collect"),
8917
- close: () => pool.destroy()
8918
- };
8919
- }
8920
- function getMemoryLimit$1(config) {
8921
- const memory = nodeos.totalmem();
8922
- const limit = getWorkerMemoryLimit(config);
8923
- if (typeof memory === "number") {
8924
- return stringToBytes(limit, config.watch ? memory / 2 : memory);
8282
+ return;
8283
+ }
8284
+ this.errorsSet.add(err);
8925
8285
  }
8926
- if (typeof limit === "number" && limit > 1 || typeof limit === "string" && limit.at(-1) !== "%") {
8927
- return stringToBytes(limit);
8286
+ clearErrors() {
8287
+ this.errorsSet.clear();
8928
8288
  }
8929
- return null;
8930
- }
8931
-
8932
- function createTypecheckPool(ctx) {
8933
- const promisesMap = /* @__PURE__ */ new WeakMap();
8934
- const rerunTriggered = /* @__PURE__ */ new WeakMap();
8935
- async function onParseEnd(project, { files, sourceErrors }) {
8936
- const checker = project.typechecker;
8937
- await ctx.report("onTaskUpdate", checker.getTestPacks());
8938
- if (!project.config.typecheck.ignoreSourceErrors) {
8939
- sourceErrors.forEach(
8940
- (error) => ctx.state.catchError(error, "Unhandled Source Error")
8941
- );
8942
- }
8943
- const processError = !hasFailed(files) && !sourceErrors.length && checker.getExitCode();
8944
- if (processError) {
8945
- const error = new Error(checker.getOutput());
8946
- error.stack = "";
8947
- ctx.state.catchError(error, "Typecheck Error");
8948
- }
8949
- promisesMap.get(project)?.resolve();
8950
- rerunTriggered.set(project, false);
8951
- if (ctx.config.watch && !ctx.runningPromise) {
8952
- await ctx.report("onFinished", files, []);
8953
- await ctx.report("onWatcherStart", files, [
8954
- ...project.config.typecheck.ignoreSourceErrors ? [] : sourceErrors,
8955
- ...ctx.state.getUnhandledErrors()
8956
- ]);
8957
- }
8958
- }
8959
- async function createWorkspaceTypechecker(project, files) {
8960
- const checker = project.typechecker ?? new Typechecker(project);
8961
- if (project.typechecker) {
8962
- return checker;
8963
- }
8964
- project.typechecker = checker;
8965
- checker.setFiles(files);
8966
- checker.onParseStart(async () => {
8967
- ctx.state.collectFiles(project, checker.getTestFiles());
8968
- await ctx.report("onCollected");
8969
- });
8970
- checker.onParseEnd((result) => onParseEnd(project, result));
8971
- checker.onWatcherRerun(async () => {
8972
- rerunTriggered.set(project, true);
8973
- if (!ctx.runningPromise) {
8974
- ctx.state.clearErrors();
8975
- await ctx.report(
8976
- "onWatcherRerun",
8977
- files,
8978
- "File change detected. Triggering rerun."
8979
- );
8980
- }
8981
- await checker.collectTests();
8982
- ctx.state.collectFiles(project, checker.getTestFiles());
8983
- await ctx.report("onTaskUpdate", checker.getTestPacks());
8984
- await ctx.report("onCollected");
8985
- });
8986
- await checker.prepare();
8987
- return checker;
8988
- }
8989
- async function startTypechecker(project, files) {
8990
- if (project.typechecker) {
8991
- return project.typechecker;
8992
- }
8993
- const checker = await createWorkspaceTypechecker(project, files);
8994
- await checker.collectTests();
8995
- await checker.start();
8996
- }
8997
- async function collectTests(specs) {
8998
- const specsByProject = groupBy(specs, ([project]) => project.getName());
8999
- for (const name in specsByProject) {
9000
- const project = specsByProject[name][0][0];
9001
- const files = specsByProject[name].map(([_, file]) => file);
9002
- const checker = await createWorkspaceTypechecker(project, files);
9003
- checker.setFiles(files);
9004
- await checker.collectTests();
9005
- ctx.state.collectFiles(project, checker.getTestFiles());
9006
- await ctx.report("onCollected");
9007
- }
9008
- }
9009
- async function runTests(specs) {
9010
- const specsByProject = groupBy(specs, ([project]) => project.getName());
9011
- const promises = [];
9012
- for (const name in specsByProject) {
9013
- const project = specsByProject[name][0][0];
9014
- const files = specsByProject[name].map(([_, file]) => file);
9015
- const promise = createDefer();
9016
- const _p = new Promise((resolve) => {
9017
- const _i = setInterval(() => {
9018
- if (!project.typechecker || rerunTriggered.get(project)) {
9019
- resolve(true);
9020
- clearInterval(_i);
9021
- }
9022
- });
9023
- setTimeout(() => {
9024
- resolve(false);
9025
- clearInterval(_i);
9026
- }, 500).unref();
9027
- });
9028
- const triggered = await _p;
9029
- if (project.typechecker && !triggered) {
9030
- ctx.state.collectFiles(project, project.typechecker.getTestFiles());
9031
- await ctx.report("onCollected");
9032
- await onParseEnd(project, project.typechecker.getResult());
9033
- continue;
9034
- }
9035
- promises.push(promise);
9036
- promisesMap.set(project, promise);
9037
- startTypechecker(project, files);
9038
- }
9039
- await Promise.all(promises);
8289
+ getUnhandledErrors() {
8290
+ return Array.from(this.errorsSet.values());
9040
8291
  }
9041
- return {
9042
- name: "typescript",
9043
- runTests,
9044
- collectTests,
9045
- async close() {
9046
- const promises = ctx.projects.map(
9047
- (project) => project.typechecker?.stop()
9048
- );
9049
- await Promise.all(promises);
9050
- }
9051
- };
9052
- }
9053
-
9054
- const suppressWarningsPath = resolve(rootDir, "./suppress-warnings.cjs");
9055
- function createChildProcessChannel(project) {
9056
- const emitter = new EventEmitter$2();
9057
- const cleanup = () => emitter.removeAllListeners();
9058
- const events = { message: "message", response: "response" };
9059
- const channel = {
9060
- onMessage: (callback) => emitter.on(events.message, callback),
9061
- postMessage: (message) => emitter.emit(events.response, message)
9062
- };
9063
- const rpc = createBirpc(
9064
- createMethodsRPC(project, { cacheFs: true }),
9065
- {
9066
- eventNames: ["onCancel"],
9067
- serialize: v8.serialize,
9068
- deserialize: (v) => v8.deserialize(Buffer.from(v)),
9069
- post(v) {
9070
- emitter.emit(events.message, v);
9071
- },
9072
- on(fn) {
9073
- emitter.on(events.response, fn);
9074
- },
9075
- onTimeoutError(functionName) {
9076
- throw new Error(`[vitest-pool]: Timeout calling "${functionName}"`);
9077
- }
9078
- }
9079
- );
9080
- project.ctx.onCancel((reason) => rpc.onCancel(reason));
9081
- return { channel, cleanup };
9082
- }
9083
- function createVmForksPool(ctx, { execArgv, env }) {
9084
- const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
9085
- const threadsCount = ctx.config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
9086
- const poolOptions = ctx.config.poolOptions?.vmForks ?? {};
9087
- const maxThreads = poolOptions.maxForks ?? ctx.config.maxWorkers ?? threadsCount;
9088
- const minThreads = poolOptions.maxForks ?? ctx.config.minWorkers ?? threadsCount;
9089
- const worker = resolve(ctx.distPath, "workers/vmForks.js");
9090
- const options = {
9091
- runtime: "child_process",
9092
- filename: resolve(ctx.distPath, "worker.js"),
9093
- maxThreads,
9094
- minThreads,
9095
- env,
9096
- execArgv: [
9097
- "--experimental-import-meta-resolve",
9098
- "--experimental-vm-modules",
9099
- "--require",
9100
- suppressWarningsPath,
9101
- ...poolOptions.execArgv ?? [],
9102
- ...execArgv
9103
- ],
9104
- terminateTimeout: ctx.config.teardownTimeout,
9105
- concurrentTasksPerWorker: 1,
9106
- maxMemoryLimitBeforeRecycle: getMemoryLimit(ctx.config) || void 0
9107
- };
9108
- if (poolOptions.singleFork || !ctx.config.fileParallelism) {
9109
- options.maxThreads = 1;
9110
- options.minThreads = 1;
9111
- }
9112
- const pool = new Tinypool$1(options);
9113
- const runWithFiles = (name) => {
9114
- let id = 0;
9115
- async function runFiles(project, config, files, environment, invalidates = []) {
9116
- ctx.state.clearFiles(project, files);
9117
- const { channel, cleanup } = createChildProcessChannel(project);
9118
- const workerId = ++id;
9119
- const data = {
9120
- pool: "forks",
9121
- worker,
9122
- config,
9123
- files,
9124
- invalidates,
9125
- environment,
9126
- workerId,
9127
- projectName: project.getName(),
9128
- providedContext: project.getProvidedContext()
9129
- };
9130
- try {
9131
- await pool.run(data, { name, channel });
9132
- } catch (error) {
9133
- if (error instanceof Error && /Failed to terminate worker/.test(error.message)) {
9134
- ctx.state.addProcessTimeoutCause(
9135
- `Failed to terminate worker while running ${files.join(", ")}.`
9136
- );
9137
- } else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message)) {
9138
- ctx.state.cancelFiles(files, project);
9139
- } else {
9140
- throw error;
9141
- }
9142
- } finally {
9143
- cleanup();
9144
- }
9145
- }
9146
- return async (specs, invalidates) => {
9147
- ctx.onCancel(() => pool.cancelPendingTasks());
9148
- const configs = /* @__PURE__ */ new Map();
9149
- const getConfig = (project) => {
9150
- if (configs.has(project)) {
9151
- return configs.get(project);
9152
- }
9153
- const _config = project.getSerializableConfig();
9154
- const config = wrapSerializableConfig(_config);
9155
- configs.set(project, config);
9156
- return config;
9157
- };
9158
- const filesByEnv = await groupFilesByEnv(specs);
9159
- const promises = Object.values(filesByEnv).flat();
9160
- const results = await Promise.allSettled(
9161
- promises.map(
9162
- ({ file, environment, project }) => runFiles(
9163
- project,
9164
- getConfig(project),
9165
- [file],
9166
- environment,
9167
- invalidates
9168
- )
9169
- )
9170
- );
9171
- const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
9172
- if (errors.length > 0) {
9173
- throw new AggregateErrorPonyfill(
9174
- errors,
9175
- "Errors occurred while running tests. For more information, see serialized error."
9176
- );
9177
- }
9178
- };
9179
- };
9180
- return {
9181
- name: "vmForks",
9182
- runTests: runWithFiles("run"),
9183
- collectTests: runWithFiles("collect"),
9184
- close: () => pool.destroy()
9185
- };
9186
- }
9187
- function getMemoryLimit(config) {
9188
- const memory = nodeos.totalmem();
9189
- const limit = getWorkerMemoryLimit(config);
9190
- if (typeof memory === "number") {
9191
- return stringToBytes(limit, config.watch ? memory / 2 : memory);
9192
- }
9193
- if (typeof limit === "number" && limit > 1 || typeof limit === "string" && limit.at(-1) !== "%") {
9194
- return stringToBytes(limit);
9195
- }
9196
- return null;
9197
- }
9198
-
9199
- const builtinPools = [
9200
- "forks",
9201
- "threads",
9202
- "browser",
9203
- "vmThreads",
9204
- "vmForks",
9205
- "typescript"
9206
- ];
9207
- function getDefaultPoolName(project, file) {
9208
- if (project.config.typecheck.enabled) {
9209
- for (const glob of project.config.typecheck.include) {
9210
- if (mm.isMatch(file, glob, { cwd: project.config.root })) {
9211
- return "typescript";
9212
- }
9213
- }
9214
- }
9215
- if (project.config.browser.enabled) {
9216
- return "browser";
9217
- }
9218
- return project.config.pool;
9219
- }
9220
- function getFilePoolName(project, file) {
9221
- for (const [glob, pool] of project.config.poolMatchGlobs) {
9222
- if (pool === "browser") {
9223
- throw new Error(
9224
- 'Since Vitest 0.31.0 "browser" pool is not supported in "poolMatchGlobs". You can create a workspace to run some of your tests in browser in parallel. Read more: https://vitest.dev/guide/workspace'
9225
- );
9226
- }
9227
- if (mm.isMatch(file, glob, { cwd: project.config.root })) {
9228
- return pool;
9229
- }
9230
- }
9231
- return getDefaultPoolName(project, file);
9232
- }
9233
- function createPool(ctx) {
9234
- const pools = {
9235
- forks: null,
9236
- threads: null,
9237
- browser: null,
9238
- vmThreads: null,
9239
- vmForks: null,
9240
- typescript: null
9241
- };
9242
- const potentialConditions = /* @__PURE__ */ new Set([
9243
- "production",
9244
- "development",
9245
- ...ctx.server.config.resolve.conditions
9246
- ]);
9247
- const conditions = [...potentialConditions].filter((condition) => {
9248
- if (condition === "production") {
9249
- return ctx.server.config.isProduction;
9250
- }
9251
- if (condition === "development") {
9252
- return !ctx.server.config.isProduction;
9253
- }
9254
- return true;
9255
- }).flatMap((c) => ["--conditions", c]);
9256
- const execArgv = process.execArgv.filter(
9257
- (execArg) => execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof") || execArg.startsWith("--diagnostic-dir")
9258
- );
9259
- async function executeTests(method, files, invalidate) {
9260
- const options = {
9261
- execArgv: [...execArgv, ...conditions],
9262
- env: {
9263
- TEST: "true",
9264
- VITEST: "true",
9265
- NODE_ENV: process.env.NODE_ENV || "test",
9266
- VITEST_MODE: ctx.config.watch ? "WATCH" : "RUN",
9267
- ...process.env,
9268
- ...ctx.config.env
9269
- }
9270
- };
9271
- if (isWindows) {
9272
- for (const name in options.env) {
9273
- options.env[name.toUpperCase()] = options.env[name];
9274
- }
9275
- }
9276
- const customPools = /* @__PURE__ */ new Map();
9277
- async function resolveCustomPool(filepath) {
9278
- if (customPools.has(filepath)) {
9279
- return customPools.get(filepath);
9280
- }
9281
- const pool = await ctx.runner.executeId(filepath);
9282
- if (typeof pool.default !== "function") {
9283
- throw new TypeError(
9284
- `Custom pool "${filepath}" must export a function as default export`
9285
- );
9286
- }
9287
- const poolInstance = await pool.default(ctx, options);
9288
- if (typeof poolInstance?.name !== "string") {
9289
- throw new TypeError(
9290
- `Custom pool "${filepath}" should return an object with "name" property`
9291
- );
9292
- }
9293
- if (typeof poolInstance?.[method] !== "function") {
9294
- throw new TypeError(
9295
- `Custom pool "${filepath}" should return an object with "${method}" method`
9296
- );
9297
- }
9298
- customPools.set(filepath, poolInstance);
9299
- return poolInstance;
9300
- }
9301
- const filesByPool = {
9302
- forks: [],
9303
- threads: [],
9304
- // browser: [],
9305
- vmThreads: [],
9306
- vmForks: [],
9307
- typescript: []
9308
- };
9309
- const factories = {
9310
- // browser: () => createBrowserPool(ctx),
9311
- vmThreads: () => createVmThreadsPool(ctx, options),
9312
- threads: () => createThreadsPool(ctx, options),
9313
- forks: () => createForksPool(ctx, options),
9314
- vmForks: () => createVmForksPool(ctx, options),
9315
- typescript: () => createTypecheckPool(ctx)
9316
- };
9317
- for (const spec of files) {
9318
- const pool = getFilePoolName(spec[0], spec[1]);
9319
- filesByPool[pool] ??= [];
9320
- filesByPool[pool].push(spec);
9321
- }
9322
- const Sequencer = ctx.config.sequence.sequencer;
9323
- const sequencer = new Sequencer(ctx);
9324
- async function sortSpecs(specs) {
9325
- if (ctx.config.shard) {
9326
- specs = await sequencer.shard(specs);
9327
- }
9328
- return sequencer.sort(specs);
9329
- }
9330
- await Promise.all(
9331
- Object.entries(filesByPool).map(async (entry) => {
9332
- const [pool, files2] = entry;
9333
- if (!files2.length) {
9334
- return null;
9335
- }
9336
- const specs = await sortSpecs(files2);
9337
- if (pool in factories) {
9338
- const factory = factories[pool];
9339
- pools[pool] ??= factory();
9340
- return pools[pool][method](specs, invalidate);
9341
- }
9342
- if (pool === "browser") {
9343
- pools[pool] ??= await (async () => {
9344
- const { createBrowserPool } = await import('@vitest/browser');
9345
- return createBrowserPool(ctx);
9346
- })();
9347
- return pools[pool][method](specs, invalidate);
9348
- }
9349
- const poolHandler = await resolveCustomPool(pool);
9350
- pools[poolHandler.name] ??= poolHandler;
9351
- return poolHandler[method](specs, invalidate);
9352
- })
9353
- );
9354
- }
9355
- return {
9356
- name: "default",
9357
- runTests: (files, invalidates) => executeTests("runTests", files, invalidates),
9358
- collectTests: (files, invalidates) => executeTests("collectTests", files, invalidates),
9359
- async close() {
9360
- await Promise.all(Object.values(pools).map((p) => p?.close?.()));
9361
- }
9362
- };
9363
- }
9364
-
9365
- async function loadCustomReporterModule(path, runner) {
9366
- let customReporterModule;
9367
- try {
9368
- customReporterModule = await runner.executeId(path);
9369
- } catch (customReporterModuleError) {
9370
- throw new Error(`Failed to load custom Reporter from ${path}`, {
9371
- cause: customReporterModuleError
9372
- });
9373
- }
9374
- if (customReporterModule.default === null || customReporterModule.default === void 0) {
9375
- throw new Error(
9376
- `Custom reporter loaded from ${path} was not the default export`
9377
- );
9378
- }
9379
- return customReporterModule.default;
9380
- }
9381
- function createReporters(reporterReferences, ctx) {
9382
- const runner = ctx.runner;
9383
- const promisedReporters = reporterReferences.map(
9384
- async (referenceOrInstance) => {
9385
- if (Array.isArray(referenceOrInstance)) {
9386
- const [reporterName, reporterOptions] = referenceOrInstance;
9387
- if (reporterName === "html") {
9388
- await ctx.packageInstaller.ensureInstalled("@vitest/ui", runner.root);
9389
- const CustomReporter = await loadCustomReporterModule(
9390
- "@vitest/ui/reporter",
9391
- runner
9392
- );
9393
- return new CustomReporter(reporterOptions);
9394
- } else if (reporterName in ReportersMap) {
9395
- const BuiltinReporter = ReportersMap[reporterName];
9396
- return new BuiltinReporter(reporterOptions);
9397
- } else {
9398
- const CustomReporter = await loadCustomReporterModule(
9399
- reporterName,
9400
- runner
9401
- );
9402
- return new CustomReporter(reporterOptions);
9403
- }
9404
- }
9405
- return referenceOrInstance;
9406
- }
9407
- );
9408
- return Promise.all(promisedReporters);
9409
- }
9410
- function createBenchmarkReporters(reporterReferences, runner) {
9411
- const promisedReporters = reporterReferences.map(
9412
- async (referenceOrInstance) => {
9413
- if (typeof referenceOrInstance === "string") {
9414
- if (referenceOrInstance in BenchmarkReportsMap) {
9415
- const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance];
9416
- return new BuiltinReporter();
9417
- } else {
9418
- const CustomReporter = await loadCustomReporterModule(
9419
- referenceOrInstance,
9420
- runner
9421
- );
9422
- return new CustomReporter();
9423
- }
9424
- }
9425
- return referenceOrInstance;
9426
- }
9427
- );
9428
- return Promise.all(promisedReporters);
9429
- }
9430
-
9431
- function isAggregateError(err) {
9432
- if (typeof AggregateError !== "undefined" && err instanceof AggregateError) {
9433
- return true;
9434
- }
9435
- return err instanceof Error && "errors" in err;
9436
- }
9437
- class StateManager {
9438
- filesMap = /* @__PURE__ */ new Map();
9439
- pathsSet = /* @__PURE__ */ new Set();
9440
- idMap = /* @__PURE__ */ new Map();
9441
- taskFileMap = /* @__PURE__ */ new WeakMap();
9442
- errorsSet = /* @__PURE__ */ new Set();
9443
- processTimeoutCauses = /* @__PURE__ */ new Set();
9444
- reportedTasksMap = /* @__PURE__ */ new WeakMap();
9445
- catchError(err, type) {
9446
- if (isAggregateError(err)) {
9447
- return err.errors.forEach((error) => this.catchError(error, type));
9448
- }
9449
- if (err === Object(err)) {
9450
- err.type = type;
9451
- } else {
9452
- err = { type, message: err };
9453
- }
9454
- const _err = err;
9455
- if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
9456
- const task = this.idMap.get(_err.taskId);
9457
- if (task) {
9458
- task.mode = "skip";
9459
- task.result ??= { state: "skip" };
9460
- task.result.state = "skip";
9461
- }
9462
- return;
9463
- }
9464
- this.errorsSet.add(err);
9465
- }
9466
- clearErrors() {
9467
- this.errorsSet.clear();
9468
- }
9469
- getUnhandledErrors() {
9470
- return Array.from(this.errorsSet.values());
9471
- }
9472
- addProcessTimeoutCause(cause) {
9473
- this.processTimeoutCauses.add(cause);
9474
- }
9475
- getProcessTimeoutCauses() {
9476
- return Array.from(this.processTimeoutCauses.values());
9477
- }
9478
- getPaths() {
9479
- return Array.from(this.pathsSet);
9480
- }
9481
- /**
9482
- * Return files that were running or collected.
9483
- */
9484
- getFiles(keys) {
9485
- if (keys) {
9486
- return keys.map((key) => this.filesMap.get(key)).flat().filter((file) => file && !file.local);
9487
- }
9488
- return Array.from(this.filesMap.values()).flat().filter((file) => !file.local);
9489
- }
9490
- getFilepaths() {
9491
- return Array.from(this.filesMap.keys());
9492
- }
9493
- getFailedFilepaths() {
9494
- return this.getFiles().filter((i) => i.result?.state === "fail").map((i) => i.filepath);
9495
- }
9496
- collectPaths(paths = []) {
9497
- paths.forEach((path) => {
9498
- this.pathsSet.add(path);
9499
- });
9500
- }
9501
- collectFiles(project, files = []) {
9502
- files.forEach((file) => {
9503
- const existing = this.filesMap.get(file.filepath) || [];
9504
- const otherProject = existing.filter(
9505
- (i) => i.projectName !== file.projectName
9506
- );
9507
- const currentFile = existing.find(
9508
- (i) => i.projectName === file.projectName
9509
- );
9510
- if (currentFile) {
9511
- file.logs = currentFile.logs;
9512
- }
9513
- otherProject.push(file);
9514
- this.filesMap.set(file.filepath, otherProject);
9515
- this.updateId(file, project);
9516
- });
9517
- }
9518
- clearFiles(project, paths = []) {
9519
- paths.forEach((path) => {
9520
- const files = this.filesMap.get(path);
9521
- const fileTask = createFileTask(
9522
- path,
9523
- project.config.root,
9524
- project.config.name
9525
- );
9526
- fileTask.local = true;
9527
- TestFile.register(fileTask, project);
9528
- this.idMap.set(fileTask.id, fileTask);
9529
- if (!files) {
9530
- this.filesMap.set(path, [fileTask]);
9531
- return;
9532
- }
9533
- const filtered = files.filter(
9534
- (file) => file.projectName !== project.config.name
9535
- );
9536
- if (!filtered.length) {
9537
- this.filesMap.set(path, [fileTask]);
9538
- } else {
9539
- this.filesMap.set(path, [...filtered, fileTask]);
9540
- }
9541
- });
9542
- }
9543
- updateId(task, project) {
9544
- if (this.idMap.get(task.id) === task) {
9545
- return;
9546
- }
9547
- if (task.type === "suite" && "filepath" in task) {
9548
- TestFile.register(task, project);
9549
- } else if (task.type === "suite") {
9550
- TestSuite.register(task, project);
9551
- } else {
9552
- TestCase.register(task, project);
9553
- }
9554
- this.idMap.set(task.id, task);
9555
- if (task.type === "suite") {
9556
- task.tasks.forEach((task2) => {
9557
- this.updateId(task2, project);
9558
- });
9559
- }
9560
- }
9561
- getReportedEntity(task) {
9562
- return this.reportedTasksMap.get(task);
9563
- }
9564
- updateTasks(packs) {
9565
- for (const [id, result, meta] of packs) {
9566
- const task = this.idMap.get(id);
9567
- if (task) {
9568
- task.result = result;
9569
- task.meta = meta;
9570
- if (result?.state === "skip") {
9571
- task.mode = "skip";
9572
- }
9573
- }
9574
- }
9575
- }
9576
- updateUserLog(log) {
9577
- const task = log.taskId && this.idMap.get(log.taskId);
9578
- if (task) {
9579
- if (!task.logs) {
9580
- task.logs = [];
9581
- }
9582
- task.logs.push(log);
9583
- }
9584
- }
9585
- getCountOfFailedTests() {
9586
- return Array.from(this.idMap.values()).filter(
9587
- (t) => t.result?.state === "fail"
9588
- ).length;
9589
- }
9590
- cancelFiles(files, project) {
9591
- this.collectFiles(
9592
- project,
9593
- files.map(
9594
- (filepath) => createFileTask(filepath, project.config.root, project.config.name)
9595
- )
9596
- );
9597
- }
9598
- }
9599
-
9600
- const JOIN_LEADING_SLASH_RE = /^\.?\//;
9601
- function withTrailingSlash(input = "", respectQueryAndFragment) {
9602
- {
9603
- return input.endsWith("/") ? input : input + "/";
9604
- }
9605
- }
9606
- function isNonEmptyURL(url) {
9607
- return url && url !== "/";
9608
- }
9609
- function joinURL(base, ...input) {
9610
- let url = base || "";
9611
- for (const segment of input.filter((url2) => isNonEmptyURL(url2))) {
9612
- if (url) {
9613
- const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
9614
- url = withTrailingSlash(url) + _segment;
9615
- } else {
9616
- url = segment;
9617
- }
9618
- }
9619
- return url;
9620
- }
9621
-
9622
- const BUILTIN_MODULES = new Set(builtinModules);
9623
- function normalizeSlash(path) {
9624
- return path.replace(/\\/g, "/");
9625
- }
9626
-
9627
- /**
9628
- * @typedef ErrnoExceptionFields
9629
- * @property {number | undefined} [errnode]
9630
- * @property {string | undefined} [code]
9631
- * @property {string | undefined} [path]
9632
- * @property {string | undefined} [syscall]
9633
- * @property {string | undefined} [url]
9634
- *
9635
- * @typedef {Error & ErrnoExceptionFields} ErrnoException
9636
- */
9637
-
9638
-
9639
- const own$1 = {}.hasOwnProperty;
9640
-
9641
- const classRegExp = /^([A-Z][a-z\d]*)+$/;
9642
- // Sorted by a rough estimate on most frequently used entries.
9643
- const kTypes = new Set([
9644
- 'string',
9645
- 'function',
9646
- 'number',
9647
- 'object',
9648
- // Accept 'Function' and 'Object' as alternative to the lower cased version.
9649
- 'Function',
9650
- 'Object',
9651
- 'boolean',
9652
- 'bigint',
9653
- 'symbol'
9654
- ]);
9655
-
9656
- const codes = {};
9657
-
9658
- /**
9659
- * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
9660
- * We cannot use Intl.ListFormat because it's not available in
9661
- * --without-intl builds.
9662
- *
9663
- * @param {Array<string>} array
9664
- * An array of strings.
9665
- * @param {string} [type]
9666
- * The list type to be inserted before the last element.
9667
- * @returns {string}
9668
- */
9669
- function formatList(array, type = 'and') {
9670
- return array.length < 3
9671
- ? array.join(` ${type} `)
9672
- : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
9673
- }
9674
-
9675
- /** @type {Map<string, MessageFunction | string>} */
9676
- const messages = new Map();
9677
- const nodeInternalPrefix = '__node_internal_';
9678
- /** @type {number} */
9679
- let userStackTraceLimit;
9680
-
9681
- codes.ERR_INVALID_ARG_TYPE = createError(
9682
- 'ERR_INVALID_ARG_TYPE',
9683
- /**
9684
- * @param {string} name
9685
- * @param {Array<string> | string} expected
9686
- * @param {unknown} actual
9687
- */
9688
- (name, expected, actual) => {
9689
- assert(typeof name === 'string', "'name' must be a string");
9690
- if (!Array.isArray(expected)) {
9691
- expected = [expected];
9692
- }
9693
-
9694
- let message = 'The ';
9695
- if (name.endsWith(' argument')) {
9696
- // For cases like 'first argument'
9697
- message += `${name} `;
9698
- } else {
9699
- const type = name.includes('.') ? 'property' : 'argument';
9700
- message += `"${name}" ${type} `;
9701
- }
9702
-
9703
- message += 'must be ';
9704
-
9705
- /** @type {Array<string>} */
9706
- const types = [];
9707
- /** @type {Array<string>} */
9708
- const instances = [];
9709
- /** @type {Array<string>} */
9710
- const other = [];
9711
-
9712
- for (const value of expected) {
9713
- assert(
9714
- typeof value === 'string',
9715
- 'All expected entries have to be of type string'
9716
- );
9717
-
9718
- if (kTypes.has(value)) {
9719
- types.push(value.toLowerCase());
9720
- } else if (classRegExp.exec(value) === null) {
9721
- assert(
9722
- value !== 'object',
9723
- 'The value "object" should be written as "Object"'
9724
- );
9725
- other.push(value);
9726
- } else {
9727
- instances.push(value);
9728
- }
9729
- }
9730
-
9731
- // Special handle `object` in case other instances are allowed to outline
9732
- // the differences between each other.
9733
- if (instances.length > 0) {
9734
- const pos = types.indexOf('object');
9735
- if (pos !== -1) {
9736
- types.slice(pos, 1);
9737
- instances.push('Object');
9738
- }
9739
- }
9740
-
9741
- if (types.length > 0) {
9742
- message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
9743
- types,
9744
- 'or'
9745
- )}`;
9746
- if (instances.length > 0 || other.length > 0) message += ' or ';
9747
- }
9748
-
9749
- if (instances.length > 0) {
9750
- message += `an instance of ${formatList(instances, 'or')}`;
9751
- if (other.length > 0) message += ' or ';
9752
- }
9753
-
9754
- if (other.length > 0) {
9755
- if (other.length > 1) {
9756
- message += `one of ${formatList(other, 'or')}`;
9757
- } else {
9758
- if (other[0].toLowerCase() !== other[0]) message += 'an ';
9759
- message += `${other[0]}`;
9760
- }
9761
- }
9762
-
9763
- message += `. Received ${determineSpecificType(actual)}`;
9764
-
9765
- return message
9766
- },
9767
- TypeError
9768
- );
9769
-
9770
- codes.ERR_INVALID_MODULE_SPECIFIER = createError(
9771
- 'ERR_INVALID_MODULE_SPECIFIER',
9772
- /**
9773
- * @param {string} request
9774
- * @param {string} reason
9775
- * @param {string} [base]
9776
- */
9777
- (request, reason, base = undefined) => {
9778
- return `Invalid module "${request}" ${reason}${
9779
- base ? ` imported from ${base}` : ''
9780
- }`
9781
- },
9782
- TypeError
9783
- );
9784
-
9785
- codes.ERR_INVALID_PACKAGE_CONFIG = createError(
9786
- 'ERR_INVALID_PACKAGE_CONFIG',
9787
- /**
9788
- * @param {string} path
9789
- * @param {string} [base]
9790
- * @param {string} [message]
9791
- */
9792
- (path, base, message) => {
9793
- return `Invalid package config ${path}${
9794
- base ? ` while importing ${base}` : ''
9795
- }${message ? `. ${message}` : ''}`
9796
- },
9797
- Error
9798
- );
9799
-
9800
- codes.ERR_INVALID_PACKAGE_TARGET = createError(
9801
- 'ERR_INVALID_PACKAGE_TARGET',
9802
- /**
9803
- * @param {string} packagePath
9804
- * @param {string} key
9805
- * @param {unknown} target
9806
- * @param {boolean} [isImport=false]
9807
- * @param {string} [base]
9808
- */
9809
- (packagePath, key, target, isImport = false, base = undefined) => {
9810
- const relatedError =
9811
- typeof target === 'string' &&
9812
- !isImport &&
9813
- target.length > 0 &&
9814
- !target.startsWith('./');
9815
- if (key === '.') {
9816
- assert(isImport === false);
9817
- return (
9818
- `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
9819
- `in the package config ${packagePath}package.json${
9820
- base ? ` imported from ${base}` : ''
9821
- }${relatedError ? '; targets must start with "./"' : ''}`
9822
- )
9823
- }
9824
-
9825
- return `Invalid "${
9826
- isImport ? 'imports' : 'exports'
9827
- }" target ${JSON.stringify(
9828
- target
9829
- )} defined for '${key}' in the package config ${packagePath}package.json${
9830
- base ? ` imported from ${base}` : ''
9831
- }${relatedError ? '; targets must start with "./"' : ''}`
9832
- },
9833
- Error
9834
- );
9835
-
9836
- codes.ERR_MODULE_NOT_FOUND = createError(
9837
- 'ERR_MODULE_NOT_FOUND',
9838
- /**
9839
- * @param {string} path
9840
- * @param {string} base
9841
- * @param {boolean} [exactUrl]
9842
- */
9843
- (path, base, exactUrl = false) => {
9844
- return `Cannot find ${
9845
- exactUrl ? 'module' : 'package'
9846
- } '${path}' imported from ${base}`
9847
- },
9848
- Error
9849
- );
9850
-
9851
- codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
9852
- 'ERR_NETWORK_IMPORT_DISALLOWED',
9853
- "import of '%s' by %s is not supported: %s",
9854
- Error
9855
- );
9856
-
9857
- codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
9858
- 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
9859
- /**
9860
- * @param {string} specifier
9861
- * @param {string} packagePath
9862
- * @param {string} base
9863
- */
9864
- (specifier, packagePath, base) => {
9865
- return `Package import specifier "${specifier}" is not defined${
9866
- packagePath ? ` in package ${packagePath}package.json` : ''
9867
- } imported from ${base}`
9868
- },
9869
- TypeError
9870
- );
9871
-
9872
- codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
9873
- 'ERR_PACKAGE_PATH_NOT_EXPORTED',
9874
- /**
9875
- * @param {string} packagePath
9876
- * @param {string} subpath
9877
- * @param {string} [base]
9878
- */
9879
- (packagePath, subpath, base = undefined) => {
9880
- if (subpath === '.')
9881
- return `No "exports" main defined in ${packagePath}package.json${
9882
- base ? ` imported from ${base}` : ''
9883
- }`
9884
- return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
9885
- base ? ` imported from ${base}` : ''
9886
- }`
9887
- },
9888
- Error
9889
- );
9890
-
9891
- codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
9892
- 'ERR_UNSUPPORTED_DIR_IMPORT',
9893
- "Directory import '%s' is not supported " +
9894
- 'resolving ES modules imported from %s',
9895
- Error
9896
- );
9897
-
9898
- codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
9899
- 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
9900
- 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
9901
- TypeError
9902
- );
9903
-
9904
- codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
9905
- 'ERR_UNKNOWN_FILE_EXTENSION',
9906
- /**
9907
- * @param {string} extension
9908
- * @param {string} path
9909
- */
9910
- (extension, path) => {
9911
- return `Unknown file extension "${extension}" for ${path}`
9912
- },
9913
- TypeError
9914
- );
9915
-
9916
- codes.ERR_INVALID_ARG_VALUE = createError(
9917
- 'ERR_INVALID_ARG_VALUE',
9918
- /**
9919
- * @param {string} name
9920
- * @param {unknown} value
9921
- * @param {string} [reason='is invalid']
9922
- */
9923
- (name, value, reason = 'is invalid') => {
9924
- let inspected = inspect(value);
9925
-
9926
- if (inspected.length > 128) {
9927
- inspected = `${inspected.slice(0, 128)}...`;
9928
- }
9929
-
9930
- const type = name.includes('.') ? 'property' : 'argument';
9931
-
9932
- return `The ${type} '${name}' ${reason}. Received ${inspected}`
9933
- },
9934
- TypeError
9935
- // Note: extra classes have been shaken out.
9936
- // , RangeError
9937
- );
9938
-
9939
- /**
9940
- * Utility function for registering the error codes. Only used here. Exported
9941
- * *only* to allow for testing.
9942
- * @param {string} sym
9943
- * @param {MessageFunction | string} value
9944
- * @param {ErrorConstructor} constructor
9945
- * @returns {new (...parameters: Array<any>) => Error}
9946
- */
9947
- function createError(sym, value, constructor) {
9948
- // Special case for SystemError that formats the error message differently
9949
- // The SystemErrors only have SystemError as their base classes.
9950
- messages.set(sym, value);
9951
-
9952
- return makeNodeErrorWithCode(constructor, sym)
9953
- }
9954
-
9955
- /**
9956
- * @param {ErrorConstructor} Base
9957
- * @param {string} key
9958
- * @returns {ErrorConstructor}
9959
- */
9960
- function makeNodeErrorWithCode(Base, key) {
9961
- // @ts-expect-error It’s a Node error.
9962
- return NodeError
9963
- /**
9964
- * @param {Array<unknown>} parameters
9965
- */
9966
- function NodeError(...parameters) {
9967
- const limit = Error.stackTraceLimit;
9968
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
9969
- const error = new Base();
9970
- // Reset the limit and setting the name property.
9971
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
9972
- const message = getMessage(key, parameters, error);
9973
- Object.defineProperties(error, {
9974
- // Note: no need to implement `kIsNodeError` symbol, would be hard,
9975
- // probably.
9976
- message: {
9977
- value: message,
9978
- enumerable: false,
9979
- writable: true,
9980
- configurable: true
9981
- },
9982
- toString: {
9983
- /** @this {Error} */
9984
- value() {
9985
- return `${this.name} [${key}]: ${this.message}`
9986
- },
9987
- enumerable: false,
9988
- writable: true,
9989
- configurable: true
9990
- }
9991
- });
9992
-
9993
- captureLargerStackTrace(error);
9994
- // @ts-expect-error It’s a Node error.
9995
- error.code = key;
9996
- return error
9997
- }
9998
- }
9999
-
10000
- /**
10001
- * @returns {boolean}
10002
- */
10003
- function isErrorStackTraceLimitWritable() {
10004
- // Do no touch Error.stackTraceLimit as V8 would attempt to install
10005
- // it again during deserialization.
10006
- try {
10007
- if (v8.startupSnapshot.isBuildingSnapshot()) {
10008
- return false
10009
- }
10010
- } catch {}
10011
-
10012
- const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
10013
- if (desc === undefined) {
10014
- return Object.isExtensible(Error)
10015
- }
10016
-
10017
- return own$1.call(desc, 'writable') && desc.writable !== undefined
10018
- ? desc.writable
10019
- : desc.set !== undefined
10020
- }
10021
-
10022
- /**
10023
- * This function removes unnecessary frames from Node.js core errors.
10024
- * @template {(...parameters: unknown[]) => unknown} T
10025
- * @param {T} wrappedFunction
10026
- * @returns {T}
10027
- */
10028
- function hideStackFrames(wrappedFunction) {
10029
- // We rename the functions that will be hidden to cut off the stacktrace
10030
- // at the outermost one
10031
- const hidden = nodeInternalPrefix + wrappedFunction.name;
10032
- Object.defineProperty(wrappedFunction, 'name', {value: hidden});
10033
- return wrappedFunction
10034
- }
10035
-
10036
- const captureLargerStackTrace = hideStackFrames(
10037
- /**
10038
- * @param {Error} error
10039
- * @returns {Error}
10040
- */
10041
- // @ts-expect-error: fine
10042
- function (error) {
10043
- const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
10044
- if (stackTraceLimitIsWritable) {
10045
- userStackTraceLimit = Error.stackTraceLimit;
10046
- Error.stackTraceLimit = Number.POSITIVE_INFINITY;
10047
- }
10048
-
10049
- Error.captureStackTrace(error);
10050
-
10051
- // Reset the limit
10052
- if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
10053
-
10054
- return error
10055
- }
10056
- );
10057
-
10058
- /**
10059
- * @param {string} key
10060
- * @param {Array<unknown>} parameters
10061
- * @param {Error} self
10062
- * @returns {string}
10063
- */
10064
- function getMessage(key, parameters, self) {
10065
- const message = messages.get(key);
10066
- assert(message !== undefined, 'expected `message` to be found');
10067
-
10068
- if (typeof message === 'function') {
10069
- assert(
10070
- message.length <= parameters.length, // Default options do not count.
10071
- `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
10072
- `match the required ones (${message.length}).`
10073
- );
10074
- return Reflect.apply(message, self, parameters)
10075
- }
10076
-
10077
- const regex = /%[dfijoOs]/g;
10078
- let expectedLength = 0;
10079
- while (regex.exec(message) !== null) expectedLength++;
10080
- assert(
10081
- expectedLength === parameters.length,
10082
- `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
10083
- `match the required ones (${expectedLength}).`
10084
- );
10085
- if (parameters.length === 0) return message
10086
-
10087
- parameters.unshift(message);
10088
- return Reflect.apply(format$2, null, parameters)
10089
- }
10090
-
10091
- /**
10092
- * Determine the specific type of a value for type-mismatch errors.
10093
- * @param {unknown} value
10094
- * @returns {string}
10095
- */
10096
- function determineSpecificType(value) {
10097
- if (value === null || value === undefined) {
10098
- return String(value)
10099
- }
10100
-
10101
- if (typeof value === 'function' && value.name) {
10102
- return `function ${value.name}`
10103
- }
10104
-
10105
- if (typeof value === 'object') {
10106
- if (value.constructor && value.constructor.name) {
10107
- return `an instance of ${value.constructor.name}`
10108
- }
10109
-
10110
- return `${inspect(value, {depth: -1})}`
10111
- }
10112
-
10113
- let inspected = inspect(value, {colors: false});
10114
-
10115
- if (inspected.length > 28) {
10116
- inspected = `${inspected.slice(0, 25)}...`;
10117
- }
10118
-
10119
- return `type ${typeof value} (${inspected})`
10120
- }
10121
-
10122
- // Manually “tree shaken” from:
10123
- // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
10124
- // Last checked on: Apr 29, 2023.
10125
- // Removed the native dependency.
10126
- // Also: no need to cache, we do that in resolve already.
10127
-
10128
-
10129
- const hasOwnProperty$1 = {}.hasOwnProperty;
10130
-
10131
- const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
10132
-
10133
- /** @type {Map<string, PackageConfig>} */
10134
- const cache = new Map();
10135
-
10136
- /**
10137
- * @param {string} jsonPath
10138
- * @param {{specifier: URL | string, base?: URL}} options
10139
- * @returns {PackageConfig}
10140
- */
10141
- function read(jsonPath, {base, specifier}) {
10142
- const existing = cache.get(jsonPath);
10143
-
10144
- if (existing) {
10145
- return existing
10146
- }
10147
-
10148
- /** @type {string | undefined} */
10149
- let string;
10150
-
10151
- try {
10152
- string = fs$8.readFileSync(path$8.toNamespacedPath(jsonPath), 'utf8');
10153
- } catch (error) {
10154
- const exception = /** @type {ErrnoException} */ (error);
10155
-
10156
- if (exception.code !== 'ENOENT') {
10157
- throw exception
10158
- }
10159
- }
10160
-
10161
- /** @type {PackageConfig} */
10162
- const result = {
10163
- exists: false,
10164
- pjsonPath: jsonPath,
10165
- main: undefined,
10166
- name: undefined,
10167
- type: 'none', // Ignore unknown types for forwards compatibility
10168
- exports: undefined,
10169
- imports: undefined
10170
- };
10171
-
10172
- if (string !== undefined) {
10173
- /** @type {Record<string, unknown>} */
10174
- let parsed;
10175
-
10176
- try {
10177
- parsed = JSON.parse(string);
10178
- } catch (error_) {
10179
- const cause = /** @type {ErrnoException} */ (error_);
10180
- const error = new ERR_INVALID_PACKAGE_CONFIG$1(
10181
- jsonPath,
10182
- (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier),
10183
- cause.message
10184
- );
10185
- error.cause = cause;
10186
- throw error
10187
- }
10188
-
10189
- result.exists = true;
10190
-
10191
- if (
10192
- hasOwnProperty$1.call(parsed, 'name') &&
10193
- typeof parsed.name === 'string'
10194
- ) {
10195
- result.name = parsed.name;
10196
- }
10197
-
10198
- if (
10199
- hasOwnProperty$1.call(parsed, 'main') &&
10200
- typeof parsed.main === 'string'
10201
- ) {
10202
- result.main = parsed.main;
10203
- }
10204
-
10205
- if (hasOwnProperty$1.call(parsed, 'exports')) {
10206
- // @ts-expect-error: assume valid.
10207
- result.exports = parsed.exports;
10208
- }
10209
-
10210
- if (hasOwnProperty$1.call(parsed, 'imports')) {
10211
- // @ts-expect-error: assume valid.
10212
- result.imports = parsed.imports;
10213
- }
10214
-
10215
- // Ignore unknown types for forwards compatibility
10216
- if (
10217
- hasOwnProperty$1.call(parsed, 'type') &&
10218
- (parsed.type === 'commonjs' || parsed.type === 'module')
10219
- ) {
10220
- result.type = parsed.type;
10221
- }
10222
- }
10223
-
10224
- cache.set(jsonPath, result);
10225
-
10226
- return result
10227
- }
10228
-
10229
- /**
10230
- * @param {URL | string} resolved
10231
- * @returns {PackageConfig}
10232
- */
10233
- function getPackageScopeConfig(resolved) {
10234
- // Note: in Node, this is now a native module.
10235
- let packageJSONUrl = new URL('package.json', resolved);
10236
-
10237
- while (true) {
10238
- const packageJSONPath = packageJSONUrl.pathname;
10239
- if (packageJSONPath.endsWith('node_modules/package.json')) {
10240
- break
10241
- }
10242
-
10243
- const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
10244
- specifier: resolved
10245
- });
10246
-
10247
- if (packageConfig.exists) {
10248
- return packageConfig
10249
- }
10250
-
10251
- const lastPackageJSONUrl = packageJSONUrl;
10252
- packageJSONUrl = new URL('../package.json', packageJSONUrl);
10253
-
10254
- // Terminates at root where ../package.json equals ../../package.json
10255
- // (can't just check "/package.json" for Windows support).
10256
- if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
10257
- break
10258
- }
10259
- }
10260
-
10261
- const packageJSONPath = fileURLToPath$1(packageJSONUrl);
10262
- // ^^ Note: in Node, this is now a native module.
10263
-
10264
- return {
10265
- pjsonPath: packageJSONPath,
10266
- exists: false,
10267
- type: 'none'
10268
- }
10269
- }
10270
-
10271
- /**
10272
- * Returns the package type for a given URL.
10273
- * @param {URL} url - The URL to get the package type for.
10274
- * @returns {PackageType}
10275
- */
10276
- function getPackageType(url) {
10277
- // To do @anonrig: Write a C++ function that returns only "type".
10278
- return getPackageScopeConfig(url).type
10279
- }
10280
-
10281
- // Manually “tree shaken” from:
10282
- // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
10283
- // Last checked on: Apr 29, 2023.
10284
-
10285
-
10286
- const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
10287
-
10288
- const hasOwnProperty = {}.hasOwnProperty;
10289
-
10290
- /** @type {Record<string, string>} */
10291
- const extensionFormatMap = {
10292
- // @ts-expect-error: hush.
10293
- __proto__: null,
10294
- '.cjs': 'commonjs',
10295
- '.js': 'module',
10296
- '.json': 'json',
10297
- '.mjs': 'module'
10298
- };
10299
-
10300
- /**
10301
- * @param {string | null} mime
10302
- * @returns {string | null}
10303
- */
10304
- function mimeToFormat(mime) {
10305
- if (
10306
- mime &&
10307
- /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
10308
- )
10309
- return 'module'
10310
- if (mime === 'application/json') return 'json'
10311
- return null
10312
- }
10313
-
10314
- /**
10315
- * @callback ProtocolHandler
10316
- * @param {URL} parsed
10317
- * @param {{parentURL: string, source?: Buffer}} context
10318
- * @param {boolean} ignoreErrors
10319
- * @returns {string | null | void}
10320
- */
10321
-
10322
- /**
10323
- * @type {Record<string, ProtocolHandler>}
10324
- */
10325
- const protocolHandlers = {
10326
- // @ts-expect-error: hush.
10327
- __proto__: null,
10328
- 'data:': getDataProtocolModuleFormat,
10329
- 'file:': getFileProtocolModuleFormat,
10330
- 'http:': getHttpProtocolModuleFormat,
10331
- 'https:': getHttpProtocolModuleFormat,
10332
- 'node:'() {
10333
- return 'builtin'
10334
- }
10335
- };
10336
-
10337
- /**
10338
- * @param {URL} parsed
10339
- */
10340
- function getDataProtocolModuleFormat(parsed) {
10341
- const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
10342
- parsed.pathname
10343
- ) || [null, null, null];
10344
- return mimeToFormat(mime)
10345
- }
10346
-
10347
- /**
10348
- * Returns the file extension from a URL.
10349
- *
10350
- * Should give similar result to
10351
- * `require('node:path').extname(require('node:url').fileURLToPath(url))`
10352
- * when used with a `file:` URL.
10353
- *
10354
- * @param {URL} url
10355
- * @returns {string}
10356
- */
10357
- function extname(url) {
10358
- const pathname = url.pathname;
10359
- let index = pathname.length;
10360
-
10361
- while (index--) {
10362
- const code = pathname.codePointAt(index);
10363
-
10364
- if (code === 47 /* `/` */) {
10365
- return ''
10366
- }
10367
-
10368
- if (code === 46 /* `.` */) {
10369
- return pathname.codePointAt(index - 1) === 47 /* `/` */
10370
- ? ''
10371
- : pathname.slice(index)
10372
- }
10373
- }
10374
-
10375
- return ''
10376
- }
10377
-
10378
- /**
10379
- * @type {ProtocolHandler}
10380
- */
10381
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
10382
- const value = extname(url);
10383
-
10384
- if (value === '.js') {
10385
- const packageType = getPackageType(url);
10386
-
10387
- if (packageType !== 'none') {
10388
- return packageType
10389
- }
10390
-
10391
- return 'commonjs'
10392
- }
10393
-
10394
- if (value === '') {
10395
- const packageType = getPackageType(url);
10396
-
10397
- // Legacy behavior
10398
- if (packageType === 'none' || packageType === 'commonjs') {
10399
- return 'commonjs'
10400
- }
10401
-
10402
- // Note: we don’t implement WASM, so we don’t need
10403
- // `getFormatOfExtensionlessFile` from `formats`.
10404
- return 'module'
10405
- }
10406
-
10407
- const format = extensionFormatMap[value];
10408
- if (format) return format
10409
-
10410
- // Explicit undefined return indicates load hook should rerun format check
10411
- if (ignoreErrors) {
10412
- return undefined
10413
- }
10414
-
10415
- const filepath = fileURLToPath$1(url);
10416
- throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
10417
- }
10418
-
10419
- function getHttpProtocolModuleFormat() {
10420
- // To do: HTTPS imports.
10421
- }
10422
-
10423
- /**
10424
- * @param {URL} url
10425
- * @param {{parentURL: string}} context
10426
- * @returns {string | null}
10427
- */
10428
- function defaultGetFormatWithoutErrors(url, context) {
10429
- const protocol = url.protocol;
10430
-
10431
- if (!hasOwnProperty.call(protocolHandlers, protocol)) {
10432
- return null
10433
- }
10434
-
10435
- return protocolHandlers[protocol](url, context, true) || null
10436
- }
10437
-
10438
- // Manually “tree shaken” from:
10439
- // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/resolve.js>
10440
- // Last checked on: Apr 29, 2023.
10441
-
10442
-
10443
- const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
10444
-
10445
- const {
10446
- ERR_NETWORK_IMPORT_DISALLOWED,
10447
- ERR_INVALID_MODULE_SPECIFIER,
10448
- ERR_INVALID_PACKAGE_CONFIG,
10449
- ERR_INVALID_PACKAGE_TARGET,
10450
- ERR_MODULE_NOT_FOUND,
10451
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
10452
- ERR_PACKAGE_PATH_NOT_EXPORTED,
10453
- ERR_UNSUPPORTED_DIR_IMPORT,
10454
- ERR_UNSUPPORTED_RESOLVE_REQUEST
10455
- } = codes;
10456
-
10457
- const own = {}.hasOwnProperty;
10458
-
10459
- const invalidSegmentRegEx =
10460
- /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
10461
- const deprecatedInvalidSegmentRegEx =
10462
- /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
10463
- const invalidPackageNameRegEx = /^\.|%|\\/;
10464
- const patternRegEx = /\*/g;
10465
- const encodedSeparatorRegEx = /%2f|%5c/i;
10466
- /** @type {Set<string>} */
10467
- const emittedPackageWarnings = new Set();
10468
-
10469
- const doubleSlashRegEx = /[/\\]{2}/;
10470
-
10471
- /**
10472
- *
10473
- * @param {string} target
10474
- * @param {string} request
10475
- * @param {string} match
10476
- * @param {URL} packageJsonUrl
10477
- * @param {boolean} internal
10478
- * @param {URL} base
10479
- * @param {boolean} isTarget
10480
- */
10481
- function emitInvalidSegmentDeprecation(
10482
- target,
10483
- request,
10484
- match,
10485
- packageJsonUrl,
10486
- internal,
10487
- base,
10488
- isTarget
10489
- ) {
10490
- // @ts-expect-error: apparently it does exist, TS.
10491
- if (process$1.noDeprecation) {
10492
- return
10493
- }
10494
-
10495
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
10496
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
10497
- process$1.emitWarning(
10498
- `Use of deprecated ${
10499
- double ? 'double slash' : 'leading or trailing slash matching'
10500
- } resolving "${target}" for module ` +
10501
- `request "${request}" ${
10502
- request === match ? '' : `matched to "${match}" `
10503
- }in the "${
10504
- internal ? 'imports' : 'exports'
10505
- }" field module resolution of the package at ${pjsonPath}${
10506
- base ? ` imported from ${fileURLToPath$1(base)}` : ''
10507
- }.`,
10508
- 'DeprecationWarning',
10509
- 'DEP0166'
10510
- );
10511
- }
10512
-
10513
- /**
10514
- * @param {URL} url
10515
- * @param {URL} packageJsonUrl
10516
- * @param {URL} base
10517
- * @param {string} [main]
10518
- * @returns {void}
10519
- */
10520
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
10521
- // @ts-expect-error: apparently it does exist, TS.
10522
- if (process$1.noDeprecation) {
10523
- return
10524
- }
10525
-
10526
- const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
10527
- if (format !== 'module') return
10528
- const urlPath = fileURLToPath$1(url.href);
10529
- const packagePath = fileURLToPath$1(new URL$2('.', packageJsonUrl));
10530
- const basePath = fileURLToPath$1(base);
10531
- if (!main) {
10532
- process$1.emitWarning(
10533
- `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
10534
- packagePath.length
10535
- )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
10536
- 'DeprecationWarning',
10537
- 'DEP0151'
10538
- );
10539
- } else if (path$8.resolve(packagePath, main) !== urlPath) {
10540
- process$1.emitWarning(
10541
- `Package ${packagePath} has a "main" field set to "${main}", ` +
10542
- `excluding the full filename and extension to the resolved file at "${urlPath.slice(
10543
- packagePath.length
10544
- )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
10545
- 'deprecated for ES modules.',
10546
- 'DeprecationWarning',
10547
- 'DEP0151'
10548
- );
10549
- }
10550
- }
10551
-
10552
- /**
10553
- * @param {string} path
10554
- * @returns {Stats | undefined}
10555
- */
10556
- function tryStatSync(path) {
10557
- // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
10558
- try {
10559
- return statSync$1(path)
10560
- } catch {
10561
- // Note: in Node code this returns `new Stats`,
10562
- // but in Node 22 that’s marked as a deprecated internal API.
10563
- // Which, well, we kinda are, but still to prevent that warning,
10564
- // just yield `undefined`.
10565
- }
10566
- }
10567
-
10568
- /**
10569
- * Legacy CommonJS main resolution:
10570
- * 1. let M = pkg_url + (json main field)
10571
- * 2. TRY(M, M.js, M.json, M.node)
10572
- * 3. TRY(M/index.js, M/index.json, M/index.node)
10573
- * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
10574
- * 5. NOT_FOUND
10575
- *
10576
- * @param {URL} url
10577
- * @returns {boolean}
10578
- */
10579
- function fileExists(url) {
10580
- const stats = statSync$1(url, {throwIfNoEntry: false});
10581
- const isFile = stats ? stats.isFile() : undefined;
10582
- return isFile === null || isFile === undefined ? false : isFile
10583
- }
10584
-
10585
- /**
10586
- * @param {URL} packageJsonUrl
10587
- * @param {PackageConfig} packageConfig
10588
- * @param {URL} base
10589
- * @returns {URL}
10590
- */
10591
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
10592
- /** @type {URL | undefined} */
10593
- let guess;
10594
- if (packageConfig.main !== undefined) {
10595
- guess = new URL$2(packageConfig.main, packageJsonUrl);
10596
- // Note: fs check redundances will be handled by Descriptor cache here.
10597
- if (fileExists(guess)) return guess
10598
-
10599
- const tries = [
10600
- `./${packageConfig.main}.js`,
10601
- `./${packageConfig.main}.json`,
10602
- `./${packageConfig.main}.node`,
10603
- `./${packageConfig.main}/index.js`,
10604
- `./${packageConfig.main}/index.json`,
10605
- `./${packageConfig.main}/index.node`
10606
- ];
10607
- let i = -1;
10608
-
10609
- while (++i < tries.length) {
10610
- guess = new URL$2(tries[i], packageJsonUrl);
10611
- if (fileExists(guess)) break
10612
- guess = undefined;
10613
- }
10614
-
10615
- if (guess) {
10616
- emitLegacyIndexDeprecation(
10617
- guess,
10618
- packageJsonUrl,
10619
- base,
10620
- packageConfig.main
10621
- );
10622
- return guess
10623
- }
10624
- // Fallthrough.
10625
- }
10626
-
10627
- const tries = ['./index.js', './index.json', './index.node'];
10628
- let i = -1;
10629
-
10630
- while (++i < tries.length) {
10631
- guess = new URL$2(tries[i], packageJsonUrl);
10632
- if (fileExists(guess)) break
10633
- guess = undefined;
10634
- }
10635
-
10636
- if (guess) {
10637
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
10638
- return guess
10639
- }
10640
-
10641
- // Not found.
10642
- throw new ERR_MODULE_NOT_FOUND(
10643
- fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10644
- fileURLToPath$1(base)
10645
- )
10646
- }
10647
-
10648
- /**
10649
- * @param {URL} resolved
10650
- * @param {URL} base
10651
- * @param {boolean} [preserveSymlinks]
10652
- * @returns {URL}
10653
- */
10654
- function finalizeResolution(resolved, base, preserveSymlinks) {
10655
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
10656
- throw new ERR_INVALID_MODULE_SPECIFIER(
10657
- resolved.pathname,
10658
- 'must not include encoded "/" or "\\" characters',
10659
- fileURLToPath$1(base)
10660
- )
10661
- }
10662
-
10663
- /** @type {string} */
10664
- let filePath;
10665
-
10666
- try {
10667
- filePath = fileURLToPath$1(resolved);
10668
- } catch (error) {
10669
- const cause = /** @type {ErrnoException} */ (error);
10670
- Object.defineProperty(cause, 'input', {value: String(resolved)});
10671
- Object.defineProperty(cause, 'module', {value: String(base)});
10672
- throw cause
10673
- }
10674
-
10675
- const stats = tryStatSync(
10676
- filePath.endsWith('/') ? filePath.slice(-1) : filePath
10677
- );
10678
-
10679
- if (stats && stats.isDirectory()) {
10680
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
10681
- // @ts-expect-error Add this for `import.meta.resolve`.
10682
- error.url = String(resolved);
10683
- throw error
10684
- }
10685
-
10686
- if (!stats || !stats.isFile()) {
10687
- const error = new ERR_MODULE_NOT_FOUND(
10688
- filePath || resolved.pathname,
10689
- base && fileURLToPath$1(base),
10690
- true
10691
- );
10692
- // @ts-expect-error Add this for `import.meta.resolve`.
10693
- error.url = String(resolved);
10694
- throw error
10695
- }
10696
-
10697
- {
10698
- const real = realpathSync(filePath);
10699
- const {search, hash} = resolved;
10700
- resolved = pathToFileURL$1(real + (filePath.endsWith(path$8.sep) ? '/' : ''));
10701
- resolved.search = search;
10702
- resolved.hash = hash;
10703
- }
10704
-
10705
- return resolved
10706
- }
10707
-
10708
- /**
10709
- * @param {string} specifier
10710
- * @param {URL | undefined} packageJsonUrl
10711
- * @param {URL} base
10712
- * @returns {Error}
10713
- */
10714
- function importNotDefined(specifier, packageJsonUrl, base) {
10715
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
10716
- specifier,
10717
- packageJsonUrl && fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10718
- fileURLToPath$1(base)
10719
- )
10720
- }
10721
-
10722
- /**
10723
- * @param {string} subpath
10724
- * @param {URL} packageJsonUrl
10725
- * @param {URL} base
10726
- * @returns {Error}
10727
- */
10728
- function exportsNotFound(subpath, packageJsonUrl, base) {
10729
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
10730
- fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10731
- subpath,
10732
- base && fileURLToPath$1(base)
10733
- )
10734
- }
10735
-
10736
- /**
10737
- * @param {string} request
10738
- * @param {string} match
10739
- * @param {URL} packageJsonUrl
10740
- * @param {boolean} internal
10741
- * @param {URL} [base]
10742
- * @returns {never}
10743
- */
10744
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
10745
- const reason = `request is not a valid match in pattern "${match}" for the "${
10746
- internal ? 'imports' : 'exports'
10747
- }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
10748
- throw new ERR_INVALID_MODULE_SPECIFIER(
10749
- request,
10750
- reason,
10751
- base && fileURLToPath$1(base)
10752
- )
10753
- }
10754
-
10755
- /**
10756
- * @param {string} subpath
10757
- * @param {unknown} target
10758
- * @param {URL} packageJsonUrl
10759
- * @param {boolean} internal
10760
- * @param {URL} [base]
10761
- * @returns {Error}
10762
- */
10763
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
10764
- target =
10765
- typeof target === 'object' && target !== null
10766
- ? JSON.stringify(target, null, '')
10767
- : `${target}`;
10768
-
10769
- return new ERR_INVALID_PACKAGE_TARGET(
10770
- fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10771
- subpath,
10772
- target,
10773
- internal,
10774
- base && fileURLToPath$1(base)
10775
- )
10776
- }
10777
-
10778
- /**
10779
- * @param {string} target
10780
- * @param {string} subpath
10781
- * @param {string} match
10782
- * @param {URL} packageJsonUrl
10783
- * @param {URL} base
10784
- * @param {boolean} pattern
10785
- * @param {boolean} internal
10786
- * @param {boolean} isPathMap
10787
- * @param {Set<string> | undefined} conditions
10788
- * @returns {URL}
10789
- */
10790
- function resolvePackageTargetString(
10791
- target,
10792
- subpath,
10793
- match,
10794
- packageJsonUrl,
10795
- base,
10796
- pattern,
10797
- internal,
10798
- isPathMap,
10799
- conditions
10800
- ) {
10801
- if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
10802
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10803
-
10804
- if (!target.startsWith('./')) {
10805
- if (internal && !target.startsWith('../') && !target.startsWith('/')) {
10806
- let isURL = false;
10807
-
10808
- try {
10809
- new URL$2(target);
10810
- isURL = true;
10811
- } catch {
10812
- // Continue regardless of error.
10813
- }
10814
-
10815
- if (!isURL) {
10816
- const exportTarget = pattern
10817
- ? RegExpPrototypeSymbolReplace.call(
10818
- patternRegEx,
10819
- target,
10820
- () => subpath
10821
- )
10822
- : target + subpath;
10823
-
10824
- return packageResolve(exportTarget, packageJsonUrl, conditions)
10825
- }
10826
- }
10827
-
10828
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10829
- }
10830
-
10831
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
10832
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
10833
- if (!isPathMap) {
10834
- const request = pattern
10835
- ? match.replace('*', () => subpath)
10836
- : match + subpath;
10837
- const resolvedTarget = pattern
10838
- ? RegExpPrototypeSymbolReplace.call(
10839
- patternRegEx,
10840
- target,
10841
- () => subpath
10842
- )
10843
- : target;
10844
- emitInvalidSegmentDeprecation(
10845
- resolvedTarget,
10846
- request,
10847
- match,
10848
- packageJsonUrl,
10849
- internal,
10850
- base,
10851
- true
10852
- );
10853
- }
10854
- } else {
10855
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10856
- }
10857
- }
10858
-
10859
- const resolved = new URL$2(target, packageJsonUrl);
10860
- const resolvedPath = resolved.pathname;
10861
- const packagePath = new URL$2('.', packageJsonUrl).pathname;
10862
-
10863
- if (!resolvedPath.startsWith(packagePath))
10864
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10865
-
10866
- if (subpath === '') return resolved
10867
-
10868
- if (invalidSegmentRegEx.exec(subpath) !== null) {
10869
- const request = pattern
10870
- ? match.replace('*', () => subpath)
10871
- : match + subpath;
10872
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
10873
- if (!isPathMap) {
10874
- const resolvedTarget = pattern
10875
- ? RegExpPrototypeSymbolReplace.call(
10876
- patternRegEx,
10877
- target,
10878
- () => subpath
10879
- )
10880
- : target;
10881
- emitInvalidSegmentDeprecation(
10882
- resolvedTarget,
10883
- request,
10884
- match,
10885
- packageJsonUrl,
10886
- internal,
10887
- base,
10888
- false
10889
- );
10890
- }
10891
- } else {
10892
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
10893
- }
10894
- }
10895
-
10896
- if (pattern) {
10897
- return new URL$2(
10898
- RegExpPrototypeSymbolReplace.call(
10899
- patternRegEx,
10900
- resolved.href,
10901
- () => subpath
10902
- )
10903
- )
10904
- }
10905
-
10906
- return new URL$2(subpath, resolved)
10907
- }
10908
-
10909
- /**
10910
- * @param {string} key
10911
- * @returns {boolean}
10912
- */
10913
- function isArrayIndex(key) {
10914
- const keyNumber = Number(key);
10915
- if (`${keyNumber}` !== key) return false
10916
- return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
10917
- }
10918
-
10919
- /**
10920
- * @param {URL} packageJsonUrl
10921
- * @param {unknown} target
10922
- * @param {string} subpath
10923
- * @param {string} packageSubpath
10924
- * @param {URL} base
10925
- * @param {boolean} pattern
10926
- * @param {boolean} internal
10927
- * @param {boolean} isPathMap
10928
- * @param {Set<string> | undefined} conditions
10929
- * @returns {URL | null}
10930
- */
10931
- function resolvePackageTarget(
10932
- packageJsonUrl,
10933
- target,
10934
- subpath,
10935
- packageSubpath,
10936
- base,
10937
- pattern,
10938
- internal,
10939
- isPathMap,
10940
- conditions
10941
- ) {
10942
- if (typeof target === 'string') {
10943
- return resolvePackageTargetString(
10944
- target,
10945
- subpath,
10946
- packageSubpath,
10947
- packageJsonUrl,
10948
- base,
10949
- pattern,
10950
- internal,
10951
- isPathMap,
10952
- conditions
10953
- )
10954
- }
10955
-
10956
- if (Array.isArray(target)) {
10957
- /** @type {Array<unknown>} */
10958
- const targetList = target;
10959
- if (targetList.length === 0) return null
10960
-
10961
- /** @type {ErrnoException | null | undefined} */
10962
- let lastException;
10963
- let i = -1;
10964
-
10965
- while (++i < targetList.length) {
10966
- const targetItem = targetList[i];
10967
- /** @type {URL | null} */
10968
- let resolveResult;
10969
- try {
10970
- resolveResult = resolvePackageTarget(
10971
- packageJsonUrl,
10972
- targetItem,
10973
- subpath,
10974
- packageSubpath,
10975
- base,
10976
- pattern,
10977
- internal,
10978
- isPathMap,
10979
- conditions
10980
- );
10981
- } catch (error) {
10982
- const exception = /** @type {ErrnoException} */ (error);
10983
- lastException = exception;
10984
- if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
10985
- throw error
10986
- }
10987
-
10988
- if (resolveResult === undefined) continue
10989
-
10990
- if (resolveResult === null) {
10991
- lastException = null;
10992
- continue
10993
- }
10994
-
10995
- return resolveResult
10996
- }
10997
-
10998
- if (lastException === undefined || lastException === null) {
10999
- return null
11000
- }
11001
-
11002
- throw lastException
11003
- }
11004
-
11005
- if (typeof target === 'object' && target !== null) {
11006
- const keys = Object.getOwnPropertyNames(target);
11007
- let i = -1;
11008
-
11009
- while (++i < keys.length) {
11010
- const key = keys[i];
11011
- if (isArrayIndex(key)) {
11012
- throw new ERR_INVALID_PACKAGE_CONFIG(
11013
- fileURLToPath$1(packageJsonUrl),
11014
- base,
11015
- '"exports" cannot contain numeric property keys.'
11016
- )
11017
- }
11018
- }
11019
-
11020
- i = -1;
11021
-
11022
- while (++i < keys.length) {
11023
- const key = keys[i];
11024
- if (key === 'default' || (conditions && conditions.has(key))) {
11025
- // @ts-expect-error: indexable.
11026
- const conditionalTarget = /** @type {unknown} */ (target[key]);
11027
- const resolveResult = resolvePackageTarget(
11028
- packageJsonUrl,
11029
- conditionalTarget,
11030
- subpath,
11031
- packageSubpath,
11032
- base,
11033
- pattern,
11034
- internal,
11035
- isPathMap,
11036
- conditions
11037
- );
11038
- if (resolveResult === undefined) continue
11039
- return resolveResult
11040
- }
11041
- }
11042
-
11043
- return null
11044
- }
11045
-
11046
- if (target === null) {
11047
- return null
11048
- }
11049
-
11050
- throw invalidPackageTarget(
11051
- packageSubpath,
11052
- target,
11053
- packageJsonUrl,
11054
- internal,
11055
- base
11056
- )
11057
- }
11058
-
11059
- /**
11060
- * @param {unknown} exports
11061
- * @param {URL} packageJsonUrl
11062
- * @param {URL} base
11063
- * @returns {boolean}
11064
- */
11065
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
11066
- if (typeof exports === 'string' || Array.isArray(exports)) return true
11067
- if (typeof exports !== 'object' || exports === null) return false
11068
-
11069
- const keys = Object.getOwnPropertyNames(exports);
11070
- let isConditionalSugar = false;
11071
- let i = 0;
11072
- let keyIndex = -1;
11073
- while (++keyIndex < keys.length) {
11074
- const key = keys[keyIndex];
11075
- const currentIsConditionalSugar = key === '' || key[0] !== '.';
11076
- if (i++ === 0) {
11077
- isConditionalSugar = currentIsConditionalSugar;
11078
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
11079
- throw new ERR_INVALID_PACKAGE_CONFIG(
11080
- fileURLToPath$1(packageJsonUrl),
11081
- base,
11082
- '"exports" cannot contain some keys starting with \'.\' and some not.' +
11083
- ' The exports object must either be an object of package subpath keys' +
11084
- ' or an object of main entry condition name keys only.'
11085
- )
11086
- }
11087
- }
11088
-
11089
- return isConditionalSugar
11090
- }
11091
-
11092
- /**
11093
- * @param {string} match
11094
- * @param {URL} pjsonUrl
11095
- * @param {URL} base
11096
- */
11097
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
11098
- // @ts-expect-error: apparently it does exist, TS.
11099
- if (process$1.noDeprecation) {
11100
- return
11101
- }
11102
-
11103
- const pjsonPath = fileURLToPath$1(pjsonUrl);
11104
- if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
11105
- emittedPackageWarnings.add(pjsonPath + '|' + match);
11106
- process$1.emitWarning(
11107
- `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
11108
- `"exports" field module resolution of the package at ${pjsonPath}${
11109
- base ? ` imported from ${fileURLToPath$1(base)}` : ''
11110
- }. Mapping specifiers ending in "/" is no longer supported.`,
11111
- 'DeprecationWarning',
11112
- 'DEP0155'
11113
- );
11114
- }
11115
-
11116
- /**
11117
- * @param {URL} packageJsonUrl
11118
- * @param {string} packageSubpath
11119
- * @param {Record<string, unknown>} packageConfig
11120
- * @param {URL} base
11121
- * @param {Set<string> | undefined} conditions
11122
- * @returns {URL}
11123
- */
11124
- function packageExportsResolve(
11125
- packageJsonUrl,
11126
- packageSubpath,
11127
- packageConfig,
11128
- base,
11129
- conditions
11130
- ) {
11131
- let exports = packageConfig.exports;
11132
-
11133
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
11134
- exports = {'.': exports};
11135
- }
11136
-
11137
- if (
11138
- own.call(exports, packageSubpath) &&
11139
- !packageSubpath.includes('*') &&
11140
- !packageSubpath.endsWith('/')
11141
- ) {
11142
- // @ts-expect-error: indexable.
11143
- const target = exports[packageSubpath];
11144
- const resolveResult = resolvePackageTarget(
11145
- packageJsonUrl,
11146
- target,
11147
- '',
11148
- packageSubpath,
11149
- base,
11150
- false,
11151
- false,
11152
- false,
11153
- conditions
11154
- );
11155
- if (resolveResult === null || resolveResult === undefined) {
11156
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
11157
- }
11158
-
11159
- return resolveResult
11160
- }
11161
-
11162
- let bestMatch = '';
11163
- let bestMatchSubpath = '';
11164
- const keys = Object.getOwnPropertyNames(exports);
11165
- let i = -1;
11166
-
11167
- while (++i < keys.length) {
11168
- const key = keys[i];
11169
- const patternIndex = key.indexOf('*');
11170
-
11171
- if (
11172
- patternIndex !== -1 &&
11173
- packageSubpath.startsWith(key.slice(0, patternIndex))
11174
- ) {
11175
- // When this reaches EOL, this can throw at the top of the whole function:
11176
- //
11177
- // if (StringPrototypeEndsWith(packageSubpath, '/'))
11178
- // throwInvalidSubpath(packageSubpath)
11179
- //
11180
- // To match "imports" and the spec.
11181
- if (packageSubpath.endsWith('/')) {
11182
- emitTrailingSlashPatternDeprecation(
11183
- packageSubpath,
11184
- packageJsonUrl,
11185
- base
11186
- );
11187
- }
11188
-
11189
- const patternTrailer = key.slice(patternIndex + 1);
11190
-
11191
- if (
11192
- packageSubpath.length >= key.length &&
11193
- packageSubpath.endsWith(patternTrailer) &&
11194
- patternKeyCompare(bestMatch, key) === 1 &&
11195
- key.lastIndexOf('*') === patternIndex
11196
- ) {
11197
- bestMatch = key;
11198
- bestMatchSubpath = packageSubpath.slice(
11199
- patternIndex,
11200
- packageSubpath.length - patternTrailer.length
11201
- );
11202
- }
11203
- }
11204
- }
11205
-
11206
- if (bestMatch) {
11207
- // @ts-expect-error: indexable.
11208
- const target = /** @type {unknown} */ (exports[bestMatch]);
11209
- const resolveResult = resolvePackageTarget(
11210
- packageJsonUrl,
11211
- target,
11212
- bestMatchSubpath,
11213
- bestMatch,
11214
- base,
11215
- true,
11216
- false,
11217
- packageSubpath.endsWith('/'),
11218
- conditions
11219
- );
11220
-
11221
- if (resolveResult === null || resolveResult === undefined) {
11222
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
11223
- }
11224
-
11225
- return resolveResult
11226
- }
11227
-
11228
- throw exportsNotFound(packageSubpath, packageJsonUrl, base)
11229
- }
11230
-
11231
- /**
11232
- * @param {string} a
11233
- * @param {string} b
11234
- */
11235
- function patternKeyCompare(a, b) {
11236
- const aPatternIndex = a.indexOf('*');
11237
- const bPatternIndex = b.indexOf('*');
11238
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
11239
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
11240
- if (baseLengthA > baseLengthB) return -1
11241
- if (baseLengthB > baseLengthA) return 1
11242
- if (aPatternIndex === -1) return 1
11243
- if (bPatternIndex === -1) return -1
11244
- if (a.length > b.length) return -1
11245
- if (b.length > a.length) return 1
11246
- return 0
11247
- }
11248
-
11249
- /**
11250
- * @param {string} name
11251
- * @param {URL} base
11252
- * @param {Set<string>} [conditions]
11253
- * @returns {URL}
11254
- */
11255
- function packageImportsResolve(name, base, conditions) {
11256
- if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
11257
- const reason = 'is not a valid internal imports specifier name';
11258
- throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
11259
- }
11260
-
11261
- /** @type {URL | undefined} */
11262
- let packageJsonUrl;
11263
-
11264
- const packageConfig = getPackageScopeConfig(base);
11265
-
11266
- if (packageConfig.exists) {
11267
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
11268
- const imports = packageConfig.imports;
11269
- if (imports) {
11270
- if (own.call(imports, name) && !name.includes('*')) {
11271
- const resolveResult = resolvePackageTarget(
11272
- packageJsonUrl,
11273
- imports[name],
11274
- '',
11275
- name,
11276
- base,
11277
- false,
11278
- true,
11279
- false,
11280
- conditions
11281
- );
11282
- if (resolveResult !== null && resolveResult !== undefined) {
11283
- return resolveResult
11284
- }
11285
- } else {
11286
- let bestMatch = '';
11287
- let bestMatchSubpath = '';
11288
- const keys = Object.getOwnPropertyNames(imports);
11289
- let i = -1;
11290
-
11291
- while (++i < keys.length) {
11292
- const key = keys[i];
11293
- const patternIndex = key.indexOf('*');
11294
-
11295
- if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
11296
- const patternTrailer = key.slice(patternIndex + 1);
11297
- if (
11298
- name.length >= key.length &&
11299
- name.endsWith(patternTrailer) &&
11300
- patternKeyCompare(bestMatch, key) === 1 &&
11301
- key.lastIndexOf('*') === patternIndex
11302
- ) {
11303
- bestMatch = key;
11304
- bestMatchSubpath = name.slice(
11305
- patternIndex,
11306
- name.length - patternTrailer.length
11307
- );
11308
- }
11309
- }
11310
- }
11311
-
11312
- if (bestMatch) {
11313
- const target = imports[bestMatch];
11314
- const resolveResult = resolvePackageTarget(
11315
- packageJsonUrl,
11316
- target,
11317
- bestMatchSubpath,
11318
- bestMatch,
11319
- base,
11320
- true,
11321
- true,
11322
- false,
11323
- conditions
11324
- );
11325
-
11326
- if (resolveResult !== null && resolveResult !== undefined) {
11327
- return resolveResult
11328
- }
11329
- }
11330
- }
11331
- }
11332
- }
11333
-
11334
- throw importNotDefined(name, packageJsonUrl, base)
11335
- }
11336
-
11337
- /**
11338
- * @param {string} specifier
11339
- * @param {URL} base
11340
- */
11341
- function parsePackageName(specifier, base) {
11342
- let separatorIndex = specifier.indexOf('/');
11343
- let validPackageName = true;
11344
- let isScoped = false;
11345
- if (specifier[0] === '@') {
11346
- isScoped = true;
11347
- if (separatorIndex === -1 || specifier.length === 0) {
11348
- validPackageName = false;
11349
- } else {
11350
- separatorIndex = specifier.indexOf('/', separatorIndex + 1);
11351
- }
11352
- }
11353
-
11354
- const packageName =
11355
- separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
11356
-
11357
- // Package name cannot have leading . and cannot have percent-encoding or
11358
- // \\ separators.
11359
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
11360
- validPackageName = false;
11361
- }
11362
-
11363
- if (!validPackageName) {
11364
- throw new ERR_INVALID_MODULE_SPECIFIER(
11365
- specifier,
11366
- 'is not a valid package name',
11367
- fileURLToPath$1(base)
11368
- )
11369
- }
11370
-
11371
- const packageSubpath =
11372
- '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
11373
-
11374
- return {packageName, packageSubpath, isScoped}
11375
- }
11376
-
11377
- /**
11378
- * @param {string} specifier
11379
- * @param {URL} base
11380
- * @param {Set<string> | undefined} conditions
11381
- * @returns {URL}
11382
- */
11383
- function packageResolve(specifier, base, conditions) {
11384
- if (builtinModules.includes(specifier)) {
11385
- return new URL$2('node:' + specifier)
11386
- }
11387
-
11388
- const {packageName, packageSubpath, isScoped} = parsePackageName(
11389
- specifier,
11390
- base
11391
- );
11392
-
11393
- // ResolveSelf
11394
- const packageConfig = getPackageScopeConfig(base);
11395
-
11396
- // Can’t test.
11397
- /* c8 ignore next 16 */
11398
- if (packageConfig.exists) {
11399
- const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
11400
- if (
11401
- packageConfig.name === packageName &&
11402
- packageConfig.exports !== undefined &&
11403
- packageConfig.exports !== null
11404
- ) {
11405
- return packageExportsResolve(
11406
- packageJsonUrl,
11407
- packageSubpath,
11408
- packageConfig,
11409
- base,
11410
- conditions
11411
- )
11412
- }
11413
- }
11414
-
11415
- let packageJsonUrl = new URL$2(
11416
- './node_modules/' + packageName + '/package.json',
11417
- base
11418
- );
11419
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
11420
- /** @type {string} */
11421
- let lastPath;
11422
- do {
11423
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
11424
- if (!stat || !stat.isDirectory()) {
11425
- lastPath = packageJsonPath;
11426
- packageJsonUrl = new URL$2(
11427
- (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
11428
- packageName +
11429
- '/package.json',
11430
- packageJsonUrl
11431
- );
11432
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
11433
- continue
11434
- }
11435
-
11436
- // Package match.
11437
- const packageConfig = read(packageJsonPath, {base, specifier});
11438
- if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
11439
- return packageExportsResolve(
11440
- packageJsonUrl,
11441
- packageSubpath,
11442
- packageConfig,
11443
- base,
11444
- conditions
11445
- )
11446
- }
11447
-
11448
- if (packageSubpath === '.') {
11449
- return legacyMainResolve(packageJsonUrl, packageConfig, base)
11450
- }
11451
-
11452
- return new URL$2(packageSubpath, packageJsonUrl)
11453
- // Cross-platform root check.
11454
- } while (packageJsonPath.length !== lastPath.length)
11455
-
11456
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false)
11457
- }
11458
-
11459
- /**
11460
- * @param {string} specifier
11461
- * @returns {boolean}
11462
- */
11463
- function isRelativeSpecifier(specifier) {
11464
- if (specifier[0] === '.') {
11465
- if (specifier.length === 1 || specifier[1] === '/') return true
11466
- if (
11467
- specifier[1] === '.' &&
11468
- (specifier.length === 2 || specifier[2] === '/')
11469
- ) {
11470
- return true
11471
- }
11472
- }
11473
-
11474
- return false
11475
- }
11476
-
11477
- /**
11478
- * @param {string} specifier
11479
- * @returns {boolean}
11480
- */
11481
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
11482
- if (specifier === '') return false
11483
- if (specifier[0] === '/') return true
11484
- return isRelativeSpecifier(specifier)
11485
- }
11486
-
11487
- /**
11488
- * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
11489
- * sync and slightly lower-level than `resolve`).
11490
- *
11491
- * @param {string} specifier
11492
- * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
11493
- * @param {URL} base
11494
- * Full URL (to a file) that `specifier` is resolved relative from.
11495
- * @param {Set<string>} [conditions]
11496
- * Conditions.
11497
- * @param {boolean} [preserveSymlinks]
11498
- * Keep symlinks instead of resolving them.
11499
- * @returns {URL}
11500
- * A URL object to the found thing.
11501
- */
11502
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
11503
- // Note: The Node code supports `base` as a string (in this internal API) too,
11504
- // we don’t.
11505
- const protocol = base.protocol;
11506
- const isData = protocol === 'data:';
11507
- const isRemote = isData || protocol === 'http:' || protocol === 'https:';
11508
- // Order swapped from spec for minor perf gain.
11509
- // Ok since relative URLs cannot parse as URLs.
11510
- /** @type {URL | undefined} */
11511
- let resolved;
11512
-
11513
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
11514
- try {
11515
- resolved = new URL$2(specifier, base);
11516
- } catch (error_) {
11517
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
11518
- error.cause = error_;
11519
- throw error
11520
- }
11521
- } else if (protocol === 'file:' && specifier[0] === '#') {
11522
- resolved = packageImportsResolve(specifier, base, conditions);
11523
- } else {
11524
- try {
11525
- resolved = new URL$2(specifier);
11526
- } catch (error_) {
11527
- // Note: actual code uses `canBeRequiredWithoutScheme`.
11528
- if (isRemote && !builtinModules.includes(specifier)) {
11529
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
11530
- error.cause = error_;
11531
- throw error
11532
- }
11533
-
11534
- resolved = packageResolve(specifier, base, conditions);
11535
- }
11536
- }
11537
-
11538
- assert(resolved !== undefined, 'expected to be defined');
11539
-
11540
- if (resolved.protocol !== 'file:') {
11541
- return resolved
11542
- }
11543
-
11544
- return finalizeResolution(resolved, base)
11545
- }
11546
-
11547
- function fileURLToPath(id) {
11548
- if (typeof id === "string" && !id.startsWith("file://")) {
11549
- return normalizeSlash(id);
11550
- }
11551
- return normalizeSlash(fileURLToPath$1(id));
11552
- }
11553
- function pathToFileURL(id) {
11554
- return pathToFileURL$1(fileURLToPath(id)).toString();
11555
- }
11556
- function normalizeid(id) {
11557
- if (typeof id !== "string") {
11558
- id = id.toString();
11559
- }
11560
- if (/(node|data|http|https|file):/.test(id)) {
11561
- return id;
11562
- }
11563
- if (BUILTIN_MODULES.has(id)) {
11564
- return "node:" + id;
11565
- }
11566
- return "file://" + encodeURI(normalizeSlash(id));
11567
- }
11568
-
11569
- const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
11570
- const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
11571
- const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
11572
- "ERR_MODULE_NOT_FOUND",
11573
- "ERR_UNSUPPORTED_DIR_IMPORT",
11574
- "MODULE_NOT_FOUND",
11575
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
11576
- ]);
11577
- function _tryModuleResolve(id, url, conditions) {
11578
- try {
11579
- return moduleResolve(id, url, conditions);
11580
- } catch (error) {
11581
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
11582
- throw error;
11583
- }
11584
- }
11585
- }
11586
- function _resolve$1(id, options = {}) {
11587
- if (typeof id !== "string") {
11588
- if (id instanceof URL) {
11589
- id = fileURLToPath(id);
11590
- } else {
11591
- throw new TypeError("input must be a `string` or `URL`");
11592
- }
11593
- }
11594
- if (/(node|data|http|https):/.test(id)) {
11595
- return id;
11596
- }
11597
- if (BUILTIN_MODULES.has(id)) {
11598
- return "node:" + id;
11599
- }
11600
- if (id.startsWith("file://")) {
11601
- id = fileURLToPath(id);
11602
- }
11603
- if (isAbsolute(id)) {
11604
- try {
11605
- const stat = statSync$1(id);
11606
- if (stat.isFile()) {
11607
- return pathToFileURL(id);
11608
- }
11609
- } catch (error) {
11610
- if (error?.code !== "ENOENT") {
11611
- throw error;
11612
- }
11613
- }
11614
- }
11615
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
11616
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
11617
- if (_urls.length === 0) {
11618
- _urls.push(new URL(pathToFileURL(process.cwd())));
11619
- }
11620
- const urls = [..._urls];
11621
- for (const url of _urls) {
11622
- if (url.protocol === "file:") {
11623
- urls.push(
11624
- new URL("./", url),
11625
- // If url is directory
11626
- new URL(joinURL(url.pathname, "_index.js"), url),
11627
- // TODO: Remove in next major version?
11628
- new URL("node_modules", url)
11629
- );
11630
- }
11631
- }
11632
- let resolved;
11633
- for (const url of urls) {
11634
- resolved = _tryModuleResolve(id, url, conditionsSet);
11635
- if (resolved) {
11636
- break;
11637
- }
11638
- for (const prefix of ["", "/index"]) {
11639
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
11640
- resolved = _tryModuleResolve(
11641
- id + prefix + extension,
11642
- url,
11643
- conditionsSet
11644
- );
11645
- if (resolved) {
11646
- break;
11647
- }
11648
- }
11649
- if (resolved) {
11650
- break;
11651
- }
11652
- }
11653
- if (resolved) {
11654
- break;
11655
- }
11656
- }
11657
- if (!resolved) {
11658
- const error = new Error(
11659
- `Cannot find module ${id} imported from ${urls.join(", ")}`
11660
- );
11661
- error.code = "ERR_MODULE_NOT_FOUND";
11662
- throw error;
11663
- }
11664
- return pathToFileURL(resolved);
11665
- }
11666
- function resolveSync(id, options) {
11667
- return _resolve$1(id, options);
11668
- }
11669
- function resolvePathSync(id, options) {
11670
- return fileURLToPath(resolveSync(id, options));
11671
- }
11672
-
11673
- function _resolve(path, options = {}) {
11674
- if (options.platform === "auto" || !options.platform)
11675
- options.platform = process$1.platform === "win32" ? "win32" : "posix";
11676
- const modulePath = resolvePathSync(path, {
11677
- url: options.paths
11678
- });
11679
- if (options.platform === "win32")
11680
- return win32.normalize(modulePath);
11681
- return modulePath;
11682
- }
11683
- function resolveModule(name, options = {}) {
11684
- try {
11685
- return _resolve(name, options);
11686
- } catch (e) {
11687
- return void 0;
11688
- }
11689
- }
11690
- function isPackageExists(name, options = {}) {
11691
- return !!resolvePackage(name, options);
11692
- }
11693
- function resolvePackage(name, options = {}) {
11694
- try {
11695
- return _resolve(`${name}/package.json`, options);
11696
- } catch {
11697
- }
11698
- try {
11699
- return _resolve(name, options);
11700
- } catch (e) {
11701
- if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
11702
- console.error(e);
11703
- return false;
11704
- }
11705
- }
11706
-
11707
- const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
11708
- const defaultExclude = [
11709
- "**/node_modules/**",
11710
- "**/dist/**",
11711
- "**/cypress/**",
11712
- "**/.{idea,git,cache,output,temp}/**",
11713
- "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*"
11714
- ];
11715
- const benchmarkConfigDefaults = {
11716
- include: ["**/*.{bench,benchmark}.?(c|m)[jt]s?(x)"],
11717
- exclude: defaultExclude,
11718
- includeSource: [],
11719
- reporters: ["default"]
11720
- };
11721
- const defaultCoverageExcludes = [
11722
- "coverage/**",
11723
- "dist/**",
11724
- "**/node_modules/**",
11725
- "**/[.]**",
11726
- "packages/*/test?(s)/**",
11727
- "**/*.d.ts",
11728
- "**/virtual:*",
11729
- "**/__x00__*",
11730
- "**/\0*",
11731
- "cypress/**",
11732
- "test?(s)/**",
11733
- "test?(-*).?(c|m)[jt]s?(x)",
11734
- "**/*{.,-}{test,spec,bench,benchmark}?(-d).?(c|m)[jt]s?(x)",
11735
- "**/__tests__/**",
11736
- "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*",
11737
- "**/vitest.{workspace,projects}.[jt]s?(on)",
11738
- "**/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}"
11739
- ];
11740
- const coverageConfigDefaults = {
11741
- provider: "v8",
11742
- enabled: false,
11743
- all: true,
11744
- clean: true,
11745
- cleanOnRerun: true,
11746
- reportsDirectory: "./coverage",
11747
- exclude: defaultCoverageExcludes,
11748
- reportOnFailure: false,
11749
- reporter: [
11750
- ["text", {}],
11751
- ["html", {}],
11752
- ["clover", {}],
11753
- ["json", {}]
11754
- ],
11755
- extension: [
11756
- ".js",
11757
- ".cjs",
11758
- ".mjs",
11759
- ".ts",
11760
- ".mts",
11761
- ".tsx",
11762
- ".jsx",
11763
- ".vue",
11764
- ".svelte",
11765
- ".marko"
11766
- ],
11767
- allowExternal: false,
11768
- ignoreEmptyLines: true,
11769
- processingConcurrency: Math.min(
11770
- 20,
11771
- nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length
11772
- )
11773
- };
11774
- const fakeTimersDefaults = {
11775
- loopLimit: 1e4,
11776
- shouldClearNativeTimers: true,
11777
- toFake: [
11778
- "setTimeout",
11779
- "clearTimeout",
11780
- "setInterval",
11781
- "clearInterval",
11782
- "setImmediate",
11783
- "clearImmediate",
11784
- "Date"
11785
- ]
11786
- };
11787
- const config = {
11788
- allowOnly: !isCI,
11789
- isolate: true,
11790
- watch: !isCI,
11791
- globals: false,
11792
- environment: "node",
11793
- pool: "forks",
11794
- clearMocks: false,
11795
- restoreMocks: false,
11796
- mockReset: false,
11797
- unstubGlobals: false,
11798
- unstubEnvs: false,
11799
- include: defaultInclude,
11800
- exclude: defaultExclude,
11801
- teardownTimeout: 1e4,
11802
- forceRerunTriggers: ["**/package.json/**", "**/{vitest,vite}.config.*/**"],
11803
- update: false,
11804
- reporters: [],
11805
- silent: false,
11806
- hideSkippedTests: false,
11807
- api: false,
11808
- ui: false,
11809
- uiBase: "/__vitest__/",
11810
- open: !isCI,
11811
- css: {
11812
- include: []
11813
- },
11814
- coverage: coverageConfigDefaults,
11815
- fakeTimers: fakeTimersDefaults,
11816
- maxConcurrency: 5,
11817
- dangerouslyIgnoreUnhandledErrors: false,
11818
- typecheck: {
11819
- checker: "tsc",
11820
- include: ["**/*.{test,spec}-d.?(c|m)[jt]s?(x)"],
11821
- exclude: defaultExclude
11822
- },
11823
- slowTestThreshold: 300,
11824
- disableConsoleIntercept: false
11825
- };
11826
- const configDefaults = Object.freeze(config);
11827
-
11828
- function getWorkersCountByPercentage(percent) {
11829
- const maxWorkersCount = nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length;
11830
- const workersCountByPercentage = Math.round(Number.parseInt(percent) / 100 * maxWorkersCount);
11831
- return Math.max(1, Math.min(maxWorkersCount, workersCountByPercentage));
11832
- }
11833
-
11834
- class FilesStatsCache {
11835
- cache = /* @__PURE__ */ new Map();
11836
- getStats(key) {
11837
- return this.cache.get(key);
11838
- }
11839
- async populateStats(root, specs) {
11840
- const promises = specs.map((spec) => {
11841
- const key = `${spec[0].getName()}:${relative(root, spec[1])}`;
11842
- return this.updateStats(spec[1], key);
11843
- });
11844
- await Promise.all(promises);
11845
- }
11846
- async updateStats(fsPath, key) {
11847
- if (!fs$8.existsSync(fsPath)) {
11848
- return;
11849
- }
11850
- const stats = await fs$8.promises.stat(fsPath);
11851
- this.cache.set(key, { size: stats.size });
11852
- }
11853
- removeStats(fsPath) {
11854
- this.cache.forEach((_, key) => {
11855
- if (key.endsWith(fsPath)) {
11856
- this.cache.delete(key);
11857
- }
11858
- });
11859
- }
11860
- }
11861
-
11862
- class ResultsCache {
11863
- cache = /* @__PURE__ */ new Map();
11864
- workspacesKeyMap = /* @__PURE__ */ new Map();
11865
- cachePath = null;
11866
- version;
11867
- root = "/";
11868
- constructor(version) {
11869
- this.version = version;
11870
- }
11871
- getCachePath() {
11872
- return this.cachePath;
11873
- }
11874
- setConfig(root, config) {
11875
- this.root = root;
11876
- if (config) {
11877
- this.cachePath = resolve(config.dir, "results.json");
11878
- }
11879
- }
11880
- getResults(key) {
11881
- return this.cache.get(key);
11882
- }
11883
- async readFromCache() {
11884
- if (!this.cachePath) {
11885
- return;
11886
- }
11887
- if (!fs$8.existsSync(this.cachePath)) {
11888
- return;
11889
- }
11890
- const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8");
11891
- const { results, version } = JSON.parse(resultsCache || "[]");
11892
- if (Number(version.split(".")[1]) >= 30) {
11893
- this.cache = new Map(results);
11894
- this.version = version;
11895
- results.forEach(([spec]) => {
11896
- const [projectName, relativePath] = spec.split(":");
11897
- const keyMap = this.workspacesKeyMap.get(relativePath) || [];
11898
- keyMap.push(projectName);
11899
- this.workspacesKeyMap.set(relativePath, keyMap);
11900
- });
11901
- }
11902
- }
11903
- updateResults(files) {
11904
- files.forEach((file) => {
11905
- const result = file.result;
11906
- if (!result) {
11907
- return;
11908
- }
11909
- const duration = result.duration || 0;
11910
- const relativePath = relative(this.root, file.filepath);
11911
- this.cache.set(`${file.projectName || ""}:${relativePath}`, {
11912
- duration: duration >= 0 ? duration : 0,
11913
- failed: result.state === "fail"
11914
- });
11915
- });
11916
- }
11917
- removeFromCache(filepath) {
11918
- this.cache.forEach((_, key) => {
11919
- if (key.endsWith(filepath)) {
11920
- this.cache.delete(key);
11921
- }
11922
- });
11923
- }
11924
- async writeToCache() {
11925
- if (!this.cachePath) {
11926
- return;
11927
- }
11928
- const results = Array.from(this.cache.entries());
11929
- const cacheDirname = dirname(this.cachePath);
11930
- if (!fs$8.existsSync(cacheDirname)) {
11931
- await fs$8.promises.mkdir(cacheDirname, { recursive: true });
11932
- }
11933
- const cache = JSON.stringify({
11934
- version: this.version,
11935
- results
11936
- });
11937
- await fs$8.promises.writeFile(this.cachePath, cache);
11938
- }
11939
- }
11940
-
11941
- class VitestCache {
11942
- results;
11943
- stats = new FilesStatsCache();
11944
- constructor(version) {
11945
- this.results = new ResultsCache(version);
11946
- }
11947
- getFileTestResults(key) {
11948
- return this.results.getResults(key);
11949
- }
11950
- getFileStats(key) {
11951
- return this.stats.getStats(key);
11952
- }
11953
- static resolveCacheDir(root, dir, projectName) {
11954
- const baseDir = slash$1(dir || "node_modules/.vite/vitest");
11955
- return projectName ? resolve(
11956
- root,
11957
- baseDir,
11958
- crypto.createHash("md5").update(projectName, "utf-8").digest("hex")
11959
- ) : resolve(root, baseDir);
11960
- }
11961
- }
11962
-
11963
- function resolvePath(path, root) {
11964
- return normalize(
11965
- /* @__PURE__ */ resolveModule(path, { paths: [root] }) ?? resolve(root, path)
11966
- );
11967
- }
11968
- function parseInspector(inspect) {
11969
- if (typeof inspect === "boolean" || inspect === void 0) {
11970
- return {};
11971
- }
11972
- if (typeof inspect === "number") {
11973
- return { port: inspect };
11974
- }
11975
- if (inspect.match(/https?:\//)) {
11976
- throw new Error(
11977
- `Inspector host cannot be a URL. Use "host:port" instead of "${inspect}"`
11978
- );
11979
- }
11980
- const [host, port] = inspect.split(":");
11981
- if (!port) {
11982
- return { host };
8292
+ addProcessTimeoutCause(cause) {
8293
+ this.processTimeoutCauses.add(cause);
11983
8294
  }
11984
- return { host, port: Number(port) || defaultInspectPort };
11985
- }
11986
- function resolveApiServerConfig(options, defaultPort2) {
11987
- let api;
11988
- if (options.ui && !options.api) {
11989
- api = { port: defaultPort2 };
11990
- } else if (options.api === true) {
11991
- api = { port: defaultPort2 };
11992
- } else if (typeof options.api === "number") {
11993
- api = { port: options.api };
8295
+ getProcessTimeoutCauses() {
8296
+ return Array.from(this.processTimeoutCauses.values());
11994
8297
  }
11995
- if (typeof options.api === "object") {
11996
- if (api) {
11997
- if (options.api.port) {
11998
- api.port = options.api.port;
11999
- }
12000
- if (options.api.strictPort) {
12001
- api.strictPort = options.api.strictPort;
12002
- }
12003
- if (options.api.host) {
12004
- api.host = options.api.host;
12005
- }
12006
- } else {
12007
- api = { ...options.api };
12008
- }
8298
+ getPaths() {
8299
+ return Array.from(this.pathsSet);
12009
8300
  }
12010
- if (api) {
12011
- if (!api.port && !api.middlewareMode) {
12012
- api.port = defaultPort2;
8301
+ /**
8302
+ * Return files that were running or collected.
8303
+ */
8304
+ getFiles(keys) {
8305
+ if (keys) {
8306
+ return keys.map((key) => this.filesMap.get(key)).flat().filter((file) => file && !file.local);
12013
8307
  }
12014
- } else {
12015
- api = { middlewareMode: true };
8308
+ return Array.from(this.filesMap.values()).flat().filter((file) => !file.local);
12016
8309
  }
12017
- return api;
12018
- }
12019
- function resolveInlineWorkerOption(value) {
12020
- if (typeof value === "string" && value.trim().endsWith("%")) {
12021
- return getWorkersCountByPercentage(value);
12022
- } else {
12023
- return Number(value);
8310
+ getFilepaths() {
8311
+ return Array.from(this.filesMap.keys());
12024
8312
  }
12025
- }
12026
- function resolveConfig(mode, options, viteConfig, logger) {
12027
- if (options.dom) {
12028
- if (viteConfig.test?.environment != null && viteConfig.test.environment !== "happy-dom") {
12029
- logger.console.warn(
12030
- c.yellow(
12031
- `${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`
12032
- )
12033
- );
12034
- }
12035
- options.environment = "happy-dom";
8313
+ getFailedFilepaths() {
8314
+ return this.getFiles().filter((i) => i.result?.state === "fail").map((i) => i.filepath);
12036
8315
  }
12037
- const resolved = {
12038
- ...configDefaults,
12039
- ...options,
12040
- root: viteConfig.root,
12041
- mode
12042
- };
12043
- const inspector = resolved.inspect || resolved.inspectBrk;
12044
- resolved.inspector = {
12045
- ...resolved.inspector,
12046
- ...parseInspector(inspector),
12047
- enabled: !!inspector,
12048
- waitForDebugger: options.inspector?.waitForDebugger ?? !!resolved.inspectBrk
12049
- };
12050
- if (viteConfig.base !== "/") {
12051
- resolved.base = viteConfig.base;
8316
+ collectPaths(paths = []) {
8317
+ paths.forEach((path) => {
8318
+ this.pathsSet.add(path);
8319
+ });
12052
8320
  }
12053
- resolved.clearScreen = resolved.clearScreen ?? viteConfig.clearScreen ?? true;
12054
- if (options.shard) {
12055
- if (resolved.watch) {
12056
- throw new Error("You cannot use --shard option with enabled watch");
12057
- }
12058
- const [indexString, countString] = options.shard.split("/");
12059
- const index = Math.abs(Number.parseInt(indexString, 10));
12060
- const count = Math.abs(Number.parseInt(countString, 10));
12061
- if (Number.isNaN(count) || count <= 0) {
12062
- throw new Error("--shard <count> must be a positive number");
12063
- }
12064
- if (Number.isNaN(index) || index <= 0 || index > count) {
12065
- throw new Error(
12066
- "--shard <index> must be a positive number less then <count>"
8321
+ collectFiles(project, files = []) {
8322
+ files.forEach((file) => {
8323
+ const existing = this.filesMap.get(file.filepath) || [];
8324
+ const otherProject = existing.filter(
8325
+ (i) => i.projectName !== file.projectName
12067
8326
  );
12068
- }
12069
- resolved.shard = { index, count };
12070
- }
12071
- if (resolved.standalone && !resolved.watch) {
12072
- throw new Error(`Vitest standalone mode requires --watch`);
12073
- }
12074
- if (resolved.mergeReports && resolved.watch) {
12075
- throw new Error(`Cannot merge reports with --watch enabled`);
12076
- }
12077
- if (resolved.maxWorkers) {
12078
- resolved.maxWorkers = resolveInlineWorkerOption(resolved.maxWorkers);
12079
- }
12080
- if (resolved.minWorkers) {
12081
- resolved.minWorkers = resolveInlineWorkerOption(resolved.minWorkers);
12082
- }
12083
- resolved.browser ??= {};
12084
- resolved.fileParallelism ??= mode !== "benchmark";
12085
- if (!resolved.fileParallelism) {
12086
- resolved.maxWorkers = 1;
12087
- resolved.minWorkers = 1;
12088
- }
12089
- if (resolved.inspect || resolved.inspectBrk) {
12090
- const isSingleThread = resolved.pool === "threads" && resolved.poolOptions?.threads?.singleThread;
12091
- const isSingleFork = resolved.pool === "forks" && resolved.poolOptions?.forks?.singleFork;
12092
- if (resolved.fileParallelism && !isSingleThread && !isSingleFork) {
12093
- const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
12094
- throw new Error(
12095
- `You cannot use ${inspectOption} without "--no-file-parallelism", "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`
8327
+ const currentFile = existing.find(
8328
+ (i) => i.projectName === file.projectName
12096
8329
  );
12097
- }
12098
- }
12099
- if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved)) {
12100
- throw new Error(
12101
- "@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead"
12102
- );
8330
+ if (currentFile) {
8331
+ file.logs = currentFile.logs;
8332
+ }
8333
+ otherProject.push(file);
8334
+ this.filesMap.set(file.filepath, otherProject);
8335
+ this.updateId(file, project);
8336
+ });
12103
8337
  }
12104
- if (resolved.coverage.enabled && resolved.coverage.reportsDirectory) {
12105
- const reportsDirectory = resolve(
12106
- resolved.root,
12107
- resolved.coverage.reportsDirectory
12108
- );
12109
- if (reportsDirectory === resolved.root || reportsDirectory === process.cwd()) {
12110
- throw new Error(
12111
- `You cannot set "coverage.reportsDirectory" as ${reportsDirectory}. Vitest needs to be able to remove this directory before test run`
8338
+ clearFiles(project, paths = []) {
8339
+ paths.forEach((path) => {
8340
+ const files = this.filesMap.get(path);
8341
+ const fileTask = createFileTask(
8342
+ path,
8343
+ project.config.root,
8344
+ project.config.name
12112
8345
  );
12113
- }
12114
- }
12115
- if (resolved.coverage.enabled && resolved.coverage.provider === "custom" && resolved.coverage.customProviderModule) {
12116
- resolved.coverage.customProviderModule = resolvePath(
12117
- resolved.coverage.customProviderModule,
12118
- resolved.root
12119
- );
12120
- }
12121
- resolved.expect ??= {};
12122
- resolved.deps ??= {};
12123
- resolved.deps.moduleDirectories ??= [];
12124
- resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map(
12125
- (dir) => {
12126
- if (!dir.startsWith("/")) {
12127
- dir = `/${dir}`;
12128
- }
12129
- if (!dir.endsWith("/")) {
12130
- dir += "/";
8346
+ fileTask.local = true;
8347
+ TestFile.register(fileTask, project);
8348
+ this.idMap.set(fileTask.id, fileTask);
8349
+ if (!files) {
8350
+ this.filesMap.set(path, [fileTask]);
8351
+ return;
12131
8352
  }
12132
- return normalize(dir);
12133
- }
12134
- );
12135
- if (!resolved.deps.moduleDirectories.includes("/node_modules/")) {
12136
- resolved.deps.moduleDirectories.push("/node_modules/");
12137
- }
12138
- resolved.deps.optimizer ??= {};
12139
- resolved.deps.optimizer.ssr ??= {};
12140
- resolved.deps.optimizer.ssr.enabled ??= true;
12141
- resolved.deps.optimizer.web ??= {};
12142
- resolved.deps.optimizer.web.enabled ??= true;
12143
- resolved.deps.web ??= {};
12144
- resolved.deps.web.transformAssets ??= true;
12145
- resolved.deps.web.transformCss ??= true;
12146
- resolved.deps.web.transformGlobPattern ??= [];
12147
- resolved.server ??= {};
12148
- resolved.server.deps ??= {};
12149
- const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
12150
- deprecatedDepsOptions.forEach((option) => {
12151
- if (resolved.deps[option] === void 0) {
12152
- return;
12153
- }
12154
- if (option === "fallbackCJS") {
12155
- logger.console.warn(
12156
- c.yellow(
12157
- `${c.inverse(
12158
- c.yellow(" Vitest ")
12159
- )} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`
12160
- )
12161
- );
12162
- } else {
12163
- const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
12164
- logger.console.warn(
12165
- c.yellow(
12166
- `${c.inverse(
12167
- c.yellow(" Vitest ")
12168
- )} "deps.${option}" is deprecated. If you rely on vite-node directly, use "server.deps.${option}" instead. Otherwise, consider using "deps.optimizer.${transformMode}.${option === "external" ? "exclude" : "include"}"`
12169
- )
8353
+ const filtered = files.filter(
8354
+ (file) => file.projectName !== project.config.name
12170
8355
  );
12171
- }
12172
- if (resolved.server.deps[option] === void 0) {
12173
- resolved.server.deps[option] = resolved.deps[option];
12174
- }
12175
- });
12176
- if (resolved.cliExclude) {
12177
- resolved.exclude.push(...resolved.cliExclude);
12178
- }
12179
- if (resolved.server.deps.inline !== true) {
12180
- const ssrOptions = viteConfig.ssr;
12181
- if (ssrOptions?.noExternal === true && resolved.server.deps.inline == null) {
12182
- resolved.server.deps.inline = true;
12183
- } else {
12184
- resolved.server.deps.inline ??= [];
12185
- resolved.server.deps.inline.push(...extraInlineDeps);
12186
- }
12187
- }
12188
- resolved.server.deps.moduleDirectories ??= [];
12189
- resolved.server.deps.moduleDirectories.push(
12190
- ...resolved.deps.moduleDirectories
12191
- );
12192
- if (resolved.runner) {
12193
- resolved.runner = resolvePath(resolved.runner, resolved.root);
12194
- }
12195
- if (resolved.snapshotEnvironment) {
12196
- resolved.snapshotEnvironment = resolvePath(
12197
- resolved.snapshotEnvironment,
12198
- resolved.root
12199
- );
12200
- }
12201
- resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
12202
- if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat) {
12203
- resolved.snapshotFormat.plugins = [];
12204
- }
12205
- const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
12206
- resolved.snapshotOptions = {
12207
- expand: resolved.expandSnapshotDiff ?? false,
12208
- snapshotFormat: resolved.snapshotFormat || {},
12209
- updateSnapshot: isCI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
12210
- resolveSnapshotPath: options.resolveSnapshotPath,
12211
- // resolved inside the worker
12212
- snapshotEnvironment: null
12213
- };
12214
- resolved.snapshotSerializers ??= [];
12215
- resolved.snapshotSerializers = resolved.snapshotSerializers.map(
12216
- (file) => resolvePath(file, resolved.root)
12217
- );
12218
- resolved.forceRerunTriggers.push(...resolved.snapshotSerializers);
12219
- if (options.resolveSnapshotPath) {
12220
- delete resolved.resolveSnapshotPath;
12221
- }
12222
- resolved.pool ??= "threads";
12223
- if (process.env.VITEST_MAX_THREADS) {
12224
- resolved.poolOptions = {
12225
- ...resolved.poolOptions,
12226
- threads: {
12227
- ...resolved.poolOptions?.threads,
12228
- maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
12229
- },
12230
- vmThreads: {
12231
- ...resolved.poolOptions?.vmThreads,
12232
- maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
12233
- }
12234
- };
12235
- }
12236
- if (process.env.VITEST_MIN_THREADS) {
12237
- resolved.poolOptions = {
12238
- ...resolved.poolOptions,
12239
- threads: {
12240
- ...resolved.poolOptions?.threads,
12241
- minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
12242
- },
12243
- vmThreads: {
12244
- ...resolved.poolOptions?.vmThreads,
12245
- minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
12246
- }
12247
- };
12248
- }
12249
- if (process.env.VITEST_MAX_FORKS) {
12250
- resolved.poolOptions = {
12251
- ...resolved.poolOptions,
12252
- forks: {
12253
- ...resolved.poolOptions?.forks,
12254
- maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
12255
- },
12256
- vmForks: {
12257
- ...resolved.poolOptions?.vmForks,
12258
- maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
12259
- }
12260
- };
12261
- }
12262
- if (process.env.VITEST_MIN_FORKS) {
12263
- resolved.poolOptions = {
12264
- ...resolved.poolOptions,
12265
- forks: {
12266
- ...resolved.poolOptions?.forks,
12267
- minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
12268
- },
12269
- vmForks: {
12270
- ...resolved.poolOptions?.vmForks,
12271
- minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
8356
+ if (!filtered.length) {
8357
+ this.filesMap.set(path, [fileTask]);
8358
+ } else {
8359
+ this.filesMap.set(path, [...filtered, fileTask]);
12272
8360
  }
12273
- };
12274
- }
12275
- const poolThreadsOptions = [
12276
- ["threads", "minThreads"],
12277
- ["threads", "maxThreads"],
12278
- ["vmThreads", "minThreads"],
12279
- ["vmThreads", "maxThreads"]
12280
- ];
12281
- for (const [poolOptionKey, workerOptionKey] of poolThreadsOptions) {
12282
- if (resolved.poolOptions?.[poolOptionKey]?.[workerOptionKey]) {
12283
- resolved.poolOptions[poolOptionKey][workerOptionKey] = resolveInlineWorkerOption(resolved.poolOptions[poolOptionKey][workerOptionKey]);
12284
- }
12285
- }
12286
- const poolForksOptions = [
12287
- ["forks", "minForks"],
12288
- ["forks", "maxForks"],
12289
- ["vmForks", "minForks"],
12290
- ["vmForks", "maxForks"]
12291
- ];
12292
- for (const [poolOptionKey, workerOptionKey] of poolForksOptions) {
12293
- if (resolved.poolOptions?.[poolOptionKey]?.[workerOptionKey]) {
12294
- resolved.poolOptions[poolOptionKey][workerOptionKey] = resolveInlineWorkerOption(resolved.poolOptions[poolOptionKey][workerOptionKey]);
12295
- }
12296
- }
12297
- if (resolved.workspace) {
12298
- resolved.workspace = options.workspace && options.workspace[0] === "." ? resolve(process.cwd(), options.workspace) : resolvePath(resolved.workspace, resolved.root);
12299
- }
12300
- if (!builtinPools.includes(resolved.pool)) {
12301
- resolved.pool = resolvePath(resolved.pool, resolved.root);
8361
+ });
12302
8362
  }
12303
- resolved.poolMatchGlobs = (resolved.poolMatchGlobs || []).map(
12304
- ([glob, pool]) => {
12305
- if (!builtinPools.includes(pool)) {
12306
- pool = resolvePath(pool, resolved.root);
12307
- }
12308
- return [glob, pool];
8363
+ updateId(task, project) {
8364
+ if (this.idMap.get(task.id) === task) {
8365
+ return;
12309
8366
  }
12310
- );
12311
- if (mode === "benchmark") {
12312
- resolved.benchmark = {
12313
- ...benchmarkConfigDefaults,
12314
- ...resolved.benchmark
12315
- };
12316
- resolved.coverage.enabled = false;
12317
- resolved.include = resolved.benchmark.include;
12318
- resolved.exclude = resolved.benchmark.exclude;
12319
- resolved.includeSource = resolved.benchmark.includeSource;
12320
- const reporters = Array.from(
12321
- /* @__PURE__ */ new Set([
12322
- ...toArray(resolved.benchmark.reporters),
12323
- // @ts-expect-error reporter is CLI flag
12324
- ...toArray(options.reporter)
12325
- ])
12326
- ).filter(Boolean);
12327
- if (reporters.length) {
12328
- resolved.benchmark.reporters = reporters;
8367
+ if (task.type === "suite" && "filepath" in task) {
8368
+ TestFile.register(task, project);
8369
+ } else if (task.type === "suite") {
8370
+ TestSuite.register(task, project);
12329
8371
  } else {
12330
- resolved.benchmark.reporters = ["default"];
12331
- }
12332
- if (options.outputFile) {
12333
- resolved.benchmark.outputFile = options.outputFile;
12334
- }
12335
- if (options.compare) {
12336
- resolved.benchmark.compare = options.compare;
8372
+ TestCase.register(task, project);
12337
8373
  }
12338
- if (options.outputJson) {
12339
- resolved.benchmark.outputJson = options.outputJson;
8374
+ this.idMap.set(task.id, task);
8375
+ if (task.type === "suite") {
8376
+ task.tasks.forEach((task2) => {
8377
+ this.updateId(task2, project);
8378
+ });
12340
8379
  }
12341
8380
  }
12342
- resolved.setupFiles = toArray(resolved.setupFiles || []).map(
12343
- (file) => resolvePath(file, resolved.root)
12344
- );
12345
- resolved.globalSetup = toArray(resolved.globalSetup || []).map(
12346
- (file) => resolvePath(file, resolved.root)
12347
- );
12348
- resolved.coverage.exclude.push(
12349
- ...resolved.setupFiles.map(
12350
- (file) => `${resolved.coverage.allowExternal ? "**/" : ""}${relative(
12351
- resolved.root,
12352
- file
12353
- )}`
12354
- )
12355
- );
12356
- resolved.forceRerunTriggers = [
12357
- ...resolved.forceRerunTriggers,
12358
- ...resolved.setupFiles
12359
- ];
12360
- if (resolved.diff) {
12361
- resolved.diff = resolvePath(resolved.diff, resolved.root);
12362
- resolved.forceRerunTriggers.push(resolved.diff);
12363
- }
12364
- resolved.api = resolveApiServerConfig(options, defaultPort);
12365
- if (options.related) {
12366
- resolved.related = toArray(options.related).map(
12367
- (file) => resolve(resolved.root, file)
12368
- );
8381
+ getReportedEntity(task) {
8382
+ return this.reportedTasksMap.get(task);
12369
8383
  }
12370
- if (options.reporters) {
12371
- if (!Array.isArray(options.reporters)) {
12372
- if (typeof options.reporters === "string") {
12373
- resolved.reporters = [[options.reporters, {}]];
12374
- } else {
12375
- resolved.reporters = [options.reporters];
12376
- }
12377
- } else {
12378
- resolved.reporters = [];
12379
- for (const reporter of options.reporters) {
12380
- if (Array.isArray(reporter)) {
12381
- resolved.reporters.push([reporter[0], reporter[1] || {}]);
12382
- } else if (typeof reporter === "string") {
12383
- resolved.reporters.push([reporter, {}]);
12384
- } else {
12385
- resolved.reporters.push(reporter);
8384
+ updateTasks(packs) {
8385
+ for (const [id, result, meta] of packs) {
8386
+ const task = this.idMap.get(id);
8387
+ if (task) {
8388
+ task.result = result;
8389
+ task.meta = meta;
8390
+ if (result?.state === "skip") {
8391
+ task.mode = "skip";
12386
8392
  }
12387
8393
  }
12388
8394
  }
12389
8395
  }
12390
- if (mode !== "benchmark") {
12391
- const reportersFromCLI = resolved.reporter;
12392
- const cliReporters = toArray(reportersFromCLI || []).map(
12393
- (reporter) => {
12394
- if (/^\.\.?\//.test(reporter)) {
12395
- return resolve(process.cwd(), reporter);
12396
- }
12397
- return reporter;
8396
+ updateUserLog(log) {
8397
+ const task = log.taskId && this.idMap.get(log.taskId);
8398
+ if (task) {
8399
+ if (!task.logs) {
8400
+ task.logs = [];
12398
8401
  }
12399
- );
12400
- if (cliReporters.length) {
12401
- resolved.reporters = Array.from(new Set(toArray(cliReporters))).filter(Boolean).map((reporter) => [reporter, {}]);
12402
- }
12403
- }
12404
- if (!resolved.reporters.length) {
12405
- resolved.reporters.push(["default", {}]);
12406
- if (process.env.GITHUB_ACTIONS === "true") {
12407
- resolved.reporters.push(["github-actions", {}]);
12408
- }
12409
- }
12410
- if (resolved.changed) {
12411
- resolved.passWithNoTests ??= true;
12412
- }
12413
- resolved.css ??= {};
12414
- if (typeof resolved.css === "object") {
12415
- resolved.css.modules ??= {};
12416
- resolved.css.modules.classNameStrategy ??= "stable";
12417
- }
12418
- if (resolved.cache !== false) {
12419
- let cacheDir = VitestCache.resolveCacheDir(
12420
- "",
12421
- resolve(viteConfig.cacheDir, "vitest"),
12422
- resolved.name
12423
- );
12424
- if (resolved.cache && resolved.cache.dir) {
12425
- logger.console.warn(
12426
- c.yellow(
12427
- `${c.inverse(
12428
- c.yellow(" Vitest ")
12429
- )} "cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir/vitest"`
12430
- )
12431
- );
12432
- cacheDir = VitestCache.resolveCacheDir(
12433
- resolved.root,
12434
- resolved.cache.dir,
12435
- resolved.name
12436
- );
8402
+ task.logs.push(log);
12437
8403
  }
12438
- resolved.cache = { dir: cacheDir };
12439
- }
12440
- resolved.sequence ??= {};
12441
- if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === "object") {
12442
- const { files, tests } = resolved.sequence.shuffle;
12443
- resolved.sequence.sequencer ??= files ? RandomSequencer : BaseSequencer;
12444
- resolved.sequence.shuffle = tests;
12445
- }
12446
- if (!resolved.sequence?.sequencer) {
12447
- resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
12448
8404
  }
12449
- resolved.sequence.hooks ??= "stack";
12450
- if (resolved.sequence.sequencer === RandomSequencer) {
12451
- resolved.sequence.seed ??= Date.now();
8405
+ getCountOfFailedTests() {
8406
+ return Array.from(this.idMap.values()).filter(
8407
+ (t) => t.result?.state === "fail"
8408
+ ).length;
12452
8409
  }
12453
- resolved.typecheck = {
12454
- ...configDefaults.typecheck,
12455
- ...resolved.typecheck
12456
- };
12457
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map(
12458
- (i) => [resolve(resolved.root, i[0]), i[1]]
12459
- );
12460
- resolved.typecheck ??= {};
12461
- resolved.typecheck.enabled ??= false;
12462
- if (resolved.typecheck.enabled) {
12463
- logger.console.warn(
12464
- c.yellow(
12465
- "Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."
8410
+ cancelFiles(files, project) {
8411
+ this.collectFiles(
8412
+ project,
8413
+ files.map(
8414
+ (filepath) => createFileTask(filepath, project.config.root, project.config.name)
12466
8415
  )
12467
8416
  );
12468
8417
  }
12469
- resolved.browser ??= {};
12470
- resolved.browser.enabled ??= false;
12471
- resolved.browser.headless ??= isCI;
12472
- resolved.browser.isolate ??= true;
12473
- resolved.browser.fileParallelism ??= options.fileParallelism ?? mode !== "benchmark";
12474
- resolved.browser.ui ??= resolved.browser.headless === true ? false : !isCI;
12475
- if (resolved.browser.screenshotDirectory) {
12476
- resolved.browser.screenshotDirectory = resolve(
12477
- resolved.root,
12478
- resolved.browser.screenshotDirectory
12479
- );
12480
- }
12481
- const isPreview = resolved.browser.provider === "preview";
12482
- if (isPreview && resolved.browser.screenshotFailures === true) {
12483
- console.warn(c.yellow(
12484
- [
12485
- `Browser provider "preview" doesn't support screenshots, `,
12486
- `so "browser.screenshotFailures" option is forcefully disabled. `,
12487
- `Set "browser.screenshotFailures" to false or remove it from the config to suppress this warning.`
12488
- ].join("")
12489
- ));
12490
- resolved.browser.screenshotFailures = false;
12491
- } else {
12492
- resolved.browser.screenshotFailures ??= !isPreview && !resolved.browser.ui;
12493
- }
12494
- resolved.browser.viewport ??= {};
12495
- resolved.browser.viewport.width ??= 414;
12496
- resolved.browser.viewport.height ??= 896;
12497
- if (resolved.browser.enabled && provider$1 === "stackblitz") {
12498
- resolved.browser.provider = "preview";
12499
- }
12500
- resolved.browser.api = resolveApiServerConfig(
12501
- resolved.browser,
12502
- defaultBrowserPort
12503
- ) || {
12504
- port: defaultBrowserPort
12505
- };
12506
- if (resolved.browser.enabled) {
12507
- if (resolved.browser.ui) {
12508
- resolved.includeTaskLocation ??= true;
12509
- }
12510
- } else if (resolved.ui) {
12511
- resolved.includeTaskLocation ??= true;
12512
- }
12513
- const htmlReporter = toArray(resolved.reporters).some((reporter) => {
12514
- if (Array.isArray(reporter)) {
12515
- return reporter[0] === "html";
12516
- }
12517
- return false;
12518
- });
12519
- if (htmlReporter) {
12520
- resolved.includeTaskLocation ??= true;
12521
- }
12522
- resolved.testTransformMode ??= {};
12523
- resolved.testTimeout ??= resolved.browser.enabled ? 15e3 : 5e3;
12524
- resolved.hookTimeout ??= resolved.browser.enabled ? 3e4 : 1e4;
12525
- return resolved;
12526
- }
12527
- function isBrowserEnabled(config) {
12528
- return Boolean(config.browser?.enabled);
12529
8418
  }
12530
8419
 
12531
8420
  function generateCssFilenameHash(filepath) {
@@ -14046,7 +9935,10 @@ function serializeConfig(config, coreConfig, viteConfig) {
14046
9935
  fileParallelism: browser.fileParallelism,
14047
9936
  ui: browser.ui,
14048
9937
  viewport: browser.viewport,
14049
- screenshotFailures: browser.screenshotFailures
9938
+ screenshotFailures: browser.screenshotFailures,
9939
+ locators: {
9940
+ testIdAttribute: browser.locators.testIdAttribute
9941
+ }
14050
9942
  };
14051
9943
  })(config.browser),
14052
9944
  standalone: config.standalone,
@@ -14195,7 +10087,7 @@ class WorkspaceProject {
14195
10087
  await Promise.all(
14196
10088
  files.map(async (file) => {
14197
10089
  try {
14198
- const code = await promises$1.readFile(file, "utf-8");
10090
+ const code = await promises.readFile(file, "utf-8");
14199
10091
  if (this.isInSourceTestFile(code)) {
14200
10092
  testFiles.push(file);
14201
10093
  }
@@ -14229,7 +10121,7 @@ class WorkspaceProject {
14229
10121
  return true;
14230
10122
  }
14231
10123
  if (this.config.includeSource?.length && mm.isMatch(relativeId, this.config.includeSource)) {
14232
- source = source || await promises$1.readFile(id, "utf-8");
10124
+ source = source || await promises.readFile(id, "utf-8");
14233
10125
  return this.isInSourceTestFile(source);
14234
10126
  }
14235
10127
  return false;
@@ -14560,7 +10452,7 @@ class Vitest {
14560
10452
  return this.config.workspace;
14561
10453
  }
14562
10454
  const configDir = this.server.config.configFile ? dirname(this.server.config.configFile) : this.config.root;
14563
- const rootFiles = await promises$1.readdir(configDir);
10455
+ const rootFiles = await promises.readdir(configDir);
14564
10456
  const workspaceConfigName = workspacesFiles.find((configFile) => {
14565
10457
  return rootFiles.includes(configFile);
14566
10458
  });
@@ -14614,7 +10506,7 @@ class Vitest {
14614
10506
  return CONFIG_NAMES.some((configName) => filename.startsWith(configName));
14615
10507
  }).map(async (filepath) => {
14616
10508
  if (filepath.endsWith("/")) {
14617
- const filesInside = await promises$1.readdir(filepath);
10509
+ const filesInside = await promises.readdir(filepath);
14618
10510
  const configFile = configFiles.find((config) => filesInside.includes(config));
14619
10511
  return configFile ? join(filepath, configFile) : filepath;
14620
10512
  }
@@ -16028,4 +11920,4 @@ var cliApi = /*#__PURE__*/Object.freeze({
16028
11920
  startVitest: startVitest
16029
11921
  });
16030
11922
 
16031
- export { FilesNotFoundError as F, GitNotFoundError as G, VitestPlugin as V, createMethodsRPC as a, VitestPackageInstaller as b, createVitest as c, resolveFsAllow as d, resolveApiServerConfig as e, resolveConfig as f, getFilePoolName as g, cliApi as h, registerConsoleShortcuts as r, startVitest as s };
11923
+ export { FilesNotFoundError as F, GitNotFoundError as G, VitestPlugin as V, VitestPackageInstaller as a, resolveFsAllow as b, createVitest as c, cliApi as d, registerConsoleShortcuts as r, startVitest as s };