vitest 1.0.0-beta.2 → 1.0.0-beta.3

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 (39) hide show
  1. package/LICENSE.md +0 -29
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/child.js +9 -4
  4. package/dist/{chunk-api-setup.5d9a93c7.js → chunk-api-setup.37a43981.js} +0 -2
  5. package/dist/{chunk-install-pkg.43d58972.js → chunk-install-pkg.6349b322.js} +10 -12
  6. package/dist/{chunk-node-git.2f1df48f.js → chunk-node-git.6c12e560.js} +1 -1
  7. package/dist/cli-wrapper.js +1 -1
  8. package/dist/cli.js +11 -18
  9. package/dist/config.d.ts +2 -2
  10. package/dist/coverage.d.ts +1 -1
  11. package/dist/coverage.js +2 -2
  12. package/dist/entry-vm.js +1 -1
  13. package/dist/entry.js +1 -1
  14. package/dist/environments.d.ts +1 -1
  15. package/dist/environments.js +1 -13
  16. package/dist/execute.d.ts +1 -1
  17. package/dist/execute.js +1 -1
  18. package/dist/index.d.ts +5 -5
  19. package/dist/node.d.ts +5 -3
  20. package/dist/node.js +14 -16
  21. package/dist/{reporters-d10f25e1.d.ts → reporters-1678fe04.d.ts} +62 -30
  22. package/dist/reporters.d.ts +1 -1
  23. package/dist/reporters.js +1 -1
  24. package/dist/runners.d.ts +3 -2
  25. package/dist/runners.js +32 -35
  26. package/dist/{suite-919dd548.d.ts → suite-0579b50d.d.ts} +1 -1
  27. package/dist/suite.d.ts +2 -2
  28. package/dist/{vendor-environments.094f240c.js → vendor-environments.dcc4a34e.js} +4 -37
  29. package/dist/{vendor-execute.07d1a420.js → vendor-execute.e6e4e89b.js} +1 -0
  30. package/dist/{vendor-index.d36f5516.js → vendor-index.3d079eea.js} +6 -1
  31. package/dist/{vendor-index.e006069f.js → vendor-index.8efe7746.js} +371 -371
  32. package/dist/{vendor-index.0b5b3600.js → vendor-loader.9c966f23.js} +36 -9
  33. package/dist/{vendor-node.e5a35bfe.js → vendor-node.327f8f1f.js} +1928 -1953
  34. package/dist/{vendor-reporters.2953082e.js → vendor-reporters.b9600369.js} +40 -23
  35. package/dist/vm.js +9 -4
  36. package/dist/worker.js +9 -4
  37. package/package.json +11 -27
  38. package/dist/loader.js +0 -100
  39. package/dist/vendor-index.98139333.js +0 -129
@@ -1,7 +1,7 @@
1
- import { relative, resolve, dirname, normalize, basename, join, extname, toNamespacedPath } from 'pathe';
1
+ import { relative, resolve, basename, dirname, join, extname, normalize, toNamespacedPath } from 'pathe';
2
2
  import { loadConfigFromFile, searchForWorkspaceRoot, version as version$2, createServer, mergeConfig } from 'vite';
3
3
  import path$a from 'node:path';
4
- import url, { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import url, { fileURLToPath } from 'node:url';
5
5
  import process$1 from 'node:process';
6
6
  import fs$8, { promises, existsSync, readFileSync } from 'node:fs';
7
7
  import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort, a as defaultBrowserPort, w as workspacesFiles, C as CONFIG_NAMES } from './vendor-constants.538d9b49.js';
@@ -19,7 +19,7 @@ import { SnapshotManager } from '@vitest/snapshot/manager';
19
19
  import { ViteNodeServer } from 'vite-node/server';
20
20
  import { r as removeUndefinedValues, a as isWindows } from './vendor-index.29282562.js';
21
21
  import { g as getCoverageProvider, C as CoverageProviderMap } from './vendor-coverage.78040316.js';
22
- import { r as rootDir, d as distDir } from './vendor-paths.84fc7a99.js';
22
+ import { r as rootDir } from './vendor-paths.84fc7a99.js';
23
23
  import v8 from 'node:v8';
24
24
  import * as nodeos from 'node:os';
25
25
  import EventEmitter from 'node:events';
@@ -28,20 +28,21 @@ import { c as createBirpc } from './vendor-index.1ca68bd5.js';
28
28
  import { g as groupBy, A as AggregateErrorPonyfill, s as slash$1, t as toArray, i as isPrimitive, d as deepMerge, n as noop$1, a as stdout } from './vendor-base.9c08bbd0.js';
29
29
  import { MessageChannel } from 'node:worker_threads';
30
30
  import { createDefer, shuffle, inspect, positionToOffset, lineSplitRE, toArray as toArray$1, notNullish } from '@vitest/utils';
31
+ import { writeFile, rm } from 'node:fs/promises';
32
+ import { performance } from 'node:perf_hooks';
33
+ import { e as execa, a as signalExit } from './vendor-index.8efe7746.js';
34
+ import { TraceMap, generatedPositionFor, parseErrorStacktrace } from '@vitest/utils/source-map';
31
35
  import { isPackageExists, resolveModule } from 'local-pkg';
32
36
  import { isCI } from 'std-env';
33
- import { R as ReportersMap, B as BenchmarkReportsMap, s as stringWidth, a as ansiStyles, b as stripAnsi, c as sliceAnsi, d as divider, F as F_POINTER, e as cliTruncate } from './vendor-reporters.2953082e.js';
34
- import crypto, { createHash } from 'node:crypto';
35
- import { o as onExit, e as execa } from './vendor-index.e006069f.js';
36
- import { TraceMap, generatedPositionFor, parseErrorStacktrace } from '@vitest/utils/source-map';
37
- import { writeFile, rm } from 'node:fs/promises';
38
37
  import ue from 'module';
39
38
  import { parse as parse$4 } from 'acorn';
40
39
  import { ancestor, simple, findNodeAround } from 'acorn-walk';
41
40
  import { generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, getTasks, hasFailed } from '@vitest/runner/utils';
41
+ import { R as ReportersMap, B as BenchmarkReportsMap, s as stringWidth, a as ansiStyles, b as stripAnsi, c as sliceAnsi, d as divider, F as F_POINTER, e as cliTruncate } from './vendor-reporters.b9600369.js';
42
+ import crypto, { createHash } from 'node:crypto';
42
43
  import MagicString from 'magic-string';
43
44
  import { stripLiteral } from 'strip-literal';
44
- import { g as getEnvPackageName } from './vendor-environments.094f240c.js';
45
+ import { g as getEnvPackageName } from './vendor-environments.dcc4a34e.js';
45
46
  import readline from 'node:readline';
46
47
  import require$$0$3 from 'readline';
47
48
 
@@ -60,7 +61,7 @@ function _mergeNamespaces(n, m) {
60
61
  return Object.freeze(n);
61
62
  }
62
63
 
63
- var version$1 = "1.0.0-beta.2";
64
+ var version$1 = "1.0.0-beta.3";
64
65
 
65
66
  const __dirname$1 = url.fileURLToPath(new URL(".", import.meta.url));
66
67
  async function ensurePackageInstalled(dependency, root) {
@@ -79,7 +80,7 @@ async function ensurePackageInstalled(dependency, root) {
79
80
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
80
81
  });
81
82
  if (install) {
82
- await (await import('./chunk-install-pkg.43d58972.js')).installPackage(dependency, { dev: true });
83
+ await (await import('./chunk-install-pkg.6349b322.js')).installPackage(dependency, { dev: true });
83
84
  process.stderr.write(c.yellow(`
84
85
  Package ${dependency} installed, re-run the command to start.
85
86
  `));
@@ -7102,7 +7103,7 @@ function createMethodsRPC(project) {
7102
7103
  const ctx = project.ctx;
7103
7104
  return {
7104
7105
  async onWorkerExit(error, code) {
7105
- await ctx.logger.printError(error, { type: "Unexpected Exit" });
7106
+ await ctx.logger.printError(error, { type: "Unexpected Exit", fullStack: true });
7106
7107
  process.exit(code || 1);
7107
7108
  },
7108
7109
  snapshotSaved(snapshot) {
@@ -7230,7 +7231,8 @@ function createChildProcessPool(ctx, { execArgv, env, forksPath }) {
7230
7231
  files,
7231
7232
  invalidates,
7232
7233
  environment,
7233
- workerId
7234
+ workerId,
7235
+ projectName: project.getName()
7234
7236
  };
7235
7237
  try {
7236
7238
  await pool.run(data, { name, channel });
@@ -7384,7 +7386,8 @@ function createThreadsPool(ctx, { execArgv, env, workerPath }) {
7384
7386
  files,
7385
7387
  invalidates,
7386
7388
  environment,
7387
- workerId
7389
+ workerId,
7390
+ projectName: project.getName()
7388
7391
  };
7389
7392
  try {
7390
7393
  await pool.run(data, { transferList: [workerPort], name });
@@ -7674,7 +7677,8 @@ function createVmThreadsPool(ctx, { execArgv, env, vmPath }) {
7674
7677
  files,
7675
7678
  invalidates,
7676
7679
  environment,
7677
- workerId
7680
+ workerId,
7681
+ projectName: project.getName()
7678
7682
  };
7679
7683
  try {
7680
7684
  await pool.run(data, { transferList: [workerPort], name });
@@ -7737,1880 +7741,1986 @@ function getMemoryLimit(config) {
7737
7741
  return null;
7738
7742
  }
7739
7743
 
7740
- const loaderPath = pathToFileURL(resolve(distDir, "./loader.js")).href;
7741
- const suppressLoaderWarningsPath = resolve(rootDir, "./suppress-warnings.cjs");
7742
- function createPool(ctx) {
7743
- const pools = {
7744
- forks: null,
7745
- threads: null,
7746
- browser: null,
7747
- vmThreads: null
7748
- };
7749
- function getDefaultPoolName(project) {
7750
- if (project.config.browser.enabled)
7751
- return "browser";
7752
- return project.config.pool;
7753
- }
7754
- function getPoolName([project, file]) {
7755
- for (const [glob, pool] of project.config.poolMatchGlobs || []) {
7756
- if (pool === "browser")
7757
- throw new Error('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');
7758
- if (mm.isMatch(file, glob, { cwd: project.config.root }))
7759
- return pool;
7760
- }
7761
- return getDefaultPoolName(project);
7762
- }
7763
- async function runTests(files, invalidate) {
7764
- var _a;
7765
- const conditions = ((_a = ctx.server.config.resolve.conditions) == null ? void 0 : _a.flatMap((c) => ["--conditions", c])) || [];
7766
- const execArgv = process.execArgv.filter(
7767
- (execArg) => execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof")
7768
- );
7769
- const options = {
7770
- ...ctx.projectFiles,
7771
- execArgv: ctx.config.deps.registerNodeLoader ? [
7772
- ...execArgv,
7773
- "--require",
7774
- suppressLoaderWarningsPath,
7775
- "--experimental-loader",
7776
- loaderPath,
7777
- ...conditions
7778
- ] : [
7779
- ...execArgv,
7780
- ...conditions
7781
- ],
7782
- env: {
7783
- TEST: "true",
7784
- VITEST: "true",
7785
- NODE_ENV: ctx.config.mode || "test",
7786
- VITEST_MODE: ctx.config.watch ? "WATCH" : "RUN",
7787
- ...process.env,
7788
- ...ctx.config.env
7789
- }
7790
- };
7791
- const filesByPool = {
7792
- forks: [],
7793
- threads: [],
7794
- browser: [],
7795
- vmThreads: []
7796
- };
7797
- for (const spec of files) {
7798
- const pool = getPoolName(spec);
7799
- if (!(pool in filesByPool))
7800
- throw new Error(`Unknown pool name "${pool}" for ${spec[1]}. Available pools: ${Object.keys(filesByPool).join(", ")}`);
7801
- filesByPool[pool].push(spec);
7802
- }
7803
- await Promise.all(Object.entries(filesByPool).map((entry) => {
7804
- const [pool, files2] = entry;
7805
- if (!files2.length)
7806
- return null;
7807
- if (pool === "browser") {
7808
- pools.browser ?? (pools.browser = createBrowserPool(ctx));
7809
- return pools.browser.runTests(files2, invalidate);
7810
- }
7811
- if (pool === "vmThreads") {
7812
- pools.vmThreads ?? (pools.vmThreads = createVmThreadsPool(ctx, options));
7813
- return pools.vmThreads.runTests(files2, invalidate);
7814
- }
7815
- if (pool === "threads") {
7816
- pools.threads ?? (pools.threads = createThreadsPool(ctx, options));
7817
- return pools.threads.runTests(files2, invalidate);
7818
- }
7819
- pools.forks ?? (pools.forks = createChildProcessPool(ctx, options));
7820
- return pools.forks.runTests(files2, invalidate);
7821
- }));
7822
- }
7823
- return {
7824
- runTests,
7825
- async close() {
7826
- await Promise.all(Object.values(pools).map((p) => p == null ? void 0 : p.close()));
7744
+ const A=r=>r!==null&&typeof r=="object",a=(r,t)=>Object.assign(new Error(`[${r}]: ${t}`),{code:r}),_$1="ERR_INVALID_PACKAGE_CONFIG",E="ERR_INVALID_PACKAGE_TARGET",I="ERR_PACKAGE_PATH_NOT_EXPORTED",R$1=/^\d+$/,O=/^(\.{1,2}|node_modules)$/i,w=/\/|\\/;var h=(r=>(r.Export="exports",r.Import="imports",r))(h||{});const f=(r,t,e,o,c)=>{if(t==null)return [];if(typeof t=="string"){const[n,...i]=t.split(w);if(n===".."||i.some(l=>O.test(l)))throw a(E,`Invalid "${r}" target "${t}" defined in the package config`);return [c?t.replace(/\*/g,c):t]}if(Array.isArray(t))return t.flatMap(n=>f(r,n,e,o,c));if(A(t)){for(const n of Object.keys(t)){if(R$1.test(n))throw a(_$1,"Cannot contain numeric property keys");if(n==="default"||o.includes(n))return f(r,t[n],e,o,c)}return []}throw a(E,`Invalid "${r}" target "${t}"`)},s="*",m=(r,t)=>{const e=r.indexOf(s),o=t.indexOf(s);return e===o?t.length>r.length:o>e};function d$1(r,t){if(!t.includes(s)&&r.hasOwnProperty(t))return [t];let e,o;for(const c of Object.keys(r))if(c.includes(s)){const[n,i,l]=c.split(s);if(l===void 0&&t.startsWith(n)&&t.endsWith(i)){const g=t.slice(n.length,-i.length||void 0);g&&(!e||m(e,c))&&(e=c,o=g);}}return [e,o]}const p=r=>Object.keys(r).reduce((t,e)=>{const o=e===""||e[0]!==".";if(t===void 0||t===o)return o;throw a(_$1,'"exports" cannot contain some keys starting with "." and some not')},void 0),u=/^\w+:/,v=(r,t,e)=>{if(!r)throw new Error('"exports" is required');t=t===""?".":`./${t}`,(typeof r=="string"||Array.isArray(r)||A(r)&&p(r))&&(r={".":r});const[o,c]=d$1(r,t),n=f(h.Export,r[o],t,e,c);if(n.length===0)throw a(I,t==="."?'No "exports" main defined':`Package subpath '${t}' is not defined by "exports"`);for(const i of n)if(!i.startsWith("./")&&!u.test(i))throw a(E,`Invalid "exports" target "${i}" defined in the package config`);return n};
7745
+
7746
+ function U(e){return e.startsWith("\\\\?\\")?e:e.replace(/\\/g,"/")}const Y=(e,s)=>{for(;;){const i=f$1.posix.join(e,s);if($.existsSync(i))return i;const n=f$1.dirname(e);if(n===e)return;e=n;}},S=/^\.{1,2}(\/.*)?$/,V=e=>{const s=U(e);return S.test(s)?s:`./${s}`};function re(e,s=!1){const i=e.length;let n=0,t="",l=0,c=16,m=0,p=0,L=0,g=0,T=0;function k(o,r){let u=0,E=0;for(;u<o||!r;){let v=e.charCodeAt(n);if(v>=48&&v<=57)E=E*16+v-48;else if(v>=65&&v<=70)E=E*16+v-65+10;else if(v>=97&&v<=102)E=E*16+v-97+10;else break;n++,u++;}return u<o&&(E=-1),E}function j(o){n=o,t="",l=0,c=16,T=0;}function w(){let o=n;if(e.charCodeAt(n)===48)n++;else for(n++;n<e.length&&_(e.charCodeAt(n));)n++;if(n<e.length&&e.charCodeAt(n)===46)if(n++,n<e.length&&_(e.charCodeAt(n)))for(n++;n<e.length&&_(e.charCodeAt(n));)n++;else return T=3,e.substring(o,n);let r=n;if(n<e.length&&(e.charCodeAt(n)===69||e.charCodeAt(n)===101))if(n++,(n<e.length&&e.charCodeAt(n)===43||e.charCodeAt(n)===45)&&n++,n<e.length&&_(e.charCodeAt(n))){for(n++;n<e.length&&_(e.charCodeAt(n));)n++;r=n;}else T=3;return e.substring(o,r)}function b(){let o="",r=n;for(;;){if(n>=i){o+=e.substring(r,n),T=2;break}const u=e.charCodeAt(n);if(u===34){o+=e.substring(r,n),n++;break}if(u===92){if(o+=e.substring(r,n),n++,n>=i){T=2;break}switch(e.charCodeAt(n++)){case 34:o+='"';break;case 92:o+="\\";break;case 47:o+="/";break;case 98:o+="\b";break;case 102:o+="\f";break;case 110:o+=`
7747
+ `;break;case 114:o+="\r";break;case 116:o+=" ";break;case 117:const v=k(4,!0);v>=0?o+=String.fromCharCode(v):T=4;break;default:T=5;}r=n;continue}if(u>=0&&u<=31)if(F(u)){o+=e.substring(r,n),T=2;break}else T=6;n++;}return o}function A(){if(t="",T=0,l=n,p=m,g=L,n>=i)return l=i,c=17;let o=e.charCodeAt(n);if(W(o)){do n++,t+=String.fromCharCode(o),o=e.charCodeAt(n);while(W(o));return c=15}if(F(o))return n++,t+=String.fromCharCode(o),o===13&&e.charCodeAt(n)===10&&(n++,t+=`
7748
+ `),m++,L=n,c=14;switch(o){case 123:return n++,c=1;case 125:return n++,c=2;case 91:return n++,c=3;case 93:return n++,c=4;case 58:return n++,c=6;case 44:return n++,c=5;case 34:return n++,t=b(),c=10;case 47:const r=n-1;if(e.charCodeAt(n+1)===47){for(n+=2;n<i&&!F(e.charCodeAt(n));)n++;return t=e.substring(r,n),c=12}if(e.charCodeAt(n+1)===42){n+=2;const u=i-1;let E=!1;for(;n<u;){const v=e.charCodeAt(n);if(v===42&&e.charCodeAt(n+1)===47){n+=2,E=!0;break}n++,F(v)&&(v===13&&e.charCodeAt(n)===10&&n++,m++,L=n);}return E||(n++,T=1),t=e.substring(r,n),c=13}return t+=String.fromCharCode(o),n++,c=16;case 45:if(t+=String.fromCharCode(o),n++,n===i||!_(e.charCodeAt(n)))return c=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return t+=w(),c=11;default:for(;n<i&&N(o);)n++,o=e.charCodeAt(n);if(l!==n){switch(t=e.substring(l,n),t){case"true":return c=8;case"false":return c=9;case"null":return c=7}return c=16}return t+=String.fromCharCode(o),n++,c=16}}function N(o){if(W(o)||F(o))return !1;switch(o){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return !1}return !0}function h(){let o;do o=A();while(o>=12&&o<=15);return o}return {setPosition:j,getPosition:()=>n,scan:s?h:A,getToken:()=>c,getTokenValue:()=>t,getTokenOffset:()=>l,getTokenLength:()=>n-l,getTokenStartLine:()=>p,getTokenStartCharacter:()=>l-g,getTokenError:()=>T}}function W(e){return e===32||e===9}function F(e){return e===10||e===13}function _(e){return e>=48&&e<=57}var Z;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab";})(Z||(Z={}));var x;(function(e){e.DEFAULT={allowTrailingComma:!1};})(x||(x={}));function pe(e,s=[],i=x.DEFAULT){let n=null,t=[];const l=[];function c(p){Array.isArray(t)?t.push(p):n!==null&&(t[n]=p);}return ge(e,{onObjectBegin:()=>{const p={};c(p),l.push(t),t=p,n=null;},onObjectProperty:p=>{n=p;},onObjectEnd:()=>{t=l.pop();},onArrayBegin:()=>{const p=[];c(p),l.push(t),t=p,n=null;},onArrayEnd:()=>{t=l.pop();},onLiteralValue:c,onError:(p,L,g)=>{s.push({error:p,offset:L,length:g});}},i),t[0]}function ge(e,s,i=x.DEFAULT){const n=re(e,!1),t=[];function l(a){return a?()=>a(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function c(a){return a?()=>a(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),()=>t.slice()):()=>!0}function m(a){return a?O=>a(O,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function p(a){return a?O=>a(O,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),()=>t.slice()):()=>!0}const L=c(s.onObjectBegin),g=p(s.onObjectProperty),T=l(s.onObjectEnd),k=c(s.onArrayBegin),j=l(s.onArrayEnd),w=p(s.onLiteralValue),b=m(s.onSeparator),A=l(s.onComment),N=m(s.onError),h=i&&i.disallowComments,o=i&&i.allowTrailingComma;function r(){for(;;){const a=n.scan();switch(n.getTokenError()){case 4:u(14);break;case 5:u(15);break;case 3:u(13);break;case 1:h||u(11);break;case 2:u(12);break;case 6:u(16);break}switch(a){case 12:case 13:h?u(10):A();break;case 16:u(1);break;case 15:case 14:break;default:return a}}}function u(a,O=[],X=[]){if(N(a),O.length+X.length>0){let y=n.getToken();for(;y!==17;){if(O.indexOf(y)!==-1){r();break}else if(X.indexOf(y)!==-1)break;y=r();}}}function E(a){const O=n.getTokenValue();return a?w(O):(g(O),t.push(O)),r(),!0}function v(){switch(n.getToken()){case 11:const a=n.getTokenValue();let O=Number(a);isNaN(O)&&(u(2),O=0),w(O);break;case 7:w(null);break;case 8:w(!0);break;case 9:w(!1);break;default:return !1}return r(),!0}function oe(){return n.getToken()!==10?(u(3,[],[2,5]),!1):(E(!1),n.getToken()===6?(b(":"),r(),P()||u(4,[],[2,5])):u(5,[],[2,5]),t.pop(),!0)}function le(){L(),r();let a=!1;for(;n.getToken()!==2&&n.getToken()!==17;){if(n.getToken()===5){if(a||u(4,[],[]),b(","),r(),n.getToken()===2&&o)break}else a&&u(6,[],[]);oe()||u(4,[],[2,5]),a=!0;}return T(),n.getToken()!==2?u(7,[2],[]):r(),!0}function ce(){k(),r();let a=!0,O=!1;for(;n.getToken()!==4&&n.getToken()!==17;){if(n.getToken()===5){if(O||u(4,[],[]),b(","),r(),n.getToken()===4&&o)break}else O&&u(6,[],[]);a?(t.push(0),a=!1):t[t.length-1]++,P()||u(4,[],[4,5]),O=!0;}return j(),a||t.pop(),n.getToken()!==4?u(8,[4],[]):r(),!0}function P(){switch(n.getToken()){case 3:return ce();case 1:return le();case 10:return E(!0);default:return v()}}return r(),n.getToken()===17?i.allowEmptyContent?!0:(u(4,[],[]),!1):P()?(n.getToken()!==17&&u(9,[],[]),!0):(u(4,[],[]),!1)}var d;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter";})(d||(d={}));var q;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF";})(q||(q={}));const ae=pe;var K;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter";})(K||(K={}));const C=e=>ae($.readFileSync(e,"utf8")),{existsSync:B}=$,me=()=>{const{findPnpApi:e}=ue;return e&&e(process.cwd())},J=(e,s,i)=>{let n="tsconfig.json";const t=C(e);if(t)if(!i&&t.exports)try{const[l]=v(t.exports,s,["require","types"]);n=l;}catch{return}else !s&&t.tsconfig&&(n=t.tsconfig);return f$1.join(e,"..",n)},M="package.json",R="tsconfig.json",ke=(e,s)=>{let i=e;if(e===".."&&(i=f$1.join(i,R)),e[0]==="."&&(i=f$1.resolve(s,i)),f$1.isAbsolute(i)){if(B(i)){if($.statSync(i).isFile())return i}else if(!i.endsWith(".json")){const k=`${i}.json`;if(B(k))return k}return}const[n,...t]=e.split("/"),l=n[0]==="@"?`${n}/${t.shift()}`:n,c=t.join("/"),m=me();if(m){const{resolveRequest:k}=m;try{if(l===e){const j=k(f$1.join(l,M),s);if(j){const w=J(j,c);if(w&&B(w))return w}}else {let j;try{j=k(e,s,{extensions:[".json"]});}catch{j=k(f$1.join(e,R),s);}if(j)return j}}catch{}}const p=Y(s,f$1.join("node_modules",l));if(!p||!$.statSync(p).isDirectory())return;const L=f$1.join(p,M);if(B(L)){const k=J(L,c);if(!k)return;if(B(k))return k}const g=f$1.join(p,c),T=g.endsWith(".json");if(!T){const k=`${g}.json`;if(B(k))return k}if(B(g)){if($.statSync(g).isDirectory()){const k=f$1.join(g,M);if(B(k)){const w=J(k,"",!0);if(w&&B(w))return w}const j=f$1.join(g,R);if(B(j))return j}else if(T)return g}},be=(e,s)=>{var i;const n=ke(e,s);if(!n)throw new Error(`File '${e}' not found.`);const t=G(n);if(delete t.references,(i=t.compilerOptions)!=null&&i.baseUrl){const{compilerOptions:l}=t;l.baseUrl=f$1.relative(s,f$1.join(f$1.dirname(n),l.baseUrl))||"./";}return t.files&&(t.files=t.files.map(l=>f$1.relative(s,f$1.join(f$1.dirname(n),l)))),t.include&&(t.include=t.include.map(l=>f$1.relative(s,f$1.join(f$1.dirname(n),l)))),t},G=e=>{let s;try{s=$.realpathSync(e);}catch{throw new Error(`Cannot resolve tsconfig at path: ${e}`)}const i=f$1.dirname(s);let n=C(s)||{};if(typeof n!="object")throw new SyntaxError(`Failed to parse tsconfig at: ${e}`);if(n.extends){const t=Array.isArray(n.extends)?n.extends:[n.extends];delete n.extends;for(const l of t.reverse()){const c=be(l,i),m={...c,...n,compilerOptions:{...c.compilerOptions,...n.compilerOptions}};c.watchOptions&&(m.watchOptions={...c.watchOptions,...n.watchOptions}),n=m;}}if(n.compilerOptions){const{compilerOptions:t}=n;if(t.baseUrl){const l=f$1.resolve(i,t.baseUrl),c=V(f$1.relative(i,l));t.baseUrl=c;}t.outDir&&(Array.isArray(n.exclude)||(n.exclude=[]),n.exclude.push(t.outDir),t.outDir=V(t.outDir));}else n.compilerOptions={};if(n.files&&(n.files=n.files.map(V)),n.include&&(n.include=n.include.map(U)),n.watchOptions){const{watchOptions:t}=n;t.excludeDirectories&&(t.excludeDirectories=t.excludeDirectories.map(l=>U(f$1.resolve(i,l))));}return n},Te=(e=process.cwd(),s="tsconfig.json")=>{const i=Y(U(e),s);if(!i)return null;const n=G(i);return {path:i,config:n}};f$1.posix;process.platform==="win32";
7749
+
7750
+ const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
7751
+ const newLineRegExp = /\r?\n/;
7752
+ const errCodeRegExp = /error TS(?<errCode>\d+)/;
7753
+ async function makeTscErrorInfo(errInfo) {
7754
+ var _a;
7755
+ const [errFilePathPos = "", ...errMsgRawArr] = errInfo.split(":");
7756
+ if (!errFilePathPos || errMsgRawArr.length === 0 || errMsgRawArr.join("").length === 0)
7757
+ return ["unknown filepath", null];
7758
+ const errMsgRaw = errMsgRawArr.join("").trim();
7759
+ const [errFilePath, errPos] = errFilePathPos.slice(0, -1).split("(");
7760
+ if (!errFilePath || !errPos)
7761
+ return ["unknown filepath", null];
7762
+ const [errLine, errCol] = errPos.split(",");
7763
+ if (!errLine || !errCol)
7764
+ return [errFilePath, null];
7765
+ const execArr = errCodeRegExp.exec(errMsgRaw);
7766
+ if (!execArr)
7767
+ return [errFilePath, null];
7768
+ const errCodeStr = ((_a = execArr.groups) == null ? void 0 : _a.errCode) ?? "";
7769
+ if (!errCodeStr)
7770
+ return [errFilePath, null];
7771
+ const line = Number(errLine);
7772
+ const col = Number(errCol);
7773
+ const errCode = Number(errCodeStr);
7774
+ return [
7775
+ errFilePath,
7776
+ {
7777
+ filePath: errFilePath,
7778
+ errCode,
7779
+ line,
7780
+ column: col,
7781
+ errMsg: errMsgRaw.slice(`error TS${errCode} `.length)
7827
7782
  }
7828
- };
7783
+ ];
7829
7784
  }
7830
-
7831
- async function loadCustomReporterModule(path, runner) {
7832
- let customReporterModule;
7785
+ async function getTsconfig(root, config) {
7786
+ const configName = config.tsconfig ? basename(config.tsconfig) : void 0;
7787
+ const configSearchPath = config.tsconfig ? dirname(resolve(root, config.tsconfig)) : root;
7788
+ const tsconfig = Te(configSearchPath, configName);
7789
+ if (!tsconfig)
7790
+ throw new Error("no tsconfig.json found");
7791
+ const tempConfigPath = join(dirname(tsconfig.path), "tsconfig.vitest-temp.json");
7833
7792
  try {
7834
- customReporterModule = await runner.executeId(path);
7835
- } catch (customReporterModuleError) {
7836
- throw new Error(`Failed to load custom Reporter from ${path}`, { cause: customReporterModuleError });
7793
+ const tmpTsConfig = { ...tsconfig.config };
7794
+ tmpTsConfig.compilerOptions = tmpTsConfig.compilerOptions || {};
7795
+ tmpTsConfig.compilerOptions.emitDeclarationOnly = false;
7796
+ tmpTsConfig.compilerOptions.incremental = true;
7797
+ tmpTsConfig.compilerOptions.tsBuildInfoFile = join(
7798
+ __dirname,
7799
+ "tsconfig.tmp.tsbuildinfo"
7800
+ );
7801
+ const tsconfigFinalContent = JSON.stringify(tmpTsConfig, null, 2);
7802
+ await writeFile(tempConfigPath, tsconfigFinalContent);
7803
+ return { path: tempConfigPath, config: tmpTsConfig };
7804
+ } catch (err) {
7805
+ throw new Error("failed to write tsconfig.temp.json", { cause: err });
7837
7806
  }
7838
- if (customReporterModule.default === null || customReporterModule.default === void 0)
7839
- throw new Error(`Custom reporter loaded from ${path} was not the default export`);
7840
- return customReporterModule.default;
7841
- }
7842
- function createReporters(reporterReferences, runner) {
7843
- const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
7844
- if (typeof referenceOrInstance === "string") {
7845
- if (referenceOrInstance === "html") {
7846
- await ensurePackageInstalled("@vitest/ui", runner.root);
7847
- const CustomReporter = await loadCustomReporterModule("@vitest/ui/reporter", runner);
7848
- return new CustomReporter();
7849
- } else if (referenceOrInstance in ReportersMap) {
7850
- const BuiltinReporter = ReportersMap[referenceOrInstance];
7851
- return new BuiltinReporter();
7852
- } else {
7853
- const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
7854
- return new CustomReporter();
7855
- }
7856
- }
7857
- return referenceOrInstance;
7858
- });
7859
- return Promise.all(promisedReporters);
7860
7807
  }
7861
- function createBenchmarkReporters(reporterReferences, runner) {
7862
- const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
7863
- if (typeof referenceOrInstance === "string") {
7864
- if (referenceOrInstance in BenchmarkReportsMap) {
7865
- const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance];
7866
- return new BuiltinReporter();
7867
- } else {
7868
- const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
7869
- return new CustomReporter();
7870
- }
7871
- }
7872
- return referenceOrInstance;
7808
+ async function getRawErrsMapFromTsCompile(tscErrorStdout) {
7809
+ const rawErrsMap = /* @__PURE__ */ new Map();
7810
+ const infos = await Promise.all(
7811
+ tscErrorStdout.split(newLineRegExp).reduce((prev, next) => {
7812
+ if (!next)
7813
+ return prev;
7814
+ else if (!next.startsWith(" "))
7815
+ prev.push(next);
7816
+ else
7817
+ prev[prev.length - 1] += `
7818
+ ${next}`;
7819
+ return prev;
7820
+ }, []).map((errInfoLine) => makeTscErrorInfo(errInfoLine))
7821
+ );
7822
+ infos.forEach(([errFilePath, errInfo]) => {
7823
+ var _a;
7824
+ if (!errInfo)
7825
+ return;
7826
+ if (!rawErrsMap.has(errFilePath))
7827
+ rawErrsMap.set(errFilePath, [errInfo]);
7828
+ else
7829
+ (_a = rawErrsMap.get(errFilePath)) == null ? void 0 : _a.push(errInfo);
7873
7830
  });
7874
- return Promise.all(promisedReporters);
7831
+ return rawErrsMap;
7875
7832
  }
7876
7833
 
7877
- function isAggregateError(err) {
7878
- if (typeof AggregateError !== "undefined" && err instanceof AggregateError)
7879
- return true;
7880
- return err instanceof Error && "errors" in err;
7881
- }
7882
- class StateManager {
7883
- filesMap = /* @__PURE__ */ new Map();
7884
- pathsSet = /* @__PURE__ */ new Set();
7885
- browserTestPromises = /* @__PURE__ */ new Map();
7886
- idMap = /* @__PURE__ */ new Map();
7887
- taskFileMap = /* @__PURE__ */ new WeakMap();
7888
- errorsSet = /* @__PURE__ */ new Set();
7889
- processTimeoutCauses = /* @__PURE__ */ new Set();
7890
- catchError(err, type) {
7891
- if (isAggregateError(err))
7892
- return err.errors.forEach((error) => this.catchError(error, type));
7893
- if (err === Object(err))
7894
- err.type = type;
7895
- else
7896
- err = { type, message: err };
7897
- const _err = err;
7898
- if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
7899
- const task = this.idMap.get(_err.taskId);
7900
- if (task) {
7901
- task.mode = "skip";
7902
- task.result ?? (task.result = { state: "skip" });
7903
- task.result.state = "skip";
7904
- }
7905
- return;
7834
+ function createIndexMap(source) {
7835
+ const map = /* @__PURE__ */ new Map();
7836
+ let index = 0;
7837
+ let line = 1;
7838
+ let column = 1;
7839
+ for (const char of source) {
7840
+ map.set(`${line}:${column}`, index++);
7841
+ if (char === "\n" || char === "\r\n") {
7842
+ line++;
7843
+ column = 0;
7844
+ } else {
7845
+ column++;
7906
7846
  }
7907
- this.errorsSet.add(err);
7908
- }
7909
- clearErrors() {
7910
- this.errorsSet.clear();
7911
- }
7912
- getUnhandledErrors() {
7913
- return Array.from(this.errorsSet.values());
7914
- }
7915
- addProcessTimeoutCause(cause) {
7916
- this.processTimeoutCauses.add(cause);
7917
7847
  }
7918
- getProcessTimeoutCauses() {
7919
- return Array.from(this.processTimeoutCauses.values());
7848
+ return map;
7849
+ }
7850
+
7851
+ async function collectTests(ctx, filepath) {
7852
+ const request = await ctx.vitenode.transformRequest(filepath, filepath);
7853
+ if (!request)
7854
+ return null;
7855
+ const ast = parse$4(request.code, {
7856
+ ecmaVersion: "latest",
7857
+ allowAwaitOutsideFunction: true
7858
+ });
7859
+ const testFilepath = relative(ctx.config.root, filepath);
7860
+ const file = {
7861
+ filepath,
7862
+ type: "suite",
7863
+ id: generateHash(`${testFilepath}${ctx.config.name || ""}`),
7864
+ name: testFilepath,
7865
+ mode: "run",
7866
+ tasks: [],
7867
+ start: ast.start,
7868
+ end: ast.end,
7869
+ projectName: ctx.getName(),
7870
+ meta: { typecheck: true }
7871
+ };
7872
+ const definitions = [];
7873
+ const getName = (callee) => {
7874
+ var _a, _b, _c;
7875
+ if (!callee)
7876
+ return null;
7877
+ if (callee.type === "Identifier")
7878
+ return callee.name;
7879
+ if (callee.type === "MemberExpression") {
7880
+ if ((_b = (_a = callee.object) == null ? void 0 : _a.name) == null ? void 0 : _b.startsWith("__vite_ssr_"))
7881
+ return getName(callee.property);
7882
+ return getName((_c = callee.object) == null ? void 0 : _c.property);
7883
+ }
7884
+ return null;
7885
+ };
7886
+ ancestor(ast, {
7887
+ CallExpression(node) {
7888
+ var _a;
7889
+ const { callee } = node;
7890
+ const name = getName(callee);
7891
+ if (!name)
7892
+ return;
7893
+ if (!["it", "test", "describe", "suite"].includes(name))
7894
+ return;
7895
+ const { arguments: [{ value: message }] } = node;
7896
+ const property = (_a = callee == null ? void 0 : callee.property) == null ? void 0 : _a.name;
7897
+ let mode = !property || property === name ? "run" : property;
7898
+ if (!["run", "skip", "todo", "only", "skipIf", "runIf"].includes(mode))
7899
+ throw new Error(`${name}.${mode} syntax is not supported when testing types`);
7900
+ if (mode === "skipIf" || mode === "runIf")
7901
+ mode = "skip";
7902
+ definitions.push({
7903
+ start: node.start,
7904
+ end: node.end,
7905
+ name: message,
7906
+ type: name === "it" || name === "test" ? "test" : "suite",
7907
+ mode
7908
+ });
7909
+ }
7910
+ });
7911
+ let lastSuite = file;
7912
+ const updateLatestSuite = (index) => {
7913
+ const suite = lastSuite;
7914
+ while (lastSuite !== file && lastSuite.end < index)
7915
+ lastSuite = suite.suite;
7916
+ return lastSuite;
7917
+ };
7918
+ definitions.sort((a, b) => a.start - b.start).forEach((definition) => {
7919
+ const latestSuite = updateLatestSuite(definition.start);
7920
+ let mode = definition.mode;
7921
+ if (latestSuite.mode !== "run")
7922
+ mode = latestSuite.mode;
7923
+ if (definition.type === "suite") {
7924
+ const task2 = {
7925
+ type: definition.type,
7926
+ id: "",
7927
+ suite: latestSuite,
7928
+ file,
7929
+ tasks: [],
7930
+ mode,
7931
+ name: definition.name,
7932
+ end: definition.end,
7933
+ start: definition.start,
7934
+ projectName: ctx.getName(),
7935
+ meta: {
7936
+ typecheck: true
7937
+ }
7938
+ };
7939
+ definition.task = task2;
7940
+ latestSuite.tasks.push(task2);
7941
+ lastSuite = task2;
7942
+ return;
7943
+ }
7944
+ const task = {
7945
+ type: definition.type,
7946
+ id: "",
7947
+ suite: latestSuite,
7948
+ file,
7949
+ mode,
7950
+ context: {},
7951
+ // not used in typecheck
7952
+ name: definition.name,
7953
+ end: definition.end,
7954
+ start: definition.start,
7955
+ meta: {
7956
+ typecheck: true
7957
+ }
7958
+ };
7959
+ definition.task = task;
7960
+ latestSuite.tasks.push(task);
7961
+ });
7962
+ calculateSuiteHash(file);
7963
+ const hasOnly = someTasksAreOnly(file);
7964
+ interpretTaskModes(file, ctx.config.testNamePattern, hasOnly, false, ctx.config.allowOnly);
7965
+ return {
7966
+ file,
7967
+ parsed: request.code,
7968
+ filepath,
7969
+ map: request.map,
7970
+ definitions
7971
+ };
7972
+ }
7973
+
7974
+ class TypeCheckError extends Error {
7975
+ constructor(message, stacks) {
7976
+ super(message);
7977
+ this.message = message;
7978
+ this.stacks = stacks;
7920
7979
  }
7921
- getPaths() {
7922
- return Array.from(this.pathsSet);
7980
+ name = "TypeCheckError";
7981
+ }
7982
+ class Typechecker {
7983
+ constructor(ctx) {
7984
+ this.ctx = ctx;
7923
7985
  }
7924
- getFiles(keys) {
7925
- if (keys)
7926
- return keys.map((key) => this.filesMap.get(key)).filter(Boolean).flat();
7927
- return Array.from(this.filesMap.values()).flat();
7986
+ _onParseStart;
7987
+ _onParseEnd;
7988
+ _onWatcherRerun;
7989
+ _result = {
7990
+ files: [],
7991
+ sourceErrors: [],
7992
+ time: 0
7993
+ };
7994
+ _startTime = 0;
7995
+ _output = "";
7996
+ _tests = {};
7997
+ tempConfigPath;
7998
+ allowJs;
7999
+ process;
8000
+ files = [];
8001
+ setFiles(files) {
8002
+ this.files = files;
7928
8003
  }
7929
- getFilepaths() {
7930
- return Array.from(this.filesMap.keys());
8004
+ onParseStart(fn) {
8005
+ this._onParseStart = fn;
7931
8006
  }
7932
- getFailedFilepaths() {
7933
- return this.getFiles().filter((i) => {
7934
- var _a;
7935
- return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
7936
- }).map((i) => i.filepath);
8007
+ onParseEnd(fn) {
8008
+ this._onParseEnd = fn;
7937
8009
  }
7938
- collectPaths(paths = []) {
7939
- paths.forEach((path) => {
7940
- this.pathsSet.add(path);
7941
- });
8010
+ onWatcherRerun(fn) {
8011
+ this._onWatcherRerun = fn;
7942
8012
  }
7943
- collectFiles(files = []) {
7944
- files.forEach((file) => {
7945
- const existing = this.filesMap.get(file.filepath) || [];
7946
- const otherProject = existing.filter((i) => i.projectName !== file.projectName);
7947
- otherProject.push(file);
7948
- this.filesMap.set(file.filepath, otherProject);
7949
- this.updateId(file);
7950
- });
8013
+ async collectFileTests(filepath) {
8014
+ return collectTests(this.ctx, filepath);
7951
8015
  }
7952
- // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
7953
- clearFiles(_project, paths = []) {
7954
- const project = _project;
7955
- paths.forEach((path) => {
7956
- const files = this.filesMap.get(path);
7957
- if (!files)
7958
- return;
7959
- const filtered = files.filter((file) => file.projectName !== project.config.name);
7960
- if (!filtered.length)
7961
- this.filesMap.delete(path);
7962
- else
7963
- this.filesMap.set(path, filtered);
8016
+ getFiles() {
8017
+ return this.files.filter((filename) => {
8018
+ const extension = extname(filename);
8019
+ return extension !== ".js" || this.allowJs;
7964
8020
  });
7965
8021
  }
7966
- updateId(task) {
7967
- if (this.idMap.get(task.id) === task)
7968
- return;
7969
- this.idMap.set(task.id, task);
7970
- if (task.type === "suite") {
7971
- task.tasks.forEach((task2) => {
7972
- this.updateId(task2);
7973
- });
7974
- }
7975
- }
7976
- updateTasks(packs) {
7977
- for (const [id, result, meta] of packs) {
7978
- const task = this.idMap.get(id);
7979
- if (task) {
7980
- task.result = result;
7981
- task.meta = meta;
7982
- if ((result == null ? void 0 : result.state) === "skip")
7983
- task.mode = "skip";
7984
- }
7985
- }
8022
+ async collectTests() {
8023
+ const tests = (await Promise.all(
8024
+ this.getFiles().map((filepath) => this.collectFileTests(filepath))
8025
+ )).reduce((acc, data) => {
8026
+ if (!data)
8027
+ return acc;
8028
+ acc[data.filepath] = data;
8029
+ return acc;
8030
+ }, {});
8031
+ this._tests = tests;
8032
+ return tests;
7986
8033
  }
7987
- updateUserLog(log) {
7988
- const task = log.taskId && this.idMap.get(log.taskId);
7989
- if (task) {
7990
- if (!task.logs)
7991
- task.logs = [];
7992
- task.logs.push(log);
8034
+ markPassed(file) {
8035
+ var _a;
8036
+ if (!((_a = file.result) == null ? void 0 : _a.state)) {
8037
+ file.result = {
8038
+ state: "pass"
8039
+ };
7993
8040
  }
8041
+ const markTasks = (tasks) => {
8042
+ var _a2;
8043
+ for (const task of tasks) {
8044
+ if ("tasks" in task)
8045
+ markTasks(task.tasks);
8046
+ if (!((_a2 = task.result) == null ? void 0 : _a2.state) && task.mode === "run") {
8047
+ task.result = {
8048
+ state: "pass"
8049
+ };
8050
+ }
8051
+ }
8052
+ };
8053
+ markTasks(file.tasks);
7994
8054
  }
7995
- getCountOfFailedTests() {
7996
- return Array.from(this.idMap.values()).filter((t) => {
7997
- var _a;
7998
- return ((_a = t.result) == null ? void 0 : _a.state) === "fail";
7999
- }).length;
8055
+ async prepareResults(output) {
8056
+ const typeErrors = await this.parseTscLikeOutput(output);
8057
+ const testFiles = new Set(this.getFiles());
8058
+ if (!this._tests)
8059
+ this._tests = await this.collectTests();
8060
+ const sourceErrors = [];
8061
+ const files = [];
8062
+ testFiles.forEach((path) => {
8063
+ const { file, definitions, map, parsed } = this._tests[path];
8064
+ const errors = typeErrors.get(path);
8065
+ files.push(file);
8066
+ if (!errors) {
8067
+ this.markPassed(file);
8068
+ return;
8069
+ }
8070
+ const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)];
8071
+ const traceMap = map && new TraceMap(map);
8072
+ const indexMap = createIndexMap(parsed);
8073
+ const markState = (task, state) => {
8074
+ task.result = {
8075
+ state: task.mode === "run" || task.mode === "only" ? state : task.mode
8076
+ };
8077
+ if (task.suite)
8078
+ markState(task.suite, state);
8079
+ };
8080
+ errors.forEach(({ error, originalError }) => {
8081
+ var _a;
8082
+ const processedPos = traceMap ? generatedPositionFor(traceMap, {
8083
+ line: originalError.line,
8084
+ column: originalError.column,
8085
+ source: basename(path)
8086
+ }) : originalError;
8087
+ const line = processedPos.line ?? originalError.line;
8088
+ const column = processedPos.column ?? originalError.column;
8089
+ const index = indexMap.get(`${line}:${column}`);
8090
+ const definition = index != null && sortedDefinitions.find((def) => def.start <= index && def.end >= index);
8091
+ const suite = definition ? definition.task : file;
8092
+ const state = suite.mode === "run" || suite.mode === "only" ? "fail" : suite.mode;
8093
+ const errors2 = ((_a = suite.result) == null ? void 0 : _a.errors) || [];
8094
+ suite.result = {
8095
+ state,
8096
+ errors: errors2
8097
+ };
8098
+ errors2.push(error);
8099
+ if (state === "fail" && suite.suite)
8100
+ markState(suite.suite, "fail");
8101
+ });
8102
+ this.markPassed(file);
8103
+ });
8104
+ typeErrors.forEach((errors, path) => {
8105
+ if (!testFiles.has(path))
8106
+ sourceErrors.push(...errors.map(({ error }) => error));
8107
+ });
8108
+ return {
8109
+ files,
8110
+ sourceErrors,
8111
+ time: performance.now() - this._startTime
8112
+ };
8000
8113
  }
8001
- cancelFiles(files, root) {
8002
- this.collectFiles(files.map((filepath) => ({
8003
- filepath,
8004
- name: relative(root, filepath),
8005
- id: filepath,
8006
- mode: "skip",
8007
- type: "suite",
8008
- result: {
8009
- state: "skip"
8010
- },
8011
- meta: {},
8012
- // Cancelled files have not yet collected tests
8013
- tasks: []
8014
- })));
8114
+ async parseTscLikeOutput(output) {
8115
+ const errorsMap = await getRawErrsMapFromTsCompile(output);
8116
+ const typesErrors = /* @__PURE__ */ new Map();
8117
+ errorsMap.forEach((errors, path) => {
8118
+ const filepath = resolve(this.ctx.config.root, path);
8119
+ const suiteErrors = errors.map((info) => {
8120
+ const limit = Error.stackTraceLimit;
8121
+ Error.stackTraceLimit = 0;
8122
+ const error = new TypeCheckError(info.errMsg, [
8123
+ {
8124
+ file: filepath,
8125
+ line: info.line,
8126
+ column: info.column,
8127
+ method: ""
8128
+ }
8129
+ ]);
8130
+ Error.stackTraceLimit = limit;
8131
+ return {
8132
+ originalError: info,
8133
+ error: {
8134
+ name: error.name,
8135
+ nameStr: String(error.name),
8136
+ message: info.errMsg,
8137
+ stacks: error.stacks,
8138
+ stack: "",
8139
+ stackStr: ""
8140
+ }
8141
+ };
8142
+ });
8143
+ typesErrors.set(filepath, suiteErrors);
8144
+ });
8145
+ return typesErrors;
8015
8146
  }
8016
- }
8017
-
8018
- const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
8019
- const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*"];
8020
- const benchmarkConfigDefaults = {
8021
- include: ["**/*.{bench,benchmark}.?(c|m)[jt]s?(x)"],
8022
- exclude: defaultExclude,
8023
- includeSource: [],
8024
- reporters: ["default"]
8025
- };
8026
- const defaultCoverageExcludes = [
8027
- "coverage/**",
8028
- "dist/**",
8029
- "packages/*/test?(s)/**",
8030
- "**/*.d.ts",
8031
- "**/virtual:*",
8032
- "**/__x00__*",
8033
- "**/\0*",
8034
- "cypress/**",
8035
- "test?(s)/**",
8036
- "test?(-*).?(c|m)[jt]s?(x)",
8037
- "**/*{.,-}{test,spec}.?(c|m)[jt]s?(x)",
8038
- "**/__tests__/**",
8039
- "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*",
8040
- "**/vitest.{workspace,projects}.[jt]s?(on)",
8041
- "**/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}"
8042
- ];
8043
- const coverageConfigDefaults = {
8044
- provider: "v8",
8045
- enabled: false,
8046
- all: true,
8047
- clean: true,
8048
- cleanOnRerun: true,
8049
- reportsDirectory: "./coverage",
8050
- exclude: defaultCoverageExcludes,
8051
- reportOnFailure: false,
8052
- reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
8053
- extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte", ".marko"],
8054
- allowExternal: false
8055
- };
8056
- const fakeTimersDefaults = {
8057
- loopLimit: 1e4,
8058
- shouldClearNativeTimers: true,
8059
- toFake: [
8060
- "setTimeout",
8061
- "clearTimeout",
8062
- "setInterval",
8063
- "clearInterval",
8064
- "setImmediate",
8065
- "clearImmediate",
8066
- "Date"
8067
- ]
8068
- };
8069
- const config = {
8070
- allowOnly: !isCI,
8071
- watch: !isCI,
8072
- globals: false,
8073
- environment: "node",
8074
- pool: "threads",
8075
- clearMocks: false,
8076
- restoreMocks: false,
8077
- mockReset: false,
8078
- include: defaultInclude,
8079
- exclude: defaultExclude,
8080
- testTimeout: 5e3,
8081
- hookTimeout: 1e4,
8082
- teardownTimeout: 1e4,
8083
- watchExclude: ["**/node_modules/**", "**/dist/**"],
8084
- forceRerunTriggers: [
8085
- "**/package.json/**",
8086
- "**/{vitest,vite}.config.*/**"
8087
- ],
8088
- update: false,
8089
- reporters: [],
8090
- silent: false,
8091
- hideSkippedTests: false,
8092
- api: false,
8093
- ui: false,
8094
- uiBase: "/__vitest__/",
8095
- open: true,
8096
- css: {
8097
- include: []
8098
- },
8099
- coverage: coverageConfigDefaults,
8100
- fakeTimers: fakeTimersDefaults,
8101
- maxConcurrency: 5,
8102
- dangerouslyIgnoreUnhandledErrors: false,
8103
- typecheck: {
8104
- checker: "tsc",
8105
- include: ["**/*.{test,spec}-d.?(c|m)[jt]s?(x)"],
8106
- exclude: defaultExclude
8107
- },
8108
- slowTestThreshold: 300
8109
- };
8110
- const configDefaults = Object.freeze(config);
8111
-
8112
- class FilesStatsCache {
8113
- cache = /* @__PURE__ */ new Map();
8114
- getStats(key) {
8115
- return this.cache.get(key);
8147
+ async clear() {
8148
+ if (this.tempConfigPath)
8149
+ await rm(this.tempConfigPath, { force: true });
8116
8150
  }
8117
- async populateStats(root, specs) {
8118
- const promises = specs.map((spec) => {
8119
- const key = `${spec[0].getName()}:${relative(root, spec[1])}`;
8120
- return this.updateStats(spec[1], key);
8121
- });
8122
- await Promise.all(promises);
8151
+ async stop() {
8152
+ var _a;
8153
+ await this.clear();
8154
+ (_a = this.process) == null ? void 0 : _a.kill();
8123
8155
  }
8124
- async updateStats(fsPath, key) {
8125
- if (!fs$8.existsSync(fsPath))
8156
+ async ensurePackageInstalled(root, checker) {
8157
+ if (checker !== "tsc" && checker !== "vue-tsc")
8126
8158
  return;
8127
- const stats = await fs$8.promises.stat(fsPath);
8128
- this.cache.set(key, { size: stats.size });
8129
- }
8130
- removeStats(fsPath) {
8131
- this.cache.forEach((_, key) => {
8132
- if (key.endsWith(fsPath))
8133
- this.cache.delete(key);
8134
- });
8159
+ const packageName = checker === "tsc" ? "typescript" : "vue-tsc";
8160
+ await ensurePackageInstalled(packageName, root);
8135
8161
  }
8136
- }
8137
-
8138
- class ResultsCache {
8139
- cache = /* @__PURE__ */ new Map();
8140
- workspacesKeyMap = /* @__PURE__ */ new Map();
8141
- cachePath = null;
8142
- version = version$1;
8143
- root = "/";
8144
- getCachePath() {
8145
- return this.cachePath;
8162
+ async prepare() {
8163
+ const { root, typecheck } = this.ctx.config;
8164
+ await this.ensurePackageInstalled(root, typecheck.checker);
8165
+ const { config, path } = await getTsconfig(root, typecheck);
8166
+ this.tempConfigPath = path;
8167
+ this.allowJs = typecheck.allowJs || config.allowJs || false;
8146
8168
  }
8147
- setConfig(root, config) {
8148
- this.root = root;
8149
- if (config)
8150
- this.cachePath = resolve(config.dir, "results.json");
8169
+ getExitCode() {
8170
+ var _a;
8171
+ return ((_a = this.process) == null ? void 0 : _a.exitCode) != null && this.process.exitCode;
8151
8172
  }
8152
- getResults(key) {
8153
- return this.cache.get(key);
8173
+ getOutput() {
8174
+ return this._output;
8154
8175
  }
8155
- async readFromCache() {
8156
- if (!this.cachePath)
8157
- return;
8158
- if (!fs$8.existsSync(this.cachePath))
8159
- return;
8160
- const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8");
8161
- const { results, version: version2 } = JSON.parse(resultsCache || "[]");
8162
- if (Number(version2.split(".")[1]) >= 30) {
8163
- this.cache = new Map(results);
8164
- this.version = version2;
8165
- results.forEach(([spec]) => {
8166
- const [projectName, relativePath] = spec.split(":");
8167
- const keyMap = this.workspacesKeyMap.get(relativePath) || [];
8168
- keyMap.push(projectName);
8169
- this.workspacesKeyMap.set(relativePath, keyMap);
8170
- });
8171
- }
8172
- }
8173
- updateResults(files) {
8174
- files.forEach((file) => {
8175
- const result = file.result;
8176
- if (!result)
8177
- return;
8178
- const duration = result.duration || 0;
8179
- const relativePath = relative(this.root, file.filepath);
8180
- this.cache.set(`${file.projectName || ""}:${relativePath}`, {
8181
- duration: duration >= 0 ? duration : 0,
8182
- failed: result.state === "fail"
8183
- });
8184
- });
8185
- }
8186
- removeFromCache(filepath) {
8187
- this.cache.forEach((_, key) => {
8188
- if (key.endsWith(filepath))
8189
- this.cache.delete(key);
8176
+ async start() {
8177
+ var _a, _b, _c;
8178
+ if (!this.tempConfigPath)
8179
+ throw new Error("tsconfig was not initialized");
8180
+ const { root, watch, typecheck } = this.ctx.config;
8181
+ const args = ["--noEmit", "--pretty", "false", "-p", this.tempConfigPath];
8182
+ if (watch)
8183
+ args.push("--watch");
8184
+ if (typecheck.allowJs)
8185
+ args.push("--allowJs", "--checkJs");
8186
+ this._output = "";
8187
+ this._startTime = performance.now();
8188
+ const child = execa(typecheck.checker, args, {
8189
+ cwd: root,
8190
+ stdout: "pipe",
8191
+ reject: false
8190
8192
  });
8191
- }
8192
- async writeToCache() {
8193
- if (!this.cachePath)
8194
- return;
8195
- const results = Array.from(this.cache.entries());
8196
- const cacheDirname = dirname(this.cachePath);
8197
- if (!fs$8.existsSync(cacheDirname))
8198
- await fs$8.promises.mkdir(cacheDirname, { recursive: true });
8199
- const cache = JSON.stringify({
8200
- version: this.version,
8201
- results
8193
+ this.process = child;
8194
+ await ((_a = this._onParseStart) == null ? void 0 : _a.call(this));
8195
+ let rerunTriggered = false;
8196
+ (_b = child.stdout) == null ? void 0 : _b.on("data", (chunk) => {
8197
+ var _a2;
8198
+ this._output += chunk;
8199
+ if (!watch)
8200
+ return;
8201
+ if (this._output.includes("File change detected") && !rerunTriggered) {
8202
+ (_a2 = this._onWatcherRerun) == null ? void 0 : _a2.call(this);
8203
+ this._startTime = performance.now();
8204
+ this._result.sourceErrors = [];
8205
+ this._result.files = [];
8206
+ this._tests = null;
8207
+ rerunTriggered = true;
8208
+ }
8209
+ if (/Found \w+ errors*. Watching for/.test(this._output)) {
8210
+ rerunTriggered = false;
8211
+ this.prepareResults(this._output).then((result) => {
8212
+ var _a3;
8213
+ this._result = result;
8214
+ (_a3 = this._onParseEnd) == null ? void 0 : _a3.call(this, result);
8215
+ });
8216
+ this._output = "";
8217
+ }
8202
8218
  });
8203
- await fs$8.promises.writeFile(this.cachePath, cache);
8204
- }
8205
- }
8206
-
8207
- class VitestCache {
8208
- results = new ResultsCache();
8209
- stats = new FilesStatsCache();
8210
- getFileTestResults(key) {
8211
- return this.results.getResults(key);
8219
+ if (!watch) {
8220
+ await child;
8221
+ this._result = await this.prepareResults(this._output);
8222
+ await ((_c = this._onParseEnd) == null ? void 0 : _c.call(this, this._result));
8223
+ }
8212
8224
  }
8213
- getFileStats(key) {
8214
- return this.stats.getStats(key);
8225
+ getResult() {
8226
+ return this._result;
8215
8227
  }
8216
- static resolveCacheDir(root, dir, projectName) {
8217
- const baseDir = slash$1(dir || "node_modules/.vitest");
8218
- return projectName ? resolve(root, baseDir, crypto.createHash("md5").update(projectName, "utf-8").digest("hex")) : resolve(root, baseDir);
8228
+ getTestFiles() {
8229
+ return Object.values(this._tests || {}).map((i) => i.file);
8219
8230
  }
8220
- static async clearCache(options) {
8221
- var _a, _b, _c;
8222
- const root = resolve(options.root || process.cwd());
8223
- const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
8224
- const config = configPath ? (_a = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath)) == null ? void 0 : _a.config : void 0;
8225
- const cache = (_b = config == null ? void 0 : config.test) == null ? void 0 : _b.cache;
8226
- const projectName = (_c = config == null ? void 0 : config.test) == null ? void 0 : _c.name;
8227
- if (cache === false)
8228
- throw new Error("Cache is disabled");
8229
- const cachePath = VitestCache.resolveCacheDir(root, cache == null ? void 0 : cache.dir, projectName);
8230
- let cleared = false;
8231
- if (fs$8.existsSync(cachePath)) {
8232
- fs$8.rmSync(cachePath, { recursive: true, force: true });
8233
- cleared = true;
8234
- }
8235
- return { dir: cachePath, cleared };
8231
+ getTestPacks() {
8232
+ return Object.values(this._tests || {}).map(({ file }) => getTasks(file)).flat().map((i) => [i.id, i.result, { typecheck: true }]);
8236
8233
  }
8237
8234
  }
8238
8235
 
8239
- class BaseSequencer {
8240
- ctx;
8241
- constructor(ctx) {
8242
- this.ctx = ctx;
8243
- }
8244
- // async so it can be extended by other sequelizers
8245
- async shard(files) {
8246
- const { config } = this.ctx;
8247
- const { index, count } = config.shard;
8248
- const shardSize = Math.ceil(files.length / count);
8249
- const shardStart = shardSize * (index - 1);
8250
- const shardEnd = shardSize * index;
8251
- return [...files].map((spec) => {
8252
- const fullPath = resolve(slash$2(config.root), slash$2(spec[1]));
8253
- const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length);
8254
- return {
8255
- spec,
8256
- hash: createHash("sha1").update(specPath).digest("hex")
8257
- };
8258
- }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ spec }) => spec);
8259
- }
8260
- // async so it can be extended by other sequelizers
8261
- async sort(files) {
8262
- const cache = this.ctx.cache;
8263
- return [...files].sort((a, b) => {
8264
- const keyA = `${a[0].getName()}:${relative(this.ctx.config.root, a[1])}`;
8265
- const keyB = `${b[0].getName()}:${relative(this.ctx.config.root, b[1])}`;
8266
- const aState = cache.getFileTestResults(keyA);
8267
- const bState = cache.getFileTestResults(keyB);
8268
- if (!aState || !bState) {
8269
- const statsA = cache.getFileStats(keyA);
8270
- const statsB = cache.getFileStats(keyB);
8271
- if (!statsA || !statsB)
8272
- return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0;
8273
- return statsB.size - statsA.size;
8236
+ function createTypecheckPool(ctx) {
8237
+ const promisesMap = /* @__PURE__ */ new WeakMap();
8238
+ const rerunTriggered = /* @__PURE__ */ new WeakMap();
8239
+ async function onParseEnd(project, { files, sourceErrors }) {
8240
+ var _a;
8241
+ const checker = project.typechecker;
8242
+ await ctx.report("onTaskUpdate", checker.getTestPacks());
8243
+ if (!project.config.typecheck.ignoreSourceErrors)
8244
+ sourceErrors.forEach((error) => ctx.state.catchError(error, "Unhandled Source Error"));
8245
+ const processError = !hasFailed(files) && checker.getExitCode();
8246
+ if (processError) {
8247
+ const error = new Error(checker.getOutput());
8248
+ error.stack = "";
8249
+ ctx.state.catchError(error, "Typecheck Error");
8250
+ }
8251
+ (_a = promisesMap.get(project)) == null ? void 0 : _a.resolve();
8252
+ rerunTriggered.set(project, false);
8253
+ if (ctx.config.watch && !ctx.runningPromise) {
8254
+ await ctx.report("onFinished", files);
8255
+ await ctx.report("onWatcherStart", files, [
8256
+ ...project.config.typecheck.ignoreSourceErrors ? [] : sourceErrors,
8257
+ ...ctx.state.getUnhandledErrors()
8258
+ ]);
8259
+ }
8260
+ }
8261
+ async function createWorkspaceTypechecker(project, files) {
8262
+ const checker = project.typechecker ?? new Typechecker(project);
8263
+ if (project.typechecker)
8264
+ return checker;
8265
+ project.typechecker = checker;
8266
+ checker.setFiles(files);
8267
+ checker.onParseStart(async () => {
8268
+ ctx.state.collectFiles(checker.getTestFiles());
8269
+ await ctx.report("onCollected");
8270
+ });
8271
+ checker.onParseEnd((result) => onParseEnd(project, result));
8272
+ checker.onWatcherRerun(async () => {
8273
+ rerunTriggered.set(project, true);
8274
+ if (!ctx.runningPromise) {
8275
+ ctx.state.clearErrors();
8276
+ await ctx.report("onWatcherRerun", files, "File change detected. Triggering rerun.");
8274
8277
  }
8275
- if (aState.failed && !bState.failed)
8276
- return -1;
8277
- if (!aState.failed && bState.failed)
8278
- return 1;
8279
- return bState.duration - aState.duration;
8278
+ await checker.collectTests();
8279
+ ctx.state.collectFiles(checker.getTestFiles());
8280
+ await ctx.report("onTaskUpdate", checker.getTestPacks());
8281
+ await ctx.report("onCollected");
8280
8282
  });
8283
+ await checker.prepare();
8284
+ await checker.collectTests();
8285
+ checker.start();
8286
+ return checker;
8287
+ }
8288
+ async function runTests(specs) {
8289
+ const specsByProject = groupBy(specs, ([project]) => project.getName());
8290
+ const promises = [];
8291
+ for (const name in specsByProject) {
8292
+ const project = specsByProject[name][0][0];
8293
+ const files = specsByProject[name].map(([_, file]) => file);
8294
+ const promise = createDefer();
8295
+ const _p = new Promise((resolve) => {
8296
+ const _i = setInterval(() => {
8297
+ if (!project.typechecker || rerunTriggered.get(project)) {
8298
+ resolve(true);
8299
+ clearInterval(_i);
8300
+ }
8301
+ });
8302
+ setTimeout(() => {
8303
+ resolve(false);
8304
+ clearInterval(_i);
8305
+ }, 500);
8306
+ });
8307
+ const triggered = await _p;
8308
+ if (project.typechecker && !triggered) {
8309
+ ctx.state.collectFiles(project.typechecker.getTestFiles());
8310
+ await ctx.report("onCollected");
8311
+ await onParseEnd(project, project.typechecker.getResult());
8312
+ continue;
8313
+ }
8314
+ promises.push(promise);
8315
+ promisesMap.set(project, promise);
8316
+ createWorkspaceTypechecker(project, files);
8317
+ }
8318
+ await Promise.all(promises);
8281
8319
  }
8320
+ return {
8321
+ runTests,
8322
+ async close() {
8323
+ const promises = ctx.projects.map((project) => {
8324
+ var _a;
8325
+ return (_a = project.typechecker) == null ? void 0 : _a.stop();
8326
+ });
8327
+ await Promise.all(promises);
8328
+ }
8329
+ };
8282
8330
  }
8283
8331
 
8284
- class RandomSequencer extends BaseSequencer {
8285
- async sort(files) {
8286
- const { sequence } = this.ctx.config;
8287
- return shuffle(files, sequence.seed);
8288
- }
8289
- }
8290
-
8291
- const extraInlineDeps = [
8292
- /^(?!.*(?:node_modules)).*\.mjs$/,
8293
- /^(?!.*(?:node_modules)).*\.cjs\.js$/,
8294
- // Vite client
8295
- /vite\w*\/dist\/client\/env.mjs/,
8296
- // Nuxt
8297
- "@nuxt/test-utils"
8298
- ];
8299
- function resolveApiServerConfig(options) {
8300
- let api;
8301
- if (options.ui && !options.api)
8302
- api = { port: defaultPort };
8303
- else if (options.api === true)
8304
- api = { port: defaultPort };
8305
- else if (typeof options.api === "number")
8306
- api = { port: options.api };
8307
- if (typeof options.api === "object") {
8308
- if (api) {
8309
- if (options.api.port)
8310
- api.port = options.api.port;
8311
- if (options.api.strictPort)
8312
- api.strictPort = options.api.strictPort;
8313
- if (options.api.host)
8314
- api.host = options.api.host;
8315
- } else {
8316
- api = { ...options.api };
8332
+ function createPool(ctx) {
8333
+ const pools = {
8334
+ forks: null,
8335
+ threads: null,
8336
+ browser: null,
8337
+ vmThreads: null,
8338
+ typescript: null
8339
+ };
8340
+ function getDefaultPoolName(project, file) {
8341
+ if (project.config.browser.enabled)
8342
+ return "browser";
8343
+ if (project.config.typecheck.enabled) {
8344
+ for (const glob of project.config.typecheck.include) {
8345
+ if (mm.isMatch(file, glob, { cwd: project.config.root }))
8346
+ return "typescript";
8347
+ }
8317
8348
  }
8349
+ return project.config.pool;
8318
8350
  }
8319
- if (api) {
8320
- if (!api.port && !api.middlewareMode)
8321
- api.port = defaultPort;
8322
- } else {
8323
- api = { middlewareMode: true };
8324
- }
8325
- return api;
8326
- }
8327
- function resolveConfig(mode, options, viteConfig) {
8328
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G;
8329
- if (options.dom) {
8330
- if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
8331
- console.warn(
8332
- c.yellow(
8333
- `${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`
8334
- )
8335
- );
8351
+ function getPoolName([project, file]) {
8352
+ for (const [glob, pool] of project.config.poolMatchGlobs || []) {
8353
+ if (pool === "browser")
8354
+ throw new Error('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');
8355
+ if (mm.isMatch(file, glob, { cwd: project.config.root }))
8356
+ return pool;
8336
8357
  }
8337
- options.environment = "happy-dom";
8358
+ return getDefaultPoolName(project, file);
8338
8359
  }
8339
- const resolved = {
8340
- ...configDefaults,
8341
- ...options,
8342
- root: viteConfig.root,
8343
- mode
8344
- };
8345
- resolved.inspect = Boolean(resolved.inspect);
8346
- resolved.inspectBrk = Boolean(resolved.inspectBrk);
8347
- if (viteConfig.base !== "/")
8348
- resolved.base = viteConfig.base;
8349
- if (options.shard) {
8350
- if (resolved.watch)
8351
- throw new Error("You cannot use --shard option with enabled watch");
8352
- const [indexString, countString] = options.shard.split("/");
8353
- const index = Math.abs(Number.parseInt(indexString, 10));
8354
- const count = Math.abs(Number.parseInt(countString, 10));
8355
- if (Number.isNaN(count) || count <= 0)
8356
- throw new Error("--shard <count> must be a positive number");
8357
- if (Number.isNaN(index) || index <= 0 || index > count)
8358
- throw new Error("--shard <index> must be a positive number less then <count>");
8359
- resolved.shard = { index, count };
8360
+ async function runTests(files, invalidate) {
8361
+ var _a;
8362
+ const conditions = ((_a = ctx.server.config.resolve.conditions) == null ? void 0 : _a.flatMap((c) => ["--conditions", c])) || [];
8363
+ const execArgv = process.execArgv.filter(
8364
+ (execArg) => execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof")
8365
+ );
8366
+ const options = {
8367
+ ...ctx.projectFiles,
8368
+ execArgv: [
8369
+ ...execArgv,
8370
+ ...conditions
8371
+ ],
8372
+ env: {
8373
+ TEST: "true",
8374
+ VITEST: "true",
8375
+ NODE_ENV: ctx.config.mode || "test",
8376
+ VITEST_MODE: ctx.config.watch ? "WATCH" : "RUN",
8377
+ ...process.env,
8378
+ ...ctx.config.env
8379
+ }
8380
+ };
8381
+ const filesByPool = {
8382
+ forks: [],
8383
+ threads: [],
8384
+ browser: [],
8385
+ vmThreads: [],
8386
+ typescript: []
8387
+ };
8388
+ for (const spec of files) {
8389
+ const pool = getPoolName(spec);
8390
+ if (!(pool in filesByPool))
8391
+ throw new Error(`Unknown pool name "${pool}" for ${spec[1]}. Available pools: ${Object.keys(filesByPool).join(", ")}`);
8392
+ filesByPool[pool].push(spec);
8393
+ }
8394
+ await Promise.all(Object.entries(filesByPool).map((entry) => {
8395
+ const [pool, files2] = entry;
8396
+ if (!files2.length)
8397
+ return null;
8398
+ if (pool === "browser") {
8399
+ pools.browser ?? (pools.browser = createBrowserPool(ctx));
8400
+ return pools.browser.runTests(files2, invalidate);
8401
+ }
8402
+ if (pool === "vmThreads") {
8403
+ pools.vmThreads ?? (pools.vmThreads = createVmThreadsPool(ctx, options));
8404
+ return pools.vmThreads.runTests(files2, invalidate);
8405
+ }
8406
+ if (pool === "threads") {
8407
+ pools.threads ?? (pools.threads = createThreadsPool(ctx, options));
8408
+ return pools.threads.runTests(files2, invalidate);
8409
+ }
8410
+ if (pool === "typescript") {
8411
+ pools.typescript ?? (pools.typescript = createTypecheckPool(ctx));
8412
+ return pools.typescript.runTests(files2);
8413
+ }
8414
+ pools.forks ?? (pools.forks = createChildProcessPool(ctx, options));
8415
+ return pools.forks.runTests(files2, invalidate);
8416
+ }));
8360
8417
  }
8361
- if (resolved.inspect || resolved.inspectBrk) {
8362
- const isSingleThread = resolved.pool === "threads" && ((_c = (_b = resolved.poolOptions) == null ? void 0 : _b.threads) == null ? void 0 : _c.singleThread);
8363
- const isSingleFork = resolved.pool === "forks" && ((_e = (_d = resolved.poolOptions) == null ? void 0 : _d.forks) == null ? void 0 : _e.singleFork);
8364
- if (!isSingleThread && !isSingleFork) {
8365
- const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
8366
- throw new Error(`You cannot use ${inspectOption} without "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`);
8418
+ return {
8419
+ runTests,
8420
+ async close() {
8421
+ await Promise.all(Object.values(pools).map((p) => p == null ? void 0 : p.close()));
8367
8422
  }
8423
+ };
8424
+ }
8425
+
8426
+ async function loadCustomReporterModule(path, runner) {
8427
+ let customReporterModule;
8428
+ try {
8429
+ customReporterModule = await runner.executeId(path);
8430
+ } catch (customReporterModuleError) {
8431
+ throw new Error(`Failed to load custom Reporter from ${path}`, { cause: customReporterModuleError });
8368
8432
  }
8369
- if (resolved.coverage.provider === "c8")
8370
- throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
8371
- if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
8372
- throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
8373
- resolved.deps ?? (resolved.deps = {});
8374
- (_f = resolved.deps).moduleDirectories ?? (_f.moduleDirectories = []);
8375
- resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
8376
- if (!dir.startsWith("/"))
8377
- dir = `/${dir}`;
8378
- if (!dir.endsWith("/"))
8379
- dir += "/";
8380
- return normalize(dir);
8433
+ if (customReporterModule.default === null || customReporterModule.default === void 0)
8434
+ throw new Error(`Custom reporter loaded from ${path} was not the default export`);
8435
+ return customReporterModule.default;
8436
+ }
8437
+ function createReporters(reporterReferences, runner) {
8438
+ const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
8439
+ if (typeof referenceOrInstance === "string") {
8440
+ if (referenceOrInstance === "html") {
8441
+ await ensurePackageInstalled("@vitest/ui", runner.root);
8442
+ const CustomReporter = await loadCustomReporterModule("@vitest/ui/reporter", runner);
8443
+ return new CustomReporter();
8444
+ } else if (referenceOrInstance in ReportersMap) {
8445
+ const BuiltinReporter = ReportersMap[referenceOrInstance];
8446
+ return new BuiltinReporter();
8447
+ } else {
8448
+ const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
8449
+ return new CustomReporter();
8450
+ }
8451
+ }
8452
+ return referenceOrInstance;
8381
8453
  });
8382
- if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
8383
- resolved.deps.moduleDirectories.push("/node_modules/");
8384
- (_g = resolved.deps).optimizer ?? (_g.optimizer = {});
8385
- (_h = resolved.deps.optimizer).ssr ?? (_h.ssr = {});
8386
- (_i = resolved.deps.optimizer.ssr).enabled ?? (_i.enabled = true);
8387
- (_j = resolved.deps.optimizer).web ?? (_j.web = {});
8388
- (_k = resolved.deps.optimizer.web).enabled ?? (_k.enabled = true);
8389
- (_l = resolved.deps).web ?? (_l.web = {});
8390
- (_m = resolved.deps.web).transformAssets ?? (_m.transformAssets = true);
8391
- (_n = resolved.deps.web).transformCss ?? (_n.transformCss = true);
8392
- (_o = resolved.deps.web).transformGlobPattern ?? (_o.transformGlobPattern = []);
8393
- resolved.server ?? (resolved.server = {});
8394
- (_p = resolved.server).deps ?? (_p.deps = {});
8395
- const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
8396
- deprecatedDepsOptions.forEach((option) => {
8397
- if (resolved.deps[option] === void 0)
8398
- return;
8399
- if (option === "fallbackCJS") {
8400
- console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`));
8401
- } else {
8402
- const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
8403
- console.warn(
8404
- c.yellow(
8405
- `${c.inverse(c.yellow(" Vitest "))} "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"}"`
8406
- )
8407
- );
8454
+ return Promise.all(promisedReporters);
8455
+ }
8456
+ function createBenchmarkReporters(reporterReferences, runner) {
8457
+ const promisedReporters = reporterReferences.map(async (referenceOrInstance) => {
8458
+ if (typeof referenceOrInstance === "string") {
8459
+ if (referenceOrInstance in BenchmarkReportsMap) {
8460
+ const BuiltinReporter = BenchmarkReportsMap[referenceOrInstance];
8461
+ return new BuiltinReporter();
8462
+ } else {
8463
+ const CustomReporter = await loadCustomReporterModule(referenceOrInstance, runner);
8464
+ return new CustomReporter();
8465
+ }
8408
8466
  }
8409
- if (resolved.server.deps[option] === void 0)
8410
- resolved.server.deps[option] = resolved.deps[option];
8467
+ return referenceOrInstance;
8411
8468
  });
8412
- if (resolved.server.deps.inline !== true) {
8413
- const ssrOptions = viteConfig.ssr;
8414
- if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
8415
- resolved.server.deps.inline = true;
8416
- } else {
8417
- (_q = resolved.server.deps).inline ?? (_q.inline = []);
8418
- resolved.server.deps.inline.push(...extraInlineDeps);
8469
+ return Promise.all(promisedReporters);
8470
+ }
8471
+
8472
+ function isAggregateError(err) {
8473
+ if (typeof AggregateError !== "undefined" && err instanceof AggregateError)
8474
+ return true;
8475
+ return err instanceof Error && "errors" in err;
8476
+ }
8477
+ class StateManager {
8478
+ filesMap = /* @__PURE__ */ new Map();
8479
+ pathsSet = /* @__PURE__ */ new Set();
8480
+ browserTestPromises = /* @__PURE__ */ new Map();
8481
+ idMap = /* @__PURE__ */ new Map();
8482
+ taskFileMap = /* @__PURE__ */ new WeakMap();
8483
+ errorsSet = /* @__PURE__ */ new Set();
8484
+ processTimeoutCauses = /* @__PURE__ */ new Set();
8485
+ catchError(err, type) {
8486
+ if (isAggregateError(err))
8487
+ return err.errors.forEach((error) => this.catchError(error, type));
8488
+ if (err === Object(err))
8489
+ err.type = type;
8490
+ else
8491
+ err = { type, message: err };
8492
+ const _err = err;
8493
+ if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
8494
+ const task = this.idMap.get(_err.taskId);
8495
+ if (task) {
8496
+ task.mode = "skip";
8497
+ task.result ?? (task.result = { state: "skip" });
8498
+ task.result.state = "skip";
8499
+ }
8500
+ return;
8419
8501
  }
8502
+ this.errorsSet.add(err);
8420
8503
  }
8421
- (_r = resolved.server.deps).moduleDirectories ?? (_r.moduleDirectories = []);
8422
- resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
8423
- if (resolved.runner) {
8424
- resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.runner);
8504
+ clearErrors() {
8505
+ this.errorsSet.clear();
8425
8506
  }
8426
- if (resolved.deps.registerNodeLoader) {
8427
- const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
8428
- console.warn(
8429
- c.yellow(
8430
- `${c.inverse(c.yellow(" Vitest "))} "deps.registerNodeLoader" is deprecated.If you rely on aliases inside external packages, use "deps.optimizer.${transformMode}.include" instead.`
8431
- )
8432
- );
8507
+ getUnhandledErrors() {
8508
+ return Array.from(this.errorsSet.values());
8433
8509
  }
8434
- resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
8435
- if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat)
8436
- resolved.snapshotFormat.plugins = [];
8437
- const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
8438
- resolved.snapshotOptions = {
8439
- snapshotFormat: resolved.snapshotFormat || {},
8440
- updateSnapshot: isCI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
8441
- resolveSnapshotPath: options.resolveSnapshotPath,
8442
- // resolved inside the worker
8443
- snapshotEnvironment: null
8444
- };
8445
- if (options.resolveSnapshotPath)
8446
- delete resolved.resolveSnapshotPath;
8447
- if (process.env.VITEST_MAX_THREADS) {
8448
- resolved.poolOptions = {
8449
- ...resolved.poolOptions,
8450
- threads: {
8451
- ...(_s = resolved.poolOptions) == null ? void 0 : _s.threads,
8452
- maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
8453
- },
8454
- vmThreads: {
8455
- ...(_t = resolved.poolOptions) == null ? void 0 : _t.vmThreads,
8456
- maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
8457
- }
8458
- };
8510
+ addProcessTimeoutCause(cause) {
8511
+ this.processTimeoutCauses.add(cause);
8459
8512
  }
8460
- if (process.env.VITEST_MIN_THREADS) {
8461
- resolved.poolOptions = {
8462
- ...resolved.poolOptions,
8463
- threads: {
8464
- ...(_u = resolved.poolOptions) == null ? void 0 : _u.threads,
8465
- minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
8466
- },
8467
- vmThreads: {
8468
- ...(_v = resolved.poolOptions) == null ? void 0 : _v.vmThreads,
8469
- minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
8470
- }
8471
- };
8513
+ getProcessTimeoutCauses() {
8514
+ return Array.from(this.processTimeoutCauses.values());
8472
8515
  }
8473
- if (process.env.VITEST_MAX_FORKS) {
8474
- resolved.poolOptions = {
8475
- ...resolved.poolOptions,
8476
- forks: {
8477
- ...(_w = resolved.poolOptions) == null ? void 0 : _w.forks,
8478
- maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
8479
- }
8480
- };
8516
+ getPaths() {
8517
+ return Array.from(this.pathsSet);
8481
8518
  }
8482
- if (process.env.VITEST_MIN_FORKS) {
8483
- resolved.poolOptions = {
8484
- ...resolved.poolOptions,
8485
- forks: {
8486
- ...(_x = resolved.poolOptions) == null ? void 0 : _x.forks,
8487
- minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
8488
- }
8489
- };
8519
+ getFiles(keys) {
8520
+ if (keys)
8521
+ return keys.map((key) => this.filesMap.get(key)).filter(Boolean).flat();
8522
+ return Array.from(this.filesMap.values()).flat();
8490
8523
  }
8491
- if (mode === "benchmark") {
8492
- resolved.benchmark = {
8493
- ...benchmarkConfigDefaults,
8494
- ...resolved.benchmark
8495
- };
8496
- resolved.coverage.enabled = false;
8497
- resolved.include = resolved.benchmark.include;
8498
- resolved.exclude = resolved.benchmark.exclude;
8499
- resolved.includeSource = resolved.benchmark.includeSource;
8500
- const reporters = Array.from(/* @__PURE__ */ new Set([
8501
- ...toArray(resolved.benchmark.reporters),
8502
- // @ts-expect-error reporter is CLI flag
8503
- ...toArray(options.reporter)
8504
- ])).filter(Boolean);
8505
- if (reporters.length)
8506
- resolved.benchmark.reporters = reporters;
8507
- else
8508
- resolved.benchmark.reporters = ["default"];
8509
- if (options.outputFile)
8510
- resolved.benchmark.outputFile = options.outputFile;
8524
+ getFilepaths() {
8525
+ return Array.from(this.filesMap.keys());
8511
8526
  }
8512
- resolved.setupFiles = toArray(resolved.setupFiles || []).map(
8513
- (file) => normalize(
8514
- resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file)
8515
- )
8516
- );
8517
- resolved.coverage.exclude.push(...resolved.setupFiles.map((file) => `${resolved.coverage.allowExternal ? "**/" : ""}${relative(resolved.root, file)}`));
8518
- resolved.forceRerunTriggers = [
8519
- ...resolved.forceRerunTriggers,
8520
- ...resolved.setupFiles
8521
- ];
8522
- if (resolved.diff) {
8523
- resolved.diff = normalize(
8524
- resolveModule(resolved.diff, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.diff)
8525
- );
8526
- resolved.forceRerunTriggers.push(resolved.diff);
8527
+ getFailedFilepaths() {
8528
+ return this.getFiles().filter((i) => {
8529
+ var _a;
8530
+ return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
8531
+ }).map((i) => i.filepath);
8527
8532
  }
8528
- resolved.api = resolveApiServerConfig(options);
8529
- if (options.related)
8530
- resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
8531
- if (mode !== "benchmark") {
8532
- const cliReporters = toArray(resolved.reporter || []).map((reporter) => {
8533
- if (/^\.\.?\//.test(reporter))
8534
- return resolve(process.cwd(), reporter);
8535
- return reporter;
8533
+ collectPaths(paths = []) {
8534
+ paths.forEach((path) => {
8535
+ this.pathsSet.add(path);
8536
8536
  });
8537
- const reporters = cliReporters.length ? cliReporters : resolved.reporters;
8538
- resolved.reporters = Array.from(new Set(toArray(reporters))).filter(Boolean);
8539
8537
  }
8540
- if (!resolved.reporters.length)
8541
- resolved.reporters.push("default");
8542
- if (resolved.changed)
8543
- resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
8544
- resolved.css ?? (resolved.css = {});
8545
- if (typeof resolved.css === "object") {
8546
- (_y = resolved.css).modules ?? (_y.modules = {});
8547
- (_z = resolved.css.modules).classNameStrategy ?? (_z.classNameStrategy = "stable");
8538
+ collectFiles(files = []) {
8539
+ files.forEach((file) => {
8540
+ const existing = this.filesMap.get(file.filepath) || [];
8541
+ const otherProject = existing.filter((i) => i.projectName !== file.projectName);
8542
+ otherProject.push(file);
8543
+ this.filesMap.set(file.filepath, otherProject);
8544
+ this.updateId(file);
8545
+ });
8548
8546
  }
8549
- resolved.cache ?? (resolved.cache = { dir: "" });
8550
- if (resolved.cache)
8551
- resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name);
8552
- resolved.sequence ?? (resolved.sequence = {});
8553
- if (!((_A = resolved.sequence) == null ? void 0 : _A.sequencer)) {
8554
- resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
8547
+ // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
8548
+ clearFiles(_project, paths = []) {
8549
+ const project = _project;
8550
+ paths.forEach((path) => {
8551
+ const files = this.filesMap.get(path);
8552
+ if (!files)
8553
+ return;
8554
+ const filtered = files.filter((file) => file.projectName !== project.config.name);
8555
+ if (!filtered.length)
8556
+ this.filesMap.delete(path);
8557
+ else
8558
+ this.filesMap.set(path, filtered);
8559
+ });
8555
8560
  }
8556
- (_B = resolved.sequence).hooks ?? (_B.hooks = "parallel");
8557
- if (resolved.sequence.sequencer === RandomSequencer)
8558
- (_C = resolved.sequence).seed ?? (_C.seed = Date.now());
8559
- resolved.typecheck = {
8560
- ...configDefaults.typecheck,
8561
- ...resolved.typecheck
8562
- };
8563
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
8564
- if (mode === "typecheck") {
8565
- resolved.include = resolved.typecheck.include;
8566
- resolved.exclude = resolved.typecheck.exclude;
8561
+ updateId(task) {
8562
+ if (this.idMap.get(task.id) === task)
8563
+ return;
8564
+ this.idMap.set(task.id, task);
8565
+ if (task.type === "suite") {
8566
+ task.tasks.forEach((task2) => {
8567
+ this.updateId(task2);
8568
+ });
8569
+ }
8570
+ }
8571
+ updateTasks(packs) {
8572
+ for (const [id, result, meta] of packs) {
8573
+ const task = this.idMap.get(id);
8574
+ if (task) {
8575
+ task.result = result;
8576
+ task.meta = meta;
8577
+ if ((result == null ? void 0 : result.state) === "skip")
8578
+ task.mode = "skip";
8579
+ }
8580
+ }
8581
+ }
8582
+ updateUserLog(log) {
8583
+ const task = log.taskId && this.idMap.get(log.taskId);
8584
+ if (task) {
8585
+ if (!task.logs)
8586
+ task.logs = [];
8587
+ task.logs.push(log);
8588
+ }
8589
+ }
8590
+ getCountOfFailedTests() {
8591
+ return Array.from(this.idMap.values()).filter((t) => {
8592
+ var _a;
8593
+ return ((_a = t.result) == null ? void 0 : _a.state) === "fail";
8594
+ }).length;
8595
+ }
8596
+ cancelFiles(files, root) {
8597
+ this.collectFiles(files.map((filepath) => ({
8598
+ filepath,
8599
+ name: relative(root, filepath),
8600
+ id: filepath,
8601
+ mode: "skip",
8602
+ type: "suite",
8603
+ result: {
8604
+ state: "skip"
8605
+ },
8606
+ meta: {},
8607
+ // Cancelled files have not yet collected tests
8608
+ tasks: []
8609
+ })));
8567
8610
  }
8568
- resolved.browser ?? (resolved.browser = {});
8569
- (_D = resolved.browser).enabled ?? (_D.enabled = false);
8570
- (_E = resolved.browser).headless ?? (_E.headless = isCI);
8571
- (_F = resolved.browser).slowHijackESM ?? (_F.slowHijackESM = true);
8572
- (_G = resolved.browser).isolate ?? (_G.isolate = true);
8573
- resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
8574
- port: defaultBrowserPort
8575
- };
8576
- resolved.testTransformMode ?? (resolved.testTransformMode = {});
8577
- return resolved;
8578
- }
8579
- function isBrowserEnabled(config) {
8580
- var _a, _b;
8581
- if ((_a = config.browser) == null ? void 0 : _a.enabled)
8582
- return true;
8583
- return ((_b = config.poolMatchGlobs) == null ? void 0 : _b.length) && config.poolMatchGlobs.some(([, pool]) => pool === "browser");
8584
8611
  }
8585
8612
 
8586
- const ESC$1 = '\u001B[';
8587
- const OSC = '\u001B]';
8588
- const BEL = '\u0007';
8589
- const SEP = ';';
8590
- const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
8591
-
8592
- const ansiEscapes = {};
8593
-
8594
- ansiEscapes.cursorTo = (x, y) => {
8595
- if (typeof x !== 'number') {
8596
- throw new TypeError('The `x` argument is required');
8597
- }
8598
-
8599
- if (typeof y !== 'number') {
8600
- return ESC$1 + (x + 1) + 'G';
8601
- }
8602
-
8603
- return ESC$1 + (y + 1) + ';' + (x + 1) + 'H';
8613
+ const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
8614
+ const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*"];
8615
+ const benchmarkConfigDefaults = {
8616
+ include: ["**/*.{bench,benchmark}.?(c|m)[jt]s?(x)"],
8617
+ exclude: defaultExclude,
8618
+ includeSource: [],
8619
+ reporters: ["default"]
8604
8620
  };
8605
-
8606
- ansiEscapes.cursorMove = (x, y) => {
8607
- if (typeof x !== 'number') {
8608
- throw new TypeError('The `x` argument is required');
8609
- }
8610
-
8611
- let returnValue = '';
8612
-
8613
- if (x < 0) {
8614
- returnValue += ESC$1 + (-x) + 'D';
8615
- } else if (x > 0) {
8616
- returnValue += ESC$1 + x + 'C';
8617
- }
8618
-
8619
- if (y < 0) {
8620
- returnValue += ESC$1 + (-y) + 'A';
8621
- } else if (y > 0) {
8622
- returnValue += ESC$1 + y + 'B';
8623
- }
8624
-
8625
- return returnValue;
8621
+ const defaultCoverageExcludes = [
8622
+ "coverage/**",
8623
+ "dist/**",
8624
+ "packages/*/test?(s)/**",
8625
+ "**/*.d.ts",
8626
+ "**/virtual:*",
8627
+ "**/__x00__*",
8628
+ "**/\0*",
8629
+ "cypress/**",
8630
+ "test?(s)/**",
8631
+ "test?(-*).?(c|m)[jt]s?(x)",
8632
+ "**/*{.,-}{test,spec}.?(c|m)[jt]s?(x)",
8633
+ "**/__tests__/**",
8634
+ "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*",
8635
+ "**/vitest.{workspace,projects}.[jt]s?(on)",
8636
+ "**/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}"
8637
+ ];
8638
+ const coverageConfigDefaults = {
8639
+ provider: "v8",
8640
+ enabled: false,
8641
+ all: true,
8642
+ clean: true,
8643
+ cleanOnRerun: true,
8644
+ reportsDirectory: "./coverage",
8645
+ exclude: defaultCoverageExcludes,
8646
+ reportOnFailure: false,
8647
+ reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
8648
+ extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte", ".marko"],
8649
+ allowExternal: false
8626
8650
  };
8627
-
8628
- ansiEscapes.cursorUp = (count = 1) => ESC$1 + count + 'A';
8629
- ansiEscapes.cursorDown = (count = 1) => ESC$1 + count + 'B';
8630
- ansiEscapes.cursorForward = (count = 1) => ESC$1 + count + 'C';
8631
- ansiEscapes.cursorBackward = (count = 1) => ESC$1 + count + 'D';
8632
-
8633
- ansiEscapes.cursorLeft = ESC$1 + 'G';
8634
- ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC$1 + 's';
8635
- ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC$1 + 'u';
8636
- ansiEscapes.cursorGetPosition = ESC$1 + '6n';
8637
- ansiEscapes.cursorNextLine = ESC$1 + 'E';
8638
- ansiEscapes.cursorPrevLine = ESC$1 + 'F';
8639
- ansiEscapes.cursorHide = ESC$1 + '?25l';
8640
- ansiEscapes.cursorShow = ESC$1 + '?25h';
8641
-
8642
- ansiEscapes.eraseLines = count => {
8643
- let clear = '';
8644
-
8645
- for (let i = 0; i < count; i++) {
8646
- clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
8647
- }
8648
-
8649
- if (count) {
8650
- clear += ansiEscapes.cursorLeft;
8651
- }
8652
-
8653
- return clear;
8654
- };
8655
-
8656
- ansiEscapes.eraseEndLine = ESC$1 + 'K';
8657
- ansiEscapes.eraseStartLine = ESC$1 + '1K';
8658
- ansiEscapes.eraseLine = ESC$1 + '2K';
8659
- ansiEscapes.eraseDown = ESC$1 + 'J';
8660
- ansiEscapes.eraseUp = ESC$1 + '1J';
8661
- ansiEscapes.eraseScreen = ESC$1 + '2J';
8662
- ansiEscapes.scrollUp = ESC$1 + 'S';
8663
- ansiEscapes.scrollDown = ESC$1 + 'T';
8664
-
8665
- ansiEscapes.clearScreen = '\u001Bc';
8666
-
8667
- ansiEscapes.clearTerminal = process.platform === 'win32' ?
8668
- `${ansiEscapes.eraseScreen}${ESC$1}0f` :
8669
- // 1. Erases the screen (Only done in case `2` is not supported)
8670
- // 2. Erases the whole screen including scrollback buffer
8671
- // 3. Moves cursor to the top-left position
8672
- // More info: https://www.real-world-systems.com/docs/ANSIcode.html
8673
- `${ansiEscapes.eraseScreen}${ESC$1}3J${ESC$1}H`;
8674
-
8675
- ansiEscapes.beep = BEL;
8676
-
8677
- ansiEscapes.link = (text, url) => {
8678
- return [
8679
- OSC,
8680
- '8',
8681
- SEP,
8682
- SEP,
8683
- url,
8684
- BEL,
8685
- text,
8686
- OSC,
8687
- '8',
8688
- SEP,
8689
- SEP,
8690
- BEL
8691
- ].join('');
8651
+ const fakeTimersDefaults = {
8652
+ loopLimit: 1e4,
8653
+ shouldClearNativeTimers: true,
8654
+ toFake: [
8655
+ "setTimeout",
8656
+ "clearTimeout",
8657
+ "setInterval",
8658
+ "clearInterval",
8659
+ "setImmediate",
8660
+ "clearImmediate",
8661
+ "Date"
8662
+ ]
8692
8663
  };
8693
-
8694
- ansiEscapes.image = (buffer, options = {}) => {
8695
- let returnValue = `${OSC}1337;File=inline=1`;
8696
-
8697
- if (options.width) {
8698
- returnValue += `;width=${options.width}`;
8699
- }
8700
-
8701
- if (options.height) {
8702
- returnValue += `;height=${options.height}`;
8703
- }
8704
-
8705
- if (options.preserveAspectRatio === false) {
8706
- returnValue += ';preserveAspectRatio=0';
8707
- }
8708
-
8709
- return returnValue + ':' + buffer.toString('base64') + BEL;
8664
+ const config = {
8665
+ allowOnly: !isCI,
8666
+ watch: !isCI,
8667
+ globals: false,
8668
+ environment: "node",
8669
+ pool: "threads",
8670
+ clearMocks: false,
8671
+ restoreMocks: false,
8672
+ mockReset: false,
8673
+ include: defaultInclude,
8674
+ exclude: defaultExclude,
8675
+ testTimeout: 5e3,
8676
+ hookTimeout: 1e4,
8677
+ teardownTimeout: 1e4,
8678
+ watchExclude: ["**/node_modules/**", "**/dist/**"],
8679
+ forceRerunTriggers: [
8680
+ "**/package.json/**",
8681
+ "**/{vitest,vite}.config.*/**"
8682
+ ],
8683
+ update: false,
8684
+ reporters: [],
8685
+ silent: false,
8686
+ hideSkippedTests: false,
8687
+ api: false,
8688
+ ui: false,
8689
+ uiBase: "/__vitest__/",
8690
+ open: true,
8691
+ css: {
8692
+ include: []
8693
+ },
8694
+ coverage: coverageConfigDefaults,
8695
+ fakeTimers: fakeTimersDefaults,
8696
+ maxConcurrency: 5,
8697
+ dangerouslyIgnoreUnhandledErrors: false,
8698
+ typecheck: {
8699
+ checker: "tsc",
8700
+ include: ["**/*.{test,spec}-d.?(c|m)[jt]s?(x)"],
8701
+ exclude: defaultExclude
8702
+ },
8703
+ slowTestThreshold: 300
8710
8704
  };
8705
+ const configDefaults = Object.freeze(config);
8711
8706
 
8712
- ansiEscapes.iTerm = {
8713
- setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
8707
+ class FilesStatsCache {
8708
+ cache = /* @__PURE__ */ new Map();
8709
+ getStats(key) {
8710
+ return this.cache.get(key);
8711
+ }
8712
+ async populateStats(root, specs) {
8713
+ const promises = specs.map((spec) => {
8714
+ const key = `${spec[0].getName()}:${relative(root, spec[1])}`;
8715
+ return this.updateStats(spec[1], key);
8716
+ });
8717
+ await Promise.all(promises);
8718
+ }
8719
+ async updateStats(fsPath, key) {
8720
+ if (!fs$8.existsSync(fsPath))
8721
+ return;
8722
+ const stats = await fs$8.promises.stat(fsPath);
8723
+ this.cache.set(key, { size: stats.size });
8724
+ }
8725
+ removeStats(fsPath) {
8726
+ this.cache.forEach((_, key) => {
8727
+ if (key.endsWith(fsPath))
8728
+ this.cache.delete(key);
8729
+ });
8730
+ }
8731
+ }
8714
8732
 
8715
- annotation: (message, options = {}) => {
8716
- let returnValue = `${OSC}1337;`;
8733
+ class ResultsCache {
8734
+ cache = /* @__PURE__ */ new Map();
8735
+ workspacesKeyMap = /* @__PURE__ */ new Map();
8736
+ cachePath = null;
8737
+ version = version$1;
8738
+ root = "/";
8739
+ getCachePath() {
8740
+ return this.cachePath;
8741
+ }
8742
+ setConfig(root, config) {
8743
+ this.root = root;
8744
+ if (config)
8745
+ this.cachePath = resolve(config.dir, "results.json");
8746
+ }
8747
+ getResults(key) {
8748
+ return this.cache.get(key);
8749
+ }
8750
+ async readFromCache() {
8751
+ if (!this.cachePath)
8752
+ return;
8753
+ if (!fs$8.existsSync(this.cachePath))
8754
+ return;
8755
+ const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8");
8756
+ const { results, version: version2 } = JSON.parse(resultsCache || "[]");
8757
+ if (Number(version2.split(".")[1]) >= 30) {
8758
+ this.cache = new Map(results);
8759
+ this.version = version2;
8760
+ results.forEach(([spec]) => {
8761
+ const [projectName, relativePath] = spec.split(":");
8762
+ const keyMap = this.workspacesKeyMap.get(relativePath) || [];
8763
+ keyMap.push(projectName);
8764
+ this.workspacesKeyMap.set(relativePath, keyMap);
8765
+ });
8766
+ }
8767
+ }
8768
+ updateResults(files) {
8769
+ files.forEach((file) => {
8770
+ const result = file.result;
8771
+ if (!result)
8772
+ return;
8773
+ const duration = result.duration || 0;
8774
+ const relativePath = relative(this.root, file.filepath);
8775
+ this.cache.set(`${file.projectName || ""}:${relativePath}`, {
8776
+ duration: duration >= 0 ? duration : 0,
8777
+ failed: result.state === "fail"
8778
+ });
8779
+ });
8780
+ }
8781
+ removeFromCache(filepath) {
8782
+ this.cache.forEach((_, key) => {
8783
+ if (key.endsWith(filepath))
8784
+ this.cache.delete(key);
8785
+ });
8786
+ }
8787
+ async writeToCache() {
8788
+ if (!this.cachePath)
8789
+ return;
8790
+ const results = Array.from(this.cache.entries());
8791
+ const cacheDirname = dirname(this.cachePath);
8792
+ if (!fs$8.existsSync(cacheDirname))
8793
+ await fs$8.promises.mkdir(cacheDirname, { recursive: true });
8794
+ const cache = JSON.stringify({
8795
+ version: this.version,
8796
+ results
8797
+ });
8798
+ await fs$8.promises.writeFile(this.cachePath, cache);
8799
+ }
8800
+ }
8717
8801
 
8718
- const hasX = typeof options.x !== 'undefined';
8719
- const hasY = typeof options.y !== 'undefined';
8720
- if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
8721
- throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
8722
- }
8802
+ class VitestCache {
8803
+ results = new ResultsCache();
8804
+ stats = new FilesStatsCache();
8805
+ getFileTestResults(key) {
8806
+ return this.results.getResults(key);
8807
+ }
8808
+ getFileStats(key) {
8809
+ return this.stats.getStats(key);
8810
+ }
8811
+ static resolveCacheDir(root, dir, projectName) {
8812
+ const baseDir = slash$1(dir || "node_modules/.vitest");
8813
+ return projectName ? resolve(root, baseDir, crypto.createHash("md5").update(projectName, "utf-8").digest("hex")) : resolve(root, baseDir);
8814
+ }
8815
+ static async clearCache(options) {
8816
+ var _a, _b, _c;
8817
+ const root = resolve(options.root || process.cwd());
8818
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
8819
+ const config = configPath ? (_a = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath)) == null ? void 0 : _a.config : void 0;
8820
+ const cache = (_b = config == null ? void 0 : config.test) == null ? void 0 : _b.cache;
8821
+ const projectName = (_c = config == null ? void 0 : config.test) == null ? void 0 : _c.name;
8822
+ if (cache === false)
8823
+ throw new Error("Cache is disabled");
8824
+ const cachePath = VitestCache.resolveCacheDir(root, cache == null ? void 0 : cache.dir, projectName);
8825
+ let cleared = false;
8826
+ if (fs$8.existsSync(cachePath)) {
8827
+ fs$8.rmSync(cachePath, { recursive: true, force: true });
8828
+ cleared = true;
8829
+ }
8830
+ return { dir: cachePath, cleared };
8831
+ }
8832
+ }
8723
8833
 
8724
- message = message.replace(/\|/g, '');
8725
-
8726
- returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
8727
-
8728
- if (options.length > 0) {
8729
- returnValue +=
8730
- (hasX ?
8731
- [message, options.length, options.x, options.y] :
8732
- [options.length, message]).join('|');
8733
- } else {
8734
- returnValue += message;
8735
- }
8736
-
8737
- return returnValue + BEL;
8738
- }
8739
- };
8740
-
8741
- var onetime$2 = {exports: {}};
8742
-
8743
- var mimicFn$2 = {exports: {}};
8744
-
8745
- const mimicFn$1 = (to, from) => {
8746
- for (const prop of Reflect.ownKeys(from)) {
8747
- Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
8748
- }
8749
-
8750
- return to;
8751
- };
8752
-
8753
- mimicFn$2.exports = mimicFn$1;
8754
- // TODO: Remove this for the next major release
8755
- mimicFn$2.exports.default = mimicFn$1;
8756
-
8757
- var mimicFnExports = mimicFn$2.exports;
8758
-
8759
- const mimicFn = mimicFnExports;
8760
-
8761
- const calledFunctions = new WeakMap();
8762
-
8763
- const onetime = (function_, options = {}) => {
8764
- if (typeof function_ !== 'function') {
8765
- throw new TypeError('Expected a function');
8766
- }
8767
-
8768
- let returnValue;
8769
- let callCount = 0;
8770
- const functionName = function_.displayName || function_.name || '<anonymous>';
8771
-
8772
- const onetime = function (...arguments_) {
8773
- calledFunctions.set(onetime, ++callCount);
8774
-
8775
- if (callCount === 1) {
8776
- returnValue = function_.apply(this, arguments_);
8777
- function_ = null;
8778
- } else if (options.throw === true) {
8779
- throw new Error(`Function \`${functionName}\` can only be called once`);
8780
- }
8781
-
8782
- return returnValue;
8783
- };
8784
-
8785
- mimicFn(onetime, function_);
8786
- calledFunctions.set(onetime, callCount);
8787
-
8788
- return onetime;
8789
- };
8790
-
8791
- onetime$2.exports = onetime;
8792
- // TODO: Remove this for the next major release
8793
- onetime$2.exports.default = onetime;
8794
-
8795
- onetime$2.exports.callCount = function_ => {
8796
- if (!calledFunctions.has(function_)) {
8797
- throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
8798
- }
8799
-
8800
- return calledFunctions.get(function_);
8801
- };
8802
-
8803
- var onetimeExports = onetime$2.exports;
8804
- var onetime$1 = /*@__PURE__*/getDefaultExportFromCjs(onetimeExports);
8805
-
8806
- const restoreCursor = onetime$1(() => {
8807
- onExit(() => {
8808
- process$1.stderr.write('\u001B[?25h');
8809
- }, {alwaysLast: true});
8810
- });
8811
-
8812
- let isHidden = false;
8813
-
8814
- const cliCursor = {};
8815
-
8816
- cliCursor.show = (writableStream = process$1.stderr) => {
8817
- if (!writableStream.isTTY) {
8818
- return;
8819
- }
8820
-
8821
- isHidden = false;
8822
- writableStream.write('\u001B[?25h');
8823
- };
8824
-
8825
- cliCursor.hide = (writableStream = process$1.stderr) => {
8826
- if (!writableStream.isTTY) {
8827
- return;
8828
- }
8829
-
8830
- restoreCursor();
8831
- isHidden = true;
8832
- writableStream.write('\u001B[?25l');
8833
- };
8834
-
8835
- cliCursor.toggle = (force, writableStream) => {
8836
- if (force !== undefined) {
8837
- isHidden = force;
8838
- }
8839
-
8840
- if (isHidden) {
8841
- cliCursor.show(writableStream);
8842
- } else {
8843
- cliCursor.hide(writableStream);
8844
- }
8845
- };
8846
-
8847
- const ESCAPES = new Set([
8848
- '\u001B',
8849
- '\u009B',
8850
- ]);
8851
-
8852
- const END_CODE = 39;
8853
- const ANSI_ESCAPE_BELL = '\u0007';
8854
- const ANSI_CSI = '[';
8855
- const ANSI_OSC = ']';
8856
- const ANSI_SGR_TERMINATOR = 'm';
8857
- const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
8858
-
8859
- const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
8860
- const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
8861
-
8862
- // Calculate the length of words split on ' ', ignoring
8863
- // the extra characters added by ansi escape codes
8864
- const wordLengths = string => string.split(' ').map(character => stringWidth(character));
8865
-
8866
- // Wrap a long word across multiple rows
8867
- // Ansi escape codes do not count towards length
8868
- const wrapWord = (rows, word, columns) => {
8869
- const characters = [...word];
8870
-
8871
- let isInsideEscape = false;
8872
- let isInsideLinkEscape = false;
8873
- let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
8874
-
8875
- for (const [index, character] of characters.entries()) {
8876
- const characterLength = stringWidth(character);
8877
-
8878
- if (visible + characterLength <= columns) {
8879
- rows[rows.length - 1] += character;
8880
- } else {
8881
- rows.push(character);
8882
- visible = 0;
8883
- }
8884
-
8885
- if (ESCAPES.has(character)) {
8886
- isInsideEscape = true;
8887
- isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
8888
- }
8889
-
8890
- if (isInsideEscape) {
8891
- if (isInsideLinkEscape) {
8892
- if (character === ANSI_ESCAPE_BELL) {
8893
- isInsideEscape = false;
8894
- isInsideLinkEscape = false;
8895
- }
8896
- } else if (character === ANSI_SGR_TERMINATOR) {
8897
- isInsideEscape = false;
8898
- }
8899
-
8900
- continue;
8901
- }
8902
-
8903
- visible += characterLength;
8904
-
8905
- if (visible === columns && index < characters.length - 1) {
8906
- rows.push('');
8907
- visible = 0;
8908
- }
8909
- }
8910
-
8911
- // It's possible that the last row we copy over is only
8912
- // ansi escape characters, handle this edge-case
8913
- if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
8914
- rows[rows.length - 2] += rows.pop();
8915
- }
8916
- };
8917
-
8918
- // Trims spaces from a string ignoring invisible sequences
8919
- const stringVisibleTrimSpacesRight = string => {
8920
- const words = string.split(' ');
8921
- let last = words.length;
8922
-
8923
- while (last > 0) {
8924
- if (stringWidth(words[last - 1]) > 0) {
8925
- break;
8926
- }
8834
+ class BaseSequencer {
8835
+ ctx;
8836
+ constructor(ctx) {
8837
+ this.ctx = ctx;
8838
+ }
8839
+ // async so it can be extended by other sequelizers
8840
+ async shard(files) {
8841
+ const { config } = this.ctx;
8842
+ const { index, count } = config.shard;
8843
+ const shardSize = Math.ceil(files.length / count);
8844
+ const shardStart = shardSize * (index - 1);
8845
+ const shardEnd = shardSize * index;
8846
+ return [...files].map((spec) => {
8847
+ const fullPath = resolve(slash$2(config.root), slash$2(spec[1]));
8848
+ const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length);
8849
+ return {
8850
+ spec,
8851
+ hash: createHash("sha1").update(specPath).digest("hex")
8852
+ };
8853
+ }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ spec }) => spec);
8854
+ }
8855
+ // async so it can be extended by other sequelizers
8856
+ async sort(files) {
8857
+ const cache = this.ctx.cache;
8858
+ return [...files].sort((a, b) => {
8859
+ const keyA = `${a[0].getName()}:${relative(this.ctx.config.root, a[1])}`;
8860
+ const keyB = `${b[0].getName()}:${relative(this.ctx.config.root, b[1])}`;
8861
+ const aState = cache.getFileTestResults(keyA);
8862
+ const bState = cache.getFileTestResults(keyB);
8863
+ if (!aState || !bState) {
8864
+ const statsA = cache.getFileStats(keyA);
8865
+ const statsB = cache.getFileStats(keyB);
8866
+ if (!statsA || !statsB)
8867
+ return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0;
8868
+ return statsB.size - statsA.size;
8869
+ }
8870
+ if (aState.failed && !bState.failed)
8871
+ return -1;
8872
+ if (!aState.failed && bState.failed)
8873
+ return 1;
8874
+ return bState.duration - aState.duration;
8875
+ });
8876
+ }
8877
+ }
8927
8878
 
8928
- last--;
8929
- }
8879
+ class RandomSequencer extends BaseSequencer {
8880
+ async sort(files) {
8881
+ const { sequence } = this.ctx.config;
8882
+ return shuffle(files, sequence.seed);
8883
+ }
8884
+ }
8930
8885
 
8931
- if (last === words.length) {
8932
- return string;
8933
- }
8886
+ const extraInlineDeps = [
8887
+ /^(?!.*(?:node_modules)).*\.mjs$/,
8888
+ /^(?!.*(?:node_modules)).*\.cjs\.js$/,
8889
+ // Vite client
8890
+ /vite\w*\/dist\/client\/env.mjs/,
8891
+ // Nuxt
8892
+ "@nuxt/test-utils"
8893
+ ];
8894
+ function resolveApiServerConfig(options) {
8895
+ let api;
8896
+ if (options.ui && !options.api)
8897
+ api = { port: defaultPort };
8898
+ else if (options.api === true)
8899
+ api = { port: defaultPort };
8900
+ else if (typeof options.api === "number")
8901
+ api = { port: options.api };
8902
+ if (typeof options.api === "object") {
8903
+ if (api) {
8904
+ if (options.api.port)
8905
+ api.port = options.api.port;
8906
+ if (options.api.strictPort)
8907
+ api.strictPort = options.api.strictPort;
8908
+ if (options.api.host)
8909
+ api.host = options.api.host;
8910
+ } else {
8911
+ api = { ...options.api };
8912
+ }
8913
+ }
8914
+ if (api) {
8915
+ if (!api.port && !api.middlewareMode)
8916
+ api.port = defaultPort;
8917
+ } else {
8918
+ api = { middlewareMode: true };
8919
+ }
8920
+ return api;
8921
+ }
8922
+ function resolveConfig(mode, options, viteConfig) {
8923
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H;
8924
+ if (options.dom) {
8925
+ if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
8926
+ console.warn(
8927
+ c.yellow(
8928
+ `${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`
8929
+ )
8930
+ );
8931
+ }
8932
+ options.environment = "happy-dom";
8933
+ }
8934
+ const resolved = {
8935
+ ...configDefaults,
8936
+ ...options,
8937
+ root: viteConfig.root,
8938
+ mode
8939
+ };
8940
+ resolved.inspect = Boolean(resolved.inspect);
8941
+ resolved.inspectBrk = Boolean(resolved.inspectBrk);
8942
+ if (viteConfig.base !== "/")
8943
+ resolved.base = viteConfig.base;
8944
+ if (options.shard) {
8945
+ if (resolved.watch)
8946
+ throw new Error("You cannot use --shard option with enabled watch");
8947
+ const [indexString, countString] = options.shard.split("/");
8948
+ const index = Math.abs(Number.parseInt(indexString, 10));
8949
+ const count = Math.abs(Number.parseInt(countString, 10));
8950
+ if (Number.isNaN(count) || count <= 0)
8951
+ throw new Error("--shard <count> must be a positive number");
8952
+ if (Number.isNaN(index) || index <= 0 || index > count)
8953
+ throw new Error("--shard <index> must be a positive number less then <count>");
8954
+ resolved.shard = { index, count };
8955
+ }
8956
+ if (resolved.inspect || resolved.inspectBrk) {
8957
+ const isSingleThread = resolved.pool === "threads" && ((_c = (_b = resolved.poolOptions) == null ? void 0 : _b.threads) == null ? void 0 : _c.singleThread);
8958
+ const isSingleFork = resolved.pool === "forks" && ((_e = (_d = resolved.poolOptions) == null ? void 0 : _d.forks) == null ? void 0 : _e.singleFork);
8959
+ if (!isSingleThread && !isSingleFork) {
8960
+ const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
8961
+ throw new Error(`You cannot use ${inspectOption} without "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`);
8962
+ }
8963
+ }
8964
+ if (resolved.coverage.provider === "c8")
8965
+ throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
8966
+ if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
8967
+ throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
8968
+ resolved.deps ?? (resolved.deps = {});
8969
+ (_f = resolved.deps).moduleDirectories ?? (_f.moduleDirectories = []);
8970
+ resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
8971
+ if (!dir.startsWith("/"))
8972
+ dir = `/${dir}`;
8973
+ if (!dir.endsWith("/"))
8974
+ dir += "/";
8975
+ return normalize(dir);
8976
+ });
8977
+ if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
8978
+ resolved.deps.moduleDirectories.push("/node_modules/");
8979
+ (_g = resolved.deps).optimizer ?? (_g.optimizer = {});
8980
+ (_h = resolved.deps.optimizer).ssr ?? (_h.ssr = {});
8981
+ (_i = resolved.deps.optimizer.ssr).enabled ?? (_i.enabled = true);
8982
+ (_j = resolved.deps.optimizer).web ?? (_j.web = {});
8983
+ (_k = resolved.deps.optimizer.web).enabled ?? (_k.enabled = true);
8984
+ (_l = resolved.deps).web ?? (_l.web = {});
8985
+ (_m = resolved.deps.web).transformAssets ?? (_m.transformAssets = true);
8986
+ (_n = resolved.deps.web).transformCss ?? (_n.transformCss = true);
8987
+ (_o = resolved.deps.web).transformGlobPattern ?? (_o.transformGlobPattern = []);
8988
+ resolved.server ?? (resolved.server = {});
8989
+ (_p = resolved.server).deps ?? (_p.deps = {});
8990
+ const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
8991
+ deprecatedDepsOptions.forEach((option) => {
8992
+ if (resolved.deps[option] === void 0)
8993
+ return;
8994
+ if (option === "fallbackCJS") {
8995
+ console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`));
8996
+ } else {
8997
+ const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
8998
+ console.warn(
8999
+ c.yellow(
9000
+ `${c.inverse(c.yellow(" Vitest "))} "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"}"`
9001
+ )
9002
+ );
9003
+ }
9004
+ if (resolved.server.deps[option] === void 0)
9005
+ resolved.server.deps[option] = resolved.deps[option];
9006
+ });
9007
+ if (resolved.server.deps.inline !== true) {
9008
+ const ssrOptions = viteConfig.ssr;
9009
+ if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
9010
+ resolved.server.deps.inline = true;
9011
+ } else {
9012
+ (_q = resolved.server.deps).inline ?? (_q.inline = []);
9013
+ resolved.server.deps.inline.push(...extraInlineDeps);
9014
+ }
9015
+ }
9016
+ (_r = resolved.server.deps).moduleDirectories ?? (_r.moduleDirectories = []);
9017
+ resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
9018
+ if (resolved.runner) {
9019
+ resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.runner);
9020
+ }
9021
+ resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
9022
+ if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat)
9023
+ resolved.snapshotFormat.plugins = [];
9024
+ const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
9025
+ resolved.snapshotOptions = {
9026
+ snapshotFormat: resolved.snapshotFormat || {},
9027
+ updateSnapshot: isCI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
9028
+ resolveSnapshotPath: options.resolveSnapshotPath,
9029
+ // resolved inside the worker
9030
+ snapshotEnvironment: null
9031
+ };
9032
+ if (options.resolveSnapshotPath)
9033
+ delete resolved.resolveSnapshotPath;
9034
+ if (process.env.VITEST_MAX_THREADS) {
9035
+ resolved.poolOptions = {
9036
+ ...resolved.poolOptions,
9037
+ threads: {
9038
+ ...(_s = resolved.poolOptions) == null ? void 0 : _s.threads,
9039
+ maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
9040
+ },
9041
+ vmThreads: {
9042
+ ...(_t = resolved.poolOptions) == null ? void 0 : _t.vmThreads,
9043
+ maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
9044
+ }
9045
+ };
9046
+ }
9047
+ if (process.env.VITEST_MIN_THREADS) {
9048
+ resolved.poolOptions = {
9049
+ ...resolved.poolOptions,
9050
+ threads: {
9051
+ ...(_u = resolved.poolOptions) == null ? void 0 : _u.threads,
9052
+ minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
9053
+ },
9054
+ vmThreads: {
9055
+ ...(_v = resolved.poolOptions) == null ? void 0 : _v.vmThreads,
9056
+ minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
9057
+ }
9058
+ };
9059
+ }
9060
+ if (process.env.VITEST_MAX_FORKS) {
9061
+ resolved.poolOptions = {
9062
+ ...resolved.poolOptions,
9063
+ forks: {
9064
+ ...(_w = resolved.poolOptions) == null ? void 0 : _w.forks,
9065
+ maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
9066
+ }
9067
+ };
9068
+ }
9069
+ if (process.env.VITEST_MIN_FORKS) {
9070
+ resolved.poolOptions = {
9071
+ ...resolved.poolOptions,
9072
+ forks: {
9073
+ ...(_x = resolved.poolOptions) == null ? void 0 : _x.forks,
9074
+ minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
9075
+ }
9076
+ };
9077
+ }
9078
+ if (mode === "benchmark") {
9079
+ resolved.benchmark = {
9080
+ ...benchmarkConfigDefaults,
9081
+ ...resolved.benchmark
9082
+ };
9083
+ resolved.coverage.enabled = false;
9084
+ resolved.include = resolved.benchmark.include;
9085
+ resolved.exclude = resolved.benchmark.exclude;
9086
+ resolved.includeSource = resolved.benchmark.includeSource;
9087
+ const reporters = Array.from(/* @__PURE__ */ new Set([
9088
+ ...toArray(resolved.benchmark.reporters),
9089
+ // @ts-expect-error reporter is CLI flag
9090
+ ...toArray(options.reporter)
9091
+ ])).filter(Boolean);
9092
+ if (reporters.length)
9093
+ resolved.benchmark.reporters = reporters;
9094
+ else
9095
+ resolved.benchmark.reporters = ["default"];
9096
+ if (options.outputFile)
9097
+ resolved.benchmark.outputFile = options.outputFile;
9098
+ }
9099
+ resolved.setupFiles = toArray(resolved.setupFiles || []).map(
9100
+ (file) => normalize(
9101
+ resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file)
9102
+ )
9103
+ );
9104
+ resolved.coverage.exclude.push(...resolved.setupFiles.map((file) => `${resolved.coverage.allowExternal ? "**/" : ""}${relative(resolved.root, file)}`));
9105
+ resolved.forceRerunTriggers = [
9106
+ ...resolved.forceRerunTriggers,
9107
+ ...resolved.setupFiles
9108
+ ];
9109
+ if (resolved.diff) {
9110
+ resolved.diff = normalize(
9111
+ resolveModule(resolved.diff, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.diff)
9112
+ );
9113
+ resolved.forceRerunTriggers.push(resolved.diff);
9114
+ }
9115
+ resolved.api = resolveApiServerConfig(options);
9116
+ if (options.related)
9117
+ resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
9118
+ if (mode !== "benchmark") {
9119
+ const cliReporters = toArray(resolved.reporter || []).map((reporter) => {
9120
+ if (/^\.\.?\//.test(reporter))
9121
+ return resolve(process.cwd(), reporter);
9122
+ return reporter;
9123
+ });
9124
+ const reporters = cliReporters.length ? cliReporters : resolved.reporters;
9125
+ resolved.reporters = Array.from(new Set(toArray(reporters))).filter(Boolean);
9126
+ }
9127
+ if (!resolved.reporters.length)
9128
+ resolved.reporters.push("default");
9129
+ if (resolved.changed)
9130
+ resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
9131
+ resolved.css ?? (resolved.css = {});
9132
+ if (typeof resolved.css === "object") {
9133
+ (_y = resolved.css).modules ?? (_y.modules = {});
9134
+ (_z = resolved.css.modules).classNameStrategy ?? (_z.classNameStrategy = "stable");
9135
+ }
9136
+ resolved.cache ?? (resolved.cache = { dir: "" });
9137
+ if (resolved.cache)
9138
+ resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name);
9139
+ resolved.sequence ?? (resolved.sequence = {});
9140
+ if (!((_A = resolved.sequence) == null ? void 0 : _A.sequencer)) {
9141
+ resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
9142
+ }
9143
+ (_B = resolved.sequence).hooks ?? (_B.hooks = "parallel");
9144
+ if (resolved.sequence.sequencer === RandomSequencer)
9145
+ (_C = resolved.sequence).seed ?? (_C.seed = Date.now());
9146
+ resolved.typecheck = {
9147
+ ...configDefaults.typecheck,
9148
+ ...resolved.typecheck
9149
+ };
9150
+ resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
9151
+ resolved.typecheck ?? (resolved.typecheck = {});
9152
+ (_D = resolved.typecheck).enabled ?? (_D.enabled = false);
9153
+ if (resolved.typecheck.enabled)
9154
+ console.warn(c.yellow("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."));
9155
+ resolved.browser ?? (resolved.browser = {});
9156
+ (_E = resolved.browser).enabled ?? (_E.enabled = false);
9157
+ (_F = resolved.browser).headless ?? (_F.headless = isCI);
9158
+ (_G = resolved.browser).slowHijackESM ?? (_G.slowHijackESM = true);
9159
+ (_H = resolved.browser).isolate ?? (_H.isolate = true);
9160
+ resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
9161
+ port: defaultBrowserPort
9162
+ };
9163
+ resolved.testTransformMode ?? (resolved.testTransformMode = {});
9164
+ return resolved;
9165
+ }
9166
+ function isBrowserEnabled(config) {
9167
+ var _a;
9168
+ return Boolean((_a = config.browser) == null ? void 0 : _a.enabled);
9169
+ }
8934
9170
 
8935
- return words.slice(0, last).join(' ') + words.slice(last).join('');
9171
+ const ESC$1 = '\u001B[';
9172
+ const OSC = '\u001B]';
9173
+ const BEL = '\u0007';
9174
+ const SEP = ';';
9175
+ const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
9176
+
9177
+ const ansiEscapes = {};
9178
+
9179
+ ansiEscapes.cursorTo = (x, y) => {
9180
+ if (typeof x !== 'number') {
9181
+ throw new TypeError('The `x` argument is required');
9182
+ }
9183
+
9184
+ if (typeof y !== 'number') {
9185
+ return ESC$1 + (x + 1) + 'G';
9186
+ }
9187
+
9188
+ return ESC$1 + (y + 1) + ';' + (x + 1) + 'H';
8936
9189
  };
8937
9190
 
8938
- // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
8939
- //
8940
- // 'hard' will never allow a string to take up more than columns characters
8941
- //
8942
- // 'soft' allows long words to expand past the column length
8943
- const exec = (string, columns, options = {}) => {
8944
- if (options.trim !== false && string.trim() === '') {
8945
- return '';
9191
+ ansiEscapes.cursorMove = (x, y) => {
9192
+ if (typeof x !== 'number') {
9193
+ throw new TypeError('The `x` argument is required');
8946
9194
  }
8947
9195
 
8948
9196
  let returnValue = '';
8949
- let escapeCode;
8950
- let escapeUrl;
8951
9197
 
8952
- const lengths = wordLengths(string);
8953
- let rows = [''];
9198
+ if (x < 0) {
9199
+ returnValue += ESC$1 + (-x) + 'D';
9200
+ } else if (x > 0) {
9201
+ returnValue += ESC$1 + x + 'C';
9202
+ }
8954
9203
 
8955
- for (const [index, word] of string.split(' ').entries()) {
8956
- if (options.trim !== false) {
8957
- rows[rows.length - 1] = rows[rows.length - 1].trimStart();
9204
+ if (y < 0) {
9205
+ returnValue += ESC$1 + (-y) + 'A';
9206
+ } else if (y > 0) {
9207
+ returnValue += ESC$1 + y + 'B';
9208
+ }
9209
+
9210
+ return returnValue;
9211
+ };
9212
+
9213
+ ansiEscapes.cursorUp = (count = 1) => ESC$1 + count + 'A';
9214
+ ansiEscapes.cursorDown = (count = 1) => ESC$1 + count + 'B';
9215
+ ansiEscapes.cursorForward = (count = 1) => ESC$1 + count + 'C';
9216
+ ansiEscapes.cursorBackward = (count = 1) => ESC$1 + count + 'D';
9217
+
9218
+ ansiEscapes.cursorLeft = ESC$1 + 'G';
9219
+ ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC$1 + 's';
9220
+ ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC$1 + 'u';
9221
+ ansiEscapes.cursorGetPosition = ESC$1 + '6n';
9222
+ ansiEscapes.cursorNextLine = ESC$1 + 'E';
9223
+ ansiEscapes.cursorPrevLine = ESC$1 + 'F';
9224
+ ansiEscapes.cursorHide = ESC$1 + '?25l';
9225
+ ansiEscapes.cursorShow = ESC$1 + '?25h';
9226
+
9227
+ ansiEscapes.eraseLines = count => {
9228
+ let clear = '';
9229
+
9230
+ for (let i = 0; i < count; i++) {
9231
+ clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
9232
+ }
9233
+
9234
+ if (count) {
9235
+ clear += ansiEscapes.cursorLeft;
9236
+ }
9237
+
9238
+ return clear;
9239
+ };
9240
+
9241
+ ansiEscapes.eraseEndLine = ESC$1 + 'K';
9242
+ ansiEscapes.eraseStartLine = ESC$1 + '1K';
9243
+ ansiEscapes.eraseLine = ESC$1 + '2K';
9244
+ ansiEscapes.eraseDown = ESC$1 + 'J';
9245
+ ansiEscapes.eraseUp = ESC$1 + '1J';
9246
+ ansiEscapes.eraseScreen = ESC$1 + '2J';
9247
+ ansiEscapes.scrollUp = ESC$1 + 'S';
9248
+ ansiEscapes.scrollDown = ESC$1 + 'T';
9249
+
9250
+ ansiEscapes.clearScreen = '\u001Bc';
9251
+
9252
+ ansiEscapes.clearTerminal = process.platform === 'win32' ?
9253
+ `${ansiEscapes.eraseScreen}${ESC$1}0f` :
9254
+ // 1. Erases the screen (Only done in case `2` is not supported)
9255
+ // 2. Erases the whole screen including scrollback buffer
9256
+ // 3. Moves cursor to the top-left position
9257
+ // More info: https://www.real-world-systems.com/docs/ANSIcode.html
9258
+ `${ansiEscapes.eraseScreen}${ESC$1}3J${ESC$1}H`;
9259
+
9260
+ ansiEscapes.beep = BEL;
9261
+
9262
+ ansiEscapes.link = (text, url) => {
9263
+ return [
9264
+ OSC,
9265
+ '8',
9266
+ SEP,
9267
+ SEP,
9268
+ url,
9269
+ BEL,
9270
+ text,
9271
+ OSC,
9272
+ '8',
9273
+ SEP,
9274
+ SEP,
9275
+ BEL
9276
+ ].join('');
9277
+ };
9278
+
9279
+ ansiEscapes.image = (buffer, options = {}) => {
9280
+ let returnValue = `${OSC}1337;File=inline=1`;
9281
+
9282
+ if (options.width) {
9283
+ returnValue += `;width=${options.width}`;
9284
+ }
9285
+
9286
+ if (options.height) {
9287
+ returnValue += `;height=${options.height}`;
9288
+ }
9289
+
9290
+ if (options.preserveAspectRatio === false) {
9291
+ returnValue += ';preserveAspectRatio=0';
9292
+ }
9293
+
9294
+ return returnValue + ':' + buffer.toString('base64') + BEL;
9295
+ };
9296
+
9297
+ ansiEscapes.iTerm = {
9298
+ setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
9299
+
9300
+ annotation: (message, options = {}) => {
9301
+ let returnValue = `${OSC}1337;`;
9302
+
9303
+ const hasX = typeof options.x !== 'undefined';
9304
+ const hasY = typeof options.y !== 'undefined';
9305
+ if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
9306
+ throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
9307
+ }
9308
+
9309
+ message = message.replace(/\|/g, '');
9310
+
9311
+ returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
9312
+
9313
+ if (options.length > 0) {
9314
+ returnValue +=
9315
+ (hasX ?
9316
+ [message, options.length, options.x, options.y] :
9317
+ [options.length, message]).join('|');
9318
+ } else {
9319
+ returnValue += message;
8958
9320
  }
8959
9321
 
8960
- let rowLength = stringWidth(rows[rows.length - 1]);
9322
+ return returnValue + BEL;
9323
+ }
9324
+ };
8961
9325
 
8962
- if (index !== 0) {
8963
- if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
8964
- // If we start with a new word but the current row length equals the length of the columns, add a new row
8965
- rows.push('');
8966
- rowLength = 0;
8967
- }
9326
+ var onetime$2 = {exports: {}};
8968
9327
 
8969
- if (rowLength > 0 || options.trim === false) {
8970
- rows[rows.length - 1] += ' ';
8971
- rowLength++;
8972
- }
8973
- }
9328
+ var mimicFn$2 = {exports: {}};
8974
9329
 
8975
- // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
8976
- if (options.hard && lengths[index] > columns) {
8977
- const remainingColumns = (columns - rowLength);
8978
- const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
8979
- const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
8980
- if (breaksStartingNextLine < breaksStartingThisLine) {
8981
- rows.push('');
8982
- }
9330
+ const mimicFn$1 = (to, from) => {
9331
+ for (const prop of Reflect.ownKeys(from)) {
9332
+ Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
9333
+ }
8983
9334
 
8984
- wrapWord(rows, word, columns);
8985
- continue;
8986
- }
9335
+ return to;
9336
+ };
8987
9337
 
8988
- if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
8989
- if (options.wordWrap === false && rowLength < columns) {
8990
- wrapWord(rows, word, columns);
8991
- continue;
8992
- }
9338
+ mimicFn$2.exports = mimicFn$1;
9339
+ // TODO: Remove this for the next major release
9340
+ mimicFn$2.exports.default = mimicFn$1;
8993
9341
 
8994
- rows.push('');
8995
- }
9342
+ var mimicFnExports = mimicFn$2.exports;
8996
9343
 
8997
- if (rowLength + lengths[index] > columns && options.wordWrap === false) {
8998
- wrapWord(rows, word, columns);
8999
- continue;
9000
- }
9344
+ const mimicFn = mimicFnExports;
9001
9345
 
9002
- rows[rows.length - 1] += word;
9003
- }
9346
+ const calledFunctions = new WeakMap();
9004
9347
 
9005
- if (options.trim !== false) {
9006
- rows = rows.map(row => stringVisibleTrimSpacesRight(row));
9348
+ const onetime = (function_, options = {}) => {
9349
+ if (typeof function_ !== 'function') {
9350
+ throw new TypeError('Expected a function');
9007
9351
  }
9008
9352
 
9009
- const pre = [...rows.join('\n')];
9353
+ let returnValue;
9354
+ let callCount = 0;
9355
+ const functionName = function_.displayName || function_.name || '<anonymous>';
9010
9356
 
9011
- for (const [index, character] of pre.entries()) {
9012
- returnValue += character;
9357
+ const onetime = function (...arguments_) {
9358
+ calledFunctions.set(onetime, ++callCount);
9013
9359
 
9014
- if (ESCAPES.has(character)) {
9015
- const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
9016
- if (groups.code !== undefined) {
9017
- const code = Number.parseFloat(groups.code);
9018
- escapeCode = code === END_CODE ? undefined : code;
9019
- } else if (groups.uri !== undefined) {
9020
- escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
9021
- }
9360
+ if (callCount === 1) {
9361
+ returnValue = function_.apply(this, arguments_);
9362
+ function_ = null;
9363
+ } else if (options.throw === true) {
9364
+ throw new Error(`Function \`${functionName}\` can only be called once`);
9022
9365
  }
9023
9366
 
9024
- const code = ansiStyles.codes.get(Number(escapeCode));
9367
+ return returnValue;
9368
+ };
9025
9369
 
9026
- if (pre[index + 1] === '\n') {
9027
- if (escapeUrl) {
9028
- returnValue += wrapAnsiHyperlink('');
9029
- }
9370
+ mimicFn(onetime, function_);
9371
+ calledFunctions.set(onetime, callCount);
9030
9372
 
9031
- if (escapeCode && code) {
9032
- returnValue += wrapAnsiCode(code);
9033
- }
9034
- } else if (character === '\n') {
9035
- if (escapeCode && code) {
9036
- returnValue += wrapAnsiCode(escapeCode);
9037
- }
9373
+ return onetime;
9374
+ };
9038
9375
 
9039
- if (escapeUrl) {
9040
- returnValue += wrapAnsiHyperlink(escapeUrl);
9041
- }
9042
- }
9376
+ onetime$2.exports = onetime;
9377
+ // TODO: Remove this for the next major release
9378
+ onetime$2.exports.default = onetime;
9379
+
9380
+ onetime$2.exports.callCount = function_ => {
9381
+ if (!calledFunctions.has(function_)) {
9382
+ throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
9043
9383
  }
9044
9384
 
9045
- return returnValue;
9385
+ return calledFunctions.get(function_);
9046
9386
  };
9047
9387
 
9048
- // For each newline, invoke the method separately
9049
- function wrapAnsi(string, columns, options) {
9050
- return String(string)
9051
- .normalize()
9052
- .replace(/\r\n/g, '\n')
9053
- .split('\n')
9054
- .map(line => exec(line, columns, options))
9055
- .join('\n');
9056
- }
9388
+ var onetimeExports = onetime$2.exports;
9389
+ var onetime$1 = /*@__PURE__*/getDefaultExportFromCjs(onetimeExports);
9057
9390
 
9058
- const defaultTerminalHeight = 24;
9391
+ const restoreCursor = onetime$1(() => {
9392
+ signalExit(() => {
9393
+ process$1.stderr.write('\u001B[?25h');
9394
+ }, {alwaysLast: true});
9395
+ });
9059
9396
 
9060
- const getWidth = stream => {
9061
- const {columns} = stream;
9397
+ let isHidden = false;
9062
9398
 
9063
- if (!columns) {
9064
- return 80;
9399
+ const cliCursor = {};
9400
+
9401
+ cliCursor.show = (writableStream = process$1.stderr) => {
9402
+ if (!writableStream.isTTY) {
9403
+ return;
9065
9404
  }
9066
9405
 
9067
- return columns;
9406
+ isHidden = false;
9407
+ writableStream.write('\u001B[?25h');
9068
9408
  };
9069
9409
 
9070
- const fitToTerminalHeight = (stream, text) => {
9071
- const terminalHeight = stream.rows || defaultTerminalHeight;
9072
- const lines = text.split('\n');
9410
+ cliCursor.hide = (writableStream = process$1.stderr) => {
9411
+ if (!writableStream.isTTY) {
9412
+ return;
9413
+ }
9073
9414
 
9074
- const toRemove = lines.length - terminalHeight;
9075
- if (toRemove <= 0) {
9076
- return text;
9415
+ restoreCursor();
9416
+ isHidden = true;
9417
+ writableStream.write('\u001B[?25l');
9418
+ };
9419
+
9420
+ cliCursor.toggle = (force, writableStream) => {
9421
+ if (force !== undefined) {
9422
+ isHidden = force;
9077
9423
  }
9078
9424
 
9079
- return sliceAnsi(
9080
- text,
9081
- stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1,
9082
- );
9425
+ if (isHidden) {
9426
+ cliCursor.show(writableStream);
9427
+ } else {
9428
+ cliCursor.hide(writableStream);
9429
+ }
9083
9430
  };
9084
9431
 
9085
- function createLogUpdate(stream, {showCursor = false} = {}) {
9086
- let previousLineCount = 0;
9087
- let previousWidth = getWidth(stream);
9088
- let previousOutput = '';
9432
+ const ESCAPES = new Set([
9433
+ '\u001B',
9434
+ '\u009B',
9435
+ ]);
9089
9436
 
9090
- const render = (...arguments_) => {
9091
- if (!showCursor) {
9092
- cliCursor.hide();
9093
- }
9437
+ const END_CODE = 39;
9438
+ const ANSI_ESCAPE_BELL = '\u0007';
9439
+ const ANSI_CSI = '[';
9440
+ const ANSI_OSC = ']';
9441
+ const ANSI_SGR_TERMINATOR = 'm';
9442
+ const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
9094
9443
 
9095
- let output = arguments_.join(' ') + '\n';
9096
- output = fitToTerminalHeight(stream, output);
9097
- const width = getWidth(stream);
9098
- if (output === previousOutput && previousWidth === width) {
9099
- return;
9100
- }
9444
+ const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
9445
+ const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
9101
9446
 
9102
- previousOutput = output;
9103
- previousWidth = width;
9104
- output = wrapAnsi(output, width, {
9105
- trim: false,
9106
- hard: true,
9107
- wordWrap: false,
9108
- });
9109
- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
9110
- previousLineCount = output.split('\n').length;
9111
- };
9447
+ // Calculate the length of words split on ' ', ignoring
9448
+ // the extra characters added by ansi escape codes
9449
+ const wordLengths = string => string.split(' ').map(character => stringWidth(character));
9112
9450
 
9113
- render.clear = () => {
9114
- stream.write(ansiEscapes.eraseLines(previousLineCount));
9115
- previousOutput = '';
9116
- previousWidth = getWidth(stream);
9117
- previousLineCount = 0;
9118
- };
9451
+ // Wrap a long word across multiple rows
9452
+ // Ansi escape codes do not count towards length
9453
+ const wrapWord = (rows, word, columns) => {
9454
+ const characters = [...word];
9119
9455
 
9120
- render.done = () => {
9121
- previousOutput = '';
9122
- previousWidth = getWidth(stream);
9123
- previousLineCount = 0;
9456
+ let isInsideEscape = false;
9457
+ let isInsideLinkEscape = false;
9458
+ let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
9124
9459
 
9125
- if (!showCursor) {
9126
- cliCursor.show();
9460
+ for (const [index, character] of characters.entries()) {
9461
+ const characterLength = stringWidth(character);
9462
+
9463
+ if (visible + characterLength <= columns) {
9464
+ rows[rows.length - 1] += character;
9465
+ } else {
9466
+ rows.push(character);
9467
+ visible = 0;
9468
+ }
9469
+
9470
+ if (ESCAPES.has(character)) {
9471
+ isInsideEscape = true;
9472
+ isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
9473
+ }
9474
+
9475
+ if (isInsideEscape) {
9476
+ if (isInsideLinkEscape) {
9477
+ if (character === ANSI_ESCAPE_BELL) {
9478
+ isInsideEscape = false;
9479
+ isInsideLinkEscape = false;
9480
+ }
9481
+ } else if (character === ANSI_SGR_TERMINATOR) {
9482
+ isInsideEscape = false;
9483
+ }
9484
+
9485
+ continue;
9127
9486
  }
9128
- };
9129
9487
 
9130
- return render;
9131
- }
9488
+ visible += characterLength;
9132
9489
 
9133
- createLogUpdate(process$1.stdout);
9490
+ if (visible === columns && index < characters.length - 1) {
9491
+ rows.push('');
9492
+ visible = 0;
9493
+ }
9494
+ }
9134
9495
 
9135
- createLogUpdate(process$1.stderr);
9496
+ // It's possible that the last row we copy over is only
9497
+ // ansi escape characters, handle this edge-case
9498
+ if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
9499
+ rows[rows.length - 2] += rows.pop();
9500
+ }
9501
+ };
9136
9502
 
9137
- var version = "1.0.0-beta.2";
9503
+ // Trims spaces from a string ignoring invisible sequences
9504
+ const stringVisibleTrimSpacesRight = string => {
9505
+ const words = string.split(' ');
9506
+ let last = words.length;
9138
9507
 
9139
- const A=r=>r!==null&&typeof r=="object",a=(r,t)=>Object.assign(new Error(`[${r}]: ${t}`),{code:r}),_$1="ERR_INVALID_PACKAGE_CONFIG",E="ERR_INVALID_PACKAGE_TARGET",I="ERR_PACKAGE_PATH_NOT_EXPORTED",R$1=/^\d+$/,O=/^(\.{1,2}|node_modules)$/i,w=/\/|\\/;var h=(r=>(r.Export="exports",r.Import="imports",r))(h||{});const f=(r,t,e,o,c)=>{if(t==null)return [];if(typeof t=="string"){const[n,...i]=t.split(w);if(n===".."||i.some(l=>O.test(l)))throw a(E,`Invalid "${r}" target "${t}" defined in the package config`);return [c?t.replace(/\*/g,c):t]}if(Array.isArray(t))return t.flatMap(n=>f(r,n,e,o,c));if(A(t)){for(const n of Object.keys(t)){if(R$1.test(n))throw a(_$1,"Cannot contain numeric property keys");if(n==="default"||o.includes(n))return f(r,t[n],e,o,c)}return []}throw a(E,`Invalid "${r}" target "${t}"`)},s="*",m=(r,t)=>{const e=r.indexOf(s),o=t.indexOf(s);return e===o?t.length>r.length:o>e};function d$1(r,t){if(!t.includes(s)&&r.hasOwnProperty(t))return [t];let e,o;for(const c of Object.keys(r))if(c.includes(s)){const[n,i,l]=c.split(s);if(l===void 0&&t.startsWith(n)&&t.endsWith(i)){const g=t.slice(n.length,-i.length||void 0);g&&(!e||m(e,c))&&(e=c,o=g);}}return [e,o]}const p=r=>Object.keys(r).reduce((t,e)=>{const o=e===""||e[0]!==".";if(t===void 0||t===o)return o;throw a(_$1,'"exports" cannot contain some keys starting with "." and some not')},void 0),u=/^\w+:/,v=(r,t,e)=>{if(!r)throw new Error('"exports" is required');t=t===""?".":`./${t}`,(typeof r=="string"||Array.isArray(r)||A(r)&&p(r))&&(r={".":r});const[o,c]=d$1(r,t),n=f(h.Export,r[o],t,e,c);if(n.length===0)throw a(I,t==="."?'No "exports" main defined':`Package subpath '${t}' is not defined by "exports"`);for(const i of n)if(!i.startsWith("./")&&!u.test(i))throw a(E,`Invalid "exports" target "${i}" defined in the package config`);return n};
9508
+ while (last > 0) {
9509
+ if (stringWidth(words[last - 1]) > 0) {
9510
+ break;
9511
+ }
9140
9512
 
9141
- function U(e){return e.startsWith("\\\\?\\")?e:e.replace(/\\/g,"/")}const Y=(e,s)=>{for(;;){const i=f$1.posix.join(e,s);if($.existsSync(i))return i;const n=f$1.dirname(e);if(n===e)return;e=n;}},S=/^\.{1,2}(\/.*)?$/,V=e=>{const s=U(e);return S.test(s)?s:`./${s}`};function re(e,s=!1){const i=e.length;let n=0,t="",l=0,c=16,m=0,p=0,L=0,g=0,T=0;function k(o,r){let u=0,E=0;for(;u<o||!r;){let v=e.charCodeAt(n);if(v>=48&&v<=57)E=E*16+v-48;else if(v>=65&&v<=70)E=E*16+v-65+10;else if(v>=97&&v<=102)E=E*16+v-97+10;else break;n++,u++;}return u<o&&(E=-1),E}function j(o){n=o,t="",l=0,c=16,T=0;}function w(){let o=n;if(e.charCodeAt(n)===48)n++;else for(n++;n<e.length&&_(e.charCodeAt(n));)n++;if(n<e.length&&e.charCodeAt(n)===46)if(n++,n<e.length&&_(e.charCodeAt(n)))for(n++;n<e.length&&_(e.charCodeAt(n));)n++;else return T=3,e.substring(o,n);let r=n;if(n<e.length&&(e.charCodeAt(n)===69||e.charCodeAt(n)===101))if(n++,(n<e.length&&e.charCodeAt(n)===43||e.charCodeAt(n)===45)&&n++,n<e.length&&_(e.charCodeAt(n))){for(n++;n<e.length&&_(e.charCodeAt(n));)n++;r=n;}else T=3;return e.substring(o,r)}function b(){let o="",r=n;for(;;){if(n>=i){o+=e.substring(r,n),T=2;break}const u=e.charCodeAt(n);if(u===34){o+=e.substring(r,n),n++;break}if(u===92){if(o+=e.substring(r,n),n++,n>=i){T=2;break}switch(e.charCodeAt(n++)){case 34:o+='"';break;case 92:o+="\\";break;case 47:o+="/";break;case 98:o+="\b";break;case 102:o+="\f";break;case 110:o+=`
9142
- `;break;case 114:o+="\r";break;case 116:o+=" ";break;case 117:const v=k(4,!0);v>=0?o+=String.fromCharCode(v):T=4;break;default:T=5;}r=n;continue}if(u>=0&&u<=31)if(F(u)){o+=e.substring(r,n),T=2;break}else T=6;n++;}return o}function A(){if(t="",T=0,l=n,p=m,g=L,n>=i)return l=i,c=17;let o=e.charCodeAt(n);if(W(o)){do n++,t+=String.fromCharCode(o),o=e.charCodeAt(n);while(W(o));return c=15}if(F(o))return n++,t+=String.fromCharCode(o),o===13&&e.charCodeAt(n)===10&&(n++,t+=`
9143
- `),m++,L=n,c=14;switch(o){case 123:return n++,c=1;case 125:return n++,c=2;case 91:return n++,c=3;case 93:return n++,c=4;case 58:return n++,c=6;case 44:return n++,c=5;case 34:return n++,t=b(),c=10;case 47:const r=n-1;if(e.charCodeAt(n+1)===47){for(n+=2;n<i&&!F(e.charCodeAt(n));)n++;return t=e.substring(r,n),c=12}if(e.charCodeAt(n+1)===42){n+=2;const u=i-1;let E=!1;for(;n<u;){const v=e.charCodeAt(n);if(v===42&&e.charCodeAt(n+1)===47){n+=2,E=!0;break}n++,F(v)&&(v===13&&e.charCodeAt(n)===10&&n++,m++,L=n);}return E||(n++,T=1),t=e.substring(r,n),c=13}return t+=String.fromCharCode(o),n++,c=16;case 45:if(t+=String.fromCharCode(o),n++,n===i||!_(e.charCodeAt(n)))return c=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return t+=w(),c=11;default:for(;n<i&&N(o);)n++,o=e.charCodeAt(n);if(l!==n){switch(t=e.substring(l,n),t){case"true":return c=8;case"false":return c=9;case"null":return c=7}return c=16}return t+=String.fromCharCode(o),n++,c=16}}function N(o){if(W(o)||F(o))return !1;switch(o){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return !1}return !0}function h(){let o;do o=A();while(o>=12&&o<=15);return o}return {setPosition:j,getPosition:()=>n,scan:s?h:A,getToken:()=>c,getTokenValue:()=>t,getTokenOffset:()=>l,getTokenLength:()=>n-l,getTokenStartLine:()=>p,getTokenStartCharacter:()=>l-g,getTokenError:()=>T}}function W(e){return e===32||e===9}function F(e){return e===10||e===13}function _(e){return e>=48&&e<=57}var Z;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab";})(Z||(Z={}));var x;(function(e){e.DEFAULT={allowTrailingComma:!1};})(x||(x={}));function pe(e,s=[],i=x.DEFAULT){let n=null,t=[];const l=[];function c(p){Array.isArray(t)?t.push(p):n!==null&&(t[n]=p);}return ge(e,{onObjectBegin:()=>{const p={};c(p),l.push(t),t=p,n=null;},onObjectProperty:p=>{n=p;},onObjectEnd:()=>{t=l.pop();},onArrayBegin:()=>{const p=[];c(p),l.push(t),t=p,n=null;},onArrayEnd:()=>{t=l.pop();},onLiteralValue:c,onError:(p,L,g)=>{s.push({error:p,offset:L,length:g});}},i),t[0]}function ge(e,s,i=x.DEFAULT){const n=re(e,!1),t=[];function l(a){return a?()=>a(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function c(a){return a?()=>a(n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),()=>t.slice()):()=>!0}function m(a){return a?O=>a(O,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter()):()=>!0}function p(a){return a?O=>a(O,n.getTokenOffset(),n.getTokenLength(),n.getTokenStartLine(),n.getTokenStartCharacter(),()=>t.slice()):()=>!0}const L=c(s.onObjectBegin),g=p(s.onObjectProperty),T=l(s.onObjectEnd),k=c(s.onArrayBegin),j=l(s.onArrayEnd),w=p(s.onLiteralValue),b=m(s.onSeparator),A=l(s.onComment),N=m(s.onError),h=i&&i.disallowComments,o=i&&i.allowTrailingComma;function r(){for(;;){const a=n.scan();switch(n.getTokenError()){case 4:u(14);break;case 5:u(15);break;case 3:u(13);break;case 1:h||u(11);break;case 2:u(12);break;case 6:u(16);break}switch(a){case 12:case 13:h?u(10):A();break;case 16:u(1);break;case 15:case 14:break;default:return a}}}function u(a,O=[],X=[]){if(N(a),O.length+X.length>0){let y=n.getToken();for(;y!==17;){if(O.indexOf(y)!==-1){r();break}else if(X.indexOf(y)!==-1)break;y=r();}}}function E(a){const O=n.getTokenValue();return a?w(O):(g(O),t.push(O)),r(),!0}function v(){switch(n.getToken()){case 11:const a=n.getTokenValue();let O=Number(a);isNaN(O)&&(u(2),O=0),w(O);break;case 7:w(null);break;case 8:w(!0);break;case 9:w(!1);break;default:return !1}return r(),!0}function oe(){return n.getToken()!==10?(u(3,[],[2,5]),!1):(E(!1),n.getToken()===6?(b(":"),r(),P()||u(4,[],[2,5])):u(5,[],[2,5]),t.pop(),!0)}function le(){L(),r();let a=!1;for(;n.getToken()!==2&&n.getToken()!==17;){if(n.getToken()===5){if(a||u(4,[],[]),b(","),r(),n.getToken()===2&&o)break}else a&&u(6,[],[]);oe()||u(4,[],[2,5]),a=!0;}return T(),n.getToken()!==2?u(7,[2],[]):r(),!0}function ce(){k(),r();let a=!0,O=!1;for(;n.getToken()!==4&&n.getToken()!==17;){if(n.getToken()===5){if(O||u(4,[],[]),b(","),r(),n.getToken()===4&&o)break}else O&&u(6,[],[]);a?(t.push(0),a=!1):t[t.length-1]++,P()||u(4,[],[4,5]),O=!0;}return j(),a||t.pop(),n.getToken()!==4?u(8,[4],[]):r(),!0}function P(){switch(n.getToken()){case 3:return ce();case 1:return le();case 10:return E(!0);default:return v()}}return r(),n.getToken()===17?i.allowEmptyContent?!0:(u(4,[],[]),!1):P()?(n.getToken()!==17&&u(9,[],[]),!0):(u(4,[],[]),!1)}var d;(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter";})(d||(d={}));var q;(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF";})(q||(q={}));const ae=pe;var K;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter";})(K||(K={}));const C=e=>ae($.readFileSync(e,"utf8")),{existsSync:B}=$,me=()=>{const{findPnpApi:e}=ue;return e&&e(process.cwd())},J=(e,s,i)=>{let n="tsconfig.json";const t=C(e);if(t)if(!i&&t.exports)try{const[l]=v(t.exports,s,["require","types"]);n=l;}catch{return}else !s&&t.tsconfig&&(n=t.tsconfig);return f$1.join(e,"..",n)},M="package.json",R="tsconfig.json",ke=(e,s)=>{let i=e;if(e===".."&&(i=f$1.join(i,R)),e[0]==="."&&(i=f$1.resolve(s,i)),f$1.isAbsolute(i)){if(B(i)){if($.statSync(i).isFile())return i}else if(!i.endsWith(".json")){const k=`${i}.json`;if(B(k))return k}return}const[n,...t]=e.split("/"),l=n[0]==="@"?`${n}/${t.shift()}`:n,c=t.join("/"),m=me();if(m){const{resolveRequest:k}=m;try{if(l===e){const j=k(f$1.join(l,M),s);if(j){const w=J(j,c);if(w&&B(w))return w}}else {let j;try{j=k(e,s,{extensions:[".json"]});}catch{j=k(f$1.join(e,R),s);}if(j)return j}}catch{}}const p=Y(s,f$1.join("node_modules",l));if(!p||!$.statSync(p).isDirectory())return;const L=f$1.join(p,M);if(B(L)){const k=J(L,c);if(!k)return;if(B(k))return k}const g=f$1.join(p,c),T=g.endsWith(".json");if(!T){const k=`${g}.json`;if(B(k))return k}if(B(g)){if($.statSync(g).isDirectory()){const k=f$1.join(g,M);if(B(k)){const w=J(k,"",!0);if(w&&B(w))return w}const j=f$1.join(g,R);if(B(j))return j}else if(T)return g}},be=(e,s)=>{var i;const n=ke(e,s);if(!n)throw new Error(`File '${e}' not found.`);const t=G(n);if(delete t.references,(i=t.compilerOptions)!=null&&i.baseUrl){const{compilerOptions:l}=t;l.baseUrl=f$1.relative(s,f$1.join(f$1.dirname(n),l.baseUrl))||"./";}return t.files&&(t.files=t.files.map(l=>f$1.relative(s,f$1.join(f$1.dirname(n),l)))),t.include&&(t.include=t.include.map(l=>f$1.relative(s,f$1.join(f$1.dirname(n),l)))),t},G=e=>{let s;try{s=$.realpathSync(e);}catch{throw new Error(`Cannot resolve tsconfig at path: ${e}`)}const i=f$1.dirname(s);let n=C(s)||{};if(typeof n!="object")throw new SyntaxError(`Failed to parse tsconfig at: ${e}`);if(n.extends){const t=Array.isArray(n.extends)?n.extends:[n.extends];delete n.extends;for(const l of t.reverse()){const c=be(l,i),m={...c,...n,compilerOptions:{...c.compilerOptions,...n.compilerOptions}};c.watchOptions&&(m.watchOptions={...c.watchOptions,...n.watchOptions}),n=m;}}if(n.compilerOptions){const{compilerOptions:t}=n;if(t.baseUrl){const l=f$1.resolve(i,t.baseUrl),c=V(f$1.relative(i,l));t.baseUrl=c;}t.outDir&&(Array.isArray(n.exclude)||(n.exclude=[]),n.exclude.push(t.outDir),t.outDir=V(t.outDir));}else n.compilerOptions={};if(n.files&&(n.files=n.files.map(V)),n.include&&(n.include=n.include.map(U)),n.watchOptions){const{watchOptions:t}=n;t.excludeDirectories&&(t.excludeDirectories=t.excludeDirectories.map(l=>U(f$1.resolve(i,l))));}return n},Te=(e=process.cwd(),s="tsconfig.json")=>{const i=Y(U(e),s);if(!i)return null;const n=G(i);return {path:i,config:n}};f$1.posix;process.platform==="win32";
9513
+ last--;
9514
+ }
9144
9515
 
9145
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
9146
- const newLineRegExp = /\r?\n/;
9147
- const errCodeRegExp = /error TS(?<errCode>\d+)/;
9148
- async function makeTscErrorInfo(errInfo) {
9149
- var _a;
9150
- const [errFilePathPos = "", ...errMsgRawArr] = errInfo.split(":");
9151
- if (!errFilePathPos || errMsgRawArr.length === 0 || errMsgRawArr.join("").length === 0)
9152
- return ["unknown filepath", null];
9153
- const errMsgRaw = errMsgRawArr.join("").trim();
9154
- const [errFilePath, errPos] = errFilePathPos.slice(0, -1).split("(");
9155
- if (!errFilePath || !errPos)
9156
- return ["unknown filepath", null];
9157
- const [errLine, errCol] = errPos.split(",");
9158
- if (!errLine || !errCol)
9159
- return [errFilePath, null];
9160
- const execArr = errCodeRegExp.exec(errMsgRaw);
9161
- if (!execArr)
9162
- return [errFilePath, null];
9163
- const errCodeStr = ((_a = execArr.groups) == null ? void 0 : _a.errCode) ?? "";
9164
- if (!errCodeStr)
9165
- return [errFilePath, null];
9166
- const line = Number(errLine);
9167
- const col = Number(errCol);
9168
- const errCode = Number(errCodeStr);
9169
- return [
9170
- errFilePath,
9171
- {
9172
- filePath: errFilePath,
9173
- errCode,
9174
- line,
9175
- column: col,
9176
- errMsg: errMsgRaw.slice(`error TS${errCode} `.length)
9177
- }
9178
- ];
9179
- }
9180
- async function getTsconfig(root, config) {
9181
- const configName = config.tsconfig ? basename(config.tsconfig) : void 0;
9182
- const configSearchPath = config.tsconfig ? dirname(resolve(root, config.tsconfig)) : root;
9183
- const tsconfig = Te(configSearchPath, configName);
9184
- if (!tsconfig)
9185
- throw new Error("no tsconfig.json found");
9186
- const tempConfigPath = join(dirname(tsconfig.path), "tsconfig.vitest-temp.json");
9187
- try {
9188
- const tmpTsConfig = { ...tsconfig.config };
9189
- tmpTsConfig.compilerOptions = tmpTsConfig.compilerOptions || {};
9190
- tmpTsConfig.compilerOptions.emitDeclarationOnly = false;
9191
- tmpTsConfig.compilerOptions.incremental = true;
9192
- tmpTsConfig.compilerOptions.tsBuildInfoFile = join(
9193
- __dirname,
9194
- "tsconfig.tmp.tsbuildinfo"
9195
- );
9196
- const tsconfigFinalContent = JSON.stringify(tmpTsConfig, null, 2);
9197
- await writeFile(tempConfigPath, tsconfigFinalContent);
9198
- return { path: tempConfigPath, config: tmpTsConfig };
9199
- } catch (err) {
9200
- throw new Error("failed to write tsconfig.temp.json", { cause: err });
9201
- }
9202
- }
9203
- async function getRawErrsMapFromTsCompile(tscErrorStdout) {
9204
- const rawErrsMap = /* @__PURE__ */ new Map();
9205
- const infos = await Promise.all(
9206
- tscErrorStdout.split(newLineRegExp).reduce((prev, next) => {
9207
- if (!next)
9208
- return prev;
9209
- else if (!next.startsWith(" "))
9210
- prev.push(next);
9211
- else
9212
- prev[prev.length - 1] += `
9213
- ${next}`;
9214
- return prev;
9215
- }, []).map((errInfoLine) => makeTscErrorInfo(errInfoLine))
9216
- );
9217
- infos.forEach(([errFilePath, errInfo]) => {
9218
- var _a;
9219
- if (!errInfo)
9220
- return;
9221
- if (!rawErrsMap.has(errFilePath))
9222
- rawErrsMap.set(errFilePath, [errInfo]);
9223
- else
9224
- (_a = rawErrsMap.get(errFilePath)) == null ? void 0 : _a.push(errInfo);
9225
- });
9226
- return rawErrsMap;
9227
- }
9516
+ if (last === words.length) {
9517
+ return string;
9518
+ }
9228
9519
 
9229
- function createIndexMap(source) {
9230
- const map = /* @__PURE__ */ new Map();
9231
- let index = 0;
9232
- let line = 1;
9233
- let column = 1;
9234
- for (const char of source) {
9235
- map.set(`${line}:${column}`, index++);
9236
- if (char === "\n" || char === "\r\n") {
9237
- line++;
9238
- column = 0;
9239
- } else {
9240
- column++;
9241
- }
9242
- }
9243
- return map;
9244
- }
9520
+ return words.slice(0, last).join(' ') + words.slice(last).join('');
9521
+ };
9245
9522
 
9246
- async function collectTests(ctx, filepath) {
9247
- const request = await ctx.vitenode.transformRequest(filepath, filepath);
9248
- if (!request)
9249
- return null;
9250
- const ast = parse$4(request.code, {
9251
- ecmaVersion: "latest",
9252
- allowAwaitOutsideFunction: true
9253
- });
9254
- const testFilepath = relative(ctx.config.root, filepath);
9255
- const file = {
9256
- filepath,
9257
- type: "suite",
9258
- id: generateHash(`${testFilepath}${ctx.config.name || ""}`),
9259
- name: testFilepath,
9260
- mode: "run",
9261
- tasks: [],
9262
- start: ast.start,
9263
- end: ast.end,
9264
- meta: { typecheck: true }
9265
- };
9266
- const definitions = [];
9267
- const getName = (callee) => {
9268
- var _a, _b, _c;
9269
- if (!callee)
9270
- return null;
9271
- if (callee.type === "Identifier")
9272
- return callee.name;
9273
- if (callee.type === "MemberExpression") {
9274
- if ((_b = (_a = callee.object) == null ? void 0 : _a.name) == null ? void 0 : _b.startsWith("__vite_ssr_"))
9275
- return getName(callee.property);
9276
- return getName((_c = callee.object) == null ? void 0 : _c.property);
9277
- }
9278
- return null;
9279
- };
9280
- ancestor(ast, {
9281
- CallExpression(node) {
9282
- var _a;
9283
- const { callee } = node;
9284
- const name = getName(callee);
9285
- if (!name)
9286
- return;
9287
- if (!["it", "test", "describe", "suite"].includes(name))
9288
- return;
9289
- const { arguments: [{ value: message }] } = node;
9290
- const property = (_a = callee == null ? void 0 : callee.property) == null ? void 0 : _a.name;
9291
- let mode = !property || property === name ? "run" : property;
9292
- if (!["run", "skip", "todo", "only", "skipIf", "runIf"].includes(mode))
9293
- throw new Error(`${name}.${mode} syntax is not supported when testing types`);
9294
- if (mode === "skipIf" || mode === "runIf")
9295
- mode = "skip";
9296
- definitions.push({
9297
- start: node.start,
9298
- end: node.end,
9299
- name: message,
9300
- type: name === "it" || name === "test" ? "test" : "suite",
9301
- mode
9302
- });
9303
- }
9304
- });
9305
- let lastSuite = file;
9306
- const updateLatestSuite = (index) => {
9307
- const suite = lastSuite;
9308
- while (lastSuite !== file && lastSuite.end < index)
9309
- lastSuite = suite.suite;
9310
- return lastSuite;
9311
- };
9312
- definitions.sort((a, b) => a.start - b.start).forEach((definition) => {
9313
- const latestSuite = updateLatestSuite(definition.start);
9314
- let mode = definition.mode;
9315
- if (latestSuite.mode !== "run")
9316
- mode = latestSuite.mode;
9317
- if (definition.type === "suite") {
9318
- const task2 = {
9319
- type: definition.type,
9320
- id: "",
9321
- suite: latestSuite,
9322
- file,
9323
- tasks: [],
9324
- mode,
9325
- name: definition.name,
9326
- end: definition.end,
9327
- start: definition.start,
9328
- meta: {
9329
- typecheck: true
9330
- }
9331
- };
9332
- definition.task = task2;
9333
- latestSuite.tasks.push(task2);
9334
- lastSuite = task2;
9335
- return;
9336
- }
9337
- const task = {
9338
- type: definition.type,
9339
- id: "",
9340
- suite: latestSuite,
9341
- file,
9342
- mode,
9343
- context: {},
9344
- // not used in typecheck
9345
- name: definition.name,
9346
- end: definition.end,
9347
- start: definition.start,
9348
- meta: {
9349
- typecheck: true
9350
- }
9351
- };
9352
- definition.task = task;
9353
- latestSuite.tasks.push(task);
9354
- });
9355
- calculateSuiteHash(file);
9356
- const hasOnly = someTasksAreOnly(file);
9357
- interpretTaskModes(file, ctx.config.testNamePattern, hasOnly, false, ctx.config.allowOnly);
9358
- return {
9359
- file,
9360
- parsed: request.code,
9361
- filepath,
9362
- map: request.map,
9363
- definitions
9364
- };
9365
- }
9523
+ // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
9524
+ //
9525
+ // 'hard' will never allow a string to take up more than columns characters
9526
+ //
9527
+ // 'soft' allows long words to expand past the column length
9528
+ const exec = (string, columns, options = {}) => {
9529
+ if (options.trim !== false && string.trim() === '') {
9530
+ return '';
9531
+ }
9366
9532
 
9367
- class TypeCheckError extends Error {
9368
- constructor(message, stacks) {
9369
- super(message);
9370
- this.message = message;
9371
- this.stacks = stacks;
9372
- }
9373
- name = "TypeCheckError";
9374
- }
9375
- class Typechecker {
9376
- constructor(ctx, files) {
9377
- this.ctx = ctx;
9378
- this.files = files;
9379
- }
9380
- _onParseStart;
9381
- _onParseEnd;
9382
- _onWatcherRerun;
9383
- _result = {
9384
- files: [],
9385
- sourceErrors: []
9386
- };
9387
- _output = "";
9388
- _tests = {};
9389
- tempConfigPath;
9390
- allowJs;
9391
- process;
9392
- onParseStart(fn) {
9393
- this._onParseStart = fn;
9394
- }
9395
- onParseEnd(fn) {
9396
- this._onParseEnd = fn;
9397
- }
9398
- onWatcherRerun(fn) {
9399
- this._onWatcherRerun = fn;
9400
- }
9401
- async collectFileTests(filepath) {
9402
- return collectTests(this.ctx, filepath);
9403
- }
9404
- getFiles() {
9405
- return this.files.filter((filename) => {
9406
- const extension = extname(filename);
9407
- return extension !== ".js" || this.allowJs;
9408
- });
9409
- }
9410
- async collectTests() {
9411
- const tests = (await Promise.all(
9412
- this.getFiles().map((filepath) => this.collectFileTests(filepath))
9413
- )).reduce((acc, data) => {
9414
- if (!data)
9415
- return acc;
9416
- acc[data.filepath] = data;
9417
- return acc;
9418
- }, {});
9419
- this._tests = tests;
9420
- return tests;
9421
- }
9422
- markPassed(file) {
9423
- var _a;
9424
- if (!((_a = file.result) == null ? void 0 : _a.state)) {
9425
- file.result = {
9426
- state: "pass"
9427
- };
9428
- }
9429
- const markTasks = (tasks) => {
9430
- var _a2;
9431
- for (const task of tasks) {
9432
- if ("tasks" in task)
9433
- markTasks(task.tasks);
9434
- if (!((_a2 = task.result) == null ? void 0 : _a2.state) && task.mode === "run") {
9435
- task.result = {
9436
- state: "pass"
9437
- };
9438
- }
9439
- }
9440
- };
9441
- markTasks(file.tasks);
9442
- }
9443
- async prepareResults(output) {
9444
- const typeErrors = await this.parseTscLikeOutput(output);
9445
- const testFiles = new Set(this.getFiles());
9446
- if (!this._tests)
9447
- this._tests = await this.collectTests();
9448
- const sourceErrors = [];
9449
- const files = [];
9450
- testFiles.forEach((path) => {
9451
- const { file, definitions, map, parsed } = this._tests[path];
9452
- const errors = typeErrors.get(path);
9453
- files.push(file);
9454
- if (!errors) {
9455
- this.markPassed(file);
9456
- return;
9457
- }
9458
- const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)];
9459
- const traceMap = map && new TraceMap(map);
9460
- const indexMap = createIndexMap(parsed);
9461
- const markState = (task, state) => {
9462
- task.result = {
9463
- state: task.mode === "run" || task.mode === "only" ? state : task.mode
9464
- };
9465
- if (task.suite)
9466
- markState(task.suite, state);
9467
- };
9468
- errors.forEach(({ error, originalError }) => {
9469
- var _a;
9470
- const processedPos = traceMap ? generatedPositionFor(traceMap, {
9471
- line: originalError.line,
9472
- column: originalError.column,
9473
- source: basename(path)
9474
- }) : originalError;
9475
- const line = processedPos.line ?? originalError.line;
9476
- const column = processedPos.column ?? originalError.column;
9477
- const index = indexMap.get(`${line}:${column}`);
9478
- const definition = index != null && sortedDefinitions.find((def) => def.start <= index && def.end >= index);
9479
- const suite = definition ? definition.task : file;
9480
- const state = suite.mode === "run" || suite.mode === "only" ? "fail" : suite.mode;
9481
- const errors2 = ((_a = suite.result) == null ? void 0 : _a.errors) || [];
9482
- suite.result = {
9483
- state,
9484
- errors: errors2
9485
- };
9486
- errors2.push(error);
9487
- if (state === "fail" && suite.suite)
9488
- markState(suite.suite, "fail");
9489
- });
9490
- this.markPassed(file);
9491
- });
9492
- typeErrors.forEach((errors, path) => {
9493
- if (!testFiles.has(path))
9494
- sourceErrors.push(...errors.map(({ error }) => error));
9495
- });
9496
- return {
9497
- files,
9498
- sourceErrors
9499
- };
9500
- }
9501
- async parseTscLikeOutput(output) {
9502
- const errorsMap = await getRawErrsMapFromTsCompile(output);
9503
- const typesErrors = /* @__PURE__ */ new Map();
9504
- errorsMap.forEach((errors, path) => {
9505
- const filepath = resolve(this.ctx.config.root, path);
9506
- const suiteErrors = errors.map((info) => {
9507
- const limit = Error.stackTraceLimit;
9508
- Error.stackTraceLimit = 0;
9509
- const error = new TypeCheckError(info.errMsg, [
9510
- {
9511
- file: filepath,
9512
- line: info.line,
9513
- column: info.column,
9514
- method: ""
9515
- }
9516
- ]);
9517
- Error.stackTraceLimit = limit;
9518
- return {
9519
- originalError: info,
9520
- error
9521
- };
9522
- });
9523
- typesErrors.set(filepath, suiteErrors);
9524
- });
9525
- return typesErrors;
9526
- }
9527
- async clear() {
9528
- if (this.tempConfigPath)
9529
- await rm(this.tempConfigPath, { force: true });
9530
- }
9531
- async stop() {
9532
- var _a;
9533
- await this.clear();
9534
- (_a = this.process) == null ? void 0 : _a.kill();
9535
- }
9536
- async ensurePackageInstalled(root, checker) {
9537
- if (checker !== "tsc" && checker !== "vue-tsc")
9538
- return;
9539
- const packageName = checker === "tsc" ? "typescript" : "vue-tsc";
9540
- await ensurePackageInstalled(packageName, root);
9541
- }
9542
- async prepare() {
9543
- const { root, typecheck } = this.ctx.config;
9544
- await this.ensurePackageInstalled(root, typecheck.checker);
9545
- const { config, path } = await getTsconfig(root, typecheck);
9546
- this.tempConfigPath = path;
9547
- this.allowJs = typecheck.allowJs || config.allowJs || false;
9548
- }
9549
- getExitCode() {
9550
- var _a;
9551
- return ((_a = this.process) == null ? void 0 : _a.exitCode) != null && this.process.exitCode;
9552
- }
9553
- getOutput() {
9554
- return this._output;
9555
- }
9556
- async start() {
9557
- var _a, _b, _c;
9558
- if (!this.tempConfigPath)
9559
- throw new Error("tsconfig was not initialized");
9560
- const { root, watch, typecheck } = this.ctx.config;
9561
- const args = ["--noEmit", "--pretty", "false", "-p", this.tempConfigPath];
9562
- if (watch)
9563
- args.push("--watch");
9564
- if (typecheck.allowJs)
9565
- args.push("--allowJs", "--checkJs");
9566
- this._output = "";
9567
- const child = execa(typecheck.checker, args, {
9568
- cwd: root,
9569
- stdout: "pipe",
9570
- reject: false
9571
- });
9572
- this.process = child;
9573
- await ((_a = this._onParseStart) == null ? void 0 : _a.call(this));
9574
- let rerunTriggered = false;
9575
- (_b = child.stdout) == null ? void 0 : _b.on("data", (chunk) => {
9576
- var _a2;
9577
- this._output += chunk;
9578
- if (!watch)
9579
- return;
9580
- if (this._output.includes("File change detected") && !rerunTriggered) {
9581
- (_a2 = this._onWatcherRerun) == null ? void 0 : _a2.call(this);
9582
- this._result.sourceErrors = [];
9583
- this._result.files = [];
9584
- this._tests = null;
9585
- rerunTriggered = true;
9586
- }
9587
- if (/Found \w+ errors*. Watching for/.test(this._output)) {
9588
- rerunTriggered = false;
9589
- this.prepareResults(this._output).then((result) => {
9590
- var _a3;
9591
- this._result = result;
9592
- (_a3 = this._onParseEnd) == null ? void 0 : _a3.call(this, result);
9593
- });
9594
- this._output = "";
9595
- }
9596
- });
9597
- if (!watch) {
9598
- await child;
9599
- this._result = await this.prepareResults(this._output);
9600
- await ((_c = this._onParseEnd) == null ? void 0 : _c.call(this, this._result));
9601
- }
9602
- }
9603
- getResult() {
9604
- return this._result;
9605
- }
9606
- getTestFiles() {
9607
- return Object.values(this._tests || {}).map((i) => i.file);
9608
- }
9609
- getTestPacks() {
9610
- return Object.values(this._tests || {}).map(({ file }) => getTasks(file)).flat().map((i) => [i.id, void 0, { typecheck: true }]);
9611
- }
9533
+ let returnValue = '';
9534
+ let escapeCode;
9535
+ let escapeUrl;
9536
+
9537
+ const lengths = wordLengths(string);
9538
+ let rows = [''];
9539
+
9540
+ for (const [index, word] of string.split(' ').entries()) {
9541
+ if (options.trim !== false) {
9542
+ rows[rows.length - 1] = rows[rows.length - 1].trimStart();
9543
+ }
9544
+
9545
+ let rowLength = stringWidth(rows[rows.length - 1]);
9546
+
9547
+ if (index !== 0) {
9548
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
9549
+ // If we start with a new word but the current row length equals the length of the columns, add a new row
9550
+ rows.push('');
9551
+ rowLength = 0;
9552
+ }
9553
+
9554
+ if (rowLength > 0 || options.trim === false) {
9555
+ rows[rows.length - 1] += ' ';
9556
+ rowLength++;
9557
+ }
9558
+ }
9559
+
9560
+ // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
9561
+ if (options.hard && lengths[index] > columns) {
9562
+ const remainingColumns = (columns - rowLength);
9563
+ const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
9564
+ const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
9565
+ if (breaksStartingNextLine < breaksStartingThisLine) {
9566
+ rows.push('');
9567
+ }
9568
+
9569
+ wrapWord(rows, word, columns);
9570
+ continue;
9571
+ }
9572
+
9573
+ if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
9574
+ if (options.wordWrap === false && rowLength < columns) {
9575
+ wrapWord(rows, word, columns);
9576
+ continue;
9577
+ }
9578
+
9579
+ rows.push('');
9580
+ }
9581
+
9582
+ if (rowLength + lengths[index] > columns && options.wordWrap === false) {
9583
+ wrapWord(rows, word, columns);
9584
+ continue;
9585
+ }
9586
+
9587
+ rows[rows.length - 1] += word;
9588
+ }
9589
+
9590
+ if (options.trim !== false) {
9591
+ rows = rows.map(row => stringVisibleTrimSpacesRight(row));
9592
+ }
9593
+
9594
+ const pre = [...rows.join('\n')];
9595
+
9596
+ for (const [index, character] of pre.entries()) {
9597
+ returnValue += character;
9598
+
9599
+ if (ESCAPES.has(character)) {
9600
+ const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
9601
+ if (groups.code !== undefined) {
9602
+ const code = Number.parseFloat(groups.code);
9603
+ escapeCode = code === END_CODE ? undefined : code;
9604
+ } else if (groups.uri !== undefined) {
9605
+ escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
9606
+ }
9607
+ }
9608
+
9609
+ const code = ansiStyles.codes.get(Number(escapeCode));
9610
+
9611
+ if (pre[index + 1] === '\n') {
9612
+ if (escapeUrl) {
9613
+ returnValue += wrapAnsiHyperlink('');
9614
+ }
9615
+
9616
+ if (escapeCode && code) {
9617
+ returnValue += wrapAnsiCode(code);
9618
+ }
9619
+ } else if (character === '\n') {
9620
+ if (escapeCode && code) {
9621
+ returnValue += wrapAnsiCode(escapeCode);
9622
+ }
9623
+
9624
+ if (escapeUrl) {
9625
+ returnValue += wrapAnsiHyperlink(escapeUrl);
9626
+ }
9627
+ }
9628
+ }
9629
+
9630
+ return returnValue;
9631
+ };
9632
+
9633
+ // For each newline, invoke the method separately
9634
+ function wrapAnsi(string, columns, options) {
9635
+ return String(string)
9636
+ .normalize()
9637
+ .replace(/\r\n/g, '\n')
9638
+ .split('\n')
9639
+ .map(line => exec(line, columns, options))
9640
+ .join('\n');
9641
+ }
9642
+
9643
+ const defaultTerminalHeight = 24;
9644
+
9645
+ const getWidth = stream => {
9646
+ const {columns} = stream;
9647
+
9648
+ if (!columns) {
9649
+ return 80;
9650
+ }
9651
+
9652
+ return columns;
9653
+ };
9654
+
9655
+ const fitToTerminalHeight = (stream, text) => {
9656
+ const terminalHeight = stream.rows || defaultTerminalHeight;
9657
+ const lines = text.split('\n');
9658
+
9659
+ const toRemove = lines.length - terminalHeight;
9660
+ if (toRemove <= 0) {
9661
+ return text;
9662
+ }
9663
+
9664
+ return sliceAnsi(
9665
+ text,
9666
+ stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1,
9667
+ );
9668
+ };
9669
+
9670
+ function createLogUpdate(stream, {showCursor = false} = {}) {
9671
+ let previousLineCount = 0;
9672
+ let previousWidth = getWidth(stream);
9673
+ let previousOutput = '';
9674
+
9675
+ const render = (...arguments_) => {
9676
+ if (!showCursor) {
9677
+ cliCursor.hide();
9678
+ }
9679
+
9680
+ let output = arguments_.join(' ') + '\n';
9681
+ output = fitToTerminalHeight(stream, output);
9682
+ const width = getWidth(stream);
9683
+ if (output === previousOutput && previousWidth === width) {
9684
+ return;
9685
+ }
9686
+
9687
+ previousOutput = output;
9688
+ previousWidth = width;
9689
+ output = wrapAnsi(output, width, {
9690
+ trim: false,
9691
+ hard: true,
9692
+ wordWrap: false,
9693
+ });
9694
+ stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
9695
+ previousLineCount = output.split('\n').length;
9696
+ };
9697
+
9698
+ render.clear = () => {
9699
+ stream.write(ansiEscapes.eraseLines(previousLineCount));
9700
+ previousOutput = '';
9701
+ previousWidth = getWidth(stream);
9702
+ previousLineCount = 0;
9703
+ };
9704
+
9705
+ render.done = () => {
9706
+ previousOutput = '';
9707
+ previousWidth = getWidth(stream);
9708
+ previousLineCount = 0;
9709
+
9710
+ if (!showCursor) {
9711
+ cliCursor.show();
9712
+ }
9713
+ };
9714
+
9715
+ return render;
9612
9716
  }
9613
9717
 
9718
+ createLogUpdate(process$1.stdout);
9719
+
9720
+ createLogUpdate(process$1.stderr);
9721
+
9722
+ var version = "1.0.0-beta.3";
9723
+
9614
9724
  async function printError(error, project, options) {
9615
9725
  const { showCodeFrame = true, fullStack = false, type } = options;
9616
9726
  const logger = options.logger;
@@ -9632,7 +9742,8 @@ async function printError(error, project, options) {
9632
9742
  return printErrorMessage(e, logger);
9633
9743
  const parserOptions = {
9634
9744
  // only browser stack traces require remapping
9635
- getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9745
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file),
9746
+ frameFilter: project.config.onStackTrace
9636
9747
  };
9637
9748
  if (fullStack)
9638
9749
  parserOptions.ignoreStackEntries = [];
@@ -9891,10 +10002,21 @@ class Logger {
9891
10002
  const comma = c.dim(", ");
9892
10003
  if (filters == null ? void 0 : filters.length)
9893
10004
  this.console.error(c.dim("filter: ") + c.yellow(filters.join(comma)));
9894
- if (config.include)
9895
- this.console.error(c.dim("include: ") + c.yellow(config.include.join(comma)));
9896
- if (config.exclude)
9897
- this.console.error(c.dim("exclude: ") + c.yellow(config.exclude.join(comma)));
10005
+ this.ctx.projects.forEach((project) => {
10006
+ const config2 = project.config;
10007
+ const name = project.getName();
10008
+ const output = project.isCore() || !name ? "" : `[${name}]`;
10009
+ if (output)
10010
+ this.console.error(c.bgCyan(`${output} Config`));
10011
+ if (config2.include)
10012
+ this.console.error(c.dim("include: ") + c.yellow(config2.include.join(comma)));
10013
+ if (config2.exclude)
10014
+ this.console.error(c.dim("exclude: ") + c.yellow(config2.exclude.join(comma)));
10015
+ if (config2.typecheck.enabled) {
10016
+ this.console.error(c.dim("typecheck include: ") + c.yellow(config2.typecheck.include.join(comma)));
10017
+ this.console.error(c.dim("typecheck exclude: ") + c.yellow(config2.typecheck.exclude.join(comma)));
10018
+ }
10019
+ });
9898
10020
  if (config.watchExclude)
9899
10021
  this.console.error(c.dim("watch exclude: ") + c.yellow(config.watchExclude.join(comma)));
9900
10022
  if (config.watch && (config.changed || ((_a = config.related) == null ? void 0 : _a.length))) {
@@ -10249,125 +10371,16 @@ async function createBrowserServer(project, configFile) {
10249
10371
  });
10250
10372
  await server.listen();
10251
10373
  await server.watcher.close();
10252
- (await import('./chunk-api-setup.5d9a93c7.js')).setup(project, server);
10374
+ (await import('./chunk-api-setup.37a43981.js')).setup(project, server);
10253
10375
  return server;
10254
10376
  }
10255
10377
 
10256
- const playwrightBrowsers = ["firefox", "webkit", "chromium"];
10257
- class PlaywrightBrowserProvider {
10258
- name = "playwright";
10259
- cachedBrowser = null;
10260
- browser;
10261
- ctx;
10262
- getSupportedBrowsers() {
10263
- return playwrightBrowsers;
10264
- }
10265
- async initialize(ctx, { browser }) {
10266
- this.ctx = ctx;
10267
- this.browser = browser;
10268
- const root = this.ctx.config.root;
10269
- if (!await ensurePackageInstalled("playwright", root))
10270
- throw new Error('Cannot find "playwright" package. Please install it manually.');
10271
- }
10272
- async openBrowser() {
10273
- if (this.cachedBrowser)
10274
- return this.cachedBrowser;
10275
- const options = this.ctx.config.browser;
10276
- const playwright = await import('playwright');
10277
- const playwrightInstance = await playwright[this.browser].launch({ headless: options.headless });
10278
- this.cachedBrowser = await playwrightInstance.newPage();
10279
- this.cachedBrowser.on("close", () => {
10280
- playwrightInstance.close();
10281
- });
10282
- return this.cachedBrowser;
10283
- }
10284
- catchError(cb) {
10285
- var _a;
10286
- (_a = this.cachedBrowser) == null ? void 0 : _a.on("pageerror", cb);
10287
- return () => {
10288
- var _a2;
10289
- (_a2 = this.cachedBrowser) == null ? void 0 : _a2.off("pageerror", cb);
10290
- };
10291
- }
10292
- async openPage(url) {
10293
- const browserInstance = await this.openBrowser();
10294
- await browserInstance.goto(url);
10295
- }
10296
- async close() {
10297
- var _a;
10298
- await ((_a = this.cachedBrowser) == null ? void 0 : _a.close());
10299
- process.exit();
10300
- }
10301
- }
10302
-
10303
- const webdriverBrowsers = ["firefox", "chrome", "edge", "safari"];
10304
- class WebdriverBrowserProvider {
10305
- name = "webdriverio";
10306
- cachedBrowser = null;
10307
- stopSafari = () => {
10308
- };
10309
- browser;
10310
- ctx;
10311
- getSupportedBrowsers() {
10312
- return webdriverBrowsers;
10313
- }
10314
- async initialize(ctx, { browser }) {
10315
- this.ctx = ctx;
10316
- this.browser = browser;
10317
- const root = this.ctx.config.root;
10318
- if (!await ensurePackageInstalled("webdriverio", root))
10319
- throw new Error('Cannot find "webdriverio" package. Please install it manually.');
10320
- if (browser === "safari" && !await ensurePackageInstalled("safaridriver", root))
10321
- throw new Error('Cannot find "safaridriver" package. Please install it manually.');
10322
- }
10323
- async openBrowser() {
10324
- if (this.cachedBrowser)
10325
- return this.cachedBrowser;
10326
- const options = this.ctx.config.browser;
10327
- if (this.browser === "safari") {
10328
- const safaridriver = await import('safaridriver');
10329
- safaridriver.start({ diagnose: true });
10330
- this.stopSafari = () => safaridriver.stop();
10331
- process.on("beforeExit", () => {
10332
- safaridriver.stop();
10333
- });
10334
- }
10335
- const { remote } = await import('webdriverio');
10336
- this.cachedBrowser = await remote({
10337
- logLevel: "error",
10338
- capabilities: {
10339
- "browserName": this.browser,
10340
- "wdio:devtoolsOptions": { headless: options.headless }
10341
- }
10342
- });
10343
- return this.cachedBrowser;
10344
- }
10345
- async openPage(url) {
10346
- const browserInstance = await this.openBrowser();
10347
- await browserInstance.url(url);
10348
- }
10349
- // TODO
10350
- catchError(_cb) {
10351
- return () => {
10352
- };
10353
- }
10354
- async close() {
10355
- var _a, _b, _c;
10356
- await Promise.all([
10357
- this.stopSafari(),
10358
- ((_a = this.cachedBrowser) == null ? void 0 : _a.sessionId) ? (_c = (_b = this.cachedBrowser) == null ? void 0 : _b.deleteSession) == null ? void 0 : _c.call(_b) : null
10359
- ]);
10360
- process.exit();
10361
- }
10362
- }
10363
-
10364
10378
  async function getBrowserProvider(options, loader) {
10365
- switch (options.provider) {
10366
- case void 0:
10367
- case "webdriverio":
10368
- return WebdriverBrowserProvider;
10369
- case "playwright":
10370
- return PlaywrightBrowserProvider;
10379
+ if (options.provider == null || options.provider === "webdriverio" || options.provider === "playwright") {
10380
+ await ensurePackageInstalled("@vitest/browser", loader.root);
10381
+ const providers = await loader.executeId("@vitest/browser/providers");
10382
+ const provider = options.provider || "webdriverio";
10383
+ return providers[provider];
10371
10384
  }
10372
10385
  let customProviderModule;
10373
10386
  try {
@@ -10665,10 +10678,9 @@ async function createViteServer(inlineConfig) {
10665
10678
  return server;
10666
10679
  }
10667
10680
 
10668
- async function loadGlobalSetupFiles(project) {
10669
- var _a;
10670
- const globalSetupFiles = toArray$1((_a = project.server.config.test) == null ? void 0 : _a.globalSetup);
10671
- return Promise.all(globalSetupFiles.map((file) => loadGlobalSetupFile(file, project.runner)));
10681
+ async function loadGlobalSetupFiles(runner, globalSetup) {
10682
+ const globalSetupFiles = toArray$1(globalSetup);
10683
+ return Promise.all(globalSetupFiles.map((file) => loadGlobalSetupFile(file, runner)));
10672
10684
  }
10673
10685
  async function loadGlobalSetupFile(file, runner) {
10674
10686
  const m = await runner.executeFile(file);
@@ -10739,7 +10751,7 @@ class WorkspaceProject {
10739
10751
  if (this._globalSetupInit)
10740
10752
  return;
10741
10753
  this._globalSetupInit = true;
10742
- this._globalSetups = await loadGlobalSetupFiles(this);
10754
+ this._globalSetups = await loadGlobalSetupFiles(this.runner, this.config.globalSetup);
10743
10755
  try {
10744
10756
  for (const globalSetupFile of this._globalSetups) {
10745
10757
  const teardown = await ((_a = globalSetupFile.setup) == null ? void 0 : _a.call(globalSetupFile));
@@ -10760,7 +10772,7 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10760
10772
  var _a;
10761
10773
  if (!this._globalSetupInit || !this._globalSetups.length)
10762
10774
  return;
10763
- for (const globalSetupFile of this._globalSetups.reverse()) {
10775
+ for (const globalSetupFile of [...this._globalSetups].reverse()) {
10764
10776
  try {
10765
10777
  await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
10766
10778
  } catch (error) {
@@ -10797,8 +10809,12 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10797
10809
  }
10798
10810
  async globTestFiles(filters = []) {
10799
10811
  const dir = this.config.dir || this.config.root;
10800
- const testFiles = await this.globAllTestFiles(this.config, dir);
10801
- return this.filterFiles(testFiles, filters, dir);
10812
+ const typecheck = this.config.typecheck;
10813
+ const [testFiles, typecheckTestFiles] = await Promise.all([
10814
+ typecheck.enabled && typecheck.only ? [] : this.globAllTestFiles(this.config, dir),
10815
+ typecheck.enabled ? this.globFiles(typecheck.include, typecheck.exclude, dir) : []
10816
+ ]);
10817
+ return this.filterFiles([...testFiles, ...typecheckTestFiles], filters, dir);
10802
10818
  }
10803
10819
  async globAllTestFiles(config, cwd) {
10804
10820
  const { include, exclude, includeSource } = config;
@@ -10866,12 +10882,16 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10866
10882
  await ((_a = this.browser) == null ? void 0 : _a.close());
10867
10883
  this.browser = await createBrowserServer(this, configFile);
10868
10884
  }
10869
- static async createCoreProject(ctx) {
10885
+ static createBasicProject(ctx) {
10870
10886
  const project = new WorkspaceProject(ctx.config.name || ctx.config.root, ctx);
10871
10887
  project.vitenode = ctx.vitenode;
10872
10888
  project.server = ctx.server;
10873
10889
  project.runner = ctx.runner;
10874
10890
  project.config = ctx.config;
10891
+ return project;
10892
+ }
10893
+ static async createCoreProject(ctx) {
10894
+ const project = WorkspaceProject.createBasicProject(ctx);
10875
10895
  await project.initBrowserServer(ctx.server.config.configFile);
10876
10896
  return project;
10877
10897
  }
@@ -10895,63 +10915,6 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10895
10915
  async report(name, ...args) {
10896
10916
  return this.ctx.report(name, ...args);
10897
10917
  }
10898
- async typecheck(filters = []) {
10899
- const dir = this.config.dir || this.config.root;
10900
- const { include, exclude } = this.config.typecheck;
10901
- const testFiles = await this.globFiles(include, exclude, dir);
10902
- const testsFilesList = this.filterFiles(testFiles, filters, dir);
10903
- const checker = new Typechecker(this, testsFilesList);
10904
- this.typechecker = checker;
10905
- checker.onParseEnd(async ({ files, sourceErrors }) => {
10906
- this.ctx.state.collectFiles(checker.getTestFiles());
10907
- await this.report("onTaskUpdate", checker.getTestPacks());
10908
- await this.report("onCollected");
10909
- const failedTests = hasFailed(files);
10910
- const exitCode = !failedTests && checker.getExitCode();
10911
- if (exitCode) {
10912
- const error = new Error(checker.getOutput());
10913
- error.stack = "";
10914
- this.ctx.state.catchError(error, "Typecheck Error");
10915
- }
10916
- if (!files.length) {
10917
- this.ctx.logger.printNoTestFound();
10918
- } else {
10919
- if (failedTests)
10920
- process.exitCode = 1;
10921
- await this.report("onFinished", files);
10922
- }
10923
- if (sourceErrors.length && !this.config.typecheck.ignoreSourceErrors) {
10924
- process.exitCode = 1;
10925
- await this.ctx.logger.printSourceTypeErrors(sourceErrors);
10926
- }
10927
- if (!files.length) {
10928
- const exitCode2 = this.config.passWithNoTests ? process.exitCode ?? 0 : 1;
10929
- await this.close();
10930
- process.exit(exitCode2);
10931
- }
10932
- if (this.config.watch) {
10933
- await this.report("onWatcherStart", files, [
10934
- ...this.config.typecheck.ignoreSourceErrors ? [] : sourceErrors,
10935
- ...this.ctx.state.getUnhandledErrors()
10936
- ]);
10937
- }
10938
- });
10939
- checker.onParseStart(async () => {
10940
- await this.report("onInit", this.ctx);
10941
- this.ctx.state.collectFiles(checker.getTestFiles());
10942
- await this.report("onCollected");
10943
- });
10944
- checker.onWatcherRerun(async () => {
10945
- await this.report("onWatcherRerun", testsFilesList, "File change detected. Triggering rerun.");
10946
- await checker.collectTests();
10947
- this.ctx.state.collectFiles(checker.getTestFiles());
10948
- await this.report("onTaskUpdate", checker.getTestPacks());
10949
- await this.report("onCollected");
10950
- });
10951
- await checker.prepare();
10952
- await checker.collectTests();
10953
- await checker.start();
10954
- }
10955
10918
  isBrowserEnabled() {
10956
10919
  return isBrowserEnabled(this.config);
10957
10920
  }
@@ -10981,6 +10944,7 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10981
10944
  resolveSnapshotPath: void 0
10982
10945
  },
10983
10946
  onConsoleLog: void 0,
10947
+ onStackTrace: void 0,
10984
10948
  sequence: {
10985
10949
  ...this.ctx.config.sequence,
10986
10950
  sequencer: void 0
@@ -11021,7 +10985,8 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
11021
10985
  throw new Error(`[${this.getName()}] Browser name is required. Please, set \`test.browser.name\` option manually.`);
11022
10986
  if (!supportedBrowsers.includes(browser))
11023
10987
  throw new Error(`[${this.getName()}] Browser "${browser}" is not supported by the browser provider "${this.browserProvider.name}". Supported browsers: ${supportedBrowsers.join(", ")}.`);
11024
- await this.browserProvider.initialize(this, { browser });
10988
+ const providerOptions = this.config.browser.providerOptions;
10989
+ await this.browserProvider.initialize(this, { browser, options: providerOptions });
11025
10990
  }
11026
10991
  }
11027
10992
 
@@ -11057,6 +11022,7 @@ class Vitest {
11057
11022
  projectsTestFiles = /* @__PURE__ */ new Map();
11058
11023
  projectFiles;
11059
11024
  _onRestartListeners = [];
11025
+ _onClose = [];
11060
11026
  _onSetServer = [];
11061
11027
  _onCancelListeners = [];
11062
11028
  async setServer(options, server, cliOptions) {
@@ -11075,7 +11041,7 @@ class Vitest {
11075
11041
  this.state = new StateManager();
11076
11042
  this.cache = new VitestCache();
11077
11043
  this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions });
11078
- if (this.config.watch && this.mode !== "typecheck")
11044
+ if (this.config.watch)
11079
11045
  this.registerWatcher();
11080
11046
  this.vitenode = new ViteNodeServer(server, this.config.server);
11081
11047
  const projectVitestPath = await this.vitenode.resolveId("vitest");
@@ -11119,6 +11085,8 @@ class Vitest {
11119
11085
  }
11120
11086
  await Promise.all(this._onSetServer.map((fn) => fn()));
11121
11087
  this.projects = await this.resolveWorkspace(cliOptions);
11088
+ if (!this.coreWorkspaceProject)
11089
+ this.coreWorkspaceProject = WorkspaceProject.createBasicProject(this);
11122
11090
  if (this.config.testNamePattern)
11123
11091
  this.configOverride.testNamePattern = this.config.testNamePattern;
11124
11092
  }
@@ -11127,7 +11095,7 @@ class Vitest {
11127
11095
  return this.coreWorkspaceProject;
11128
11096
  }
11129
11097
  getCoreWorkspaceProject() {
11130
- return this.coreWorkspaceProject || null;
11098
+ return this.coreWorkspaceProject;
11131
11099
  }
11132
11100
  getProjectByTaskId(taskId) {
11133
11101
  var _a;
@@ -11240,15 +11208,9 @@ class Vitest {
11240
11208
  async initBrowserProviders() {
11241
11209
  return Promise.all(this.projects.map((w) => w.initBrowserProvider()));
11242
11210
  }
11243
- typecheck(filters) {
11244
- return Promise.all(this.projects.map((project) => project.typecheck(filters)));
11245
- }
11246
11211
  async start(filters) {
11247
11212
  var _a, _b;
11248
- if (this.mode === "typecheck") {
11249
- await this.typecheck(filters);
11250
- return;
11251
- }
11213
+ this._onClose = [];
11252
11214
  try {
11253
11215
  await this.initCoverageProvider();
11254
11216
  await ((_a = this.coverageProvider) == null ? void 0 : _a.clean(this.config.coverage.clean));
@@ -11300,7 +11262,7 @@ class Vitest {
11300
11262
  }
11301
11263
  async filterTestsBySource(specs) {
11302
11264
  if (this.config.changed && !this.config.related) {
11303
- const { VitestGit } = await import('./chunk-node-git.2f1df48f.js');
11265
+ const { VitestGit } = await import('./chunk-node-git.6c12e560.js');
11304
11266
  const vitestGit = new VitestGit(this.config.root);
11305
11267
  const related2 = await vitestGit.findChangedFiles({
11306
11268
  changedSince: this.config.changed
@@ -11339,7 +11301,13 @@ class Vitest {
11339
11301
  return Array.from(projects).map((project) => [project, file]);
11340
11302
  }
11341
11303
  async initializeGlobalSetup(paths) {
11342
- await Promise.all(paths.map(async ([project]) => project.initializeGlobalSetup()));
11304
+ const projects = new Set(paths.map(([project]) => project));
11305
+ const coreProject = this.getCoreWorkspaceProject();
11306
+ if (!projects.has(coreProject))
11307
+ projects.add(coreProject);
11308
+ await Promise.all(
11309
+ Array.from(projects).map((project) => project.initializeGlobalSetup())
11310
+ );
11343
11311
  }
11344
11312
  async runFiles(paths) {
11345
11313
  const filepaths = paths.map(([, file]) => file);
@@ -11571,10 +11539,11 @@ class Vitest {
11571
11539
  async close() {
11572
11540
  if (!this.closingPromise) {
11573
11541
  const closePromises = this.projects.map((w) => w.close().then(() => w.server = void 0));
11574
- if (!this.coreWorkspaceProject || !this.projects.includes(this.coreWorkspaceProject))
11575
- closePromises.push(this.server.close().then(() => this.server = void 0));
11542
+ if (!this.projects.includes(this.coreWorkspaceProject))
11543
+ closePromises.push(this.coreWorkspaceProject.close().then(() => this.server = void 0));
11576
11544
  if (this.pool)
11577
11545
  closePromises.push(this.pool.close().then(() => this.pool = void 0));
11546
+ closePromises.push(...this._onClose.map((fn) => fn()));
11578
11547
  this.closingPromise = Promise.allSettled(closePromises).then((results) => {
11579
11548
  results.filter((r) => r.status === "rejected").forEach((err) => {
11580
11549
  this.logger.error("error during close", err.reason);
@@ -11644,6 +11613,9 @@ class Vitest {
11644
11613
  onCancel(fn) {
11645
11614
  this._onCancelListeners.push(fn);
11646
11615
  }
11616
+ onClose(fn) {
11617
+ this._onClose.push(fn);
11618
+ }
11647
11619
  }
11648
11620
 
11649
11621
  async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
@@ -11764,7 +11736,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
11764
11736
  try {
11765
11737
  await ctx.setServer(options, server, userConfig);
11766
11738
  if (options.api && options.watch)
11767
- (await import('./chunk-api-setup.5d9a93c7.js')).setup(ctx);
11739
+ (await import('./chunk-api-setup.37a43981.js')).setup(ctx);
11768
11740
  } catch (err) {
11769
11741
  await ctx.logger.printError(err, { fullStack: true });
11770
11742
  process.exit(1);
@@ -18113,8 +18085,6 @@ function registerConsoleShortcuts(ctx) {
18113
18085
  process.kill(process.pid, "SIGTSTP");
18114
18086
  return;
18115
18087
  }
18116
- if (!ctx.config.watch)
18117
- return;
18118
18088
  const name = key == null ? void 0 : key.name;
18119
18089
  if (ctx.runningPromise) {
18120
18090
  if (cancelKeys.includes(name))
@@ -18123,8 +18093,6 @@ function registerConsoleShortcuts(ctx) {
18123
18093
  }
18124
18094
  if (name === "q")
18125
18095
  return ctx.exit(true);
18126
- if (ctx.mode === "typecheck")
18127
- return;
18128
18096
  if (name === "h")
18129
18097
  return printShortcutsHelp();
18130
18098
  if (name === "u")
@@ -18190,7 +18158,7 @@ function registerConsoleShortcuts(ctx) {
18190
18158
  }
18191
18159
 
18192
18160
  async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
18193
- var _a;
18161
+ var _a, _b;
18194
18162
  process.env.TEST = "true";
18195
18163
  process.env.VITEST = "true";
18196
18164
  (_a = process.env).NODE_ENV ?? (_a.NODE_ENV = options.mode || "test");
@@ -18209,6 +18177,13 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
18209
18177
  options.browser = { enabled: true, name: options.browser };
18210
18178
  if (typeof options.browser === "object" && !("enabled" in options.browser))
18211
18179
  options.browser.enabled = true;
18180
+ if (typeof options.typecheck === "boolean")
18181
+ options.typecheck = { enabled: true };
18182
+ if (typeof ((_b = options.typecheck) == null ? void 0 : _b.only) === "boolean") {
18183
+ options.typecheck ?? (options.typecheck = {});
18184
+ options.typecheck.only = true;
18185
+ options.typecheck.enabled = true;
18186
+ }
18212
18187
  const ctx = await createVitest(mode, options, viteOverrides);
18213
18188
  if (mode === "test" && ctx.config.coverage.enabled) {
18214
18189
  const provider = ctx.config.coverage.provider || "v8";
@@ -18226,7 +18201,7 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
18226
18201
  return ctx;
18227
18202
  }
18228
18203
  let stdinCleanup;
18229
- if (process.stdin.isTTY)
18204
+ if (process.stdin.isTTY && ctx.config.watch)
18230
18205
  stdinCleanup = registerConsoleShortcuts(ctx);
18231
18206
  ctx.onServerRestart((reason) => {
18232
18207
  ctx.report("onServerRestart", reason);
@@ -18251,4 +18226,4 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
18251
18226
  return ctx;
18252
18227
  }
18253
18228
 
18254
- export { BaseSequencer as B, VitestPlugin as V, createVitest as c, onetimeExports as o, registerConsoleShortcuts as r, startVitest as s, version$1 as v };
18229
+ export { BaseSequencer as B, VitestPlugin as V, createVitest as c, ensurePackageInstalled as e, onetimeExports as o, registerConsoleShortcuts as r, startVitest as s, version$1 as v };