@vitest-agent/plugin 6.1.0 → 6.2.0

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/index.d.ts CHANGED
@@ -569,6 +569,14 @@ interface AgentReporterConstructorOptions extends AgentReporterOptions {
569
569
  consoleMode?: ConsoleMode;
570
570
  mcp?: boolean;
571
571
  githubActions?: boolean;
572
+ /**
573
+ * The sync filesystem the module cache directory is read through (issue
574
+ * #741). Defaults to `@effected/walker`'s `nodeWalkerSyncOps`; tests pass a
575
+ * virtual volume.
576
+ *
577
+ * @internal
578
+ */
579
+ moduleCacheOps?: WalkerSyncOps$1;
572
580
  /**
573
581
  * The `.vitest/<scope>` directory name for `report`-targeted rendered
574
582
  * output. Undefined disables report files.
@@ -690,6 +698,13 @@ export declare class AgentReporter {
690
698
  * fired (tests invoking `onTestRunEnd` directly).
691
699
  */
692
700
  private runStartedAt;
701
+ /**
702
+ * `Date.now()` at this run's `onTestRunStart`: the cutoff for counting the
703
+ * module cache entries the run wrote (issue #741).
704
+ */
705
+ private runStartedAtEpoch;
706
+ /** The sync filesystem the module cache directory is read through. */
707
+ private readonly moduleCacheOps;
693
708
  /**
694
709
  * Stored Vitest instance from {@link AgentReporter.onInit | onInit}.
695
710
  *
@@ -1200,6 +1215,8 @@ export declare class AgentReporter {
1200
1215
  * files changed.
1201
1216
  */
1202
1217
  onWatcherRerun(files: ReadonlyArray<string>, trigger?: string): void;
1218
+ /** The Vitest project root, when the stashed Vitest instance exposes one. */
1219
+ private vitestRoot;
1203
1220
  private ensureDbPath;
1204
1221
  /**
1205
1222
  * Stash coverage data for merging into reports.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitest-agent/plugin",
3
- "version": "6.1.0",
3
+ "version": "6.2.0",
4
4
  "private": false,
5
5
  "description": "Vitest plugin for the vitest-agent ecosystem: owns persistence, classification, baselines, trends, and dispatches rendering to a configurable reporter.",
6
6
  "keywords": [
@@ -49,12 +49,12 @@
49
49
  "@effected/env": "0.12.0",
50
50
  "@effected/glob": "0.23.0",
51
51
  "@effected/walker": "0.30.0",
52
- "@effected/workspaces": "0.48.2",
53
- "@vitest-agent/cli": "4.1.18",
54
- "@vitest-agent/engine": "3.3.0",
55
- "@vitest-agent/mcp": "6.2.0",
56
- "@vitest-agent/reporter": "6.1.12",
57
- "@vitest-agent/sdk": "9.1.0",
52
+ "@effected/workspaces": "0.49.1",
53
+ "@vitest-agent/cli": "4.1.20",
54
+ "@vitest-agent/engine": "3.4.0",
55
+ "@vitest-agent/mcp": "6.3.0",
56
+ "@vitest-agent/reporter": "6.2.0",
57
+ "@vitest-agent/sdk": "9.2.0",
58
58
  "effect": "4.1.5",
59
59
  "magic-string": "^1.4.5"
60
60
  },
package/reporter.js CHANGED
@@ -4,7 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
4
4
  import { RuntimeEnv } from "@effected/env";
5
5
  import { ConfigLive, DataReader, DataStore, DetailResolver, EnvironmentDetector, ExecutorResolver, HistoryTracker, OutputPipelineLive, PathResolutionLive, VitestAgentConfigFile, ensureMigrated, formatFatalError, historyKey, probeHostMetadataFromEnv, resolveDataPath, resolveLogFile, resolveLogLevel, withPersistTransaction } from "@vitest-agent/engine";
6
6
  import { DefaultVitestAgentReporter } from "@vitest-agent/reporter";
7
- import { RunRetentionPolicy, VitestAgentConfig, buildAgentReport, coerceErrorField, computeTrend, finalAttemptErrors, isTimeoutError, suggestedActionsFromRunDiagnostics } from "@vitest-agent/sdk";
7
+ import { RunRetentionPolicy, VitestAgentConfig, buildAgentReport, coerceErrorField, computeTrend, finalAttemptErrors, isTimeoutError, normalizeTraceSteps, suggestedActionsFromRunDiagnostics } from "@vitest-agent/sdk";
8
8
  import { Effect, Option, PubSub } from "effect";
9
9
  import { SecureRandom } from "effect/crypto";
10
10
  import { CoverageAnalyzerLive } from "./layers/CoverageAnalyzerLive.js";
@@ -16,6 +16,7 @@ import { captureSettings, hashSettings } from "./utils/capture-settings.js";
16
16
  import { collectPerformanceHints } from "./utils/collect-performance-hints.js";
17
17
  import { formatFailureSummary, shouldWriteFailureSummary } from "./utils/failure-summary.js";
18
18
  import { isPartialRun } from "./utils/is-partial-run.js";
19
+ import { collectModuleCacheStats } from "./utils/module-cache-stats.js";
19
20
  import { processFailure } from "./utils/process-failure.js";
20
21
  import { assertReportCapable, createReportWriter } from "./utils/report-writer.js";
21
22
  import { resolveNoColor } from "./utils/resolve-no-color.js";
@@ -56,6 +57,19 @@ const withStrayOutput = (reports, strayOutput) => strayOutput === void 0 ? repor
56
57
  strayOutput
57
58
  }));
58
59
  /**
60
+ * One project's module cache stat on its report (issue #741). The reporter
61
+ * groups an unnamed Vitest project under `"default"`; the stats are keyed by
62
+ * Vitest's own name for it (`""`).
63
+ */
64
+ const moduleCacheOf = (projectName, stats) => stats.get(projectName) ?? (projectName === "default" ? stats.get("") : void 0);
65
+ const withModuleCache = (report, projectName, stats) => {
66
+ const stat = moduleCacheOf(projectName, stats);
67
+ return stat === void 0 ? report : {
68
+ ...report,
69
+ moduleCache: stat
70
+ };
71
+ };
72
+ /**
59
73
  * Safely read a raw Vitest error object's `stacks` array. The property
60
74
  * access itself can throw on hostile shapes (live getters — the same
61
75
  * ConfigError class of failure `coerceErrorField` guards); frames are
@@ -212,6 +226,94 @@ const toAttachmentInputs = (attachments) => attachments.map(toAttachmentInput);
212
226
  */
213
227
  const toAttachmentDescriptors = (attachments) => toAttachmentInputs(attachments).map(({ body: _body, bodyEncoding: _bodyEncoding, ...descriptor }) => descriptor);
214
228
  /**
229
+ * Read `TestCase.attempts()` (Vitest 5.1+) defensively: a missing method (an
230
+ * older Vitest), a throwing getter or a malformed entry yields no row rather
231
+ * than failing the run's persistence.
232
+ * @internal
233
+ */
234
+ const readAttemptRows = (testCase) => {
235
+ let raw = [];
236
+ try {
237
+ const attempts = testCase.attempts?.();
238
+ if (Array.isArray(attempts)) raw = attempts;
239
+ } catch {
240
+ return [];
241
+ }
242
+ const rows = [];
243
+ for (const entry of raw) try {
244
+ const a = entry;
245
+ if (a.state !== "passed" && a.state !== "failed" && a.state !== "skipped") continue;
246
+ if (typeof a.retryIndex !== "number" || typeof a.repeatIndex !== "number") continue;
247
+ rows.push({
248
+ input: {
249
+ retryIndex: a.retryIndex,
250
+ repeatIndex: a.repeatIndex,
251
+ state: a.state,
252
+ ...typeof a.duration === "number" && Number.isFinite(a.duration) && { duration: a.duration },
253
+ ...typeof a.startTime === "number" && Number.isFinite(a.startTime) && { startTime: a.startTime }
254
+ },
255
+ errors: Array.isArray(a.errors) ? a.errors : []
256
+ });
257
+ } catch {}
258
+ return rows;
259
+ };
260
+ /**
261
+ * Which attempt raised `error`: by object identity (Vitest slices each
262
+ * attempt's errors out of the test result's list), else by message (the last matching attempt, since retries
263
+ * usually repeat one message and the final attempt is the one reported) for
264
+ * a result that crossed a serialization boundary.
265
+ * @internal
266
+ */
267
+ const attemptIndexForError = (rows, error, message) => {
268
+ const byIdentity = rows.findIndex((r) => r.errors.includes(error));
269
+ if (byIdentity !== -1) return byIdentity;
270
+ const byMessage = rows.findLastIndex((r) => r.errors.some((e) => coerceErrorField(e, "message") === message));
271
+ return byMessage === -1 ? void 0 : byMessage;
272
+ };
273
+ /**
274
+ * Read the Vitest 5.1 trace-timeline steps (`internal:browserTrace`
275
+ * artifacts, `experimental.traceTimeline`) of a failed test's deciding attempt.
276
+ *
277
+ * @remarks
278
+ * Only a failed test reports steps: a test that passed on a retry still holds
279
+ * the failed attempt's trace artifact, but its failure is not reported. The
280
+ * deciding attempt is the last one that recorded errors (the one
281
+ * `finalAttemptErrors` reports); without `attempts()` the last attempt a
282
+ * trace exists for is used. `artifact.data` is experimental and typed
283
+ * `unknown`, so every read is guarded: anything unreadable yields no steps and
284
+ * never fails the caller. This is a read-only carve-out of the one
285
+ * `internal:` type; the artifact itself is never persisted to `test_artifacts`.
286
+ * @internal
287
+ */
288
+ const traceStepsOf = (testCase, rows, root) => {
289
+ try {
290
+ const tc = testCase;
291
+ if (tc.result?.()?.state !== "failed") return {
292
+ steps: [],
293
+ attemptIndex: void 0
294
+ };
295
+ const artifacts = tc.artifacts?.();
296
+ if (!Array.isArray(artifacts)) return {
297
+ steps: [],
298
+ attemptIndex: void 0
299
+ };
300
+ const decided = rows.findLastIndex((r) => r.errors.length > 0);
301
+ const row = decided === -1 ? void 0 : rows[decided];
302
+ return {
303
+ steps: normalizeTraceSteps(artifacts, row === void 0 ? void 0 : {
304
+ retryIndex: row.input.retryIndex,
305
+ repeatIndex: row.input.repeatIndex
306
+ }, root),
307
+ attemptIndex: row === void 0 ? void 0 : decided
308
+ };
309
+ } catch {
310
+ return {
311
+ steps: [],
312
+ attemptIndex: void 0
313
+ };
314
+ }
315
+ };
316
+ /**
215
317
  * Map Vitest annotations onto `DataStore.writeAnnotations` inputs.
216
318
  * @internal
217
319
  */
@@ -356,6 +458,13 @@ var AgentReporter = class {
356
458
  */
357
459
  runStartedAt = void 0;
358
460
  /**
461
+ * `Date.now()` at this run's `onTestRunStart`: the cutoff for counting the
462
+ * module cache entries the run wrote (issue #741).
463
+ */
464
+ runStartedAtEpoch = void 0;
465
+ /** The sync filesystem the module cache directory is read through. */
466
+ moduleCacheOps;
467
+ /**
359
468
  * Stored Vitest instance from {@link AgentReporter.onInit | onInit}.
360
469
  *
361
470
  * @remarks
@@ -487,6 +596,7 @@ var AgentReporter = class {
487
596
  this.logFile = resolveLogFile(process.env);
488
597
  this.onRunEvent = options.onRunEvent;
489
598
  this.hasCustomReporter = options.reporter !== void 0;
599
+ this.moduleCacheOps = options.moduleCacheOps;
490
600
  this.runEvents = Effect.runSync(PubSub.unbounded());
491
601
  const rawThresholds = options.coverageThresholds;
492
602
  const resolvedThresholds = rawThresholds && "global" in rawThresholds ? rawThresholds : resolveThresholds(rawThresholds);
@@ -741,6 +851,7 @@ var AgentReporter = class {
741
851
  this.coverage = null;
742
852
  this.runStartCount += 1;
743
853
  this.runStartedAt = performance.now();
854
+ this.runStartedAtEpoch = Date.now();
744
855
  this.startedSpecCount = _specifications.length;
745
856
  this.strayCapture?.reset();
746
857
  if (this.neutralizedThresholdSnapshot.size > 0) {
@@ -857,11 +968,13 @@ var AgentReporter = class {
857
968
  const firstError = finalAttemptErrors(testCase)?.[0];
858
969
  const expectedStr = stringifyFailureValue(firstError?.expected);
859
970
  const receivedStr = stringifyFailureValue(firstError?.actual);
971
+ const { steps: traceSteps } = firstError !== void 0 ? traceStepsOf(testCase, readAttemptRows(testCase), this.vitestRoot()) : { steps: [] };
860
972
  const error = firstError !== void 0 ? {
861
973
  message: firstError.message,
862
974
  ...firstError.diff !== void 0 && { diff: firstError.diff },
863
975
  ...expectedStr !== void 0 && { expected: expectedStr },
864
- ...receivedStr !== void 0 && { received: receivedStr }
976
+ ...receivedStr !== void 0 && { received: receivedStr },
977
+ ...traceSteps.length > 0 && { traceSteps }
865
978
  } : void 0;
866
979
  const timedOut = result?.state === "failed" && firstError !== void 0 && isTimeoutError(firstError);
867
980
  this.emit({
@@ -1100,6 +1213,11 @@ var AgentReporter = class {
1100
1213
  ...trigger !== void 0 && { reason: trigger }
1101
1214
  });
1102
1215
  }
1216
+ /** The Vitest project root, when the stashed Vitest instance exposes one. */
1217
+ vitestRoot() {
1218
+ const root = this._vitest?.config?.root;
1219
+ return typeof root === "string" ? root : void 0;
1220
+ }
1103
1221
  async ensureDbPath() {
1104
1222
  if (this.dbPath) return this.dbPath;
1105
1223
  if (this.options.cacheDir) {
@@ -1156,6 +1274,7 @@ var AgentReporter = class {
1156
1274
  const errors = unhandledErrors;
1157
1275
  this.strayCapture?.flush();
1158
1276
  const strayOutput = this.strayCapture?.snapshot();
1277
+ const moduleCacheStats = typeof this._vitest === "object" && this._vitest !== null ? collectModuleCacheStats(this._vitest, this.runStartedAtEpoch, this.moduleCacheOps) : /* @__PURE__ */ new Map();
1159
1278
  if (this.wantsRunEvents() && this.currentRunId !== null) {
1160
1279
  let pass = 0;
1161
1280
  let fail = 0;
@@ -1186,7 +1305,11 @@ var AgentReporter = class {
1186
1305
  // @vitest-agent/ui, which both populate `collectedModules` on their
1187
1306
  collectedModules: testModules.length,
1188
1307
  ...errors.length > 0 && { unhandledErrors: errors },
1189
- ...strayOutput !== void 0 && { strayOutput }
1308
+ ...strayOutput !== void 0 && { strayOutput },
1309
+ ...moduleCacheStats.size > 0 && { moduleCache: [...moduleCacheStats].map(([project, moduleCache]) => ({
1310
+ ...project !== "" && { project },
1311
+ moduleCache
1312
+ })) }
1190
1313
  });
1191
1314
  }
1192
1315
  const modules = testModules;
@@ -1381,8 +1504,11 @@ var AgentReporter = class {
1381
1504
  const uiReports = [];
1382
1505
  const summaryReports = uiReports;
1383
1506
  for (const [projectName, projectModules] of uiProjectGroups) {
1384
- const report = buildAgentReport(projectModules, errors, reason, { omitPassingTests: opts.omitPassingTests }, isMultiProject ? projectName : void 0);
1385
- uiReports.push(report);
1507
+ const report = buildAgentReport(projectModules, errors, reason, {
1508
+ omitPassingTests: opts.omitPassingTests,
1509
+ ...coverageRoot !== void 0 && { root: coverageRoot }
1510
+ }, isMultiProject ? projectName : void 0);
1511
+ uiReports.push(withModuleCache(report, projectName, moduleCacheStats));
1386
1512
  }
1387
1513
  const uiProgram = Effect.gen(function* () {
1388
1514
  const detector = yield* EnvironmentDetector;
@@ -1461,7 +1587,10 @@ var AgentReporter = class {
1461
1587
  }
1462
1588
  const isMultiProjectFallback = fallbackProjectGroups.size > 1 || !!opts.projectFilter;
1463
1589
  fallbackReports = [];
1464
- for (const [projectName, projectModules] of fallbackProjectGroups) fallbackReports.push(buildAgentReport(projectModules, errors, reason, { omitPassingTests: opts.omitPassingTests }, isMultiProjectFallback ? projectName : void 0));
1590
+ for (const [projectName, projectModules] of fallbackProjectGroups) fallbackReports.push(withModuleCache(buildAgentReport(projectModules, errors, reason, {
1591
+ omitPassingTests: opts.omitPassingTests,
1592
+ ...coverageRoot !== void 0 && { root: coverageRoot }
1593
+ }, isMultiProjectFallback ? projectName : void 0), projectName, moduleCacheStats));
1465
1594
  } catch (err) {
1466
1595
  process.stderr.write(`vitest-agent: ${formatFatalError(err)}\n`);
1467
1596
  return;
@@ -1504,7 +1633,10 @@ var AgentReporter = class {
1504
1633
  let fileCoverageWritten = false;
1505
1634
  for (const [projectName, projectModules] of projectGroups) {
1506
1635
  const project = projectName === "default" ? "default" : projectName;
1507
- const baseReport = buildAgentReport(projectModules, errors, reason, { omitPassingTests: opts.omitPassingTests }, isMultiProject ? projectName : void 0);
1636
+ const baseReport = buildAgentReport(projectModules, errors, reason, {
1637
+ omitPassingTests: opts.omitPassingTests,
1638
+ ...coverageRoot !== void 0 && { root: coverageRoot }
1639
+ }, isMultiProject ? projectName : void 0);
1508
1640
  let totalDuration = 0;
1509
1641
  for (const mod of projectModules) totalDuration += mod.diagnostic()?.duration ?? 0;
1510
1642
  const envAgentId = process.env.VITEST_AGENT_AGENT_ID;
@@ -1542,7 +1674,8 @@ var AgentReporter = class {
1542
1674
  hostSource: hostProbe.source,
1543
1675
  hostValue: hostProbe.value,
1544
1676
  hostMetadata: hostProbe.metadata,
1545
- strayOutput: strayOutput ?? null
1677
+ strayOutput: strayOutput ?? null,
1678
+ moduleCache: moduleCacheOf(projectName, moduleCacheStats) ?? null
1546
1679
  });
1547
1680
  for (const mod of projectModules) {
1548
1681
  const fileId = yield* store.ensureFile(mod.relativeModuleId);
@@ -1607,6 +1740,13 @@ var AgentReporter = class {
1607
1740
  for (const testCase of mod.children.allTests()) {
1608
1741
  const result = testCase.result();
1609
1742
  const testCaseId = testCaseIds[testIdx];
1743
+ const attemptRows = readAttemptRows(testCase);
1744
+ const attemptIds = attemptRows.length > 0 ? yield* store.writeTestAttempts(testCaseId, attemptRows.map((a) => a.input)) : [];
1745
+ const trace = traceStepsOf(testCase, attemptRows, coverageRoot);
1746
+ if (trace.steps.length > 0) {
1747
+ const traceAttemptId = trace.attemptIndex === void 0 ? void 0 : attemptIds[trace.attemptIndex];
1748
+ yield* store.writeTraceSteps(testCaseId, traceAttemptId ?? null, trace.steps);
1749
+ }
1610
1750
  if (result?.errors && result.errors.length > 0) {
1611
1751
  const inputs = [];
1612
1752
  const countedSignatures = /* @__PURE__ */ new Set();
@@ -1634,8 +1774,11 @@ var AgentReporter = class {
1634
1774
  countOccurrence: countsOccurrence
1635
1775
  });
1636
1776
  }
1777
+ const attemptIndex = attemptIndexForError(attemptRows, e, messageText);
1778
+ const attemptId = attemptIndex === void 0 ? void 0 : attemptIds[attemptIndex];
1637
1779
  inputs.push({
1638
1780
  testCaseId,
1781
+ ...attemptId !== void 0 && { attemptId },
1639
1782
  scope: "test",
1640
1783
  message: messageText,
1641
1784
  ...nameText !== void 0 && { name: nameText },
@@ -1785,7 +1928,7 @@ var AgentReporter = class {
1785
1928
  ...reportWithTags,
1786
1929
  coverage: coverageReport
1787
1930
  } : reportWithTags;
1788
- reports.push(report);
1931
+ reports.push(withModuleCache(report, projectName, moduleCacheStats));
1789
1932
  if (coverageReport && !fileCoverageWritten) {
1790
1933
  fileCoverageWritten = true;
1791
1934
  const tierByFile = /* @__PURE__ */ new Map();
@@ -0,0 +1,169 @@
1
+ import { GlobPattern } from "@effected/glob";
2
+ import { descendEntriesSync } from "@effected/walker";
3
+ import { nodeWalkerSyncOps } from "@effected/walker/node-sync";
4
+ import { Result } from "effect";
5
+ import { statOrNull } from "./walker-fs.js";
6
+
7
+ // src/utils/module-cache-stats.ts
8
+ /**
9
+ * Module cache effectiveness per project (issue #741).
10
+ *
11
+ * Vitest exposes no hit or miss counters for its fs module cache
12
+ * (`fsModuleCache`). Two signals are derivable, and both follow vitest@5.1.1:
13
+ *
14
+ * - Time the cache removes: each file task carries `setupFetchDuration` and
15
+ * `collectFetchDuration` (time spent transforming or serving modules), and
16
+ * Vitest's own transform diagnostic (`reporters/base.ts`,
17
+ * `reportTransformDiagnostic`) sums them per project over that project's
18
+ * tracked time.
19
+ * - Cache writes: each module written to the cache directory is a miss the
20
+ * cache saved for the next run. Projects share one cache root by default, so
21
+ * a project's writes are the fresh entries its own manifest
22
+ * (`_manifest-<label>-<key>.json`, matched by JSON `name` and `root`; Vitest
23
+ * writes it before the run-end hook) lists in `modules`: a project with no
24
+ * manifest wrote nothing. Projects sharing a module key both count it, so
25
+ * the per-project counts can sum to more than the directory holds. An entry is a file named by a 40-hex-digit
26
+ * sha1 key directly in the cache root (`FileSystemModuleCache.
27
+ * generateCachePath`); the root also holds `_metadata.json`,
28
+ * `_manifest-*.json`, `CACHEDIR.TAG` and dot-prefixed temp files, none of
29
+ * which are entries. Exact hit counts are unavailable and never estimated.
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ /** Every direct child of the cache root; dot entries (Vitest's `.tmp-*` files) are skipped by default. */
34
+ const DIRECT_CHILDREN = Result.getOrThrow(GlobPattern.compileResult("*"));
35
+ /** A cache entry's file name: Vitest's sha1 cache key. */
36
+ const CACHE_ENTRY_NAME = /^[0-9a-f]{40}$/;
37
+ /** A cache manifest file's name: `_manifest-<label>-<key>.json`. */
38
+ const MANIFEST_NAME = /^_manifest-.+\.json$/;
39
+ /**
40
+ * The cache entry file names a manifest lists, when it belongs to `project`
41
+ * (its JSON `name` and `root` match) and has the expected shape; otherwise
42
+ * `undefined`. Malformed JSON or shape is ignored, never thrown.
43
+ */
44
+ function manifestEntries(raw, project) {
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(raw);
48
+ } catch {
49
+ return;
50
+ }
51
+ if (typeof parsed !== "object" || parsed === null) return void 0;
52
+ const { name, root, modules } = parsed;
53
+ if (name !== project.name || root !== project.root) return void 0;
54
+ if (typeof modules !== "object" || modules === null) return void 0;
55
+ const out = [];
56
+ for (const environment of Object.values(modules)) {
57
+ if (typeof environment !== "object" || environment === null) continue;
58
+ for (const file of Object.values(environment)) if (typeof file === "string") out.push(file);
59
+ }
60
+ return out;
61
+ }
62
+ /**
63
+ * How many cache entries `project` wrote in the run: files in `dir` named by a
64
+ * cache key, modified at or after `sinceMs` (the run's start), AND listed among
65
+ * the `modules` values of the project's own manifest (`_manifest-*.json`, found
66
+ * by its JSON `name` and `root`). Projects share one cache root by default, so
67
+ * the directory total is not any one project's; the manifest is the only
68
+ * per-project attribution Vitest records. Two projects that share a module key
69
+ * both count it, so the per-project numbers can sum to more than the
70
+ * directory's total. A readable directory with no matching manifest means the
71
+ * project wrote nothing this run: `0`. Reads through the injected `ops`, never
72
+ * `node:fs`. Answers `undefined` when `dir` is missing or unreadable, so
73
+ * "nothing written" and "could not look" stay distinct.
74
+ *
75
+ * @param dir - the resolved cache directory
76
+ * @param sinceMs - the run's start, in epoch milliseconds
77
+ * @param project - the project's `config.name` and `config.root`
78
+ * @param ops - the sync filesystem the walk and manifest reads go through
79
+ * @internal
80
+ */
81
+ function countModulesWritten(dir, sinceMs, project, ops) {
82
+ const stats = statOrNull(ops, dir);
83
+ if (stats === null || !stats.isDirectory()) return void 0;
84
+ const entries = descendEntriesSync(DIRECT_CHILDREN, {
85
+ cwd: dir,
86
+ onUnreadable: "skip",
87
+ ...ops
88
+ });
89
+ if (Result.isFailure(entries)) return void 0;
90
+ const owned = /* @__PURE__ */ new Set();
91
+ for (const entry of entries.success) {
92
+ if (!MANIFEST_NAME.test(entry.path)) continue;
93
+ let raw;
94
+ try {
95
+ raw = ops.fileSystem.readFile(ops.path.join(dir, entry.path));
96
+ } catch {
97
+ continue;
98
+ }
99
+ for (const file of manifestEntries(raw, project) ?? []) owned.add(file);
100
+ }
101
+ return entries.success.filter((entry) => CACHE_ENTRY_NAME.test(entry.path) && entry.info.mtimeMs >= sinceMs && owned.has(entry.path)).length;
102
+ }
103
+ /** Summed time of a file's tracked phases (base.ts `trackedFileTime`). */
104
+ const trackedFileTime = (file) => (file.environmentLoad || 0) + (file.setupDuration || 0) + (file.collectDuration || 0) + (file.prepareDuration || 0) + (file.result?.duration || 0);
105
+ /**
106
+ * The directory `project`'s modules are cached in: Vitest's own resolution
107
+ * (`FileSystemModuleCache.getCacheRoot`, which also creates the directory and
108
+ * answers `null` when it cannot) when the instance exposes it, else the
109
+ * project's explicit `fsModuleCachePath`. `undefined` when neither resolves.
110
+ */
111
+ const cacheDirOf = (vitest, project) => {
112
+ try {
113
+ const root = vitest.cache?._modules?.getCacheRoot?.(project.config);
114
+ if (typeof root === "string") return root;
115
+ } catch {}
116
+ const configured = project.config?.fsModuleCachePath;
117
+ return typeof configured === "string" && configured.length > 0 ? configured : void 0;
118
+ };
119
+ /**
120
+ * Per-project module cache stats for a finished run (issue #741), keyed by
121
+ * project name (`""` for an unnamed project). A project appears only when it
122
+ * has tracked time to report; merged blob reports replay the durations of
123
+ * past runs, so they yield nothing. Never throws.
124
+ *
125
+ * @param vitest - the Vitest instance (read structurally)
126
+ * @param startMs - the run's start, in epoch milliseconds; without it no writes are counted
127
+ * @param ops - the sync filesystem the cache directory is read through
128
+ * @internal
129
+ */
130
+ function collectModuleCacheStats(vitest, startMs, ops = nodeWalkerSyncOps) {
131
+ const out = /* @__PURE__ */ new Map();
132
+ try {
133
+ const v = vitest;
134
+ if (v.state?.blobs) return out;
135
+ const projects = Array.isArray(v.projects) ? v.projects : [];
136
+ const getFiles = v.state?.getFiles;
137
+ const files = typeof getFiles === "function" ? getFiles.call(v.state) ?? [] : [];
138
+ for (const project of projects) {
139
+ const name = project.name ?? "";
140
+ let transformMs = 0;
141
+ let trackedMs = 0;
142
+ for (const file of files) {
143
+ if ((file.projectName || "") !== name) continue;
144
+ transformMs += (file.setupFetchDuration || 0) + (file.collectFetchDuration || 0);
145
+ trackedMs += trackedFileTime(file);
146
+ }
147
+ if (trackedMs <= 0) continue;
148
+ const enabled = project.config?.fsModuleCache === true;
149
+ const dir = enabled && startMs !== void 0 ? cacheDirOf(v, project) : void 0;
150
+ const root = project.config?.root;
151
+ const modulesWritten = dir === void 0 || startMs === void 0 || typeof root !== "string" ? void 0 : countModulesWritten(dir, startMs, {
152
+ name,
153
+ root
154
+ }, ops);
155
+ out.set(name, {
156
+ enabled,
157
+ transformMs,
158
+ trackedMs,
159
+ share: transformMs / trackedMs,
160
+ ...modulesWritten !== void 0 && { modulesWritten }
161
+ });
162
+ }
163
+ } catch {
164
+ return /* @__PURE__ */ new Map();
165
+ }
166
+ return out;
167
+ }
168
+
169
+ export { collectModuleCacheStats, countModulesWritten };
package/version.js CHANGED
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @public
10
10
  */
11
- const CURRENT_PLUGIN_VERSION = "6.1.0";
11
+ const CURRENT_PLUGIN_VERSION = "6.2.0";
12
12
 
13
13
  export { CURRENT_PLUGIN_VERSION };