vouchington-tooling 0.54.0 → 0.55.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/README.md CHANGED
@@ -563,6 +563,17 @@ case it prints the multi-line report and optional pool metrics. `waitForForkLeak
563
563
  waits for a caller-supplied pool snapshot to settle. `installTestNetworkAllowlist` takes the
564
564
  allowed hosts, an exempt predicate, and the state key. `checkAndRestoreFakeTimers` restores real
565
565
  timers and returns a diagnostic when a test left fake timers installed.
566
+ `countResourcesByType` turns resource names into per-type counts and `recordForkLeakCheckpoint`
567
+ feeds a handshake settlement's counts to a detector. `formatForkLeakDiagnostics` takes an optional
568
+ fourth argument, `{ poolMetricsLabel }`, to replace the default `pool metrics:` label (for example
569
+ `'PostgreSQL pool metrics:'`).
570
+
571
+ `vouchington-tooling/vitest-diagnostics/browser` is the browser-safe entry for Storybook and Vitest
572
+ browser projects, for example a root fake-timer setup file shared with a Node project. It exports
573
+ only `checkAndRestoreFakeTimers`, `formatFakeTimerLeakDiagnostics`, and the `FakeTimerController`
574
+ type, and its import graph contains no `node:*` imports (a test enforces this), so it needs no Vite
575
+ `optimizeDeps` entry. The resource, fork-leak, reporter, and network-allowlist helpers stay in the
576
+ Node entry, and the effective-timeout cap is a config-time plugin that belongs in Node config.
566
577
 
567
578
  Use a caller-owned run directory: the reporter clears only regular numeric PID `.jsonl` files
568
579
  there at construction and leaves the directory and other files alone. Application metrics and CI artifact handling stay with the caller.
@@ -596,6 +607,18 @@ random suffixes, viewport sizes, a 1x1 PNG fixture, RFC 6238 TOTP codes, and a t
596
607
  reporter. The reporter prints one JSON line per test with the marker `playwright-test-lifecycle`.
597
608
  `@playwright/test` is an optional peer. TOTP setup and cleanup stay with the caller.
598
609
 
610
+ `createBrowserErrorsFixture`, `withMonitoredPage`, and `BrowserIssueMonitor` take the narrow
611
+ exported `MonitoredTestInfo` type (`attach`, `status`, `expectedStatus`, `timeout`) instead of
612
+ Playwright's full `TestInfo`. A real `TestInfo` is assignable to it, so no cast is needed.
613
+
614
+ `TestLifecycleReporter` accepts `failOnSkippedTests`, a plain boolean that defaults to `false`; the
615
+ reporter never reads `process.env.CI`, so the caller opts in explicitly:
616
+ `reporter: [[TestLifecycleReporter.modulePath, { failOnSkippedTests: Boolean(process.env.CI) }]]`.
617
+ When enabled, a run that would otherwise pass fails through the reporter's `onEnd` result status,
618
+ and stderr lists each skipped test's title path and `file:line`. Every test whose latest attempt
619
+ is `skipped` counts, including `test.fixme`, `test.skip`, and runtime `test.skip()`, because
620
+ Playwright reports all of them as `skipped`. A run that already failed keeps its status.
621
+
599
622
  `browser-session-runner` supervises caller-created browser-test processes. Callers supply command
600
623
  construction, line classification, retry/outcome policy, and budgets; the library owns process-group
601
624
  termination, output line buffering, shared deadlines, progress watchdogs, diagnostics, and parent signals.
@@ -6,7 +6,6 @@ import { runPostReviewCli } from "../gha-post-review/cli.mjs";
6
6
  import { runStageReviewPayloadCli } from "../gha-review-payload/cli.mjs";
7
7
  import { runSwiftSemanticEqualCli } from "../swift-semantic-equal/cli.mjs";
8
8
  import { runGhaArtifactsCleanup } from "./commands/gha-artifacts-cleanup.mjs";
9
- import { runStoryCoverage } from "./commands/story-coverage.mjs";
10
9
  import { runGhaRuntimeAudit } from "./commands/gha-runtime-audit.mjs";
11
10
  import { runHttpOrigin } from "./commands/http-origin.mjs";
12
11
  import { runPnpmInstallCli } from "./commands/pnpm-install.mjs";
@@ -31,6 +30,7 @@ import { runAstGrepPackCommand } from "./commands/ast-grep-pack.mjs";
31
30
  import { runGhaWorkspacePolicy } from "./commands/gha-workspace-policy.mjs";
32
31
  import { readInstalledVersion } from "./installed-version.mjs";
33
32
  import { parseCli } from "./parse.mjs";
33
+ import { runStoryCoverageLazy } from "./story-coverage-lazy.mjs";
34
34
  import { packageScriptPath } from "./script-path.mjs";
35
35
  import { commandUsage, printUsage } from "./usage.mjs";
36
36
  const SCRIPT_PATHS = {
@@ -130,7 +130,7 @@ export function runCli(argv = process.argv) {
130
130
  case 'gha-artifacts-cleanup':
131
131
  return runGhaArtifactsCleanup(parsed);
132
132
  case 'story-coverage':
133
- return runStoryCoverage(parsed);
133
+ return runStoryCoverageLazy(parsed);
134
134
  case 'retrospective-transcript':
135
135
  return runRetrospectiveTranscriptCommand(parsed.args);
136
136
  case 'link-skill':
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Loads a command module that value-imports an optional peer dependency. A missing peer becomes
3
+ * an actionable error; any other load failure is rethrown unchanged.
4
+ */
5
+ export declare function loadWithOptionalPeer<T>(command: string, peer: string, load: () => Promise<T>): Promise<T>;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Loads a command module that value-imports an optional peer dependency. A missing peer becomes
3
+ * an actionable error; any other load failure is rethrown unchanged.
4
+ */
5
+ export async function loadWithOptionalPeer(command, peer, load) {
6
+ try {
7
+ return await load();
8
+ }
9
+ catch (error) {
10
+ if (error.code === 'ERR_MODULE_NOT_FOUND' &&
11
+ error instanceof Error &&
12
+ error.message.includes(`'${peer}'`)) {
13
+ throw new Error(`${command} requires the optional peer dependency ${peer}; install it alongside vouchington-tooling`, { cause: error });
14
+ }
15
+ throw error;
16
+ }
17
+ }
@@ -0,0 +1,3 @@
1
+ import type { ParsedStoryCoverage } from './parse-story-coverage.mts';
2
+ /** story-coverage value-imports the optional peer no-mistakes, so it loads only when dispatched. */
3
+ export declare function runStoryCoverageLazy(parsed: ParsedStoryCoverage): Promise<number>;
@@ -0,0 +1,6 @@
1
+ import { loadWithOptionalPeer } from "./optional-peer.mjs";
2
+ /** story-coverage value-imports the optional peer no-mistakes, so it loads only when dispatched. */
3
+ export async function runStoryCoverageLazy(parsed) {
4
+ const { runStoryCoverage } = await loadWithOptionalPeer('story-coverage', 'no-mistakes', () => import("./commands/story-coverage.mjs"));
5
+ return runStoryCoverage(parsed);
6
+ }
@@ -1,5 +1,6 @@
1
- import type { BrowserContext, TestInfo } from '@playwright/test';
1
+ import type { BrowserContext } from '@playwright/test';
2
2
  import { type BrowserIssueAllowlistEntry } from './browser-issue-records.mts';
3
+ import type { MonitoredTestInfo } from './monitored-test-info.mts';
3
4
  interface BrowserIssueMonitorOptions {
4
5
  allowlist?: BrowserIssueAllowlistEntry[];
5
6
  warningPattern?: RegExp;
@@ -10,7 +11,7 @@ export declare class BrowserIssueMonitor {
10
11
  private readonly monitoredContexts;
11
12
  private readonly testInfo;
12
13
  private readonly warningPattern;
13
- constructor(testInfo: TestInfo, options?: BrowserIssueMonitorOptions);
14
+ constructor(testInfo: MonitoredTestInfo, options?: BrowserIssueMonitorOptions);
14
15
  monitorContext(context: BrowserContext): void;
15
16
  dispose(): void;
16
17
  attachIssuesIfAny(): Promise<boolean>;
@@ -1,5 +1,6 @@
1
- import { expect, type Browser, type BrowserContext, type Page, type TestInfo } from '@playwright/test';
1
+ import { expect, type Browser, type BrowserContext, type Page } from '@playwright/test';
2
2
  import { BrowserIssueMonitor } from './browser-errors.mts';
3
+ import type { MonitoredTestInfo } from './monitored-test-info.mts';
3
4
  import type { BrowserIssueAllowlistEntry } from './browser-issue-records.mts';
4
5
  import { type BlockedExternalNetworkRule } from './blocked-external-network.mts';
5
6
  export interface BrowserTestOptions {
@@ -14,8 +15,8 @@ interface BrowserErrorFixtures {
14
15
  }
15
16
  export declare function createBrowserErrorsFixture(options?: BrowserTestOptions): ({ context }: {
16
17
  context: BrowserContext;
17
- }, run: (monitor: BrowserIssueMonitor) => Promise<void>, testInfo: TestInfo) => Promise<void>;
18
+ }, run: (monitor: BrowserIssueMonitor) => Promise<void>, testInfo: MonitoredTestInfo) => Promise<void>;
18
19
  export declare function createBrowserTest(options?: BrowserTestOptions): import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & BrowserErrorFixtures, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
19
20
  export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & BrowserErrorFixtures, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
20
21
  export { expect };
21
- export declare function withMonitoredPage<T>(browserOrContext: Browser | BrowserContext, testInfo: TestInfo, callback: (page: Page) => Promise<T>, options?: BrowserTestOptions): Promise<T>;
22
+ export declare function withMonitoredPage<T>(browserOrContext: Browser | BrowserContext, testInfo: MonitoredTestInfo, callback: (page: Page) => Promise<T>, options?: BrowserTestOptions): Promise<T>;
@@ -9,6 +9,7 @@ export { BLOCKED_EXTERNAL_NETWORK_RULES, blockedExternalRequestFailureAllowlist,
9
9
  export type { BlockedExternalNetworkRule } from './blocked-external-network.mts';
10
10
  export { createBrowserErrorsFixture, createBrowserTest, expect, test, withMonitoredPage, } from './browser-test.mts';
11
11
  export type { BrowserTestOptions } from './browser-test.mts';
12
+ export type { MonitoredTestInfo } from './monitored-test-info.mts';
12
13
  export type { Browser, BrowserContext, Locator, Page, Request, TestInfo } from '@playwright/test';
13
14
  export { navigateTo } from './navigate-to.mts';
14
15
  export { retryOnConnectionLost } from './retry-on-connection-lost.mts';
@@ -25,6 +26,7 @@ export { randomSuffix } from './random-id.mts';
25
26
  export { storybookBundleHasStory } from './storybook.mts';
26
27
  export { TEST_PNG } from './test-fixtures.mts';
27
28
  export { TestLifecycleReporter };
29
+ export type { TestLifecycleReporterOptions } from './test-lifecycle-reporter.mts';
28
30
  export { generateTotpCode } from './totp.mts';
29
31
  export { DESKTOP_VIEWPORT, MOBILE_VIEWPORTS } from './viewport-constants.mts';
30
32
  export { setupVirtualAuthenticator } from './virtual-authenticator.mts';
@@ -0,0 +1,14 @@
1
+ import type { TestInfo } from '@playwright/test';
2
+ /**
3
+ * The members of Playwright's `TestInfo` that the browser-issue helpers read or call.
4
+ * A real `TestInfo` is assignable to it, and so is a small object literal.
5
+ */
6
+ export interface MonitoredTestInfo {
7
+ attach(name: string, options: {
8
+ body: Buffer;
9
+ contentType: string;
10
+ }): Promise<void>;
11
+ readonly expectedStatus: TestInfo['expectedStatus'];
12
+ readonly status?: TestInfo['status'];
13
+ readonly timeout: number;
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,11 +1,27 @@
1
- import type { FullConfig, Reporter, TestCase, TestResult } from '@playwright/test/reporter';
1
+ import type { FullConfig, FullResult, Reporter, TestCase, TestResult } from '@playwright/test/reporter';
2
+ export interface TestLifecycleReporterOptions {
3
+ /**
4
+ * Fail the run when any test ends with status `skipped`. This includes `test.fixme`,
5
+ * `test.skip`, and tests skipped at runtime, because Playwright reports all of them as
6
+ * `skipped`. Defaults to `false`; the caller decides, for example
7
+ * `failOnSkippedTests: Boolean(process.env.CI)`.
8
+ */
9
+ failOnSkippedTests?: boolean;
10
+ }
2
11
  export default class TestLifecycleReporter implements Reporter {
3
12
  static readonly modulePath: string;
13
+ private readonly failOnSkippedTests;
14
+ private readonly skipped;
4
15
  private rootDir;
5
16
  private shard;
17
+ constructor(options?: TestLifecycleReporterOptions);
6
18
  onBegin(config: FullConfig): void;
7
19
  onTestBegin(test: TestCase, result: TestResult): void;
8
20
  onTestEnd(test: TestCase, result: TestResult): void;
21
+ onEnd(result: FullResult): Promise<{
22
+ status: FullResult['status'];
23
+ } | undefined>;
9
24
  printsToStdio(): boolean;
25
+ private relativeFile;
10
26
  private record;
11
27
  }
@@ -1,8 +1,13 @@
1
1
  import { relative } from 'node:path';
2
2
  export default class TestLifecycleReporter {
3
3
  static modulePath = import.meta.filename;
4
+ failOnSkippedTests;
5
+ skipped = new Map();
4
6
  rootDir = '';
5
7
  shard = null;
8
+ constructor(options = {}) {
9
+ this.failOnSkippedTests = options.failOnSkippedTests ?? false;
10
+ }
6
11
  onBegin(config) {
7
12
  this.rootDir = config.rootDir;
8
13
  this.shard = config.shard;
@@ -12,17 +17,34 @@ export default class TestLifecycleReporter {
12
17
  }
13
18
  onTestEnd(test, result) {
14
19
  this.record('end', test, result);
20
+ // Only a test's latest attempt counts: serial suites skip tests that a retry later runs.
21
+ if (result.status !== 'skipped') {
22
+ this.skipped.delete(test.id);
23
+ return;
24
+ }
25
+ const title = test.titlePath().filter(Boolean).join(' > ');
26
+ this.skipped.set(test.id, `${title} (${this.relativeFile(test)}:${test.location.line})`);
27
+ }
28
+ async onEnd(result) {
29
+ if (!this.failOnSkippedTests || this.skipped.size === 0)
30
+ return undefined;
31
+ const lines = [...this.skipped.values()].map((entry) => ` - ${entry}`).join('\n');
32
+ process.stderr.write(`${this.skipped.size} test(s) were skipped and failOnSkippedTests is enabled:\n${lines}\n`);
33
+ return result.status === 'passed' ? { status: 'failed' } : undefined;
15
34
  }
16
35
  printsToStdio() {
17
36
  return true;
18
37
  }
38
+ relativeFile(test) {
39
+ return relative(this.rootDir, test.location.file);
40
+ }
19
41
  record(event, test, result) {
20
42
  process.stdout.write(`${JSON.stringify({
21
43
  marker: 'playwright-test-lifecycle',
22
44
  event,
23
45
  observedAt: new Date().toISOString(),
24
46
  testId: test.id,
25
- file: relative(this.rootDir, test.location.file),
47
+ file: this.relativeFile(test),
26
48
  line: test.location.line,
27
49
  project: test.parent.project()?.name,
28
50
  shard: this.shard,
@@ -0,0 +1,2 @@
1
+ export { checkAndRestoreFakeTimers, formatFakeTimerLeakDiagnostics, } from './vitest-fake-timer-guard.mts';
2
+ export type { FakeTimerController } from './vitest-fake-timer-guard.mts';
@@ -0,0 +1,6 @@
1
+ // Browser-safe entry for Storybook and Vitest browser projects. Everything re-exported here must
2
+ // stay free of `node:*` imports and Node-only globals; `browser.test.mts` checks the import graph.
3
+ // Resource, fork-leak, reporter, and network-allowlist helpers need Node, so they live only in the
4
+ // Node entry (`vouchington-tooling/vitest-diagnostics`). The effective-timeout cap is a
5
+ // config-time Vite plugin and also stays out of the browser bundle.
6
+ export { checkAndRestoreFakeTimers, formatFakeTimerLeakDiagnostics, } from "./vitest-fake-timer-guard.mjs";
@@ -10,28 +10,11 @@ export { consumeTestNetworkAllowlistViolation, installTestNetworkAllowlist, } fr
10
10
  export type { TestNetworkAllowlistOptions } from './vitest-network-allowlist.mts';
11
11
  export { getRegisteredPoolMetrics, getRegisteredPoolSocketHandles, } from './vitest-fork-leak-diagnostics.mts';
12
12
  export { FORK_LEAK_HANDSHAKE_MAX_TURNS, FORK_LEAK_HANDSHAKE_STABLE_OBSERVATIONS, formatActiveResources, formatProcessResources, formatResourceCounts, waitForForkLeakHandshakeSettle, } from './vitest-fork-leak-handshake.mts';
13
+ export { countResourcesByType } from './vitest-process-resources.mts';
14
+ export { recordForkLeakCheckpoint } from './vitest-fork-leak-handshake-samples.mts';
13
15
  export type { ForkLeakHandshakeSettlement } from './vitest-fork-leak-handshake.mts';
14
16
  export type { PoolMetrics, PoolSocketHandles } from './vitest-fork-leak-handshake-samples.mts';
17
+ export type { ForkLeakDiagnosticsOptions } from './vitest-fork-leak-diagnostics.mts';
15
18
  export type { ForkLeakDetector, ForkLeakDetectorOptions, ForkLeakVerdict, } from './vitest-fork-leak-detection.mts';
16
- export { MAX_DIAGNOSTIC_REPORT_BYTES } from './read-file.mts';
17
- export declare const DEFAULT_MAX_DIAGNOSTIC_REPORTS = 100;
18
- export declare const DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS = 20;
19
- export declare const HARD_MAX_DIAGNOSTIC_REPORTS = 100;
20
- export { HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES } from './directory.mts';
21
- export interface DiagnosticReportSummary {
22
- file: string;
23
- trigger: string;
24
- event: string;
25
- threadId: number | null;
26
- heapUsedMB: string;
27
- heapTotalMB: string;
28
- heapLimitMB: string;
29
- maxRssMB: string;
30
- topNativeFrameModule: string | null;
31
- }
32
- export interface DiagnosticReportLimitOptions {
33
- maxReports?: number;
34
- }
35
- export declare function summarizeDiagnosticReport(file: string, report: unknown): DiagnosticReportSummary;
36
- export declare function readDiagnosticReportSummaries(directory: string, options?: DiagnosticReportLimitOptions): DiagnosticReportSummary[];
37
- export declare function formatDiagnosticReportSummaries(summaries: readonly unknown[], options?: DiagnosticReportLimitOptions): string;
19
+ export { DEFAULT_MAX_DIAGNOSTIC_REPORTS, DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS, formatDiagnosticReportSummaries, HARD_MAX_DIAGNOSTIC_REPORTS, MAX_DIAGNOSTIC_REPORT_BYTES, HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES, readDiagnosticReportSummaries, summarizeDiagnosticReport, } from './report-summary.mts';
20
+ export type { DiagnosticReportLimitOptions, DiagnosticReportSummary } from './report-summary.mts';
@@ -1,4 +1,3 @@
1
- import { join, posix, win32 } from 'node:path';
2
1
  export { registerForkExitSentinel, setCurrentForkExitModule, setCurrentForkExitProject, } from "./vitest-fork-exit-sentinel.mjs";
3
2
  export { clearForkExitRecords, formatForkExitSentinelSection, readForkExitRecords, summarizeForkExitRecords, } from "./vitest-fork-exit-records.mjs";
4
3
  export { createVitestWorkerExitDiagnosticsReporter, formatWorkerExitDiagnostics, isWorkerExitError, } from "./vitest-worker-exit-diagnostics-reporter.mjs";
@@ -7,125 +6,6 @@ export { checkAndRestoreFakeTimers, formatFakeTimerLeakDiagnostics, } from "./vi
7
6
  export { consumeTestNetworkAllowlistViolation, installTestNetworkAllowlist, } from "./vitest-network-allowlist.mjs";
8
7
  export { getRegisteredPoolMetrics, getRegisteredPoolSocketHandles, } from "./vitest-fork-leak-diagnostics.mjs";
9
8
  export { FORK_LEAK_HANDSHAKE_MAX_TURNS, FORK_LEAK_HANDSHAKE_STABLE_OBSERVATIONS, formatActiveResources, formatProcessResources, formatResourceCounts, waitForForkLeakHandshakeSettle, } from "./vitest-fork-leak-handshake.mjs";
10
- import { isDiagnosticReportDirectoryCurrent, readDiagnosticReportDirectory } from "./directory.mjs";
11
- import { readBoundedRegularFile } from "./read-file.mjs";
12
- export { MAX_DIAGNOSTIC_REPORT_BYTES } from "./read-file.mjs";
13
- export const DEFAULT_MAX_DIAGNOSTIC_REPORTS = 100;
14
- export const DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS = 20;
15
- export const HARD_MAX_DIAGNOSTIC_REPORTS = 100;
16
- export { HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES } from "./directory.mjs";
17
- const TEXT_LIMIT = 200;
18
- const PATH_LIMIT = 240;
19
- function objectValue(value) {
20
- return typeof value === 'object' && value !== null && !Array.isArray(value)
21
- ? value
22
- : {};
23
- }
24
- function boundedText(value, fallback, limit) {
25
- if (typeof value !== 'string')
26
- return fallback;
27
- const normalized = value
28
- .slice(0, limit * 4)
29
- .replace(/[\p{Cc}\p{Cf}]/gu, ' ')
30
- .replace(/\s+/g, ' ')
31
- .trim();
32
- return normalized.length === 0 ? fallback : normalized.slice(0, limit);
33
- }
34
- function formatMebibytes(value) {
35
- const bytes = typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
36
- return (bytes / 1024 / 1024).toFixed(1);
37
- }
38
- function threadId(value) {
39
- return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
40
- }
41
- function nativeModulePath(value) {
42
- const module = boundedText(value, '', PATH_LIMIT);
43
- return posix.isAbsolute(module) || win32.isAbsolute(module) ? module : null;
44
- }
45
- function topNativeFrameModule(value) {
46
- if (!Array.isArray(value))
47
- return null;
48
- const symbol = objectValue(value[0]).symbol;
49
- if (typeof symbol !== 'string')
50
- return null;
51
- const tail = symbol.slice(-PATH_LIMIT * 2).trimEnd();
52
- if (!tail.endsWith(']'))
53
- return null;
54
- const opening = tail.lastIndexOf('[');
55
- if (opening < 0)
56
- return null;
57
- return nativeModulePath(tail.slice(opening + 1, -1));
58
- }
59
- function reportLimit(value, fallback) {
60
- if (value === undefined)
61
- return fallback;
62
- if (!Number.isFinite(value))
63
- return fallback;
64
- return Math.min(Math.max(Math.floor(value), 0), HARD_MAX_DIAGNOSTIC_REPORTS);
65
- }
66
- export function summarizeDiagnosticReport(file, report) {
67
- const root = objectValue(report);
68
- const header = objectValue(root.header);
69
- const heap = objectValue(root.javascriptHeap);
70
- const resourceUsage = objectValue(root.resourceUsage);
71
- return {
72
- file: boundedText(file, 'unknown', PATH_LIMIT),
73
- trigger: boundedText(header.trigger, 'unknown', TEXT_LIMIT),
74
- event: boundedText(header.event, 'unknown', TEXT_LIMIT),
75
- threadId: threadId(header.threadId),
76
- heapUsedMB: formatMebibytes(heap.usedMemory),
77
- heapTotalMB: formatMebibytes(heap.totalMemory),
78
- heapLimitMB: formatMebibytes(heap.memoryLimit),
79
- maxRssMB: formatMebibytes(resourceUsage.maxRss),
80
- topNativeFrameModule: topNativeFrameModule(root.nativeStack),
81
- };
82
- }
83
- export function readDiagnosticReportSummaries(directory, options = {}) {
84
- const maxReports = reportLimit(options.maxReports, DEFAULT_MAX_DIAGNOSTIC_REPORTS);
85
- if (maxReports === 0)
86
- return [];
87
- const reportsDirectory = readDiagnosticReportDirectory(directory);
88
- if (reportsDirectory === undefined)
89
- return [];
90
- const filenames = reportsDirectory.filenames.sort();
91
- const selected = filenames.slice(-maxReports);
92
- const summaries = [];
93
- for (const filename of selected) {
94
- try {
95
- if (!isDiagnosticReportDirectoryCurrent(directory, reportsDirectory.identity))
96
- return [];
97
- const contents = readBoundedRegularFile(join(directory, filename));
98
- if (!isDiagnosticReportDirectoryCurrent(directory, reportsDirectory.identity))
99
- return [];
100
- if (contents === undefined)
101
- continue;
102
- const report = JSON.parse(contents);
103
- summaries.push(summarizeDiagnosticReport(filename, report));
104
- }
105
- catch {
106
- // Node can leave a partial report if the process exits while writing it.
107
- }
108
- }
109
- return summaries;
110
- }
111
- export function formatDiagnosticReportSummaries(summaries, options = {}) {
112
- const maxReports = reportLimit(options.maxReports, DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS);
113
- const lines = ['[vitest-diagnostics]', `reports provided: ${summaries.length}`];
114
- if (summaries.length === 0)
115
- lines.push(' (none recorded)');
116
- for (const value of summaries.slice(0, maxReports)) {
117
- const summary = objectValue(value);
118
- lines.push(` - file=${boundedText(summary.file, 'unknown', PATH_LIMIT)} ` +
119
- `trigger=${boundedText(summary.trigger, 'unknown', TEXT_LIMIT)} ` +
120
- `event=${boundedText(summary.event, 'unknown', TEXT_LIMIT)} ` +
121
- `threadId=${threadId(summary.threadId) ?? 'unknown'} ` +
122
- `heapUsedMB=${boundedText(summary.heapUsedMB, '0.0', TEXT_LIMIT)} ` +
123
- `heapTotalMB=${boundedText(summary.heapTotalMB, '0.0', TEXT_LIMIT)} ` +
124
- `heapLimitMB=${boundedText(summary.heapLimitMB, '0.0', TEXT_LIMIT)} ` +
125
- `maxRssMB=${boundedText(summary.maxRssMB, '0.0', TEXT_LIMIT)} ` +
126
- `topNativeFrameModule=${nativeModulePath(summary.topNativeFrameModule) ?? 'none'}`);
127
- }
128
- if (summaries.length > maxReports)
129
- lines.push(` ... ${summaries.length - maxReports} more`);
130
- return `${lines.join('\n')}\n`;
131
- }
9
+ export { countResourcesByType } from "./vitest-process-resources.mjs";
10
+ export { recordForkLeakCheckpoint } from "./vitest-fork-leak-handshake-samples.mjs";
11
+ export { DEFAULT_MAX_DIAGNOSTIC_REPORTS, DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS, formatDiagnosticReportSummaries, HARD_MAX_DIAGNOSTIC_REPORTS, MAX_DIAGNOSTIC_REPORT_BYTES, HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES, readDiagnosticReportSummaries, summarizeDiagnosticReport, } from "./report-summary.mjs";
@@ -0,0 +1,22 @@
1
+ export { MAX_DIAGNOSTIC_REPORT_BYTES } from './read-file.mts';
2
+ export declare const DEFAULT_MAX_DIAGNOSTIC_REPORTS = 100;
3
+ export declare const DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS = 20;
4
+ export declare const HARD_MAX_DIAGNOSTIC_REPORTS = 100;
5
+ export { HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES } from './directory.mts';
6
+ export interface DiagnosticReportSummary {
7
+ file: string;
8
+ trigger: string;
9
+ event: string;
10
+ threadId: number | null;
11
+ heapUsedMB: string;
12
+ heapTotalMB: string;
13
+ heapLimitMB: string;
14
+ maxRssMB: string;
15
+ topNativeFrameModule: string | null;
16
+ }
17
+ export interface DiagnosticReportLimitOptions {
18
+ maxReports?: number;
19
+ }
20
+ export declare function summarizeDiagnosticReport(file: string, report: unknown): DiagnosticReportSummary;
21
+ export declare function readDiagnosticReportSummaries(directory: string, options?: DiagnosticReportLimitOptions): DiagnosticReportSummary[];
22
+ export declare function formatDiagnosticReportSummaries(summaries: readonly unknown[], options?: DiagnosticReportLimitOptions): string;
@@ -0,0 +1,123 @@
1
+ import { join, posix, win32 } from 'node:path';
2
+ import { isDiagnosticReportDirectoryCurrent, readDiagnosticReportDirectory } from "./directory.mjs";
3
+ import { readBoundedRegularFile } from "./read-file.mjs";
4
+ export { MAX_DIAGNOSTIC_REPORT_BYTES } from "./read-file.mjs";
5
+ export const DEFAULT_MAX_DIAGNOSTIC_REPORTS = 100;
6
+ export const DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS = 20;
7
+ export const HARD_MAX_DIAGNOSTIC_REPORTS = 100;
8
+ export { HARD_MAX_DIAGNOSTIC_DIRECTORY_ENTRIES } from "./directory.mjs";
9
+ const TEXT_LIMIT = 200;
10
+ const PATH_LIMIT = 240;
11
+ function objectValue(value) {
12
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
13
+ ? value
14
+ : {};
15
+ }
16
+ function boundedText(value, fallback, limit) {
17
+ if (typeof value !== 'string')
18
+ return fallback;
19
+ const normalized = value
20
+ .slice(0, limit * 4)
21
+ .replace(/[\p{Cc}\p{Cf}]/gu, ' ')
22
+ .replace(/\s+/g, ' ')
23
+ .trim();
24
+ return normalized.length === 0 ? fallback : normalized.slice(0, limit);
25
+ }
26
+ function formatMebibytes(value) {
27
+ const bytes = typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
28
+ return (bytes / 1024 / 1024).toFixed(1);
29
+ }
30
+ function threadId(value) {
31
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
32
+ }
33
+ function nativeModulePath(value) {
34
+ const module = boundedText(value, '', PATH_LIMIT);
35
+ return posix.isAbsolute(module) || win32.isAbsolute(module) ? module : null;
36
+ }
37
+ function topNativeFrameModule(value) {
38
+ if (!Array.isArray(value))
39
+ return null;
40
+ const symbol = objectValue(value[0]).symbol;
41
+ if (typeof symbol !== 'string')
42
+ return null;
43
+ const tail = symbol.slice(-PATH_LIMIT * 2).trimEnd();
44
+ if (!tail.endsWith(']'))
45
+ return null;
46
+ const opening = tail.lastIndexOf('[');
47
+ if (opening < 0)
48
+ return null;
49
+ return nativeModulePath(tail.slice(opening + 1, -1));
50
+ }
51
+ function reportLimit(value, fallback) {
52
+ if (value === undefined)
53
+ return fallback;
54
+ if (!Number.isFinite(value))
55
+ return fallback;
56
+ return Math.min(Math.max(Math.floor(value), 0), HARD_MAX_DIAGNOSTIC_REPORTS);
57
+ }
58
+ export function summarizeDiagnosticReport(file, report) {
59
+ const root = objectValue(report);
60
+ const header = objectValue(root.header);
61
+ const heap = objectValue(root.javascriptHeap);
62
+ const resourceUsage = objectValue(root.resourceUsage);
63
+ return {
64
+ file: boundedText(file, 'unknown', PATH_LIMIT),
65
+ trigger: boundedText(header.trigger, 'unknown', TEXT_LIMIT),
66
+ event: boundedText(header.event, 'unknown', TEXT_LIMIT),
67
+ threadId: threadId(header.threadId),
68
+ heapUsedMB: formatMebibytes(heap.usedMemory),
69
+ heapTotalMB: formatMebibytes(heap.totalMemory),
70
+ heapLimitMB: formatMebibytes(heap.memoryLimit),
71
+ maxRssMB: formatMebibytes(resourceUsage.maxRss),
72
+ topNativeFrameModule: topNativeFrameModule(root.nativeStack),
73
+ };
74
+ }
75
+ export function readDiagnosticReportSummaries(directory, options = {}) {
76
+ const maxReports = reportLimit(options.maxReports, DEFAULT_MAX_DIAGNOSTIC_REPORTS);
77
+ if (maxReports === 0)
78
+ return [];
79
+ const reportsDirectory = readDiagnosticReportDirectory(directory);
80
+ if (reportsDirectory === undefined)
81
+ return [];
82
+ const filenames = reportsDirectory.filenames.sort();
83
+ const selected = filenames.slice(-maxReports);
84
+ const summaries = [];
85
+ for (const filename of selected) {
86
+ try {
87
+ if (!isDiagnosticReportDirectoryCurrent(directory, reportsDirectory.identity))
88
+ return [];
89
+ const contents = readBoundedRegularFile(join(directory, filename));
90
+ if (!isDiagnosticReportDirectoryCurrent(directory, reportsDirectory.identity))
91
+ return [];
92
+ if (contents === undefined)
93
+ continue;
94
+ const report = JSON.parse(contents);
95
+ summaries.push(summarizeDiagnosticReport(filename, report));
96
+ }
97
+ catch {
98
+ // Node can leave a partial report if the process exits while writing it.
99
+ }
100
+ }
101
+ return summaries;
102
+ }
103
+ export function formatDiagnosticReportSummaries(summaries, options = {}) {
104
+ const maxReports = reportLimit(options.maxReports, DEFAULT_MAX_FORMATTED_DIAGNOSTIC_REPORTS);
105
+ const lines = ['[vitest-diagnostics]', `reports provided: ${summaries.length}`];
106
+ if (summaries.length === 0)
107
+ lines.push(' (none recorded)');
108
+ for (const value of summaries.slice(0, maxReports)) {
109
+ const summary = objectValue(value);
110
+ lines.push(` - file=${boundedText(summary.file, 'unknown', PATH_LIMIT)} ` +
111
+ `trigger=${boundedText(summary.trigger, 'unknown', TEXT_LIMIT)} ` +
112
+ `event=${boundedText(summary.event, 'unknown', TEXT_LIMIT)} ` +
113
+ `threadId=${threadId(summary.threadId) ?? 'unknown'} ` +
114
+ `heapUsedMB=${boundedText(summary.heapUsedMB, '0.0', TEXT_LIMIT)} ` +
115
+ `heapTotalMB=${boundedText(summary.heapTotalMB, '0.0', TEXT_LIMIT)} ` +
116
+ `heapLimitMB=${boundedText(summary.heapLimitMB, '0.0', TEXT_LIMIT)} ` +
117
+ `maxRssMB=${boundedText(summary.maxRssMB, '0.0', TEXT_LIMIT)} ` +
118
+ `topNativeFrameModule=${nativeModulePath(summary.topNativeFrameModule) ?? 'none'}`);
119
+ }
120
+ if (summaries.length > maxReports)
121
+ lines.push(` ... ${summaries.length - maxReports} more`);
122
+ return `${lines.join('\n')}\n`;
123
+ }
@@ -6,7 +6,14 @@ type PoolSocketHandles = {
6
6
  };
7
7
  export declare function getRegisteredPoolMetrics(): PoolMetrics | null;
8
8
  export declare function getRegisteredPoolSocketHandles(): PoolSocketHandles | null;
9
- /** One-line summary, or a multi-line report when resource counts are supplied. */
9
+ export type ForkLeakDiagnosticsOptions = {
10
+ /** Text printed before the pool metrics line. Defaults to `pool metrics:`. */
11
+ poolMetricsLabel?: string;
12
+ };
13
+ /**
14
+ * One-line summary, or a multi-line report when resource counts are supplied. The multi-line
15
+ * report ends with a pool metrics line whose label comes from `options.poolMetricsLabel`.
16
+ */
10
17
  export declare function formatForkLeakDiagnostics(verdict: ForkLeakVerdict): string;
11
- export declare function formatForkLeakDiagnostics(verdict: ForkLeakVerdict, counts: ReadonlyMap<string, number>, poolMetrics?: PoolMetrics | null): string;
18
+ export declare function formatForkLeakDiagnostics(verdict: ForkLeakVerdict, counts: ReadonlyMap<string, number>, poolMetrics?: PoolMetrics | null, options?: ForkLeakDiagnosticsOptions): string;
12
19
  export {};
@@ -9,7 +9,8 @@ export function getRegisteredPoolSocketHandles() {
9
9
  const provider = globalThis[POOL_SOCKETS_KEY];
10
10
  return provider?.() ?? null;
11
11
  }
12
- export function formatForkLeakDiagnostics(verdict, counts, poolMetrics) {
12
+ const DEFAULT_POOL_METRICS_LABEL = 'pool metrics:';
13
+ export function formatForkLeakDiagnostics(verdict, counts, poolMetrics, options = {}) {
13
14
  if (counts === undefined)
14
15
  return formatForkLeakSummary(verdict);
15
16
  return [
@@ -23,7 +24,7 @@ export function formatForkLeakDiagnostics(verdict, counts, poolMetrics) {
23
24
  `suspected growth file: ${verdict.suspectedGrowth?.testFile ?? 'unknown'}`,
24
25
  `largest growth step: ${formatGrowthStep(verdict.suspectedGrowth)}`,
25
26
  `tracked resource counts: ${formatResourceCounts(counts)}`,
26
- `pool metrics: ${formatPoolMetrics(poolMetrics ?? null)}`,
27
+ `${options.poolMetricsLabel ?? DEFAULT_POOL_METRICS_LABEL} ${formatPoolMetrics(poolMetrics ?? null)}`,
27
28
  ].join('\n');
28
29
  }
29
30
  function formatForkLeakSummary(verdict) {
@@ -28,6 +28,11 @@ export type ForkLeakHandshakeSnapshot = {
28
28
  tcpSocketHandles: ReadonlySet<object>;
29
29
  poolMetrics: PoolMetrics | null;
30
30
  };
31
+ /**
32
+ * Records one fork-leak checkpoint from a handshake settlement. It counts the resources of the
33
+ * coalesced snapshot, or of the detector snapshot otherwise, and passes them to `record` (for
34
+ * example a fork leak detector's `record`) with the test file name. Returns what `record` returns.
35
+ */
31
36
  export declare function recordForkLeakCheckpoint<T>(record: (counts: ReadonlyMap<string, number>, testFile: string) => T[], settlement: {
32
37
  snapshot: ForkLeakHandshakeSnapshot;
33
38
  detectorSnapshot: ForkLeakHandshakeSnapshot;
@@ -30,6 +30,11 @@ export function pendingPoolSocketEpisode(options) {
30
30
  !options.ownedHandlesObserved.has(handle),
31
31
  };
32
32
  }
33
+ /**
34
+ * Records one fork-leak checkpoint from a handshake settlement. It counts the resources of the
35
+ * coalesced snapshot, or of the detector snapshot otherwise, and passes them to `record` (for
36
+ * example a fork leak detector's `record`) with the test file name. Returns what `record` returns.
37
+ */
33
38
  export function recordForkLeakCheckpoint(record, settlement, testFile) {
34
39
  const checkpoint = settlement.coalesced ? settlement.snapshot : settlement.detectorSnapshot;
35
40
  return record(countResourcesByType(checkpoint.resources), testFile);
@@ -1,5 +1,9 @@
1
1
  export declare function formatProcessResources(): string;
2
2
  export declare function formatActiveResources(): string;
3
+ /**
4
+ * Counts how many times each resource type appears, such as the names returned by
5
+ * `process.getActiveResourcesInfo()`. Pass the result to a fork leak detector's `record`.
6
+ */
3
7
  export declare function countResourcesByType(resources: readonly string[]): Map<string, number>;
4
8
  export declare function formatResourceCounts(counts: ReadonlyMap<string, number>): string;
5
9
  export declare function formatBytes(bytes: number): string;
@@ -24,7 +24,10 @@ export function formatActiveResources() {
24
24
  return '(none)';
25
25
  return resources.slice(0, 20).join(', ');
26
26
  }
27
- // Used by the fork-leak failure text to name per-type counts instead of the flat list above.
27
+ /**
28
+ * Counts how many times each resource type appears, such as the names returned by
29
+ * `process.getActiveResourcesInfo()`. Pass the result to a fork leak detector's `record`.
30
+ */
28
31
  export function countResourcesByType(resources) {
29
32
  const counts = new Map();
30
33
  for (const resource of resources) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.54.0",
3
+ "version": "0.55.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -326,6 +326,11 @@
326
326
  "import": "./dist/vitest-diagnostics/index.mjs",
327
327
  "default": "./dist/vitest-diagnostics/index.mjs"
328
328
  },
329
+ "./vitest-diagnostics/browser": {
330
+ "types": "./dist/vitest-diagnostics/browser.d.mts",
331
+ "import": "./dist/vitest-diagnostics/browser.mjs",
332
+ "default": "./dist/vitest-diagnostics/browser.mjs"
333
+ },
329
334
  "./vitest-effective-timeout": {
330
335
  "types": "./dist/vitest-effective-timeout/index.d.mts",
331
336
  "import": "./dist/vitest-effective-timeout/index.mjs",