vitest 0.0.112 → 0.0.116

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.
package/dist/entry.js CHANGED
@@ -1,19 +1,21 @@
1
1
  import fs, { promises } from 'fs';
2
- import { f as equals, h as iterableEquality, j as subsetEquality, k as isA, J as JestChaiExpect, l as clearContext, m as defaultSuite, n as setHooks, o as getHooks, p as context, s as setState, q as getFn, b as getState, e as vi } from './vi-cb9e4e4e.js';
2
+ import { f as equals, h as iterableEquality, j as subsetEquality, k as isA, J as JestChaiExpect, l as clearContext, m as defaultSuite, n as setHooks, o as getHooks, p as context, s as setState, q as getFn, b as getState, e as vi } from './vi-b3412f83.js';
3
3
  import { Console } from 'console';
4
4
  import { Writable } from 'stream';
5
5
  import { importModule } from 'local-pkg';
6
6
  import chai$1, { expect, util } from 'chai';
7
7
  import { a as commonjsRequire, c as commonjsGlobal } from './_commonjsHelpers-c9e3b764.js';
8
- import { l as index, o as getNames, c as c$1, t as toArray, r as relative, p as interpretOnlyMode, q as partitionSuiteChildren, u as hasTests, j as hasFailed } from './utils-cb6b1266.js';
9
- import { r as rpc, s as send } from './rpc-7de86f29.js';
10
- import { u as unifiedDiff } from './diff-66d6bb83.js';
8
+ import { q as index, s as slash, u as getNames, c as c$1, t as toArray, r as relative, v as interpretOnlyMode, w as partitionSuiteChildren, x as hasTests, h as hasFailed } from './index-bf29f0e6.js';
9
+ import { r as rpc } from './rpc-8c7cc374.js';
10
+ import { l as getOriginalPos, m as posToNumber, n as parseStack, u as unifiedDiff } from './diff-80c47cfa.js';
11
11
  import { performance } from 'perf_hooks';
12
- import { n as nanoid } from './jest-mock-a57b745c.js';
12
+ import { createHash } from 'crypto';
13
13
  import { format as format$1 } from 'util';
14
+ import './jest-mock-4a754991.js';
15
+ import 'tinyspy';
16
+ import 'url';
14
17
  import 'tty';
15
18
  import 'path';
16
- import 'tinyspy';
17
19
 
18
20
  var node = {
19
21
  name: "node",
@@ -382,6 +384,47 @@ var chaiSubset = {exports: {}};
382
384
 
383
385
  var Subset = chaiSubset.exports;
384
386
 
387
+ async function saveInlineSnapshots(snapshots) {
388
+ const MagicString = (await import('./magic-string.es-94000aea.js')).default;
389
+ const files = new Set(snapshots.map((i) => i.file));
390
+ await Promise.all(Array.from(files).map(async (file) => {
391
+ const map = await rpc().getSourceMap(file);
392
+ const snaps = snapshots.filter((i) => i.file === file);
393
+ const code = await promises.readFile(file, "utf8");
394
+ const s = new MagicString(code);
395
+ for (const snap of snaps) {
396
+ const pos = await getOriginalPos(map, snap);
397
+ const index = posToNumber(code, pos);
398
+ replaceInlineSnap(code, s, index, snap.snapshot);
399
+ }
400
+ const transformed = s.toString();
401
+ if (transformed !== code)
402
+ await promises.writeFile(file, transformed, "utf-8");
403
+ }));
404
+ }
405
+ const startRegex = /toMatchInlineSnapshot\s*\(\s*(['"`\)])/m;
406
+ function replaceInlineSnap(code, s, index, newSnap, indent = "") {
407
+ const startMatch = startRegex.exec(code.slice(index));
408
+ if (!startMatch)
409
+ return false;
410
+ newSnap = newSnap.replace(/\\/g, "\\\\").split("\n").map((i) => (indent + i).trimEnd()).join("\n");
411
+ const isOneline = !newSnap.includes("\n");
412
+ const snapString = isOneline ? `'${newSnap.replace(/'/g, "\\'").trim()}'` : `\`${newSnap.replace(/`/g, "\\`").trimEnd()}\``;
413
+ const quote = startMatch[1];
414
+ const startIndex = index + startMatch.index + startMatch[0].length;
415
+ if (quote === ")") {
416
+ s.appendRight(startIndex - 1, snapString);
417
+ return true;
418
+ }
419
+ const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`);
420
+ const endMatch = quoteEndRE.exec(code.slice(startIndex));
421
+ if (!endMatch)
422
+ return false;
423
+ const endIndex = startIndex + endMatch.index + endMatch[0].length;
424
+ s.overwrite(startIndex - 1, endIndex, snapString);
425
+ return true;
426
+ }
427
+
385
428
  var naturalCompare$2 = {exports: {}};
386
429
 
387
430
  /*
@@ -2830,13 +2873,13 @@ function ensureDirectoryExists(filePath) {
2830
2873
  function normalizeNewlines(string) {
2831
2874
  return string.replace(/\r\n|\r/g, "\n");
2832
2875
  }
2833
- function saveSnapshotFile(snapshotData, snapshotPath) {
2876
+ async function saveSnapshotFile(snapshotData, snapshotPath) {
2834
2877
  const snapshots = Object.keys(snapshotData).sort(naturalCompare$1).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
2835
2878
  ensureDirectoryExists(snapshotPath);
2836
- fs.writeFileSync(snapshotPath, `${writeSnapshotVersion()}
2879
+ await promises.writeFile(snapshotPath, `${writeSnapshotVersion()}
2837
2880
 
2838
2881
  ${snapshots.join("\n\n")}
2839
- `);
2882
+ `, "utf-8");
2840
2883
  }
2841
2884
 
2842
2885
  var __defProp$1 = Object.defineProperty;
@@ -2862,6 +2905,7 @@ class SnapshotState {
2862
2905
  this._initialData = data;
2863
2906
  this._snapshotData = data;
2864
2907
  this._dirty = dirty;
2908
+ this._inlineSnapshots = [];
2865
2909
  this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
2866
2910
  this._counters = /* @__PURE__ */ new Map();
2867
2911
  this._index = 0;
@@ -2883,7 +2927,20 @@ class SnapshotState {
2883
2927
  }
2884
2928
  _addSnapshot(key, receivedSerialized, options) {
2885
2929
  this._dirty = true;
2886
- this._snapshotData[key] = receivedSerialized;
2930
+ if (options.isInline) {
2931
+ const error = options.error || new Error("Unknown error");
2932
+ const stacks = parseStack(error.stack || "");
2933
+ stacks.forEach((i) => i.file = slash(i.file));
2934
+ const stack = stacks.find((i) => process.__vitest_worker__.ctx.files.includes(i.file));
2935
+ if (!stack) {
2936
+ throw new Error("Vitest: Couldn't infer stack frame for inline snapshot.");
2937
+ }
2938
+ this._inlineSnapshots.push(__spreadValues$1({
2939
+ snapshot: receivedSerialized
2940
+ }, stack));
2941
+ } else {
2942
+ this._snapshotData[key] = receivedSerialized;
2943
+ }
2887
2944
  }
2888
2945
  clear() {
2889
2946
  this._snapshotData = this._initialData;
@@ -2894,16 +2951,19 @@ class SnapshotState {
2894
2951
  this.unmatched = 0;
2895
2952
  this.updated = 0;
2896
2953
  }
2897
- save() {
2954
+ async save() {
2898
2955
  const hasExternalSnapshots = Object.keys(this._snapshotData).length;
2899
- const isEmpty = !hasExternalSnapshots;
2956
+ const hasInlineSnapshots = this._inlineSnapshots.length;
2957
+ const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
2900
2958
  const status = {
2901
2959
  deleted: false,
2902
2960
  saved: false
2903
2961
  };
2904
2962
  if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
2905
2963
  if (hasExternalSnapshots)
2906
- saveSnapshotFile(this._snapshotData, this._snapshotPath);
2964
+ await saveSnapshotFile(this._snapshotData, this._snapshotPath);
2965
+ if (hasInlineSnapshots)
2966
+ await saveInlineSnapshots(this._inlineSnapshots);
2907
2967
  status.saved = true;
2908
2968
  } else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) {
2909
2969
  if (this._updateSnapshot === "all")
@@ -3019,7 +3079,7 @@ class SnapshotClient {
3019
3079
  clearTest() {
3020
3080
  this.test = void 0;
3021
3081
  }
3022
- assert(received, message, inlineSnapshot) {
3082
+ assert(received, message, isInline = false, inlineSnapshot) {
3023
3083
  if (!this.test)
3024
3084
  throw new Error("Snapshot cannot be used outside of test");
3025
3085
  const testName = [
@@ -3029,7 +3089,7 @@ class SnapshotClient {
3029
3089
  const { actual, expected, key, pass } = this.snapshotState.match({
3030
3090
  testName,
3031
3091
  received,
3032
- isInline: !!inlineSnapshot,
3092
+ isInline,
3033
3093
  inlineSnapshot: inlineSnapshot == null ? void 0 : inlineSnapshot.trim()
3034
3094
  });
3035
3095
  if (!pass) {
@@ -3044,13 +3104,13 @@ class SnapshotClient {
3044
3104
  async saveSnap() {
3045
3105
  if (!this.testFile || !this.snapshotState)
3046
3106
  return;
3047
- const result = packSnapshotState(this.testFile, this.snapshotState);
3048
- await rpc("snapshotSaved", result);
3107
+ const result = await packSnapshotState(this.testFile, this.snapshotState);
3108
+ await rpc().snapshotSaved(result);
3049
3109
  this.testFile = "";
3050
3110
  this.snapshotState = void 0;
3051
3111
  }
3052
3112
  }
3053
- function packSnapshotState(filepath, state) {
3113
+ async function packSnapshotState(filepath, state) {
3054
3114
  const snapshot = {
3055
3115
  filepath,
3056
3116
  added: 0,
@@ -3065,7 +3125,7 @@ function packSnapshotState(filepath, state) {
3065
3125
  const uncheckedKeys = state.getUncheckedKeys();
3066
3126
  if (uncheckedCount)
3067
3127
  state.removeUncheckedKeys();
3068
- const status = state.save();
3128
+ const status = await state.save();
3069
3129
  snapshot.fileDeleted = status.deleted;
3070
3130
  snapshot.added = state.added;
3071
3131
  snapshot.matched = state.matched;
@@ -3091,7 +3151,7 @@ const SnapshotPlugin = (chai, utils) => {
3091
3151
  }
3092
3152
  utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function(inlineSnapshot, message) {
3093
3153
  const expected = utils.flag(this, "object");
3094
- getSnapshotClient().assert(expected, message, inlineSnapshot);
3154
+ getSnapshotClient().assert(expected, message, true, inlineSnapshot);
3095
3155
  });
3096
3156
  };
3097
3157
 
@@ -3472,13 +3532,13 @@ async function setupGlobalEnv(config) {
3472
3532
  setupConsoleLogSpy();
3473
3533
  await setupChai();
3474
3534
  if (config.global)
3475
- (await import('./global-201fd559.js')).registerApiGlobally();
3535
+ (await import('./global-a73dfade.js')).registerApiGlobally();
3476
3536
  }
3477
3537
  function setupConsoleLogSpy() {
3478
3538
  const stdout = new Writable({
3479
3539
  write(data, encoding, callback) {
3480
3540
  var _a;
3481
- send("log", {
3541
+ rpc().onUserLog({
3482
3542
  type: "stdout",
3483
3543
  content: String(data),
3484
3544
  taskId: (_a = process.__vitest_worker__.current) == null ? void 0 : _a.id
@@ -3489,7 +3549,7 @@ function setupConsoleLogSpy() {
3489
3549
  const stderr = new Writable({
3490
3550
  write(data, encoding, callback) {
3491
3551
  var _a;
3492
- send("log", {
3552
+ rpc().onUserLog({
3493
3553
  type: "stderr",
3494
3554
  content: String(data),
3495
3555
  taskId: (_a = process.__vitest_worker__.current) == null ? void 0 : _a.id
@@ -3520,21 +3580,24 @@ async function runSetupFiles(config) {
3520
3580
  }));
3521
3581
  }
3522
3582
 
3523
- function serializeError(val) {
3583
+ function serializeError(val, seen = /* @__PURE__ */ new WeakSet()) {
3524
3584
  if (!val || typeof val === "string")
3525
3585
  return val;
3526
3586
  if (typeof val === "function")
3527
3587
  return `Function<${val.name}>`;
3528
3588
  if (typeof val !== "object")
3529
3589
  return val;
3530
- if (val instanceof Promise || "then" in val)
3590
+ if (val instanceof Promise || "then" in val || val.constructor && val.constructor.prototype === "AsyncFunction")
3531
3591
  return "Promise";
3532
3592
  if (typeof Element !== "undefined" && val instanceof Element)
3533
3593
  return val.tagName;
3534
3594
  if (typeof val.asymmetricMatch === "function")
3535
3595
  return `${val.toString()} ${format$1(val.sample)}`;
3596
+ if (seen.has(val))
3597
+ return val;
3598
+ seen.add(val);
3536
3599
  Object.keys(val).forEach((key) => {
3537
- val[key] = serializeError(val[key]);
3600
+ val[key] = serializeError(val[key], seen);
3538
3601
  });
3539
3602
  return val;
3540
3603
  }
@@ -3552,12 +3615,16 @@ function processError(err) {
3552
3615
  return serializeError(err);
3553
3616
  }
3554
3617
 
3618
+ function hash(str, length = 10) {
3619
+ return createHash("md5").update(str).digest("hex").slice(0, length);
3620
+ }
3555
3621
  async function collectTests(paths, config) {
3556
3622
  const files = [];
3557
3623
  for (const filepath of paths) {
3624
+ const path = relative(config.root, filepath);
3558
3625
  const file = {
3559
- id: nanoid(),
3560
- name: relative(config.root, filepath),
3626
+ id: hash(path),
3627
+ name: path,
3561
3628
  type: "suite",
3562
3629
  mode: "run",
3563
3630
  computeMode: "serial",
@@ -3589,12 +3656,20 @@ async function collectTests(paths, config) {
3589
3656
  };
3590
3657
  process.stdout.write("\0");
3591
3658
  }
3659
+ calculateHash(file);
3592
3660
  files.push(file);
3593
3661
  }
3594
3662
  const tasks = files.reduce((tasks2, file) => tasks2.concat(file.tasks), []);
3595
3663
  interpretOnlyMode(tasks);
3596
3664
  return files;
3597
3665
  }
3666
+ function calculateHash(parent) {
3667
+ parent.tasks.forEach((t, idx) => {
3668
+ t.id = `${parent.id}_${idx}`;
3669
+ if (t.type === "suite")
3670
+ calculateHash(t);
3671
+ });
3672
+ }
3598
3673
 
3599
3674
  async function callSuiteHook(suite, name, args) {
3600
3675
  if (name === "beforeEach" && suite.suite)
@@ -3603,8 +3678,24 @@ async function callSuiteHook(suite, name, args) {
3603
3678
  if (name === "afterEach" && suite.suite)
3604
3679
  await callSuiteHook(suite.suite, name, args);
3605
3680
  }
3681
+ const packs = [];
3682
+ let updateTimer;
3683
+ let previousUpdate;
3606
3684
  function updateTask(task) {
3607
- return rpc("onTaskUpdate", [task.id, task.result]);
3685
+ packs.push([task.id, task.result]);
3686
+ clearTimeout(updateTimer);
3687
+ updateTimer = setTimeout(() => {
3688
+ previousUpdate = sendTasksUpdate();
3689
+ }, 10);
3690
+ }
3691
+ async function sendTasksUpdate() {
3692
+ clearTimeout(updateTimer);
3693
+ await previousUpdate;
3694
+ if (packs.length) {
3695
+ const p = rpc().onTaskUpdate(packs);
3696
+ packs.length = 0;
3697
+ return p;
3698
+ }
3608
3699
  }
3609
3700
  async function runTest(test) {
3610
3701
  if (test.mode !== "run")
@@ -3703,9 +3794,10 @@ async function runSuites(suites) {
3703
3794
  }
3704
3795
  async function startTests(paths, config) {
3705
3796
  const files = await collectTests(paths, config);
3706
- send("onCollected", files);
3797
+ rpc().onCollected(files);
3707
3798
  await runSuites(files);
3708
3799
  await getSnapshotClient().saveSnap();
3800
+ await sendTasksUpdate();
3709
3801
  }
3710
3802
  function clearModuleMocks() {
3711
3803
  const { clearMocks, mockReset, restoreMocks } = process.__vitest_worker__.config;
@@ -1,15 +1,15 @@
1
- import { g as globalApis } from './constants-2b0310b7.js';
2
- import { i as index } from './index-2bb9fd4d.js';
1
+ import { g as globalApis } from './constants-080f26e8.js';
2
+ import { i as index } from './index-80d9a771.js';
3
3
  import 'url';
4
- import './utils-cb6b1266.js';
4
+ import './index-bf29f0e6.js';
5
5
  import 'tty';
6
6
  import 'local-pkg';
7
7
  import 'path';
8
- import './vi-cb9e4e4e.js';
9
- import './jest-mock-a57b745c.js';
8
+ import './vi-b3412f83.js';
9
+ import './_commonjsHelpers-c9e3b764.js';
10
+ import './jest-mock-4a754991.js';
10
11
  import 'chai';
11
12
  import 'tinyspy';
12
- import './_commonjsHelpers-c9e3b764.js';
13
13
 
14
14
  function registerApiGlobally() {
15
15
  globalApis.forEach((api) => {