vitest 4.0.0-beta.1 → 4.0.0-beta.11

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 (90) hide show
  1. package/LICENSE.md +83 -2
  2. package/dist/browser.d.ts +19 -16
  3. package/dist/browser.js +11 -7
  4. package/dist/chunks/{benchmark.CYdenmiT.js → benchmark.LXhJ0F0X.js} +7 -9
  5. package/dist/chunks/{benchmark.d.BwvBVTda.d.ts → benchmark.d.DAaHLpsq.d.ts} +4 -4
  6. package/dist/chunks/{browser.d.q8Z0P0q1.d.ts → browser.d.Dx7DO_Ce.d.ts} +5 -5
  7. package/dist/chunks/{cac.D3EzDDZd.js → cac.elvK37c9.js} +71 -153
  8. package/dist/chunks/{cli-api.Dn5gKePv.js → cli-api.C7plPyhs.js} +1376 -1693
  9. package/dist/chunks/{config.d.HJdfX-8k.d.ts → config.d.B_LthbQq.d.ts} +58 -63
  10. package/dist/chunks/{console.CtFJOzRO.js → console.CiTi59Jy.js} +35 -71
  11. package/dist/chunks/{constants.DnKduX2e.js → constants.D_Q9UYh-.js} +1 -9
  12. package/dist/chunks/{coverage.Cwa-XhJt.js → coverage.CG6Uhorw.js} +522 -792
  13. package/dist/chunks/{coverage.DVF1vEu8.js → coverage.D_JHT54q.js} +2 -2
  14. package/dist/chunks/{coverage.d.S9RMNXIe.d.ts → coverage.d.BZtK59WP.d.ts} +10 -8
  15. package/dist/chunks/{creator.GK6I-cL4.js → creator.08Gi-vCA.js} +93 -77
  16. package/dist/chunks/{date.Bq6ZW5rf.js → date.-jtEtIeV.js} +6 -17
  17. package/dist/chunks/{environment.d.CUq4cUgQ.d.ts → environment.d.BsToaxti.d.ts} +27 -6
  18. package/dist/chunks/{git.BVQ8w_Sw.js → git.BFNcloKD.js} +1 -2
  19. package/dist/chunks/{global.d.CVbXEflG.d.ts → global.d.BK3X7FW1.d.ts} +2 -5
  20. package/dist/chunks/{globals.Cxal6MLI.js → globals.BjvYA-AD.js} +11 -9
  21. package/dist/chunks/{index.BWf_gE5n.js → index.AZOjjqWP.js} +7 -6
  22. package/dist/chunks/{index.B521nVV-.js → index.Bgo3tNWt.js} +23 -4
  23. package/dist/chunks/{index.TfbsX-3I.js → index.BhY64fF0.js} +16 -26
  24. package/dist/chunks/{index.CZI_8rVt.js → index.BwBttQPf.js} +340 -663
  25. package/dist/chunks/{index.CmSc2RE5.js → index.DIWhzsUh.js} +72 -118
  26. package/dist/chunks/{inspector.C914Efll.js → inspector.CvQD-Nie.js} +10 -25
  27. package/dist/chunks/moduleRunner.d.BNa-CL9e.d.ts +201 -0
  28. package/dist/chunks/{node.fjCdwEIl.js → node.BsdMi6DV.js} +2 -2
  29. package/dist/chunks/{plugin.d.C2EcJUjo.d.ts → plugin.d.C5phQR6o.d.ts} +1 -1
  30. package/dist/chunks/{reporters.d.DxZg19fy.d.ts → reporters.d.CVzhsTvK.d.ts} +1233 -1293
  31. package/dist/chunks/resolveSnapshotEnvironment.DQVamkje.js +81 -0
  32. package/dist/chunks/rpc.jKGRSXIH.js +65 -0
  33. package/dist/chunks/{setup-common.D7ZqXFx-.js → setup-common.NAWRuMRP.js} +18 -30
  34. package/dist/chunks/startModuleRunner.oAuCu1yL.js +682 -0
  35. package/dist/chunks/{suite.d.FvehnV49.d.ts → suite.d.BJWk38HB.d.ts} +1 -1
  36. package/dist/chunks/test.KC5tH8hC.js +214 -0
  37. package/dist/chunks/typechecker.gXq-5P3n.js +1438 -0
  38. package/dist/chunks/{utils.XdZDrNZV.js → utils.DGKhod2J.js} +9 -28
  39. package/dist/chunks/{vi.bdSIJ99Y.js → vi.CiJ0Laa6.js} +159 -306
  40. package/dist/chunks/worker.d.B_Fd9M_w.d.ts +100 -0
  41. package/dist/chunks/worker.rPGLlbkW.js +200 -0
  42. package/dist/cli.js +8 -6
  43. package/dist/config.cjs +3 -9
  44. package/dist/config.d.ts +49 -54
  45. package/dist/config.js +1 -1
  46. package/dist/coverage.d.ts +27 -26
  47. package/dist/coverage.js +6 -8
  48. package/dist/environments.d.ts +9 -13
  49. package/dist/environments.js +1 -1
  50. package/dist/index.d.ts +38 -45
  51. package/dist/index.js +10 -10
  52. package/dist/module-evaluator.d.ts +13 -0
  53. package/dist/module-evaluator.js +276 -0
  54. package/dist/module-runner.js +15 -0
  55. package/dist/node.d.ts +44 -42
  56. package/dist/node.js +30 -36
  57. package/dist/reporters.d.ts +12 -13
  58. package/dist/reporters.js +7 -5
  59. package/dist/runners.d.ts +3 -3
  60. package/dist/runners.js +15 -232
  61. package/dist/snapshot.js +3 -3
  62. package/dist/suite.d.ts +2 -2
  63. package/dist/suite.js +4 -3
  64. package/dist/worker-base.js +203 -0
  65. package/dist/{chunks/vm.BThCzidc.js → worker-vm.js} +179 -228
  66. package/dist/workers/runVmTests.js +39 -56
  67. package/globals.d.ts +17 -17
  68. package/package.json +40 -38
  69. package/browser.d.ts +0 -1
  70. package/dist/chunks/base.Bj3pWTr1.js +0 -38
  71. package/dist/chunks/execute.B7h3T_Hc.js +0 -708
  72. package/dist/chunks/index.D-VkfKhf.js +0 -105
  73. package/dist/chunks/rpc.CsFtxqeq.js +0 -83
  74. package/dist/chunks/runBaseTests.BC7ZIH5L.js +0 -129
  75. package/dist/chunks/typechecker.CVytUJuF.js +0 -874
  76. package/dist/chunks/utils.CAioKnHs.js +0 -61
  77. package/dist/chunks/worker.d.CmvJfRGs.d.ts +0 -8
  78. package/dist/chunks/worker.d.DoNjFAiv.d.ts +0 -169
  79. package/dist/execute.d.ts +0 -148
  80. package/dist/execute.js +0 -13
  81. package/dist/worker.js +0 -124
  82. package/dist/workers/forks.js +0 -43
  83. package/dist/workers/threads.js +0 -31
  84. package/dist/workers/vmForks.js +0 -47
  85. package/dist/workers/vmThreads.js +0 -37
  86. package/dist/workers.d.ts +0 -37
  87. package/dist/workers.js +0 -30
  88. package/execute.d.ts +0 -1
  89. package/utils.d.ts +0 -1
  90. package/workers.d.ts +0 -1
@@ -1,874 +0,0 @@
1
- import nodeos__default from 'node:os';
2
- import { performance } from 'node:perf_hooks';
3
- import { TraceMap, generatedPositionFor, eachMapping } from '@vitest/utils/source-map';
4
- import { relative, basename, resolve, join } from 'pathe';
5
- import { x } from 'tinyexec';
6
- import { distDir } from '../path.js';
7
- import { getTests, generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes } from '@vitest/runner/utils';
8
- import '@vitest/utils';
9
- import { parseAstAsync } from 'vite';
10
-
11
- const REGEXP_WRAP_PREFIX = "$$vitest:";
12
- function getOutputFile(config, reporter) {
13
- if (!config?.outputFile) return;
14
- if (typeof config.outputFile === "string") return config.outputFile;
15
- return config.outputFile[reporter];
16
- }
17
- /**
18
- * Prepares `SerializedConfig` for serialization, e.g. `node:v8.serialize`
19
- */
20
- function wrapSerializableConfig(config) {
21
- let testNamePattern = config.testNamePattern;
22
- let defines = config.defines;
23
- // v8 serialize does not support regex
24
- if (testNamePattern && typeof testNamePattern !== "string") testNamePattern = `${REGEXP_WRAP_PREFIX}${testNamePattern.toString()}`;
25
- // v8 serialize drops properties with undefined value
26
- if (defines) defines = {
27
- keys: Object.keys(defines),
28
- original: defines
29
- };
30
- return {
31
- ...config,
32
- testNamePattern,
33
- defines
34
- };
35
- }
36
-
37
- function hasFailedSnapshot(suite) {
38
- return getTests(suite).some((s) => {
39
- return s.result?.errors?.some((e) => typeof e?.message === "string" && e.message.match(/Snapshot .* mismatched/));
40
- });
41
- }
42
- function convertTasksToEvents(file, onTask) {
43
- const packs = [];
44
- const events = [];
45
- function visit(suite) {
46
- onTask?.(suite);
47
- packs.push([
48
- suite.id,
49
- suite.result,
50
- suite.meta
51
- ]);
52
- events.push([
53
- suite.id,
54
- "suite-prepare",
55
- void 0
56
- ]);
57
- suite.tasks.forEach((task) => {
58
- if (task.type === "suite") visit(task);
59
- else {
60
- onTask?.(task);
61
- if (suite.mode !== "skip" && suite.mode !== "todo") {
62
- packs.push([
63
- task.id,
64
- task.result,
65
- task.meta
66
- ]);
67
- events.push([
68
- task.id,
69
- "test-prepare",
70
- void 0
71
- ]);
72
- task.annotations.forEach((annotation) => {
73
- events.push([
74
- task.id,
75
- "test-annotation",
76
- { annotation }
77
- ]);
78
- });
79
- events.push([
80
- task.id,
81
- "test-finished",
82
- void 0
83
- ]);
84
- }
85
- }
86
- });
87
- events.push([
88
- suite.id,
89
- "suite-finished",
90
- void 0
91
- ]);
92
- }
93
- visit(file);
94
- return {
95
- packs,
96
- events
97
- };
98
- }
99
-
100
- // AST walker module for ESTree compatible trees
101
-
102
-
103
- // An ancestor walk keeps an array of ancestor nodes (including the
104
- // current node) and passes them to the callback as third parameter
105
- // (and also as state parameter when no other state is present).
106
- function ancestor(node, visitors, baseVisitor, state, override) {
107
- var ancestors = [];
108
- if (!baseVisitor) { baseVisitor = base
109
- ; }(function c(node, st, override) {
110
- var type = override || node.type;
111
- var isNew = node !== ancestors[ancestors.length - 1];
112
- if (isNew) { ancestors.push(node); }
113
- baseVisitor[type](node, st, c);
114
- if (visitors[type]) { visitors[type](node, st || ancestors, ancestors); }
115
- if (isNew) { ancestors.pop(); }
116
- })(node, state, override);
117
- }
118
-
119
- function skipThrough(node, st, c) { c(node, st); }
120
- function ignore(_node, _st, _c) {}
121
-
122
- // Node walkers.
123
-
124
- var base = {};
125
-
126
- base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
127
- for (var i = 0, list = node.body; i < list.length; i += 1)
128
- {
129
- var stmt = list[i];
130
-
131
- c(stmt, st, "Statement");
132
- }
133
- };
134
- base.Statement = skipThrough;
135
- base.EmptyStatement = ignore;
136
- base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
137
- function (node, st, c) { return c(node.expression, st, "Expression"); };
138
- base.IfStatement = function (node, st, c) {
139
- c(node.test, st, "Expression");
140
- c(node.consequent, st, "Statement");
141
- if (node.alternate) { c(node.alternate, st, "Statement"); }
142
- };
143
- base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
144
- base.BreakStatement = base.ContinueStatement = ignore;
145
- base.WithStatement = function (node, st, c) {
146
- c(node.object, st, "Expression");
147
- c(node.body, st, "Statement");
148
- };
149
- base.SwitchStatement = function (node, st, c) {
150
- c(node.discriminant, st, "Expression");
151
- for (var i = 0, list = node.cases; i < list.length; i += 1) {
152
- var cs = list[i];
153
-
154
- c(cs, st);
155
- }
156
- };
157
- base.SwitchCase = function (node, st, c) {
158
- if (node.test) { c(node.test, st, "Expression"); }
159
- for (var i = 0, list = node.consequent; i < list.length; i += 1)
160
- {
161
- var cons = list[i];
162
-
163
- c(cons, st, "Statement");
164
- }
165
- };
166
- base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
167
- if (node.argument) { c(node.argument, st, "Expression"); }
168
- };
169
- base.ThrowStatement = base.SpreadElement =
170
- function (node, st, c) { return c(node.argument, st, "Expression"); };
171
- base.TryStatement = function (node, st, c) {
172
- c(node.block, st, "Statement");
173
- if (node.handler) { c(node.handler, st); }
174
- if (node.finalizer) { c(node.finalizer, st, "Statement"); }
175
- };
176
- base.CatchClause = function (node, st, c) {
177
- if (node.param) { c(node.param, st, "Pattern"); }
178
- c(node.body, st, "Statement");
179
- };
180
- base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
181
- c(node.test, st, "Expression");
182
- c(node.body, st, "Statement");
183
- };
184
- base.ForStatement = function (node, st, c) {
185
- if (node.init) { c(node.init, st, "ForInit"); }
186
- if (node.test) { c(node.test, st, "Expression"); }
187
- if (node.update) { c(node.update, st, "Expression"); }
188
- c(node.body, st, "Statement");
189
- };
190
- base.ForInStatement = base.ForOfStatement = function (node, st, c) {
191
- c(node.left, st, "ForInit");
192
- c(node.right, st, "Expression");
193
- c(node.body, st, "Statement");
194
- };
195
- base.ForInit = function (node, st, c) {
196
- if (node.type === "VariableDeclaration") { c(node, st); }
197
- else { c(node, st, "Expression"); }
198
- };
199
- base.DebuggerStatement = ignore;
200
-
201
- base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
202
- base.VariableDeclaration = function (node, st, c) {
203
- for (var i = 0, list = node.declarations; i < list.length; i += 1)
204
- {
205
- var decl = list[i];
206
-
207
- c(decl, st);
208
- }
209
- };
210
- base.VariableDeclarator = function (node, st, c) {
211
- c(node.id, st, "Pattern");
212
- if (node.init) { c(node.init, st, "Expression"); }
213
- };
214
-
215
- base.Function = function (node, st, c) {
216
- if (node.id) { c(node.id, st, "Pattern"); }
217
- for (var i = 0, list = node.params; i < list.length; i += 1)
218
- {
219
- var param = list[i];
220
-
221
- c(param, st, "Pattern");
222
- }
223
- c(node.body, st, node.expression ? "Expression" : "Statement");
224
- };
225
-
226
- base.Pattern = function (node, st, c) {
227
- if (node.type === "Identifier")
228
- { c(node, st, "VariablePattern"); }
229
- else if (node.type === "MemberExpression")
230
- { c(node, st, "MemberPattern"); }
231
- else
232
- { c(node, st); }
233
- };
234
- base.VariablePattern = ignore;
235
- base.MemberPattern = skipThrough;
236
- base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
237
- base.ArrayPattern = function (node, st, c) {
238
- for (var i = 0, list = node.elements; i < list.length; i += 1) {
239
- var elt = list[i];
240
-
241
- if (elt) { c(elt, st, "Pattern"); }
242
- }
243
- };
244
- base.ObjectPattern = function (node, st, c) {
245
- for (var i = 0, list = node.properties; i < list.length; i += 1) {
246
- var prop = list[i];
247
-
248
- if (prop.type === "Property") {
249
- if (prop.computed) { c(prop.key, st, "Expression"); }
250
- c(prop.value, st, "Pattern");
251
- } else if (prop.type === "RestElement") {
252
- c(prop.argument, st, "Pattern");
253
- }
254
- }
255
- };
256
-
257
- base.Expression = skipThrough;
258
- base.ThisExpression = base.Super = base.MetaProperty = ignore;
259
- base.ArrayExpression = function (node, st, c) {
260
- for (var i = 0, list = node.elements; i < list.length; i += 1) {
261
- var elt = list[i];
262
-
263
- if (elt) { c(elt, st, "Expression"); }
264
- }
265
- };
266
- base.ObjectExpression = function (node, st, c) {
267
- for (var i = 0, list = node.properties; i < list.length; i += 1)
268
- {
269
- var prop = list[i];
270
-
271
- c(prop, st);
272
- }
273
- };
274
- base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
275
- base.SequenceExpression = function (node, st, c) {
276
- for (var i = 0, list = node.expressions; i < list.length; i += 1)
277
- {
278
- var expr = list[i];
279
-
280
- c(expr, st, "Expression");
281
- }
282
- };
283
- base.TemplateLiteral = function (node, st, c) {
284
- for (var i = 0, list = node.quasis; i < list.length; i += 1)
285
- {
286
- var quasi = list[i];
287
-
288
- c(quasi, st);
289
- }
290
-
291
- for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
292
- {
293
- var expr = list$1[i$1];
294
-
295
- c(expr, st, "Expression");
296
- }
297
- };
298
- base.TemplateElement = ignore;
299
- base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
300
- c(node.argument, st, "Expression");
301
- };
302
- base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
303
- c(node.left, st, "Expression");
304
- c(node.right, st, "Expression");
305
- };
306
- base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
307
- c(node.left, st, "Pattern");
308
- c(node.right, st, "Expression");
309
- };
310
- base.ConditionalExpression = function (node, st, c) {
311
- c(node.test, st, "Expression");
312
- c(node.consequent, st, "Expression");
313
- c(node.alternate, st, "Expression");
314
- };
315
- base.NewExpression = base.CallExpression = function (node, st, c) {
316
- c(node.callee, st, "Expression");
317
- if (node.arguments)
318
- { for (var i = 0, list = node.arguments; i < list.length; i += 1)
319
- {
320
- var arg = list[i];
321
-
322
- c(arg, st, "Expression");
323
- } }
324
- };
325
- base.MemberExpression = function (node, st, c) {
326
- c(node.object, st, "Expression");
327
- if (node.computed) { c(node.property, st, "Expression"); }
328
- };
329
- base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
330
- if (node.declaration)
331
- { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
332
- if (node.source) { c(node.source, st, "Expression"); }
333
- };
334
- base.ExportAllDeclaration = function (node, st, c) {
335
- if (node.exported)
336
- { c(node.exported, st); }
337
- c(node.source, st, "Expression");
338
- };
339
- base.ImportDeclaration = function (node, st, c) {
340
- for (var i = 0, list = node.specifiers; i < list.length; i += 1)
341
- {
342
- var spec = list[i];
343
-
344
- c(spec, st);
345
- }
346
- c(node.source, st, "Expression");
347
- };
348
- base.ImportExpression = function (node, st, c) {
349
- c(node.source, st, "Expression");
350
- };
351
- base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
352
-
353
- base.TaggedTemplateExpression = function (node, st, c) {
354
- c(node.tag, st, "Expression");
355
- c(node.quasi, st, "Expression");
356
- };
357
- base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
358
- base.Class = function (node, st, c) {
359
- if (node.id) { c(node.id, st, "Pattern"); }
360
- if (node.superClass) { c(node.superClass, st, "Expression"); }
361
- c(node.body, st);
362
- };
363
- base.ClassBody = function (node, st, c) {
364
- for (var i = 0, list = node.body; i < list.length; i += 1)
365
- {
366
- var elt = list[i];
367
-
368
- c(elt, st);
369
- }
370
- };
371
- base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
372
- if (node.computed) { c(node.key, st, "Expression"); }
373
- if (node.value) { c(node.value, st, "Expression"); }
374
- };
375
-
376
- async function collectTests(ctx, filepath) {
377
- const request = await ctx.vitenode.transformRequest(filepath, filepath);
378
- if (!request) return null;
379
- const ast = await parseAstAsync(request.code);
380
- const testFilepath = relative(ctx.config.root, filepath);
381
- const projectName = ctx.name;
382
- const typecheckSubprojectName = projectName ? `${projectName}:__typecheck__` : "__typecheck__";
383
- const file = {
384
- filepath,
385
- type: "suite",
386
- id: generateHash(`${testFilepath}${typecheckSubprojectName}`),
387
- name: testFilepath,
388
- mode: "run",
389
- tasks: [],
390
- start: ast.start,
391
- end: ast.end,
392
- projectName,
393
- meta: { typecheck: true },
394
- file: null
395
- };
396
- file.file = file;
397
- const definitions = [];
398
- const getName = (callee) => {
399
- if (!callee) return null;
400
- if (callee.type === "Identifier") return callee.name;
401
- if (callee.type === "CallExpression") return getName(callee.callee);
402
- if (callee.type === "TaggedTemplateExpression") return getName(callee.tag);
403
- if (callee.type === "MemberExpression") {
404
- if (callee.object?.type === "Identifier" && [
405
- "it",
406
- "test",
407
- "describe",
408
- "suite"
409
- ].includes(callee.object.name)) return callee.object?.name;
410
- // direct call as `__vite_ssr_exports_0__.test()`
411
- if (callee.object?.name?.startsWith("__vite_ssr_")) return getName(callee.property);
412
- // call as `__vite_ssr__.test.skip()`
413
- return getName(callee.object?.property);
414
- }
415
- // unwrap (0, ...)
416
- if (callee.type === "SequenceExpression" && callee.expressions.length === 2) {
417
- const [e0, e1] = callee.expressions;
418
- if (e0.type === "Literal" && e0.value === 0) return getName(e1);
419
- }
420
- return null;
421
- };
422
- ancestor(ast, { CallExpression(node) {
423
- const { callee } = node;
424
- const name = getName(callee);
425
- if (!name) return;
426
- if (![
427
- "it",
428
- "test",
429
- "describe",
430
- "suite"
431
- ].includes(name)) return;
432
- const property = callee?.property?.name;
433
- let mode = !property || property === name ? "run" : property;
434
- // they will be picked up in the next iteration
435
- if ([
436
- "each",
437
- "for",
438
- "skipIf",
439
- "runIf"
440
- ].includes(mode)) return;
441
- let start;
442
- const end = node.end;
443
- // .each
444
- if (callee.type === "CallExpression") start = callee.end;
445
- else if (callee.type === "TaggedTemplateExpression") start = callee.end + 1;
446
- else start = node.start;
447
- const { arguments: [messageNode] } = node;
448
- const isQuoted = messageNode?.type === "Literal" || messageNode?.type === "TemplateLiteral";
449
- const message = isQuoted ? request.code.slice(messageNode.start + 1, messageNode.end - 1) : request.code.slice(messageNode.start, messageNode.end);
450
- // cannot statically analyze, so we always skip it
451
- if (mode === "skipIf" || mode === "runIf") mode = "skip";
452
- definitions.push({
453
- start,
454
- end,
455
- name: message,
456
- type: name === "it" || name === "test" ? "test" : "suite",
457
- mode,
458
- task: null
459
- });
460
- } });
461
- let lastSuite = file;
462
- const updateLatestSuite = (index) => {
463
- while (lastSuite.suite && lastSuite.end < index) lastSuite = lastSuite.suite;
464
- return lastSuite;
465
- };
466
- definitions.sort((a, b) => a.start - b.start).forEach((definition) => {
467
- const latestSuite = updateLatestSuite(definition.start);
468
- let mode = definition.mode;
469
- if (latestSuite.mode !== "run")
470
- // inherit suite mode, if it's set
471
- mode = latestSuite.mode;
472
- if (definition.type === "suite") {
473
- const task = {
474
- type: definition.type,
475
- id: "",
476
- suite: latestSuite,
477
- file,
478
- tasks: [],
479
- mode,
480
- name: definition.name,
481
- end: definition.end,
482
- start: definition.start,
483
- meta: { typecheck: true }
484
- };
485
- definition.task = task;
486
- latestSuite.tasks.push(task);
487
- lastSuite = task;
488
- return;
489
- }
490
- const task = {
491
- type: definition.type,
492
- id: "",
493
- suite: latestSuite,
494
- file,
495
- mode,
496
- timeout: 0,
497
- context: {},
498
- name: definition.name,
499
- end: definition.end,
500
- start: definition.start,
501
- annotations: [],
502
- meta: { typecheck: true }
503
- };
504
- definition.task = task;
505
- latestSuite.tasks.push(task);
506
- });
507
- calculateSuiteHash(file);
508
- const hasOnly = someTasksAreOnly(file);
509
- interpretTaskModes(file, ctx.config.testNamePattern, void 0, hasOnly, false, ctx.config.allowOnly);
510
- return {
511
- file,
512
- parsed: request.code,
513
- filepath,
514
- map: request.map,
515
- definitions
516
- };
517
- }
518
-
519
- const newLineRegExp = /\r?\n/;
520
- const errCodeRegExp = /error TS(?<errCode>\d+)/;
521
- async function makeTscErrorInfo(errInfo) {
522
- const [errFilePathPos = "", ...errMsgRawArr] = errInfo.split(":");
523
- if (!errFilePathPos || errMsgRawArr.length === 0 || errMsgRawArr.join("").length === 0) return ["unknown filepath", null];
524
- const errMsgRaw = errMsgRawArr.join("").trim();
525
- // get filePath, line, col
526
- const [errFilePath, errPos] = errFilePathPos.slice(0, -1).split("(");
527
- if (!errFilePath || !errPos) return ["unknown filepath", null];
528
- const [errLine, errCol] = errPos.split(",");
529
- if (!errLine || !errCol) return [errFilePath, null];
530
- // get errCode, errMsg
531
- const execArr = errCodeRegExp.exec(errMsgRaw);
532
- if (!execArr) return [errFilePath, null];
533
- const errCodeStr = execArr.groups?.errCode ?? "";
534
- if (!errCodeStr) return [errFilePath, null];
535
- const line = Number(errLine);
536
- const col = Number(errCol);
537
- const errCode = Number(errCodeStr);
538
- return [errFilePath, {
539
- filePath: errFilePath,
540
- errCode,
541
- line,
542
- column: col,
543
- errMsg: errMsgRaw.slice(`error TS${errCode} `.length)
544
- }];
545
- }
546
- async function getRawErrsMapFromTsCompile(tscErrorStdout) {
547
- const rawErrsMap = /* @__PURE__ */ new Map();
548
- // Merge details line with main line (i.e. which contains file path)
549
- const infos = await Promise.all(tscErrorStdout.split(newLineRegExp).reduce((prev, next) => {
550
- if (!next) return prev;
551
- else if (!next.startsWith(" ")) prev.push(next);
552
- else prev[prev.length - 1] += `\n${next}`;
553
- return prev;
554
- }, []).map((errInfoLine) => makeTscErrorInfo(errInfoLine)));
555
- infos.forEach(([errFilePath, errInfo]) => {
556
- if (!errInfo) return;
557
- if (!rawErrsMap.has(errFilePath)) rawErrsMap.set(errFilePath, [errInfo]);
558
- else rawErrsMap.get(errFilePath)?.push(errInfo);
559
- });
560
- return rawErrsMap;
561
- }
562
-
563
- function createIndexMap(source) {
564
- const map = /* @__PURE__ */ new Map();
565
- let index = 0;
566
- let line = 1;
567
- let column = 1;
568
- for (const char of source) {
569
- map.set(`${line}:${column}`, index++);
570
- if (char === "\n" || char === "\r\n") {
571
- line++;
572
- column = 0;
573
- } else column++;
574
- }
575
- return map;
576
- }
577
-
578
- class TypeCheckError extends Error {
579
- name = "TypeCheckError";
580
- constructor(message, stacks) {
581
- super(message);
582
- this.message = message;
583
- this.stacks = stacks;
584
- }
585
- }
586
- class Typechecker {
587
- _onParseStart;
588
- _onParseEnd;
589
- _onWatcherRerun;
590
- _result = {
591
- files: [],
592
- sourceErrors: [],
593
- time: 0
594
- };
595
- _startTime = 0;
596
- _output = "";
597
- _tests = {};
598
- process;
599
- files = [];
600
- constructor(project) {
601
- this.project = project;
602
- }
603
- setFiles(files) {
604
- this.files = files;
605
- }
606
- onParseStart(fn) {
607
- this._onParseStart = fn;
608
- }
609
- onParseEnd(fn) {
610
- this._onParseEnd = fn;
611
- }
612
- onWatcherRerun(fn) {
613
- this._onWatcherRerun = fn;
614
- }
615
- async collectFileTests(filepath) {
616
- return collectTests(this.project, filepath);
617
- }
618
- getFiles() {
619
- return this.files;
620
- }
621
- async collectTests() {
622
- const tests = (await Promise.all(this.getFiles().map((filepath) => this.collectFileTests(filepath)))).reduce((acc, data) => {
623
- if (!data) return acc;
624
- acc[data.filepath] = data;
625
- return acc;
626
- }, {});
627
- this._tests = tests;
628
- return tests;
629
- }
630
- markPassed(file) {
631
- if (!file.result?.state) file.result = { state: "pass" };
632
- const markTasks = (tasks) => {
633
- for (const task of tasks) {
634
- if ("tasks" in task) markTasks(task.tasks);
635
- if (!task.result?.state && (task.mode === "run" || task.mode === "queued")) task.result = { state: "pass" };
636
- }
637
- };
638
- markTasks(file.tasks);
639
- }
640
- async prepareResults(output) {
641
- const typeErrors = await this.parseTscLikeOutput(output);
642
- const testFiles = new Set(this.getFiles());
643
- if (!this._tests) this._tests = await this.collectTests();
644
- const sourceErrors = [];
645
- const files = [];
646
- testFiles.forEach((path) => {
647
- const { file, definitions, map, parsed } = this._tests[path];
648
- const errors = typeErrors.get(path);
649
- files.push(file);
650
- if (!errors) {
651
- this.markPassed(file);
652
- return;
653
- }
654
- const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)];
655
- // has no map for ".js" files that use // @ts-check
656
- const traceMap = map && new TraceMap(map);
657
- const indexMap = createIndexMap(parsed);
658
- const markState = (task, state) => {
659
- task.result = { state: task.mode === "run" || task.mode === "only" ? state : task.mode };
660
- if (task.suite) markState(task.suite, state);
661
- else if (task.file && task !== task.file) markState(task.file, state);
662
- };
663
- errors.forEach(({ error, originalError }) => {
664
- const processedPos = traceMap ? findGeneratedPosition(traceMap, {
665
- line: originalError.line,
666
- column: originalError.column,
667
- source: basename(path)
668
- }) : originalError;
669
- const line = processedPos.line ?? originalError.line;
670
- const column = processedPos.column ?? originalError.column;
671
- const index = indexMap.get(`${line}:${column}`);
672
- const definition = index != null && sortedDefinitions.find((def) => def.start <= index && def.end >= index);
673
- const suite = definition ? definition.task : file;
674
- const state = suite.mode === "run" || suite.mode === "only" ? "fail" : suite.mode;
675
- const errors = suite.result?.errors || [];
676
- suite.result = {
677
- state,
678
- errors
679
- };
680
- errors.push(error);
681
- if (state === "fail") {
682
- if (suite.suite) markState(suite.suite, "fail");
683
- else if (suite.file && suite !== suite.file) markState(suite.file, "fail");
684
- }
685
- });
686
- this.markPassed(file);
687
- });
688
- typeErrors.forEach((errors, path) => {
689
- if (!testFiles.has(path)) sourceErrors.push(...errors.map(({ error }) => error));
690
- });
691
- return {
692
- files,
693
- sourceErrors,
694
- time: performance.now() - this._startTime
695
- };
696
- }
697
- async parseTscLikeOutput(output) {
698
- const errorsMap = await getRawErrsMapFromTsCompile(output);
699
- const typesErrors = /* @__PURE__ */ new Map();
700
- errorsMap.forEach((errors, path) => {
701
- const filepath = resolve(this.project.config.root, path);
702
- const suiteErrors = errors.map((info) => {
703
- const limit = Error.stackTraceLimit;
704
- Error.stackTraceLimit = 0;
705
- // Some expect-type errors have the most useful information on the second line e.g. `This expression is not callable.\n Type 'ExpectString<number>' has no call signatures.`
706
- const errMsg = info.errMsg.replace(/\r?\n\s*(Type .* has no call signatures)/g, " $1");
707
- const error = new TypeCheckError(errMsg, [{
708
- file: filepath,
709
- line: info.line,
710
- column: info.column,
711
- method: ""
712
- }]);
713
- Error.stackTraceLimit = limit;
714
- return {
715
- originalError: info,
716
- error: {
717
- name: error.name,
718
- message: errMsg,
719
- stacks: error.stacks,
720
- stack: ""
721
- }
722
- };
723
- });
724
- typesErrors.set(filepath, suiteErrors);
725
- });
726
- return typesErrors;
727
- }
728
- async stop() {
729
- this.process?.kill();
730
- this.process = void 0;
731
- }
732
- async ensurePackageInstalled(ctx, checker) {
733
- if (checker !== "tsc" && checker !== "vue-tsc") return;
734
- const packageName = checker === "tsc" ? "typescript" : "vue-tsc";
735
- await ctx.packageInstaller.ensureInstalled(packageName, ctx.config.root);
736
- }
737
- getExitCode() {
738
- return this.process?.exitCode != null && this.process.exitCode;
739
- }
740
- getOutput() {
741
- return this._output;
742
- }
743
- async spawn() {
744
- const { root, watch, typecheck } = this.project.config;
745
- const args = [
746
- "--noEmit",
747
- "--pretty",
748
- "false",
749
- "--incremental",
750
- "--tsBuildInfoFile",
751
- join(process.versions.pnp ? join(nodeos__default.tmpdir(), this.project.hash) : distDir, "tsconfig.tmp.tsbuildinfo")
752
- ];
753
- // use builtin watcher because it's faster
754
- if (watch) args.push("--watch");
755
- if (typecheck.allowJs) args.push("--allowJs", "--checkJs");
756
- if (typecheck.tsconfig) args.push("-p", resolve(root, typecheck.tsconfig));
757
- this._output = "";
758
- this._startTime = performance.now();
759
- const child = x(typecheck.checker, args, {
760
- nodeOptions: {
761
- cwd: root,
762
- stdio: "pipe"
763
- },
764
- throwOnError: false
765
- });
766
- this.process = child.process;
767
- let rerunTriggered = false;
768
- let dataReceived = false;
769
- return new Promise((resolve, reject) => {
770
- if (!child.process || !child.process.stdout) {
771
- reject(new Error(`Failed to initialize ${typecheck.checker}. This is a bug in Vitest - please, open an issue with reproduction.`));
772
- return;
773
- }
774
- child.process.stdout.on("data", (chunk) => {
775
- dataReceived = true;
776
- this._output += chunk;
777
- if (!watch) return;
778
- if (this._output.includes("File change detected") && !rerunTriggered) {
779
- this._onWatcherRerun?.();
780
- this._startTime = performance.now();
781
- this._result.sourceErrors = [];
782
- this._result.files = [];
783
- this._tests = null;
784
- rerunTriggered = true;
785
- }
786
- if (/Found \w+ errors*. Watching for/.test(this._output)) {
787
- rerunTriggered = false;
788
- this.prepareResults(this._output).then((result) => {
789
- this._result = result;
790
- this._onParseEnd?.(result);
791
- });
792
- this._output = "";
793
- }
794
- });
795
- const timeout = setTimeout(() => reject(new Error(`${typecheck.checker} spawn timed out`)), this.project.config.typecheck.spawnTimeout);
796
- function onError(cause) {
797
- clearTimeout(timeout);
798
- reject(new Error("Spawning typechecker failed - is typescript installed?", { cause }));
799
- }
800
- child.process.once("spawn", () => {
801
- this._onParseStart?.();
802
- child.process?.off("error", onError);
803
- clearTimeout(timeout);
804
- if (process.platform === "win32")
805
- // on Windows, the process might be spawned but fail to start
806
- // we wait for a potential error here. if "close" event didn't trigger,
807
- // we resolve the promise
808
- setTimeout(() => {
809
- resolve({ result: child });
810
- }, 200);
811
- else resolve({ result: child });
812
- });
813
- if (process.platform === "win32") child.process.once("close", (code) => {
814
- if (code != null && code !== 0 && !dataReceived) onError(new Error(`The ${typecheck.checker} command exited with code ${code}.`));
815
- });
816
- child.process.once("error", onError);
817
- });
818
- }
819
- async start() {
820
- if (this.process) return;
821
- const { watch } = this.project.config;
822
- const { result: child } = await this.spawn();
823
- if (!watch) {
824
- await child;
825
- this._result = await this.prepareResults(this._output);
826
- await this._onParseEnd?.(this._result);
827
- }
828
- }
829
- getResult() {
830
- return this._result;
831
- }
832
- getTestFiles() {
833
- return Object.values(this._tests || {}).map((i) => i.file);
834
- }
835
- getTestPacksAndEvents() {
836
- const packs = [];
837
- const events = [];
838
- for (const { file } of Object.values(this._tests || {})) {
839
- const result = convertTasksToEvents(file);
840
- packs.push(...result.packs);
841
- events.push(...result.events);
842
- }
843
- return {
844
- packs,
845
- events
846
- };
847
- }
848
- }
849
- function findGeneratedPosition(traceMap, { line, column, source }) {
850
- const found = generatedPositionFor(traceMap, {
851
- line,
852
- column,
853
- source
854
- });
855
- if (found.line !== null) return found;
856
- // find the next source token position when the exact error position doesn't exist in source map.
857
- // this can happen, for example, when the type error is in the comment "// @ts-expect-error"
858
- // and comments are stripped away in the generated code.
859
- const mappings = [];
860
- eachMapping(traceMap, (m) => {
861
- if (m.source === source && m.originalLine !== null && m.originalColumn !== null && (line === m.originalLine ? column < m.originalColumn : line < m.originalLine)) mappings.push(m);
862
- });
863
- const next = mappings.sort((a, b) => a.originalLine === b.originalLine ? a.originalColumn - b.originalColumn : a.originalLine - b.originalLine).at(0);
864
- if (next) return {
865
- line: next.generatedLine,
866
- column: next.generatedColumn
867
- };
868
- return {
869
- line: null,
870
- column: null
871
- };
872
- }
873
-
874
- export { TypeCheckError as T, Typechecker as a, convertTasksToEvents as c, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };