sumlyzer 1.4.1 → 1.6.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,30 @@
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 { resolveWorkspacePaths, loadWorkspaces } from "./workspaces.mjs";
6
+ import { runWorkspaces } from "./schedule.mjs";
7
+ import { writeJunitReport } from "./junitReport.mjs";
8
+ import { resolveChangedRef, selectAffectedWorkspaces } from "./changed.mjs";
9
+ import { watchAndRerun } from "./watch.mjs";
8
10
 
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 }) {
11
+ // Returns whether the run failed: a workspace failed or the JUnit report couldn't be written.
12
+ async function runOnce({ options, reporter, workspaces, junitPath }) {
395
13
  const junitDir = junitPath ? await mkdtemp(path.join(tmpdir(), "sumlyzer-junit-")) : null;
396
14
 
397
- let completed, skipped;
15
+ let completed, skipped, junit;
398
16
  try {
399
- ({ completed, skipped } = await runWorkspaces({ root, workspacesToRun, scriptName, scriptCommands, ff, junitDir, concurrency }));
17
+ ({ completed, skipped } = await runWorkspaces({
18
+ ...options,
19
+ workspaces,
20
+ junitDir,
21
+ onStart: (workspace) => reporter.printWorkspaceStart(workspace.name),
22
+ onResult: (workspace, result) => reporter.printWorkspaceResult(workspace.name, result)
23
+ }));
400
24
 
401
25
  if (junitDir) {
402
- await writeJunitReport(root, junitPath, completed);
26
+ junit = await writeJunitReport(options.root, junitPath, completed);
27
+ reporter.printJunitReport(junit);
403
28
  }
404
29
  }
405
30
  finally {
@@ -408,105 +33,73 @@ async function runOnce({ root, workspacesToRun, scriptName, scriptCommands, ff,
408
33
  }
409
34
  }
410
35
 
411
- printSummary(completed, skipped);
412
- reportOutcome(completed);
413
- }
414
-
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));
36
+ reporter.printSummary(completed, skipped);
37
+ reporter.reportOutcome(completed);
423
38
 
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();
444
- }
39
+ return completed.some((result) => result.exitCode !== 0) || Boolean(junit?.error);
445
40
  }
446
41
 
447
- function runWatchMode({ root, workspaces, workspacesToRun, scriptName, scriptCommands, ff, concurrency }) {
448
- const dependentsGraph = buildDependentsGraph(root, workspaces);
449
- const settling = new Set();
42
+ // Returns the workspaces to run, or null when nothing changed.
43
+ function selectChanged({ reporter, root, allPaths, workspaces, ref }) {
44
+ const changedRef = resolveChangedRef(root, ref);
45
+ reporter.printChangedRef(changedRef);
450
46
 
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
- });
47
+ const selection = selectAffectedWorkspaces({ root, allPaths, workspaces, ref: changedRef.ref });
48
+ reporter.printChangedSelection({ label: changedRef.label, total: workspaces.length, selection });
457
49
 
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
- });
50
+ return selection.affected.length > 0 ? selection.affected : null;
467
51
  }
468
52
 
469
- export async function main({ root, scriptName, ff, junitPath, concurrency = 1, changed = false, ref, watch = false }) {
53
+ /**
54
+ * @param {object} params
55
+ * @param {string} params.root
56
+ * @param {string} params.scriptName
57
+ * @param {boolean} params.ff
58
+ * @param {string} [params.junitPath]
59
+ * @param {number} [params.concurrency]
60
+ * @param {boolean} [params.changed]
61
+ * @param {string} [params.ref]
62
+ * @param {boolean} [params.watch]
63
+ * @param {typeof import("./reporter.mjs")} params.reporter output for every step
64
+ * @returns {Promise<{ failed: boolean }>}
65
+ */
66
+ export async function main({ root, scriptName, ff, junitPath, concurrency = 1, changed = false, ref, watch = false, reporter }) {
67
+ const options = { root, scriptName, ff, concurrency };
470
68
 
471
- const { workspaces } = readJson(path.join(root, "package.json"));
69
+ const allPaths = await resolveWorkspacePaths(root);
70
+ const { runnable, ownReporterConflicts } = loadWorkspaces(root, allPaths, scriptName);
472
71
 
473
- if (!workspaces || workspaces.length === 0) {
474
- throw new NoWorkspacesError();
72
+ reporter.printOwnReporterSkips(scriptName, ownReporterConflicts);
73
+ if (runnable.length === 0) {
74
+ reporter.printNothingToRun(scriptName, ownReporterConflicts);
75
+ return { failed: false };
475
76
  }
476
77
 
477
- const resolvedWorkspaces = await resolveWorkspacePaths(root, workspaces);
478
-
479
- const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson, scriptCommands } = listEligibleWorkspaces(root, resolvedWorkspaces, scriptName);
480
-
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
- }
488
-
489
- if (workspacesToRun.length === 0) {
490
- console.log(dim(ownReporterConflicts.length > 0
491
- ? `All workspaces with a "${scriptName}" script were skipped (own --test-reporter detected).`
492
- : `No workspace has a "${scriptName}" script.`));
493
- return;
494
- }
495
-
496
- let finalWorkspacesToRun = workspacesToRun;
78
+ let workspaces = runnable;
497
79
  if (changed) {
498
- finalWorkspacesToRun = applyChangedFilter(root, resolvedWorkspaces, workspacesToRun, ref);
499
- if (finalWorkspacesToRun === null) {
80
+ workspaces = selectChanged({ reporter, root, allPaths, workspaces, ref });
81
+ if (workspaces === null) {
500
82
  if (junitPath) {
501
- console.log(dim(`--junit: no report written to "${junitPath}" (no workspace ran)`));
83
+ reporter.printNoJunitWritten(junitPath);
502
84
  }
503
- return;
85
+ return { failed: false };
504
86
  }
505
87
  }
506
88
 
507
- await runOnce({ root, workspacesToRun: finalWorkspacesToRun, scriptName, scriptCommands, ff, junitPath, concurrency });
89
+ let failed = await runOnce({ options, reporter, workspaces, junitPath });
508
90
 
509
91
  if (watch) {
510
- await runWatchMode({ root, workspaces: resolvedWorkspaces, workspacesToRun: finalWorkspacesToRun, scriptName, scriptCommands, ff, concurrency });
92
+ await watchAndRerun({
93
+ root,
94
+ allPaths,
95
+ workspaces,
96
+ rerun: async (affected, changedPaths) => {
97
+ reporter.printWatchRerun(changedPaths, affected);
98
+ failed = (await runOnce({ options, reporter, workspaces: affected, junitPath: undefined })) || failed;
99
+ }
100
+ });
101
+ reporter.printWatchStopping();
511
102
  }
103
+
104
+ return { failed };
512
105
  }
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,58 @@
1
+ import path from "node:path";
2
+
3
+ import { WorkspaceLaunchError } from "./errors.mjs";
4
+ import { killAll, runWorkspace, withInterruptHandling } from "./workspaceProcess.mjs";
5
+
6
+ // A slot left undefined never started (--ff stopped scheduling first): skipped.
7
+ function partitionResults(results, workspaces) {
8
+ const completed = [];
9
+ const skipped = [];
10
+ for (const [index, result] of results.entries()) {
11
+ if (result === undefined) {
12
+ skipped.push(workspaces[index]);
13
+ }
14
+ else {
15
+ completed.push(result);
16
+ }
17
+ }
18
+
19
+ return { completed, skipped };
20
+ }
21
+
22
+ export async function runWorkspaces({ root, workspaces, scriptName, ff, concurrency, junitDir, onStart, onResult }) {
23
+ const results = new Array(workspaces.length);
24
+ const activeChildren = new Set();
25
+ let stopScheduling = false;
26
+ let nextIndex = 0;
27
+
28
+ async function worker() {
29
+ while (!stopScheduling && nextIndex < workspaces.length) {
30
+ const index = nextIndex++;
31
+ const workspace = workspaces[index];
32
+ onStart(workspace);
33
+
34
+ const junitDestPath = junitDir ? path.join(junitDir, `${index}.xml`) : undefined;
35
+
36
+ let result;
37
+ try {
38
+ result = await runWorkspace({ root, workspace, junitDestPath, activeChildren });
39
+ }
40
+ catch (error) {
41
+ stopScheduling = true;
42
+ killAll(activeChildren);
43
+ throw new WorkspaceLaunchError(workspace, scriptName, error);
44
+ }
45
+ results[index] = result;
46
+ onResult(workspace, result);
47
+
48
+ if (result.exitCode !== 0 && ff) {
49
+ stopScheduling = true;
50
+ }
51
+ }
52
+ }
53
+
54
+ const workerCount = Math.max(1, Math.min(concurrency, workspaces.length));
55
+ await withInterruptHandling(activeChildren, () => Promise.all(Array.from({ length: workerCount }, worker)));
56
+
57
+ return partitionResults(results, workspaces);
58
+ }