sumlyzer 1.4.1 → 1.5.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/CHANGELOG.md CHANGED
@@ -6,6 +6,21 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.5.0] - 2026-11-26
10
+
11
+ ### Added
12
+
13
+ - `-v, --version` prints the installed version.
14
+
15
+ ### Fixed
16
+
17
+ - Scripts and their `pre`/`post` hooks get the same `npm_package_*` and
18
+ `npm_lifecycle_*` variables as with `npm run`.
19
+ - A missing or invalid root `package.json` prints a one-line error instead
20
+ of a stack trace.
21
+ - Windows: `node:test` workspaces crashed, `--junit` paths lost their
22
+ separators, `--changed`/`--watch` matched no workspace.
23
+
9
24
  ## [1.4.1] - 2026-11-25
10
25
 
11
26
  ### Security
@@ -100,7 +115,8 @@ No release notes, see the [diff](https://github.com/ErwanRaulo/sumlyzer/compare/
100
115
  Earlier versions (`0.1.1` to `0.5.3`) have no release notes, see the
101
116
  [tags](https://github.com/ErwanRaulo/sumlyzer/tags).
102
117
 
103
- [Unreleased]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.4.1...HEAD
118
+ [Unreleased]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.5.0...HEAD
119
+ [1.5.0]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.4.1...v1.5.0
104
120
  [1.4.1]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.4.0...v1.4.1
105
121
  [1.4.0]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.3.1...v1.4.0
106
122
  [1.3.1]: https://github.com/ErwanRaulo/sumlyzer/compare/v1.3.0...v1.3.1
package/README.md CHANGED
@@ -20,7 +20,8 @@ output. Sumlyzer fixes that, and runs workspaces concurrently too (~3.5x
20
20
  faster, see [Benchmark](#benchmark)).
21
21
 
22
22
  Scope: **npm workspaces** running **`node:test`** only, for now. No
23
- pnpm/yarn, no Jest/Vitest/Mocha.
23
+ pnpm/yarn, no Jest/Vitest/Mocha. Tested on Linux, macOS and Windows, with
24
+ Node.js 22, 24 and 26.
24
25
 
25
26
  ## Install
26
27
 
@@ -45,6 +46,7 @@ Run from the root of an npm workspaces project.
45
46
  | `--junit <path>` | off | write an aggregated JUnit XML report |
46
47
  | `--ref <ref>` | auto-detect | git ref to diff against for `--changed` |
47
48
  | `-w, --watch` | off | re-run on file change (can't be combined with `--junit`) |
49
+ | `-v, --version` | | print the sumlyzer version |
48
50
  | `-h, --help` | | print usage |
49
51
 
50
52
  Exit code is `1` if any workspace fails, `0` otherwise — safe to drop straight into CI.
package/bin/sumlyzer.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
2
3
  import { parseArgs } from "node:util";
3
4
  import path from "node:path";
4
5
  import { availableParallelism } from "node:os";
5
6
 
6
7
  import { main } from "../src/run.mjs";
7
- import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError, GitDiffError } from "../src/errors.mjs";
8
+ import { NoWorkspacesError, InvalidPackageJsonError, RootPackageJsonError, WorkspaceLaunchError, GitDiffError } from "../src/errors.mjs";
8
9
  import { red } from "../src/reporter.mjs";
9
10
 
10
11
  function printWorkspaceError(message) {
@@ -22,7 +23,8 @@ try {
22
23
  changed: { type: "boolean", default: false },
23
24
  ref: { type: "string" },
24
25
  watch: { type: "boolean", short: "w", default: false },
25
- help: { type: "boolean", short: "h", default: false }
26
+ help: { type: "boolean", short: "h", default: false },
27
+ version: { type: "boolean", short: "v", default: false }
26
28
  }
27
29
  }));
28
30
  }
@@ -33,6 +35,12 @@ catch (error) {
33
35
  process.exit(1);
34
36
  }
35
37
 
38
+ if (args.version) {
39
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
40
+ console.log(version);
41
+ process.exit(0);
42
+ }
43
+
36
44
  let concurrency = Number.parseInt(args.concurrency, 10);
37
45
  if (!Number.isInteger(concurrency) || concurrency < 1 || String(concurrency) !== args.concurrency) {
38
46
  console.info(`--concurrency must be a positive integer, got "${args.concurrency}". Run "sumlyzer --help" for usage.`);
@@ -72,6 +80,7 @@ Options:
72
80
  -w, --watch re-run on file change, only for changed workspaces
73
81
  and the ones that depend on them (can't be combined
74
82
  with --junit)
83
+ -v, --version print the sumlyzer version
75
84
  -h, --help show this help
76
85
  `);
77
86
  process.exit(0);
@@ -93,7 +102,7 @@ catch (error) {
93
102
  if (error instanceof NoWorkspacesError) {
94
103
  console.info(error.message);
95
104
  }
96
- else if (error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError || error instanceof GitDiffError) {
105
+ else if (error instanceof RootPackageJsonError || error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError || error instanceof GitDiffError) {
97
106
  printWorkspaceError(error.message);
98
107
  }
99
108
  else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumlyzer",
3
- "version": "1.4.1",
3
+ "version": "1.5.0",
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": {
@@ -17,9 +17,9 @@
17
17
  "node": ">=22.0.0"
18
18
  },
19
19
  "scripts": {
20
- "test": "node --test \"./test/*.spec.mjs\"",
20
+ "test": "node --test --test-timeout=60000 \"./test/*.spec.mjs\"",
21
21
  "pretest:coverage": "mkdir -p coverage",
22
- "test:coverage": "node --no-warnings --experimental-test-coverage --test-coverage-lines=95 --test-coverage-functions=95 --test-coverage-branches=85 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test \"./test/*.spec.mjs\"",
22
+ "test:coverage": "node --no-warnings --experimental-test-coverage --test-coverage-lines=95 --test-coverage-functions=95 --test-coverage-branches=85 --test-timeout=60000 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test \"./test/*.spec.mjs\"",
23
23
  "security-scan": "node scripts/security-scan.mjs",
24
24
  "postversion": "git push && git push --tags",
25
25
  "prepublishOnly": "npm test",
package/src/changed.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
 
3
3
  import { GitDiffError } from "./errors.mjs";
4
+ import { dim } from "./reporter.mjs";
4
5
 
5
6
  function runGit(root, args, ref) {
6
7
  const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
@@ -21,8 +22,7 @@ function tryGit(root, args) {
21
22
  }
22
23
 
23
24
  export function getChangedFiles(root, ref) {
24
- // --end-of-options keeps a ref like "--output=<file>" from being parsed as an
25
- // option, the trailing "--" keeps it from being parsed as a pathspec.
25
+ // The ref can't be read as an option (--end-of-options) or a pathspec (--).
26
26
  const tracked = runGit(root, ["diff", "--name-only", "--end-of-options", ref, "--"], ref);
27
27
  const untracked = runGit(root, ["ls-files", "--others", "--exclude-standard"], ref);
28
28
 
@@ -48,8 +48,7 @@ export function resolveDefaultRef(root) {
48
48
  return { ref: upstream, label: upstream, reason: "no merge-base found" };
49
49
  }
50
50
 
51
- // Attributes each changed file to the resolved workspace whose directory contains
52
- // it. A file outside every workspace directory is reported as "rootChangeFiles"
51
+ // Maps each changed file to its innermost workspace; the rest are root changes.
53
52
  export function selectChangedWorkspaces(resolvedWorkspaces, changedFiles) {
54
53
  const sorted = [...resolvedWorkspaces].sort((a, b) => b.length - a.length);
55
54
  const workspaces = new Set();
@@ -67,3 +66,41 @@ export function selectChangedWorkspaces(resolvedWorkspaces, changedFiles) {
67
66
 
68
67
  return { workspaces, rootChangeFiles };
69
68
  }
69
+
70
+ function resolveRef(root, explicitRef) {
71
+ if (explicitRef) {
72
+ return { ref: explicitRef, label: explicitRef };
73
+ }
74
+
75
+ const resolved = resolveDefaultRef(root);
76
+ console.log(dim(`--changed: no --ref given, comparing against "${resolved.label}" (${resolved.reason})`));
77
+ return resolved;
78
+ }
79
+
80
+ // Returns the workspaces with changes, or null when there's nothing to run (already reported).
81
+ export function filterChangedWorkspaces({ root, allPaths, workspaces, ref: explicitRef }) {
82
+ const { ref, label } = resolveRef(root, explicitRef);
83
+
84
+ const changedFiles = getChangedFiles(root, ref);
85
+ if (changedFiles.length === 0) {
86
+ console.log(dim(`No changes detected against "${label}".`));
87
+ return null;
88
+ }
89
+
90
+ const { workspaces: changedPaths, rootChangeFiles } = selectChangedWorkspaces(allPaths, changedFiles);
91
+
92
+ if (rootChangeFiles.length > 0) {
93
+ const suffix = rootChangeFiles.length > 1 ? ` (+${rootChangeFiles.length - 1} more)` : "";
94
+ console.log(dim(`--changed: "${rootChangeFiles[0]}"${suffix} is outside every workspace, ignoring`));
95
+ }
96
+
97
+ const filtered = workspaces.filter((workspace) => changedPaths.has(workspace.path));
98
+ console.log(dim(`--changed: running ${filtered.length}/${workspaces.length} workspace(s) with changes since "${label}"`));
99
+
100
+ if (filtered.length === 0) {
101
+ console.log(dim("No eligible workspace changed."));
102
+ return null;
103
+ }
104
+
105
+ return filtered;
106
+ }
package/src/errors.mjs CHANGED
@@ -7,6 +7,15 @@ export class NoWorkspacesError extends Error {
7
7
  }
8
8
  }
9
9
 
10
+ export class RootPackageJsonError extends Error {
11
+ constructor(root, cause) {
12
+ super(cause.code === "ENOENT"
13
+ ? `No package.json found in ${root}. Run sumlyzer from the root of an npm workspaces project.`
14
+ : `could not read the root package.json (${cause.message})`, { cause });
15
+ this.name = "RootPackageJsonError";
16
+ }
17
+ }
18
+
10
19
  export class InvalidPackageJsonError extends Error {
11
20
  constructor(entries) {
12
21
  super(entries.map(({ wsPath, message }) => `${workspaceName(wsPath)}: could not read its package.json (${message})`).join("\n"));
@@ -0,0 +1,50 @@
1
+ import { readFile, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { buildJunitReport } from "./junit.mjs";
5
+ import { red, dim, workspaceName } from "./reporter.mjs";
6
+
7
+ const DEFAULT_JUNIT_FILENAME = "junit.xml";
8
+
9
+ async function collectJunitEntries(results) {
10
+ const entries = [];
11
+ const missing = [];
12
+
13
+ for (const result of results) {
14
+ if (!result.junitDestPath) {
15
+ continue;
16
+ }
17
+ try {
18
+ entries.push({ name: workspaceName(result.wsPath), xml: await readFile(result.junitDestPath, "utf8") });
19
+ }
20
+ catch {
21
+ missing.push(workspaceName(result.wsPath));
22
+ }
23
+ }
24
+
25
+ return { entries, missing };
26
+ }
27
+
28
+ async function resolveDestination(root, junitPath) {
29
+ const destination = path.resolve(root, junitPath);
30
+ const isDirectory = await stat(destination).then((stats) => stats.isDirectory(), () => false);
31
+
32
+ return isDirectory ? path.join(destination, DEFAULT_JUNIT_FILENAME) : destination;
33
+ }
34
+
35
+ export async function writeJunitReport(root, junitPath, results) {
36
+ const { entries, missing } = await collectJunitEntries(results);
37
+ const destination = await resolveDestination(root, junitPath);
38
+
39
+ if (missing.length > 0) {
40
+ console.log(dim(`${missing.length} workspace(s) missing from the JUnit report: ${missing.join(", ")}`));
41
+ }
42
+
43
+ try {
44
+ await writeFile(destination, buildJunitReport(entries));
45
+ }
46
+ catch (error) {
47
+ console.error(red(`Could not write JUnit report to "${destination}" (${error.message})`));
48
+ process.exitCode = 1;
49
+ }
50
+ }
@@ -0,0 +1,43 @@
1
+ import path from "node:path";
2
+
3
+ // Mirrors @npmcli/run-script: package fields flattened to npm_package_<path>,
4
+ // with arrays indexed, null/false as "" and undefined skipped.
5
+ function flattenPackageFields(fields, prefix, env = {}) {
6
+ for (const [key, value] of Object.entries(fields)) {
7
+ if (value === undefined) {
8
+ continue;
9
+ }
10
+ if (value === null || value === false) {
11
+ env[`${prefix}${key}`] = "";
12
+ }
13
+ else if (Array.isArray(value)) {
14
+ value.forEach((item, index) => flattenPackageFields({ [`${key}_${index}`]: item }, prefix, env));
15
+ }
16
+ else if (typeof value === "object") {
17
+ flattenPackageFields(value, `${prefix}${key}_`, env);
18
+ }
19
+ else {
20
+ env[`${prefix}${key}`] = String(value);
21
+ }
22
+ }
23
+
24
+ return env;
25
+ }
26
+
27
+ // The variables npm run sets for a lifecycle script, so a workspace script behaves
28
+ // the same under sumlyzer. Only the fields npm itself exposes (npm/rfcs#183).
29
+ export function npmScriptEnv({ pkg, pkgDir, event, script }) {
30
+ return {
31
+ ...flattenPackageFields({
32
+ name: pkg.name,
33
+ version: pkg.version,
34
+ config: pkg.config,
35
+ engines: pkg.engines,
36
+ // npm exposes nothing for a string "bin", only for the object form.
37
+ bin: typeof pkg.bin === "object" ? pkg.bin : undefined
38
+ }, "npm_package_"),
39
+ npm_package_json: path.resolve(pkgDir, "package.json"),
40
+ npm_lifecycle_event: event,
41
+ npm_lifecycle_script: script
42
+ };
43
+ }
@@ -0,0 +1,12 @@
1
+ // Windows env names are case-insensitive ("Path"): replace the key instead of adding a duplicate.
2
+ export function withPath(env, value, platform = process.platform) {
3
+ if (platform !== "win32") {
4
+ return { ...env, PATH: value };
5
+ }
6
+
7
+ const isPathKey = (key) => key.toUpperCase() === "PATH";
8
+ const key = Object.keys(env).find(isPathKey) ?? "Path";
9
+ const rest = Object.fromEntries(Object.entries(env).filter(([name]) => !isPathKey(name)));
10
+
11
+ return { ...rest, [key]: value };
12
+ }
package/src/reporter.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { styleText } from "node:util";
2
2
 
3
- export const green = (str) => styleText("green", str);
3
+ const green = (str) => styleText("green", str);
4
4
  export const red = (str) => styleText("red", str);
5
- export const blue = (str) => styleText("blue", str);
5
+ const blue = (str) => styleText("blue", str);
6
6
  export const dim = (str) => styleText("dim", str);
7
- export const bold = (str) => styleText("bold", str);
7
+ const bold = (str) => styleText("bold", str);
8
8
 
9
9
  export function formatSeconds(ms) {
10
10
  const seconds = Number.isFinite(ms) ? ms / 1000 : 0;
package/src/run.mjs CHANGED
@@ -1,405 +1,23 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { readFileSync } from "node:fs";
3
- import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
1
+ import { mkdtemp, rm } from "node:fs/promises";
4
2
  import { tmpdir } from "node:os";
5
3
  import path from "node:path";
6
4
 
7
- import { glob } from "glob";
5
+ import { dim, workspaceName, printSummary, reportOutcome } from "./reporter.mjs";
6
+ import { resolveWorkspacePaths, loadWorkspaces } from "./workspaces.mjs";
7
+ import { runWorkspaces } from "./schedule.mjs";
8
+ import { writeJunitReport } from "./junitReport.mjs";
9
+ import { filterChangedWorkspaces } from "./changed.mjs";
10
+ import { watchAndRerun } from "./watch.mjs";
8
11
 
9
- import { buildJunitReport } from "./junit.mjs";
10
- import { buildDependentsGraph, expandWithDependents } from "./graph.mjs";
11
- import { watchWorkspaces } from "./watch.mjs";
12
- import { red, dim, workspaceName, githubGroupSyntax, printWorkspaceResult, printSummary, reportOutcome } from "./reporter.mjs";
13
- import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "./errors.mjs";
14
- import { hasOwnReporter, prepareEnv, parseResult } from "./runners/nodeTest.mjs";
15
- import { getChangedFiles, resolveDefaultRef, selectChangedWorkspaces } from "./changed.mjs";
16
-
17
- const runner = { hasOwnReporter, prepareEnv, parseResult };
18
-
19
- // Rethink this synchronous approach in case of very large package.json files, or huge amount of workspaces,
20
- // but for now it's simpler than async and should be fine in practice.
21
- function readJson(file) {
22
- return JSON.parse(readFileSync(file, "utf8"));
23
- }
24
-
25
- // Splits "workspaces" entries into directory-only glob patterns to include and
26
- // (from any leading "!") patterns to exclude, matching npm's own interpretation
27
- // of the field.
28
- function splitWorkspacePatterns(workspaces) {
29
- const patterns = [];
30
- const ignore = ["**/node_modules/**"];
31
-
32
- for (const entry of workspaces) {
33
- if (entry.startsWith("!")) {
34
- ignore.push(entry.slice(1));
35
- }
36
- else {
37
- patterns.push(entry.endsWith("/") ? entry : `${entry}/`);
38
- }
39
- }
40
-
41
- return { patterns, ignore };
42
- }
43
-
44
- // The "workspaces" field holds glob patterns (e.g. "packages/*"), not necessarily
45
- // concrete paths. Resolve it the same way npm itself does: glob each pattern
46
- // against directories only, in declaration order.
47
- async function resolveWorkspacePaths(root, workspaces) {
48
- const { patterns, ignore } = splitWorkspacePatterns(workspaces);
49
- const resolved = new Set();
50
-
51
- for (const pattern of patterns) {
52
- const matches = await glob(pattern, { cwd: root, ignore });
53
-
54
- for (const match of matches.sort((a, b) => a.localeCompare(b, "en"))) {
55
- resolved.add(match);
56
- }
57
- }
58
-
59
- return [...resolved];
60
- }
61
-
62
- function classifyWorkspace(root, wsPath, scriptName) {
63
- const pkgFile = path.join(root, wsPath, "package.json");
64
- let pkg;
65
- try {
66
- pkg = readJson(pkgFile);
67
- }
68
- catch (error) {
69
- return error.code === "ENOENT" ? { kind: "absent" } : { kind: "invalid", message: error.message };
70
- }
71
-
72
- const script = pkg.scripts?.[scriptName];
73
- if (!script) {
74
- return { kind: "absent" };
75
- }
76
-
77
- const pre = pkg.scripts?.[`pre${scriptName}`];
78
- const post = pkg.scripts?.[`post${scriptName}`];
79
-
80
- const hasConflict = [pre, script, post].some((command) => command && runner.hasOwnReporter(command));
81
- return hasConflict ? { kind: "ownReporterConflict" } : { kind: "eligible", pre, script, post };
82
- }
83
-
84
- function listEligibleWorkspaces(root, workspaces, scriptName) {
85
- const eligible = [];
86
- const ownReporterConflicts = [];
87
- const invalidPackageJson = [];
88
- const scriptCommands = new Map();
89
-
90
- for (const wsPath of workspaces) {
91
- const classification = classifyWorkspace(root, wsPath, scriptName);
92
- switch (classification.kind) {
93
- case "invalid":
94
- invalidPackageJson.push({ wsPath, message: classification.message });
95
- break;
96
- case "ownReporterConflict":
97
- ownReporterConflicts.push(wsPath);
98
- break;
99
- case "eligible":
100
- eligible.push(wsPath);
101
- scriptCommands.set(wsPath, { pre: classification.pre, script: classification.script, post: classification.post });
102
- break;
103
- }
104
- }
105
-
106
- return { eligible, ownReporterConflicts, invalidPackageJson, scriptCommands };
107
- }
108
-
109
- function buildWorkspacePath(root, wsPath) {
110
- const rootDir = path.resolve(root);
111
- const binDirs = [];
112
- let dir = path.resolve(root, wsPath);
113
-
114
- while (true) {
115
- binDirs.push(path.join(dir, "node_modules", ".bin"));
116
- if (dir === rootDir) break;
117
- const parent = path.dirname(dir);
118
- if (parent === dir) break;
119
- dir = parent;
120
- }
121
-
122
- return [...binDirs, process.env.PATH].join(path.delimiter);
123
- }
124
-
125
- // The spawned shell is the actual test runner's parent, so killing just it
126
- // leaves that grandchild running. Giving it its own process group (POSIX)
127
- // or asking Windows to kill the whole tree ensures nothing is left behind.
128
- function killWorkspaceChild(child) {
129
- if (process.platform === "win32") {
130
- spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"]);
131
- return;
132
- }
133
-
134
- try {
135
- process.kill(-child.pid, "SIGTERM");
136
- }
137
- catch {
138
- child.kill("SIGTERM");
139
- }
140
- }
141
-
142
- function waitForExit(child) {
143
- return new Promise((resolve, reject) => {
144
- child.on("error", reject);
145
- child.on("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
146
- });
147
- }
148
-
149
- async function runPhase(command, options, activeChildren) {
150
- const child = spawn(command, options);
151
- activeChildren.add(child);
152
- const stdoutChunks = [];
153
- const stderrChunks = [];
154
-
155
- child.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
156
- child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
157
-
158
- try {
159
- const exitCode = await waitForExit(child);
160
- return { exitCode, stdoutChunks, stderrChunks };
161
- }
162
- finally {
163
- activeChildren.delete(child);
164
- }
165
- }
166
-
167
- // Only the main script gets sumlyzer's own node:test reporter forced onto it via
168
- // NODE_OPTIONS. pre/post run with a plain environment: forcing our JSON reporter onto
169
- // them too would let a hook that happens to run its own `node --test` silently overwrite
170
- // the main script's parsed counts/JUnit report with its own, whichever phase runs last.
171
- function buildPhaseOptions({ root, wsPath, junitDestPath }) {
172
- const cwd = path.join(root, wsPath);
173
- const PATH = buildWorkspacePath(root, wsPath);
174
- const shellOptions = { cwd, shell: true, detached: process.platform !== "win32" };
175
-
176
- return {
177
- hook: { ...shellOptions, env: { ...process.env, PATH } },
178
- script: { ...shellOptions, env: { ...runner.prepareEnv(process.env, junitDestPath), PATH } }
179
- };
180
- }
181
-
182
- async function captureWorkspaceOutput({ root, wsPath, scriptPhases, junitDestPath, activeChildren }) {
183
- const phaseOptions = buildPhaseOptions({ root, wsPath, junitDestPath });
184
-
185
- const phases = [
186
- scriptPhases.pre && { command: scriptPhases.pre, options: phaseOptions.hook },
187
- { command: scriptPhases.script, options: phaseOptions.script },
188
- scriptPhases.post && { command: scriptPhases.post, options: phaseOptions.hook }
189
- ].filter(Boolean);
190
-
191
- const stdoutChunks = [];
192
- const stderrChunks = [];
193
- let exitCode = 0;
194
-
195
- for (const { command, options } of phases) {
196
- const phase = await runPhase(command, options, activeChildren);
197
- exitCode = phase.exitCode;
198
- stdoutChunks.push(...phase.stdoutChunks);
199
- stderrChunks.push(...phase.stderrChunks);
200
-
201
- if (exitCode !== 0) {
202
- break;
203
- }
204
- }
205
-
206
- return {
207
- exitCode,
208
- stdout: Buffer.concat(stdoutChunks).toString("utf8"),
209
- stderr: Buffer.concat(stderrChunks).toString("utf8")
210
- };
211
- }
212
-
213
- function killActiveChildren(activeChildren) {
214
- for (const child of activeChildren) {
215
- killWorkspaceChild(child);
216
- }
217
- }
218
-
219
- async function withInterruptHandling(activeChildren, run) {
220
- function onInterrupt(signal) {
221
- killActiveChildren(activeChildren);
222
- process.exit(signal === "SIGINT" ? 130 : 143);
223
- }
224
-
225
- process.once("SIGINT", onInterrupt);
226
- process.once("SIGTERM", onInterrupt);
227
-
228
- try {
229
- return await run();
230
- }
231
- finally {
232
- process.off("SIGINT", onInterrupt);
233
- process.off("SIGTERM", onInterrupt);
234
- }
235
- }
236
-
237
- async function runWorkspaceScript({ root, wsPath, scriptPhases, junitDestPath, activeChildren }) {
238
- const start = Date.now();
239
- const captured = await captureWorkspaceOutput({ root, wsPath, scriptPhases, junitDestPath, activeChildren });
240
-
241
- return {
242
- wsPath,
243
- exitCode: captured.exitCode,
244
- durationMs: Date.now() - start,
245
- junitDestPath,
246
- ...runner.parseResult(captured)
247
- };
248
- }
249
-
250
- async function collectJunitEntries(results) {
251
- const entries = [];
252
- const missing = [];
253
-
254
- for (const result of results) {
255
- if (!result.junitDestPath) {
256
- continue;
257
- }
258
- try {
259
- entries.push({ name: workspaceName(result.wsPath), xml: await readFile(result.junitDestPath, "utf8") });
260
- }
261
- catch {
262
- missing.push(workspaceName(result.wsPath));
263
- }
264
- }
265
-
266
- return { entries, missing };
267
- }
268
-
269
- // A worker leaves its slot in `results` undefined when it never got to start
270
- // (--ff stopped scheduling first); that's the signal to bucket it as skipped.
271
- function partitionResults(results, workspacesToRun) {
272
- const completed = [];
273
- const skipped = [];
274
- for (const [index, result] of results.entries()) {
275
- if (result === undefined) {
276
- skipped.push(workspacesToRun[index]);
277
- }
278
- else {
279
- completed.push(result);
280
- }
281
- }
282
-
283
- return { completed, skipped };
284
- }
285
-
286
- async function runWorkspaces({ root, workspacesToRun, scriptName, scriptCommands, ff, junitDir, concurrency }) {
287
- const results = new Array(workspacesToRun.length);
288
- const ciGroup = githubGroupSyntax(process.env);
289
- const activeChildren = new Set();
290
- let stopScheduling = false;
291
- let nextIndex = 0;
292
-
293
-
294
- async function worker() {
295
- while (!stopScheduling && nextIndex < workspacesToRun.length) {
296
- const index = nextIndex++;
297
- const wsPath = workspacesToRun[index];
298
- const name = workspaceName(wsPath);
299
- process.stdout.write(dim(`running ${name}\n`));
300
-
301
- const junitDestPath = junitDir ? path.join(junitDir, `${index}.xml`) : undefined;
302
-
303
- let result;
304
- try {
305
- result = await runWorkspaceScript({ root, wsPath, scriptPhases: scriptCommands.get(wsPath), junitDestPath, activeChildren });
306
- }
307
- catch (error) {
308
- stopScheduling = true;
309
- killActiveChildren(activeChildren);
310
- throw new WorkspaceLaunchError(wsPath, scriptName, error);
311
- }
312
- results[index] = result;
313
- printWorkspaceResult(name, result, ciGroup);
314
-
315
- if (result.exitCode !== 0 && ff) {
316
- stopScheduling = true;
317
- }
318
- }
319
- }
320
-
321
- const workerCount = Math.max(1, Math.min(concurrency, workspacesToRun.length));
322
- await withInterruptHandling(activeChildren, () => Promise.all(Array.from({ length: workerCount }, worker)));
323
-
324
- return partitionResults(results, workspacesToRun);
325
- }
326
-
327
- // Resolves which ref to diff against: the explicit --ref, or an auto-detected
328
- // one (logged so the choice is never silent).
329
- function resolveRefToUse(root, explicitRef) {
330
- if (explicitRef) {
331
- return { ref: explicitRef, label: explicitRef };
332
- }
333
-
334
- const resolved = resolveDefaultRef(root);
335
- console.log(dim(`--changed: no --ref given, comparing against "${resolved.label}" (${resolved.reason})`));
336
- return resolved;
337
- }
338
-
339
- // Returns the filtered workspace list to run, or null when nothing should run
340
- // (already reported to the user), so main() can return early.
341
- function applyChangedFilter(root, resolvedWorkspaces, workspacesToRun, explicitRef) {
342
- const { ref, label } = resolveRefToUse(root, explicitRef);
343
-
344
- const changedFiles = getChangedFiles(root, ref);
345
- if (changedFiles.length === 0) {
346
- console.log(dim(`No changes detected against "${label}".`));
347
- return null;
348
- }
349
-
350
- const { workspaces: changedWorkspaces, rootChangeFiles } = selectChangedWorkspaces(resolvedWorkspaces, changedFiles);
351
-
352
- if (rootChangeFiles.length > 0) {
353
- const suffix = rootChangeFiles.length > 1 ? ` (+${rootChangeFiles.length - 1} more)` : "";
354
- console.log(dim(`--changed: "${rootChangeFiles[0]}"${suffix} is outside every workspace, ignoring`));
355
- }
356
-
357
- const filtered = workspacesToRun.filter((wsPath) => changedWorkspaces.has(wsPath));
358
- console.log(dim(`--changed: running ${filtered.length}/${workspacesToRun.length} workspace(s) with changes since "${label}"`));
359
-
360
- if (filtered.length === 0) {
361
- console.log(dim("No eligible workspace changed."));
362
- return null;
363
- }
364
-
365
- return filtered;
366
- }
367
-
368
- const DEFAULT_JUNIT_FILENAME = "junit.xml";
369
-
370
- async function resolveJunitDestination(root, junitPath) {
371
- const destination = path.resolve(root, junitPath);
372
- const isExistingDirectory = await stat(destination).then((stats) => stats.isDirectory(), () => false);
373
-
374
- return isExistingDirectory ? path.join(destination, DEFAULT_JUNIT_FILENAME) : destination;
375
- }
376
-
377
- async function writeJunitReport(root, junitPath, results) {
378
- const { entries, missing } = await collectJunitEntries(results);
379
- const destination = await resolveJunitDestination(root, junitPath);
380
-
381
- if (missing.length > 0) {
382
- console.log(dim(`${missing.length} workspace(s) missing from the JUnit report: ${missing.join(", ")}`));
383
- }
384
-
385
- try {
386
- await writeFile(destination, buildJunitReport(entries));
387
- }
388
- catch (error) {
389
- console.error(red(`Could not write JUnit report to "${destination}" (${error.message})`));
390
- process.exitCode = 1;
391
- }
392
- }
393
-
394
- async function runOnce({ root, workspacesToRun, scriptName, scriptCommands, ff, junitPath, concurrency }) {
12
+ async function runOnce(options, workspaces, junitPath) {
395
13
  const junitDir = junitPath ? await mkdtemp(path.join(tmpdir(), "sumlyzer-junit-")) : null;
396
14
 
397
15
  let completed, skipped;
398
16
  try {
399
- ({ completed, skipped } = await runWorkspaces({ root, workspacesToRun, scriptName, scriptCommands, ff, junitDir, concurrency }));
17
+ ({ completed, skipped } = await runWorkspaces({ ...options, workspaces, junitDir }));
400
18
 
401
19
  if (junitDir) {
402
- await writeJunitReport(root, junitPath, completed);
20
+ await writeJunitReport(options.root, junitPath, completed);
403
21
  }
404
22
  }
405
23
  finally {
@@ -412,91 +30,31 @@ async function runOnce({ root, workspacesToRun, scriptName, scriptCommands, ff,
412
30
  reportOutcome(completed);
413
31
  }
414
32
 
415
- // A workspace's own test run can write files inside itself (e.g. coverage, though that's
416
- // already ignored) shortly after it exits. Without this, those trailing writes get picked
417
- // up as a fresh change and the workspace re-runs itself indefinitely.
418
- const SETTLE_COOLDOWN_MS = 500;
419
-
420
- async function handleWatchChange({ changedPaths, dependentsGraph, settling, workspacesToRun, root, scriptName, scriptCommands, ff, concurrency }) {
421
- const affected = [...expandWithDependents(changedPaths, dependentsGraph)]
422
- .filter((wsPath) => workspacesToRun.includes(wsPath));
423
-
424
- if (affected.length === 0) {
425
- return;
426
- }
427
-
428
- const changedNames = [...changedPaths].map(workspaceName).join(", ");
429
- const affectedNames = affected.map(workspaceName).join(", ");
430
- console.log(dim(`\n[watch] change detected in ${changedNames} → re-running: ${affectedNames}\n`));
431
-
432
- for (const wsPath of affected) {
433
- settling.add(wsPath);
434
- }
435
- try {
436
- await runOnce({ root, workspacesToRun: affected, scriptName, scriptCommands, ff, junitPath: undefined, concurrency });
437
- }
438
- finally {
439
- setTimeout(() => {
440
- for (const wsPath of affected) {
441
- settling.delete(wsPath);
442
- }
443
- }, SETTLE_COOLDOWN_MS).unref();
33
+ function reportOwnReporterSkips(scriptName, ownReporterConflicts) {
34
+ for (const wsPath of ownReporterConflicts) {
35
+ console.log(dim(`⊘ ${workspaceName(wsPath)}: skipped, own --test-reporter detected in its "${scriptName}" script`));
444
36
  }
445
37
  }
446
38
 
447
- function runWatchMode({ root, workspaces, workspacesToRun, scriptName, scriptCommands, ff, concurrency }) {
448
- const dependentsGraph = buildDependentsGraph(root, workspaces);
449
- const settling = new Set();
450
-
451
- const watcher = watchWorkspaces({
452
- root,
453
- workspaces,
454
- isSuppressed: (wsPath) => settling.has(wsPath),
455
- onChange: (changedPaths) => handleWatchChange({ changedPaths, dependentsGraph, settling, workspacesToRun, root, scriptName, scriptCommands, ff, concurrency })
456
- });
457
-
458
- return new Promise((resolve) => {
459
- const stop = () => {
460
- console.log(dim("\n[watch] stopping.\n"));
461
- watcher.close();
462
- resolve();
463
- };
464
- process.once("SIGINT", stop);
465
- process.once("SIGTERM", stop);
466
- });
467
- }
468
-
469
39
  export async function main({ root, scriptName, ff, junitPath, concurrency = 1, changed = false, ref, watch = false }) {
40
+ const options = { root, scriptName, ff, concurrency };
470
41
 
471
- const { workspaces } = readJson(path.join(root, "package.json"));
472
-
473
- if (!workspaces || workspaces.length === 0) {
474
- throw new NoWorkspacesError();
475
- }
476
-
477
- const resolvedWorkspaces = await resolveWorkspacePaths(root, workspaces);
478
-
479
- const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson, scriptCommands } = listEligibleWorkspaces(root, resolvedWorkspaces, scriptName);
42
+ const allPaths = await resolveWorkspacePaths(root);
43
+ const { runnable, ownReporterConflicts } = loadWorkspaces(root, allPaths, scriptName);
480
44
 
481
- if (invalidPackageJson.length > 0) {
482
- throw new InvalidPackageJsonError(invalidPackageJson);
483
- }
484
-
485
- for (const wsPath of ownReporterConflicts) {
486
- console.log(dim(`⊘ ${workspaceName(wsPath)}: skipped, own --test-reporter detected in its "${scriptName}" script`));
487
- }
45
+ reportOwnReporterSkips(scriptName, ownReporterConflicts);
488
46
 
489
- if (workspacesToRun.length === 0) {
47
+ if (runnable.length === 0) {
490
48
  console.log(dim(ownReporterConflicts.length > 0
491
49
  ? `All workspaces with a "${scriptName}" script were skipped (own --test-reporter detected).`
492
50
  : `No workspace has a "${scriptName}" script.`));
493
51
  return;
494
52
  }
495
53
 
496
- let finalWorkspacesToRun = workspacesToRun;
54
+ let workspaces = runnable;
497
55
  if (changed) {
498
- finalWorkspacesToRun = applyChangedFilter(root, resolvedWorkspaces, workspacesToRun, ref);
499
- if (finalWorkspacesToRun === null) {
56
+ workspaces = filterChangedWorkspaces({ root, allPaths, workspaces, ref });
57
+ if (workspaces === null) {
500
58
  if (junitPath) {
501
59
  console.log(dim(`--junit: no report written to "${junitPath}" (no workspace ran)`));
502
60
  }
@@ -504,9 +62,9 @@ export async function main({ root, scriptName, ff, junitPath, concurrency = 1, c
504
62
  }
505
63
  }
506
64
 
507
- await runOnce({ root, workspacesToRun: finalWorkspacesToRun, scriptName, scriptCommands, ff, junitPath, concurrency });
65
+ await runOnce(options, workspaces, junitPath);
508
66
 
509
67
  if (watch) {
510
- await runWatchMode({ root, workspaces: resolvedWorkspaces, workspacesToRun: finalWorkspacesToRun, scriptName, scriptCommands, ff, concurrency });
68
+ await watchAndRerun({ root, allPaths, workspaces, rerun: (affected) => runOnce(options, affected) });
511
69
  }
512
70
  }
package/src/runner.mjs ADDED
@@ -0,0 +1,2 @@
1
+ // The only supported test runner; swap this import to support another one.
2
+ export * as runner from "./runners/nodeTest.mjs";
@@ -1,9 +1,8 @@
1
- import { fileURLToPath } from "node:url";
2
-
3
1
  import { stripNpmNoise } from "../parseOutput.mjs";
4
2
  import { parseReporterEvents, renderFailureRecap, renderSummaryText } from "../testEventReporter.mjs";
5
3
 
6
- const TEST_EVENT_REPORTER_PATH = fileURLToPath(new URL("../testEventReporter.mjs", import.meta.url));
4
+ // URL, not path: Windows' ESM loader rejects "D:\..." specifiers.
5
+ const TEST_EVENT_REPORTER_URL = new URL("../testEventReporter.mjs", import.meta.url).href;
7
6
 
8
7
  const OWN_TEST_REPORTER_FLAG = /--test-reporter(?!-destination)\b/;
9
8
 
@@ -11,10 +10,15 @@ export function hasOwnReporter(scriptCommand) {
11
10
  return OWN_TEST_REPORTER_FLAG.test(scriptCommand);
12
11
  }
13
12
 
13
+ // node unescapes "\\" inside quoted NODE_OPTIONS values.
14
+ function quoteNodeOption(value) {
15
+ return `"${value.replace(/[\\"]/g, "\\$&")}"`;
16
+ }
17
+
14
18
  export function prepareEnv(env, junitDestPath) {
15
19
  const existing = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ` : "";
16
- const testReporterFlags = `--test-reporter="${TEST_EVENT_REPORTER_PATH}" --test-reporter-destination=stdout`;
17
- const junitFlags = junitDestPath ? ` --test-reporter=junit --test-reporter-destination="${junitDestPath}"` : "";
20
+ const testReporterFlags = `--test-reporter=${quoteNodeOption(TEST_EVENT_REPORTER_URL)} --test-reporter-destination=stdout`;
21
+ const junitFlags = junitDestPath ? ` --test-reporter=junit --test-reporter-destination=${quoteNodeOption(junitDestPath)}` : "";
18
22
 
19
23
  // Drop NODE_TEST_CONTEXT: if sumlyzer itself is invoked from inside a node:test run, this var would otherwise leak.
20
24
  const rest = { ...env };
@@ -0,0 +1,60 @@
1
+ import path from "node:path";
2
+
3
+ import { dim, githubGroupSyntax, printWorkspaceResult } from "./reporter.mjs";
4
+ import { WorkspaceLaunchError } from "./errors.mjs";
5
+ import { killAll, runWorkspace, withInterruptHandling } from "./workspaceProcess.mjs";
6
+
7
+ // A slot left undefined never started (--ff stopped scheduling first): skipped.
8
+ function partitionResults(results, workspaces) {
9
+ const completed = [];
10
+ const skipped = [];
11
+ for (const [index, result] of results.entries()) {
12
+ if (result === undefined) {
13
+ skipped.push(workspaces[index].path);
14
+ }
15
+ else {
16
+ completed.push(result);
17
+ }
18
+ }
19
+
20
+ return { completed, skipped };
21
+ }
22
+
23
+ export async function runWorkspaces({ root, workspaces, scriptName, ff, concurrency, junitDir }) {
24
+ const results = new Array(workspaces.length);
25
+ const ciGroup = githubGroupSyntax(process.env);
26
+ const activeChildren = new Set();
27
+ let stopScheduling = false;
28
+ let nextIndex = 0;
29
+
30
+ async function worker() {
31
+ while (!stopScheduling && nextIndex < workspaces.length) {
32
+ const index = nextIndex++;
33
+ const workspace = workspaces[index];
34
+ process.stdout.write(dim(`running ${workspace.name}\n`));
35
+
36
+ const junitDestPath = junitDir ? path.join(junitDir, `${index}.xml`) : undefined;
37
+
38
+ let result;
39
+ try {
40
+ result = await runWorkspace({ root, workspace, junitDestPath, activeChildren });
41
+ }
42
+ catch (error) {
43
+ stopScheduling = true;
44
+ killAll(activeChildren);
45
+ throw new WorkspaceLaunchError(workspace.path, scriptName, error);
46
+ }
47
+ results[index] = result;
48
+ printWorkspaceResult(workspace.name, result, ciGroup);
49
+
50
+ if (result.exitCode !== 0 && ff) {
51
+ stopScheduling = true;
52
+ }
53
+ }
54
+ }
55
+
56
+ const workerCount = Math.max(1, Math.min(concurrency, workspaces.length));
57
+ await withInterruptHandling(activeChildren, () => Promise.all(Array.from({ length: workerCount }, worker)));
58
+
59
+ return partitionResults(results, workspaces);
60
+ }
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+
3
+ import { npmScriptEnv } from "./npmScriptEnv.mjs";
4
+ import { withPath } from "./pathEnv.mjs";
5
+ import { runner } from "./runner.mjs";
6
+
7
+ // node_modules/.bin of the workspace and each parent up to the root, like npm run.
8
+ function binPath(root, cwd) {
9
+ const rootDir = path.resolve(root);
10
+ const binDirs = [];
11
+ let dir = path.resolve(cwd);
12
+
13
+ while (true) {
14
+ binDirs.push(path.join(dir, "node_modules", ".bin"));
15
+ const parent = path.dirname(dir);
16
+ if (dir === rootDir || parent === dir) {
17
+ break;
18
+ }
19
+ dir = parent;
20
+ }
21
+
22
+ return [...binDirs, process.env.PATH].join(path.delimiter);
23
+ }
24
+
25
+ // Only the main script gets the runner's reporter: a hook running its own
26
+ // `node --test` would otherwise overwrite the main script's counts and JUnit report.
27
+ export function scriptEnv({ root, workspace, phase, junitDestPath }) {
28
+ const cwd = path.join(root, workspace.path);
29
+ const base = phase.isMain ? runner.prepareEnv(process.env, junitDestPath) : process.env;
30
+
31
+ return withPath(
32
+ { ...base, ...npmScriptEnv({ pkg: workspace.pkg, pkgDir: cwd, event: phase.event, script: phase.command }) },
33
+ binPath(root, cwd)
34
+ );
35
+ }
package/src/watch.mjs CHANGED
@@ -1,6 +1,9 @@
1
1
  import { watch } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
+ import { buildDependentsGraph, expandWithDependents } from "./graph.mjs";
5
+ import { dim, workspaceName } from "./reporter.mjs";
6
+
4
7
  const IGNORED_SEGMENTS = new Set(["node_modules", "coverage", ".git"]);
5
8
 
6
9
  function isIgnored(relPath) {
@@ -12,7 +15,7 @@ function matchWorkspace(relPath, workspaces) {
12
15
  return workspaces.find((wsPath) => normalized === wsPath || normalized.startsWith(`${wsPath}/`));
13
16
  }
14
17
 
15
- export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300, isSuppressed = () => false }) {
18
+ function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300, isSuppressed = () => false }) {
16
19
  const pending = new Set();
17
20
  let timer = null;
18
21
 
@@ -42,3 +45,54 @@ export function watchWorkspaces({ root, workspaces, onChange, debounceMs = 300,
42
45
  }
43
46
  };
44
47
  }
48
+
49
+ // A run can write files inside its own workspace (coverage, artifacts) just after it
50
+ // exits; ignoring them briefly stops the workspace from re-triggering itself forever.
51
+ const SETTLE_COOLDOWN_MS = 500;
52
+
53
+ // Runs `rerun` on each change, for the changed workspaces and their dependents,
54
+ // until SIGINT/SIGTERM.
55
+ export function watchAndRerun({ root, allPaths, workspaces, rerun }) {
56
+ const dependentsGraph = buildDependentsGraph(root, allPaths);
57
+ const byPath = new Map(workspaces.map((workspace) => [workspace.path, workspace]));
58
+ const settling = new Set();
59
+
60
+ async function onChange(changedPaths) {
61
+ const affected = [...expandWithDependents(changedPaths, dependentsGraph)]
62
+ .map((wsPath) => byPath.get(wsPath))
63
+ .filter(Boolean);
64
+ if (affected.length === 0) {
65
+ return;
66
+ }
67
+
68
+ const changedNames = [...changedPaths].map(workspaceName).join(", ");
69
+ const affectedNames = affected.map((workspace) => workspace.name).join(", ");
70
+ console.log(dim(`\n[watch] change detected in ${changedNames} → re-running: ${affectedNames}\n`));
71
+
72
+ for (const workspace of affected) {
73
+ settling.add(workspace.path);
74
+ }
75
+ try {
76
+ await rerun(affected);
77
+ }
78
+ finally {
79
+ setTimeout(() => {
80
+ for (const workspace of affected) {
81
+ settling.delete(workspace.path);
82
+ }
83
+ }, SETTLE_COOLDOWN_MS).unref();
84
+ }
85
+ }
86
+
87
+ const watcher = watchWorkspaces({ root, workspaces: allPaths, isSuppressed: (wsPath) => settling.has(wsPath), onChange });
88
+
89
+ return new Promise((resolve) => {
90
+ const stop = () => {
91
+ console.log(dim("\n[watch] stopping.\n"));
92
+ watcher.close();
93
+ resolve();
94
+ };
95
+ process.once("SIGINT", stop);
96
+ process.once("SIGTERM", stop);
97
+ });
98
+ }
@@ -0,0 +1,108 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ import { runner } from "./runner.mjs";
5
+ import { scriptEnv } from "./scriptEnv.mjs";
6
+
7
+ // The shell is the test runner's parent: kill the whole process group (POSIX)
8
+ // or tree (Windows), otherwise the runner outlives it.
9
+ function killTree(child) {
10
+ if (process.platform === "win32") {
11
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"]);
12
+ return;
13
+ }
14
+
15
+ try {
16
+ process.kill(-child.pid, "SIGTERM");
17
+ }
18
+ catch {
19
+ child.kill("SIGTERM");
20
+ }
21
+ }
22
+
23
+ export function killAll(activeChildren) {
24
+ for (const child of activeChildren) {
25
+ killTree(child);
26
+ }
27
+ }
28
+
29
+ export async function withInterruptHandling(activeChildren, run) {
30
+ function onInterrupt(signal) {
31
+ killAll(activeChildren);
32
+ process.exit(signal === "SIGINT" ? 130 : 143);
33
+ }
34
+
35
+ process.once("SIGINT", onInterrupt);
36
+ process.once("SIGTERM", onInterrupt);
37
+
38
+ try {
39
+ return await run();
40
+ }
41
+ finally {
42
+ process.off("SIGINT", onInterrupt);
43
+ process.off("SIGTERM", onInterrupt);
44
+ }
45
+ }
46
+
47
+ function waitForExit(child) {
48
+ return new Promise((resolve, reject) => {
49
+ child.on("error", reject);
50
+ child.on("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
51
+ });
52
+ }
53
+
54
+ async function runPhase(command, options, activeChildren) {
55
+ const child = spawn(command, options);
56
+ activeChildren.add(child);
57
+ const stdout = [];
58
+ const stderr = [];
59
+
60
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
61
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
62
+
63
+ try {
64
+ return { exitCode: await waitForExit(child), stdout, stderr };
65
+ }
66
+ finally {
67
+ activeChildren.delete(child);
68
+ }
69
+ }
70
+
71
+ // Phases stop at the first failure, like npm run.
72
+ async function runPhases({ root, workspace, junitDestPath, activeChildren }) {
73
+ const cwd = path.join(root, workspace.path);
74
+ const stdout = [];
75
+ const stderr = [];
76
+ let exitCode = 0;
77
+
78
+ for (const phase of workspace.phases) {
79
+ const options = { cwd, shell: true, detached: process.platform !== "win32", env: scriptEnv({ root, workspace, phase, junitDestPath }) };
80
+ const result = await runPhase(phase.command, options, activeChildren);
81
+ exitCode = result.exitCode;
82
+ stdout.push(...result.stdout);
83
+ stderr.push(...result.stderr);
84
+
85
+ if (exitCode !== 0) {
86
+ break;
87
+ }
88
+ }
89
+
90
+ return {
91
+ exitCode,
92
+ stdout: Buffer.concat(stdout).toString("utf8"),
93
+ stderr: Buffer.concat(stderr).toString("utf8")
94
+ };
95
+ }
96
+
97
+ export async function runWorkspace({ root, workspace, junitDestPath, activeChildren }) {
98
+ const start = Date.now();
99
+ const captured = await runPhases({ root, workspace, junitDestPath, activeChildren });
100
+
101
+ return {
102
+ wsPath: workspace.path,
103
+ exitCode: captured.exitCode,
104
+ durationMs: Date.now() - start,
105
+ junitDestPath,
106
+ ...runner.parseResult(captured)
107
+ };
108
+ }
@@ -0,0 +1,112 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { glob } from "glob";
5
+
6
+ import { workspaceName } from "./reporter.mjs";
7
+ import { runner } from "./runner.mjs";
8
+ import { NoWorkspacesError, InvalidPackageJsonError, RootPackageJsonError } from "./errors.mjs";
9
+
10
+ function readJson(file) {
11
+ return JSON.parse(readFileSync(file, "utf8"));
12
+ }
13
+
14
+ // npm's interpretation of "workspaces": directory globs, "!" entries excluded.
15
+ function splitWorkspacePatterns(entries) {
16
+ const patterns = [];
17
+ const ignore = ["**/node_modules/**"];
18
+
19
+ for (const entry of entries) {
20
+ if (entry.startsWith("!")) {
21
+ ignore.push(entry.slice(1));
22
+ }
23
+ else {
24
+ patterns.push(entry.endsWith("/") ? entry : `${entry}/`);
25
+ }
26
+ }
27
+
28
+ return { patterns, ignore };
29
+ }
30
+
31
+ export async function resolveWorkspacePaths(root) {
32
+ let rootPkg;
33
+ try {
34
+ rootPkg = readJson(path.join(root, "package.json"));
35
+ }
36
+ catch (error) {
37
+ throw new RootPackageJsonError(root, error);
38
+ }
39
+
40
+ if (!rootPkg.workspaces || rootPkg.workspaces.length === 0) {
41
+ throw new NoWorkspacesError();
42
+ }
43
+
44
+ const { patterns, ignore } = splitWorkspacePatterns(rootPkg.workspaces);
45
+ const resolved = new Set();
46
+
47
+ for (const pattern of patterns) {
48
+ // posix: "/" separators on Windows too, like git and fs.watch.
49
+ const matches = await glob(pattern, { cwd: root, ignore, posix: true });
50
+
51
+ for (const match of matches.sort((a, b) => a.localeCompare(b, "en"))) {
52
+ resolved.add(match);
53
+ }
54
+ }
55
+
56
+ return [...resolved];
57
+ }
58
+
59
+ // pre/post hooks run like npm run does, around the main script.
60
+ function scriptPhases(scripts, scriptName) {
61
+ return [
62
+ { event: `pre${scriptName}`, command: scripts[`pre${scriptName}`] },
63
+ { event: scriptName, command: scripts[scriptName], isMain: true },
64
+ { event: `post${scriptName}`, command: scripts[`post${scriptName}`] }
65
+ ].filter((phase) => phase.command);
66
+ }
67
+
68
+ function loadWorkspace(root, wsPath, scriptName) {
69
+ let pkg;
70
+ try {
71
+ pkg = readJson(path.join(root, wsPath, "package.json"));
72
+ }
73
+ catch (error) {
74
+ return error.code === "ENOENT" ? { kind: "absent" } : { kind: "invalid", message: error.message };
75
+ }
76
+
77
+ if (!pkg.scripts?.[scriptName]) {
78
+ return { kind: "absent" };
79
+ }
80
+
81
+ const phases = scriptPhases(pkg.scripts, scriptName);
82
+ if (phases.some((phase) => runner.hasOwnReporter(phase.command))) {
83
+ return { kind: "ownReporterConflict" };
84
+ }
85
+
86
+ return { kind: "runnable", workspace: { path: wsPath, name: workspaceName(wsPath), pkg, phases } };
87
+ }
88
+
89
+ export function loadWorkspaces(root, wsPaths, scriptName) {
90
+ const runnable = [];
91
+ const ownReporterConflicts = [];
92
+ const invalid = [];
93
+
94
+ for (const wsPath of wsPaths) {
95
+ const loaded = loadWorkspace(root, wsPath, scriptName);
96
+ if (loaded.kind === "runnable") {
97
+ runnable.push(loaded.workspace);
98
+ }
99
+ else if (loaded.kind === "ownReporterConflict") {
100
+ ownReporterConflicts.push(wsPath);
101
+ }
102
+ else if (loaded.kind === "invalid") {
103
+ invalid.push({ wsPath, message: loaded.message });
104
+ }
105
+ }
106
+
107
+ if (invalid.length > 0) {
108
+ throw new InvalidPackageJsonError(invalid);
109
+ }
110
+
111
+ return { runnable, ownReporterConflicts };
112
+ }