sumlyzer 1.4.0 → 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/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
+ }