sumlyzer 0.6.0 → 1.0.1

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
@@ -11,18 +11,13 @@
11
11
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/sumlyzer.svg" alt="license" /></a>
12
12
  </p>
13
13
 
14
- ## Ever lost a failing test in thousands of lines of workspace output?
15
14
 
16
- ## Ever wished your npm workspaces stopped at the first failure?
15
+ ## Ever wished a faster feedback when testing your npm workspaces?
17
16
 
18
17
  `npm run test --workspaces --if-present` runs every workspace, but gives you no
19
- aggregated summary and no way to fail fast, an early failure just scrolls off
20
- screen once later workspaces print their own output.
18
+ aggregated summary and no way to fail fast, no way to catch an early failure that scrolled off screen.
21
19
 
22
- Sumlyzer runs each workspace's test script, one by one or concurrently.
23
- Passing workspaces collapse to a single line, failing ones print just the
24
- relevant failure detail, and everything ends with an aggregated pass/fail
25
- summary table so nothing scrolls out of the terminal.
20
+ Sumlyzer gives you all those possibilities and even more like concurrency or JUnit reports.
26
21
 
27
22
  ## Requirements
28
23
 
@@ -32,10 +27,18 @@ summary table so nothing scrolls out of the terminal.
32
27
  ## Scope
33
28
 
34
29
  This tool is intentionally narrow: **npm workspaces** running **`node:test`**.
30
+
35
31
  It orchestrates `npm run <script> --workspace=<path>` for every workspace that
36
- declares the target script, and it parses node test's own reporter output to build
37
- the summary. It does not support pnpm/yarn workspaces or other test runners
38
- (Jest, Vitest, Mocha etc.).
32
+ declares the target script, and it parses node test's own output to build
33
+ the global and per workspace summary.
34
+
35
+ It does not support pnpm/yarn workspaces or other test runners
36
+ (Jest, Vitest, Mocha etc.). (for the moment)
37
+
38
+ sumlyzer forces its own `node:test` reporter onto every workspace via
39
+ `NODE_OPTIONS`, so a workspace's `test` script should just run `node --test`
40
+ without configuring its own `--test-reporter`.
41
+ sumlyzer detects this ahead of time and skips that workspace instead of running into it.
39
42
 
40
43
  ## Install
41
44
 
@@ -62,14 +65,12 @@ Options:
62
65
  | `-c, --concurrency <n>` | `1` | run up to `<n>` workspaces at once |
63
66
  | `-h, --help` | | print usage |
64
67
 
65
- Exit code is `1` if any workspace fails (or if the project has no
66
- workspaces), `0` otherwise, wire it straight into CI without extra parsing.
68
+ Exit code is `1` if any workspace fails (even if every workspace's tests passed), `0` otherwise, wire it straight into CI without extra parsing.
67
69
  This also applies when `--junit` can't write its report.
68
- The exit code is `1` even if every workspace's tests passed.
69
70
 
70
71
  ## Features
71
72
 
72
- - Aggregated pass/fail summary table, so nothing scrolls out of the terminal
73
+ - Aggregated pass/fail summary table.
73
74
  - Fail-fast (`--ff`): stop at the first failing workspace
74
75
  - Aggregated JUnit XML report (`--junit`), merging every workspace's own results
75
76
  - GitHub Actions log folding: each workspace's output collapsed into an
@@ -173,8 +174,7 @@ every workspace's own `node:test` results. Each workspace runs with `node:test`'
173
174
  built-in `junit` reporter enabled alongside the terminal one, and sumlyzer combines
174
175
  the resulting files into one document, prefixing every `<testsuite>` name with the
175
176
  workspace it came from so CI test-report UIs (GitLab, Jenkins, Azure DevOps, ...)
176
- can tell them apart. If `<path>` is an existing directory, the report is written
177
- to `<path>/junit.xml`:
177
+ can tell them apart.
178
178
 
179
179
  ```
180
180
  npx sumlyzer --junit reports/junit.xml
@@ -188,16 +188,15 @@ npx sumlyzer --junit reports/ # writes reports/junit.xml
188
188
  </testsuites>
189
189
  ```
190
190
 
191
- A workspace whose script never produces a junit file (for example,
192
- `--script` points at something that isn't `node:test`, or the workspace crashed
193
- before it could write one) is left out of the aggregated report and sumlyzer
191
+ A workspace whose script never produces a junit file is left out of the aggregated report and sumlyzer
194
192
  prints a warning naming it.
195
193
 
196
194
  ### GitHub Actions log folding
197
195
 
198
196
  On GitHub Actions (detected via `GITHUB_ACTIONS=true`), each workspace's full
199
197
  `node:test` output is wrapped in a collapsible `::group::`/`::endgroup::`
200
- section instead of the terminal's collapsed-line-or-failure-detail format.
198
+ section instead of the terminal's formal.
199
+
201
200
  This is automatic, no flag needed, and keeps the job log short by default
202
201
  while still letting you expand any workspace, passing or failing, to see its
203
202
  full suite output.
@@ -209,9 +208,7 @@ only one whose log folding sumlyzer has actually verified end-to-end.
209
208
 
210
209
  `--concurrency <n>` runs up to `<n>` workspaces' scripts at the same time
211
210
  instead of one after another, which can noticeably cut wall-clock time on
212
- projects with many workspaces. There is no ordering dependency to worry about
213
- here: unlike a `build` script, one workspace's `node:test` run never depends
214
- on another workspace's test run, so nothing needs to be sequenced.
211
+ projects with many workspaces.
215
212
 
216
213
  Since workspaces can now finish in any order, their output interleaves in
217
214
  whatever order they complete, rather than following the `workspaces` list
package/bin/sumlyzer.mjs CHANGED
@@ -4,6 +4,12 @@ import path from "node:path";
4
4
  import { availableParallelism } from "node:os";
5
5
 
6
6
  import { main } from "../src/run.mjs";
7
+ import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "../src/errors.mjs";
8
+ import { red } from "../src/reporter.mjs";
9
+
10
+ function printWorkspaceError(message) {
11
+ console.error(red(message.split("\n").map((line) => `✗ ${line}`).join("\n")));
12
+ }
7
13
 
8
14
  let args;
9
15
  try {
@@ -53,10 +59,24 @@ Options:
53
59
  process.exit(0);
54
60
  }
55
61
 
56
- await main({
57
- root: path.resolve(process.cwd()),
58
- scriptName: args.script,
59
- ff: args.ff,
60
- junitPath: args.junit,
61
- concurrency
62
- });
62
+ try {
63
+ await main({
64
+ root: path.resolve(process.cwd()),
65
+ scriptName: args.script,
66
+ ff: args.ff,
67
+ junitPath: args.junit,
68
+ concurrency
69
+ });
70
+ }
71
+ catch (error) {
72
+ if (error instanceof NoWorkspacesError) {
73
+ console.info(error.message);
74
+ }
75
+ else if (error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError) {
76
+ printWorkspaceError(error.message);
77
+ }
78
+ else {
79
+ throw error;
80
+ }
81
+ process.exitCode = 1;
82
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumlyzer",
3
- "version": "0.6.0",
3
+ "version": "1.0.1",
4
4
  "description": "Run every npm workspace's test script, only show output for the ones that fail, and finish with an aggregated pass/fail summary.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/errors.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import { workspaceName } from "./reporter.mjs";
2
+
3
+ export class NoWorkspacesError extends Error {
4
+ constructor() {
5
+ super("Your project does not have any workspaces.");
6
+ this.name = "NoWorkspacesError";
7
+ }
8
+ }
9
+
10
+ export class InvalidPackageJsonError extends Error {
11
+ constructor(entries) {
12
+ super(entries.map(({ wsPath, message }) => `${workspaceName(wsPath)}: could not read its package.json (${message})`).join("\n"));
13
+ this.name = "InvalidPackageJsonError";
14
+ this.entries = entries;
15
+ }
16
+ }
17
+
18
+ export class WorkspaceLaunchError extends Error {
19
+ constructor(wsPath, scriptName, cause) {
20
+ super(`${workspaceName(wsPath)}: could not launch "${scriptName}" (${cause.message})`, { cause });
21
+ this.name = "WorkspaceLaunchError";
22
+ this.wsPath = wsPath;
23
+ this.scriptName = scriptName;
24
+ }
25
+ }
@@ -1,53 +1,3 @@
1
- const COUNT_INDEX = 1;
2
-
3
- const countTestsRegex = new RegExp(String.raw`ℹ tests (\d+)`);
4
- const countPassRegex = new RegExp(String.raw`ℹ pass (\d+)`);
5
- const countFailRegex = new RegExp(String.raw`ℹ fail (\d+)`);
6
- const countSkippedRegex = new RegExp(String.raw`ℹ skipped (\d+)`);
7
- const countTodoRegex = new RegExp(String.raw`ℹ todo (\d+)`);
8
- const countCancelledRegex = new RegExp(String.raw`ℹ cancelled (\d+)`);
9
- const countDurationRegex = new RegExp(String.raw`ℹ duration_ms (\d+)`);
10
-
11
- const count = (regex, output) => regex.exec(output)?.[COUNT_INDEX];
12
-
13
- // skip/todo/cancelled fall back to "0" rather than "?": unlike pass/fail, a missing
14
- // line here is far more likely to mean "zero" than "parsing went wrong somehow".
15
- export function parseTestCounts(output) {
16
- const tests = count(countTestsRegex, output);
17
-
18
- if (!tests) {
19
- return null;
20
- }
21
-
22
- return {
23
- tests,
24
- pass: count(countPassRegex, output) ?? "?",
25
- fail: count(countFailRegex, output) ?? "?",
26
- skip: count(countSkippedRegex, output) ?? "0",
27
- todo: count(countTodoRegex, output) ?? "0",
28
- cancelled: count(countCancelledRegex, output) ?? "0",
29
- durationMs: count(countDurationRegex, output)
30
- };
31
- }
32
-
33
- export function parseFailingTests(failureSection) {
34
- if (!failureSection) {
35
- return [];
36
- }
37
-
38
- return [...failureSection.matchAll(/^✖ (.+) \([\d.]+ms\)$/gm)].map((match) => match[1]);
39
- }
40
-
41
1
  export function stripNpmNoise(output) {
42
2
  return output.replace(/^npm warn .*\n?/gm, "");
43
3
  }
44
-
45
- export function extractFailureDetails(output, failureSection) {
46
- if (!failureSection) {
47
- return output.trim();
48
- }
49
-
50
- const details = failureSection.split(/\n(?=npm )/)[0].trim();
51
-
52
- return details.includes("'test failed'") ? output.trim() : details;
53
- }
package/src/run.mjs CHANGED
@@ -1,25 +1,26 @@
1
- import { execFile } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
- import { promisify } from "node:util";
5
+ import { fileURLToPath } from "node:url";
6
6
  import path from "node:path";
7
7
 
8
8
  import { buildJunitReport } from "./junit.mjs";
9
- import { parseTestCounts, parseFailingTests, stripNpmNoise, extractFailureDetails } from "./parseOutput.mjs";
9
+ import { stripNpmNoise } from "./parseOutput.mjs";
10
+ import { parseReporterEvents, renderFailureRecap, renderSummaryText } from "./testEventReporter.mjs";
10
11
  import { red, dim, workspaceName, githubGroupSyntax, printWorkspaceResult, printSummary, reportOutcome } from "./reporter.mjs";
12
+ import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "./errors.mjs";
11
13
 
12
- const execFileAsync = promisify(execFile);
14
+ const TEST_EVENT_REPORTER_PATH = fileURLToPath(new URL("./testEventReporter.mjs", import.meta.url));
13
15
 
14
- const SPEC_REPORTER_FLAGS = "--test-reporter=spec --test-reporter-destination=stdout";
15
-
16
- export function envWithSpecReporter(env, junitDestPath) {
16
+ export function envWithTestReporter(env, junitDestPath) {
17
17
  const existing = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ` : "";
18
+ const testReporterFlags = `--test-reporter=${TEST_EVENT_REPORTER_PATH} --test-reporter-destination=stdout`;
18
19
  const junitFlags = junitDestPath ? ` --test-reporter=junit --test-reporter-destination=${junitDestPath}` : "";
19
20
  // Drop NODE_TEST_CONTEXT: if sumlyzer itself is invoked from inside a node:test run, this var would otherwise leak.
20
21
  const rest = { ...env };
21
22
  delete rest.NODE_TEST_CONTEXT;
22
- return { ...rest, NODE_OPTIONS: `${existing}${SPEC_REPORTER_FLAGS}${junitFlags}` };
23
+ return { ...rest, NODE_OPTIONS: `${existing}${testReporterFlags}${junitFlags}` };
23
24
  }
24
25
 
25
26
  // Rethink this synchronous approach in case of very large package.json files, or huge amount of workspaces,
@@ -28,55 +29,146 @@ function readJson(file) {
28
29
  return JSON.parse(readFileSync(file, "utf8"));
29
30
  }
30
31
 
32
+ const OWN_TEST_REPORTER_FLAG = /--test-reporter(?!-destination)\b/;
33
+
34
+ export function hasOwnTestReporter(scriptCommand) {
35
+ return OWN_TEST_REPORTER_FLAG.test(scriptCommand);
36
+ }
37
+
31
38
  function listEligibleWorkspaces(root, workspaces, scriptName) {
32
- return workspaces.filter((wsPath) => {
39
+ const eligible = [];
40
+ const ownReporterConflicts = [];
41
+ const invalidPackageJson = [];
42
+
43
+ for (const wsPath of workspaces) {
33
44
  const pkgFile = path.join(root, wsPath, "package.json");
45
+ let pkg;
34
46
  try {
35
- return Boolean(readJson(pkgFile).scripts?.[scriptName]);
47
+ pkg = readJson(pkgFile);
36
48
  }
37
- catch {
38
- return false;
49
+ catch (error) {
50
+ if (error.code === "ENOENT") {
51
+ continue;
52
+ }
53
+ invalidPackageJson.push({ wsPath, message: error.message });
54
+ continue;
55
+ }
56
+
57
+ const script = pkg.scripts?.[scriptName];
58
+ if (!script) {
59
+ continue;
60
+ }
61
+ if (hasOwnTestReporter(script)) {
62
+ ownReporterConflicts.push(wsPath);
63
+ }
64
+ else {
65
+ eligible.push(wsPath);
39
66
  }
40
- });
67
+ }
68
+
69
+ return { eligible, ownReporterConflicts, invalidPackageJson };
41
70
  }
42
71
 
43
- async function runWorkspaceScript(root, wsPath, scriptName, junitDestPath) {
44
- const start = Date.now();
72
+ // npm spawns the actual test runner as its own child, so killing just the "npm"
73
+ // process leaves that grandchild running. Giving it its own process group (POSIX)
74
+ // or asking Windows to kill the whole tree ensures nothing is left behind.
75
+ function killWorkspaceChild(child) {
76
+ if (process.platform === "win32") {
77
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"]);
78
+ return;
79
+ }
80
+
81
+ try {
82
+ process.kill(-child.pid, "SIGTERM");
83
+ }
84
+ catch {
85
+ child.kill("SIGTERM");
86
+ }
87
+ }
88
+
89
+ async function captureWorkspaceOutput({ root, wsPath, scriptName, junitDestPath, activeChildren }) {
45
90
  const options = {
46
91
  cwd: root,
47
92
  shell: process.platform === "win32",
48
- maxBuffer: 20 * 1024 * 1024,
49
- env: envWithSpecReporter(process.env, junitDestPath)
93
+ detached: process.platform !== "win32",
94
+ env: envWithTestReporter(process.env, junitDestPath)
50
95
  };
51
96
 
52
- let exitCode = 0;
53
- let output;
97
+ const child = spawn("npm", ["run", scriptName, "--workspace=" + wsPath], options);
98
+ activeChildren.add(child);
99
+ const stdoutChunks = [];
100
+ const stderrChunks = [];
101
+
102
+ child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
103
+ child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
104
+
54
105
  try {
55
- const { stdout, stderr } = await execFileAsync("npm", ["run", scriptName, "--workspace=" + wsPath], options);
56
- output = stripNpmNoise(stdout + stderr);
106
+ const exitCode = await new Promise((resolve, reject) => {
107
+ child.on("error", reject);
108
+ child.on("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
109
+ });
110
+
111
+ return {
112
+ exitCode,
113
+ stdout: Buffer.concat(stdoutChunks).toString("utf8"),
114
+ stderr: Buffer.concat(stderrChunks).toString("utf8")
115
+ };
57
116
  }
58
- catch (error) {
59
- if (typeof error.code !== "number") {
60
- throw error;
61
- }
62
- exitCode = error.code;
63
- output = stripNpmNoise((error.stdout ?? "") + (error.stderr ?? ""));
117
+ finally {
118
+ activeChildren.delete(child);
119
+ }
120
+ }
121
+
122
+ function killActiveChildren(activeChildren) {
123
+ for (const child of activeChildren) {
124
+ killWorkspaceChild(child);
125
+ }
126
+ }
127
+
128
+ async function withInterruptHandling(activeChildren, run) {
129
+ function onInterrupt(signal) {
130
+ killActiveChildren(activeChildren);
131
+ process.exit(signal === "SIGINT" ? 130 : 143);
132
+ }
133
+
134
+ process.once("SIGINT", onInterrupt);
135
+ process.once("SIGTERM", onInterrupt);
136
+
137
+ try {
138
+ return await run();
139
+ }
140
+ finally {
141
+ process.off("SIGINT", onInterrupt);
142
+ process.off("SIGTERM", onInterrupt);
64
143
  }
144
+ }
65
145
 
66
- const [, failureSection] = output.split("✖ failing tests:");
146
+ function buildWorkspaceResult(wsPath, junitDestPath, durationMs, { exitCode, stdout, stderr }) {
147
+ const { counts, failingTests, failures } = parseReporterEvents(stdout);
148
+
149
+ // Workspaces that don't run through node:test never emit our JSON events; fall
150
+ // back to their raw (npm-noise-stripped) output so failures are still visible.
151
+ const fallbackOutput = stripNpmNoise(stdout + stderr).trim();
152
+ const failureRecap = failures.length > 0 ? renderFailureRecap(failures) : null;
67
153
 
68
154
  return {
69
155
  wsPath,
70
156
  exitCode,
71
- failureDetails: exitCode === 0 ? null : extractFailureDetails(output, failureSection),
72
- durationMs: Date.now() - start,
73
- counts: parseTestCounts(output),
74
- failingTests: parseFailingTests(failureSection),
157
+ failureDetails: exitCode === 0 ? null : (failureRecap ?? fallbackOutput),
158
+ durationMs,
159
+ counts,
160
+ failingTests,
75
161
  junitDestPath,
76
- rawOutput: output
162
+ rawOutput: counts ? [renderSummaryText(counts), failureRecap].filter(Boolean).join("\n\n") : fallbackOutput
77
163
  };
78
164
  }
79
165
 
166
+ async function runWorkspaceScript({ root, wsPath, scriptName, junitDestPath, activeChildren }) {
167
+ const start = Date.now();
168
+ const captured = await captureWorkspaceOutput({ root, wsPath, scriptName, junitDestPath, activeChildren });
169
+ return buildWorkspaceResult(wsPath, junitDestPath, Date.now() - start, captured);
170
+ }
171
+
80
172
  async function collectJunitEntries(results) {
81
173
  const entries = [];
82
174
  const missing = [];
@@ -99,9 +191,11 @@ async function collectJunitEntries(results) {
99
191
  async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir, concurrency }) {
100
192
  const results = new Array(workspacesToRun.length);
101
193
  const ciGroup = githubGroupSyntax(process.env);
194
+ const activeChildren = new Set();
102
195
  let stopScheduling = false;
103
196
  let nextIndex = 0;
104
197
 
198
+
105
199
  async function worker() {
106
200
  while (!stopScheduling && nextIndex < workspacesToRun.length) {
107
201
  const index = nextIndex++;
@@ -113,11 +207,12 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
113
207
 
114
208
  let result;
115
209
  try {
116
- result = await runWorkspaceScript(root, wsPath, scriptName, junitDestPath);
210
+ result = await runWorkspaceScript({ root, wsPath, scriptName, junitDestPath, activeChildren });
117
211
  }
118
212
  catch (error) {
119
- console.error(red(`✗ ${name}: could not launch "${scriptName}" (${error.message})`));
120
- process.exit(1);
213
+ stopScheduling = true;
214
+ killActiveChildren(activeChildren);
215
+ throw new WorkspaceLaunchError(wsPath, scriptName, error);
121
216
  }
122
217
  results[index] = result;
123
218
  printWorkspaceResult(name, result, ciGroup);
@@ -129,7 +224,7 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
129
224
  }
130
225
 
131
226
  const workerCount = Math.max(1, Math.min(concurrency, workspacesToRun.length));
132
- await Promise.all(Array.from({ length: workerCount }, worker));
227
+ await withInterruptHandling(activeChildren, () => Promise.all(Array.from({ length: workerCount }, worker)));
133
228
 
134
229
  return results.filter((result) => result !== undefined);
135
230
  }
@@ -165,11 +260,19 @@ export async function main({ root, scriptName, ff, junitPath, concurrency = 1 })
165
260
  const { workspaces } = readJson(path.join(root, "package.json"));
166
261
 
167
262
  if (!workspaces || workspaces.length === 0) {
168
- console.info("Your project does not have any workspaces.");
169
- process.exit(1);
263
+ throw new NoWorkspacesError();
264
+ }
265
+
266
+ const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson } = listEligibleWorkspaces(root, workspaces, scriptName);
267
+
268
+ if (invalidPackageJson.length > 0) {
269
+ throw new InvalidPackageJsonError(invalidPackageJson);
270
+ }
271
+
272
+ for (const wsPath of ownReporterConflicts) {
273
+ console.log(dim(`⊘ ${workspaceName(wsPath)}: skipped, own --test-reporter detected in its "${scriptName}" script`));
170
274
  }
171
275
 
172
- const workspacesToRun = listEligibleWorkspaces(root, workspaces, scriptName);
173
276
  const junitDir = junitPath ? await mkdtemp(path.join(tmpdir(), "sumlyzer-junit-")) : null;
174
277
 
175
278
  let results;
@@ -0,0 +1,185 @@
1
+ /**
2
+ * @typedef {object} NodeTestFailEvent
3
+ * @property {"test:fail"} type
4
+ * @property {object} data
5
+ * @property {string} data.name
6
+ * @property {object} [data.details]
7
+ * @property {number} [data.details.duration_ms]
8
+ * @property {Error & { cause?: Error }} [data.details.error]
9
+ */
10
+
11
+ /**
12
+ * @typedef {object} NodeTestSummaryEvent
13
+ * @property {"test:summary"} type
14
+ * @property {object} data
15
+ * @property {string} [data.file] absent only on the one aggregate summary emitted at the end of the run
16
+ * @property {number} data.duration_ms
17
+ * @property {object} data.counts
18
+ * @property {number} data.counts.tests
19
+ * @property {number} data.counts.passed
20
+ * @property {number} data.counts.failed
21
+ * @property {number} data.counts.skipped
22
+ * @property {number} data.counts.todo
23
+ * @property {number} data.counts.cancelled
24
+ */
25
+
26
+ /** @typedef {NodeTestFailEvent | NodeTestSummaryEvent | { type: string, data: object }} NodeTestEvent */
27
+
28
+ /**
29
+ * @typedef {object} ReportedError
30
+ * @property {string} message
31
+ * @property {string | null} stack
32
+ */
33
+
34
+ /**
35
+ * @typedef {object} ReportedFailure
36
+ * @property {string} name
37
+ * @property {number} durationMs
38
+ * @property {ReportedError | null} error
39
+ */
40
+
41
+ /**
42
+ * @typedef {object} ReportedCounts
43
+ * @property {number} tests
44
+ * @property {number} pass
45
+ * @property {number} fail
46
+ * @property {number} skip
47
+ * @property {number} todo
48
+ * @property {number} cancelled
49
+ * @property {number} [durationMs] present once merged with the summary's own duration in parseReporterEvents
50
+ */
51
+
52
+ /**
53
+ * @param {Error & { cause?: Error }} [error]
54
+ * @returns {ReportedError | null}
55
+ */
56
+ function pickError(error) {
57
+ if (!error) {
58
+ return null;
59
+ }
60
+ // node:test wraps assertion failures in an ERR_TEST_FAILURE error whose own .stack
61
+ // has no frames; the actual file:line trace lives on .cause (e.g. an AssertionError).
62
+ return { message: error.message ?? String(error), stack: error.cause?.stack ?? error.stack ?? null };
63
+ }
64
+
65
+ /**
66
+ * node:test emits a "test:summary" per file plus one aggregate at the end;
67
+ * the aggregate is the only one without a "file" attached.
68
+ * @param {NodeTestSummaryEvent["data"]} data
69
+ * @returns {boolean}
70
+ */
71
+ function isAggregateSummary(data) {
72
+ return data.file == null;
73
+ }
74
+
75
+ /**
76
+ * The node:test custom reporter itself (`--test-reporter=<this file>`). Runs inside the
77
+ * spawned workspace's process; only test:fail and the aggregate test:summary are kept,
78
+ * each re-emitted as one JSON line on stdout for the parent process to read back.
79
+ * @param {AsyncIterable<NodeTestEvent>} source
80
+ * @returns {AsyncGenerator<string>}
81
+ */
82
+ export default async function* testEventReporter(source) {
83
+ for await (const event of source) {
84
+ if (event.type === "test:fail") {
85
+ const line = {
86
+ type: "test:fail",
87
+ name: event.data.name,
88
+ durationMs: event.data.details?.duration_ms ?? 0,
89
+ error: pickError(event.data.details?.error)
90
+ };
91
+ yield `${JSON.stringify(line)}\n`;
92
+ continue;
93
+ }
94
+
95
+ if (event.type === "test:summary" && isAggregateSummary(event.data)) {
96
+ const { counts, duration_ms: durationMs } = event.data;
97
+ const line = {
98
+ type: "test:summary",
99
+ counts: {
100
+ tests: counts.tests,
101
+ pass: counts.passed,
102
+ fail: counts.failed,
103
+ skip: counts.skipped,
104
+ todo: counts.todo,
105
+ cancelled: counts.cancelled
106
+ },
107
+ durationMs
108
+ };
109
+ yield `${JSON.stringify(line)}\n`;
110
+ }
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Parses the JSON lines emitted by {@link testEventReporter} back out of a workspace's
116
+ * captured stdout, running in the parent process. Lines that aren't valid JSON (npm noise,
117
+ * or a workspace script that never runs node:test at all) are silently skipped rather than
118
+ * treated as a parsing error.
119
+ * @param {string} output
120
+ * @returns {{ counts: ReportedCounts | null, failingTests: string[], failures: ReportedFailure[] }}
121
+ */
122
+ export function parseReporterEvents(output) {
123
+ let counts = null;
124
+ let durationMs = null;
125
+ const failures = [];
126
+
127
+ for (const rawLine of output.split("\n")) {
128
+ const line = rawLine.trim();
129
+ if (!line) {
130
+ continue;
131
+ }
132
+
133
+ let event;
134
+ try {
135
+ event = JSON.parse(line);
136
+ }
137
+ catch {
138
+ continue;
139
+ }
140
+
141
+ if (event?.type === "test:fail" && typeof event.name === "string") {
142
+ failures.push({ name: event.name, durationMs: event.durationMs, error: event.error });
143
+ }
144
+ else if (event?.type === "test:summary" && event.counts) {
145
+ counts = event.counts;
146
+ durationMs = event.durationMs;
147
+ }
148
+ }
149
+
150
+ return {
151
+ counts: counts ? { ...counts, durationMs } : null,
152
+ failingTests: failures.map((failure) => failure.name),
153
+ failures
154
+ };
155
+ }
156
+
157
+ /**
158
+ * @param {ReportedFailure[]} failures
159
+ * @returns {string}
160
+ */
161
+ export function renderFailureRecap(failures) {
162
+ return failures
163
+ .map(({ name, durationMs, error }) => {
164
+ const header = `✖ ${name} (${Number(durationMs ?? 0).toFixed(1)}ms)`;
165
+ const detail = error?.stack ?? error?.message ?? "";
166
+ return detail ? `${header}\n${detail}` : header;
167
+ })
168
+ .join("\n\n");
169
+ }
170
+
171
+ /**
172
+ * @param {ReportedCounts} counts
173
+ * @returns {string}
174
+ */
175
+ export function renderSummaryText(counts) {
176
+ return [
177
+ `ℹ tests ${counts.tests}`,
178
+ `ℹ pass ${counts.pass}`,
179
+ `ℹ fail ${counts.fail}`,
180
+ `ℹ skipped ${counts.skip}`,
181
+ `ℹ todo ${counts.todo}`,
182
+ `ℹ cancelled ${counts.cancelled}`,
183
+ `ℹ duration_ms ${counts.durationMs}`
184
+ ].join("\n");
185
+ }