@hughescr/stryker-bun-runner 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +502 -15
- package/dist/index.d.ts +388 -22
- package/dist/index.js +2540 -225
- package/dist/templates/coverage-preload.js +722 -64
- package/dist/templates/import-scan.js +902 -0
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import { PluginKind, declareClassPlugin } from "@stryker-mutator/api/plugin";
|
|
3
3
|
|
|
4
4
|
// src/bun-test-runner.ts
|
|
5
|
-
import { randomBytes as
|
|
6
|
-
import * as
|
|
5
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
6
|
+
import * as fsPromises3 from "node:fs/promises";
|
|
7
7
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
8
|
-
import
|
|
8
|
+
import path15 from "node:path";
|
|
9
9
|
import { tokens, commonTokens } from "@stryker-mutator/api/plugin";
|
|
10
10
|
import {
|
|
11
11
|
DryRunStatus,
|
|
@@ -15,11 +15,15 @@ import {
|
|
|
15
15
|
toMutantRunResult
|
|
16
16
|
} from "@stryker-mutator/api/test-runner";
|
|
17
17
|
|
|
18
|
-
// src/coverage/
|
|
19
|
-
import {
|
|
18
|
+
// src/coverage/dry-run-files.ts
|
|
19
|
+
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
20
|
+
import * as fsPromises from "node:fs/promises";
|
|
20
21
|
import path2 from "node:path";
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
|
|
23
|
+
// src/utils/is-plain-record.ts
|
|
24
|
+
function isPlainRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
}
|
|
23
27
|
|
|
24
28
|
// src/utils/private-temp-dir.ts
|
|
25
29
|
import { createHash } from "node:crypto";
|
|
@@ -34,9 +38,9 @@ class UnsafeTempDirError extends Error {
|
|
|
34
38
|
this.name = "UnsafeTempDirError";
|
|
35
39
|
}
|
|
36
40
|
}
|
|
37
|
-
function readLinuxPidSpaceIds() {
|
|
38
|
-
const bootId =
|
|
39
|
-
return `${bootId}:${
|
|
41
|
+
function readLinuxPidSpaceIds(readFile = readFileSync, readLink = readlinkSync) {
|
|
42
|
+
const bootId = readFile("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
43
|
+
return `${bootId}:${readLink("/proc/self/ns/pid")}`;
|
|
40
44
|
}
|
|
41
45
|
function computePidSpace(platform = process.platform, readIds = readLinuxPidSpaceIds) {
|
|
42
46
|
if (platform !== "linux") {
|
|
@@ -269,6 +273,1007 @@ function removeRunTempDirsOnExit(proc = process) {
|
|
|
269
273
|
});
|
|
270
274
|
}
|
|
271
275
|
|
|
276
|
+
// src/coverage/dry-run-files.ts
|
|
277
|
+
function watchListFileFor(generation) {
|
|
278
|
+
return `watch-list-${generation}.json`;
|
|
279
|
+
}
|
|
280
|
+
var ABORT_MARKER_FILE = "abort-marker.json";
|
|
281
|
+
function newGeneration() {
|
|
282
|
+
return randomBytes(16).toString("hex");
|
|
283
|
+
}
|
|
284
|
+
function newLaunchFile(dir, prefix) {
|
|
285
|
+
return path2.join(dir, `${prefix}-${process.pid}-${randomBytes(8).toString("hex")}.json`);
|
|
286
|
+
}
|
|
287
|
+
function newRecordFile(dir) {
|
|
288
|
+
return newLaunchFile(dir, "dry-run-record");
|
|
289
|
+
}
|
|
290
|
+
async function readRecordFile(file) {
|
|
291
|
+
try {
|
|
292
|
+
return { text: await fsPromises.readFile(file, "utf8") };
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const code = error.code;
|
|
295
|
+
return { problem: code === "ENOENT" ? "was not written" : `cannot be read (${error.message})` };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function removeQuietly(file) {
|
|
299
|
+
await fsPromises.rm(file, { force: true }).catch(() => {
|
|
300
|
+
return;
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
async function campaignFingerprint(files) {
|
|
304
|
+
const stats = await Promise.all(files.map(async (file) => {
|
|
305
|
+
try {
|
|
306
|
+
const stat2 = await fsPromises.stat(file, { bigint: true });
|
|
307
|
+
return `${file}\x00${stat2.dev}\x00${stat2.ino}\x00${stat2.size}\x00${stat2.mtimeNs}`;
|
|
308
|
+
} catch {
|
|
309
|
+
return `${file}\x00missing`;
|
|
310
|
+
}
|
|
311
|
+
}));
|
|
312
|
+
return createHash2("sha256").update(stats.join(`
|
|
313
|
+
`)).digest("hex");
|
|
314
|
+
}
|
|
315
|
+
async function writeAbortMarker(dir, marker) {
|
|
316
|
+
const file = path2.join(dir, ABORT_MARKER_FILE);
|
|
317
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
318
|
+
await writePrivateFile(temporary, JSON.stringify(marker));
|
|
319
|
+
try {
|
|
320
|
+
await fsPromises.rename(temporary, file);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
await removeQuietly(temporary);
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
async function readAbortMarker(dir) {
|
|
327
|
+
let value;
|
|
328
|
+
try {
|
|
329
|
+
value = JSON.parse(await fsPromises.readFile(path2.join(dir, ABORT_MARKER_FILE), "utf8"));
|
|
330
|
+
} catch {}
|
|
331
|
+
if (!isPlainRecord(value)) {
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const { generation, message } = value;
|
|
335
|
+
return typeof generation === "string" && generation !== "" && typeof message === "string" && message !== "" ? { generation, message } : undefined;
|
|
336
|
+
}
|
|
337
|
+
function parseCampaignState(value) {
|
|
338
|
+
if (typeof value !== "object" || value === null) {
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
const { generation, watchList, watchListFile, fingerprint } = value;
|
|
342
|
+
const isList = Array.isArray(watchList) && watchList.every((file) => typeof file === "string" && file !== "");
|
|
343
|
+
if (typeof generation !== "string" || generation === "" || !isList || fingerprint !== null && typeof fingerprint !== "string") {
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const expectedFile = watchList.length === 0 ? null : watchListFileFor(generation);
|
|
347
|
+
if (watchListFile !== expectedFile) {
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
return { generation, watchList, watchListFile: expectedFile, fingerprint };
|
|
351
|
+
}
|
|
352
|
+
async function readRegistryCampaign(registryFile) {
|
|
353
|
+
try {
|
|
354
|
+
return parseCampaignState(JSON.parse(await fsPromises.readFile(registryFile, "utf8")).campaign);
|
|
355
|
+
} catch {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/coverage/dry-run-messages.ts
|
|
361
|
+
import path3 from "node:path";
|
|
362
|
+
|
|
363
|
+
// src/utils/redact-secrets.ts
|
|
364
|
+
var REDACTED = "[redacted]";
|
|
365
|
+
var INSPECTOR_URL_PATH_RE = /\b(wss?:\/\/[^\s/]+)\/[^\s,)"']+/gi;
|
|
366
|
+
var INSPECTOR_BROWSER_URL_RE = /\b(https?:\/\/debug\.bun\.sh\/#)[^\s,)"']+/gi;
|
|
367
|
+
var ANSI_RE = /\u001B\[[0-9:;<=>?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g;
|
|
368
|
+
function stripAnsiForDiagnostics(text) {
|
|
369
|
+
return text.replaceAll(ANSI_RE, "");
|
|
370
|
+
}
|
|
371
|
+
function cleanDiagnosticText(text, secrets = []) {
|
|
372
|
+
return redactSecrets(stripAnsiForDiagnostics(text), secrets);
|
|
373
|
+
}
|
|
374
|
+
function redactSecrets(text, secrets = []) {
|
|
375
|
+
let redacted = text.replaceAll(INSPECTOR_URL_PATH_RE, `$1/${REDACTED}`).replaceAll(INSPECTOR_BROWSER_URL_RE, `$1${REDACTED}`);
|
|
376
|
+
for (const secret of secrets.filter((s) => s !== "").toSorted((a, b) => b.length - a.length)) {
|
|
377
|
+
redacted = redacted.replaceAll(secret, REDACTED);
|
|
378
|
+
}
|
|
379
|
+
return redacted;
|
|
380
|
+
}
|
|
381
|
+
function escapeControlCharacters(text) {
|
|
382
|
+
return text.replaceAll(/[\u0000-\u001F\u007F-\u009F]/g, (char) => String.raw`\x${char.codePointAt(0).toString(16).padStart(2, "0")}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// src/coverage/dry-run-messages.ts
|
|
386
|
+
var LISTED_ENTRIES = 10;
|
|
387
|
+
function projectPath(file, projectDir) {
|
|
388
|
+
const relative = path3.relative(projectDir, file);
|
|
389
|
+
return relative === "" || relative === ".." || relative.startsWith(`..${path3.sep}`) ? file : relative.split(path3.sep).join("/");
|
|
390
|
+
}
|
|
391
|
+
var NEEDS_QUOTES_RE = /[,"']|[^\S ]| {2}|^ | $|[\u0000-\u001F\u007F-\u009F]/;
|
|
392
|
+
function quoted(text) {
|
|
393
|
+
return escapeControlCharacters(JSON.stringify(text));
|
|
394
|
+
}
|
|
395
|
+
function displayName(name) {
|
|
396
|
+
return NEEDS_QUOTES_RE.test(name) ? quoted(name) : name;
|
|
397
|
+
}
|
|
398
|
+
function shownPath(file, projectDir) {
|
|
399
|
+
return displayName(projectPath(file, projectDir));
|
|
400
|
+
}
|
|
401
|
+
function displayError(text) {
|
|
402
|
+
return escapeControlCharacters(cleanDiagnosticText(text));
|
|
403
|
+
}
|
|
404
|
+
function listText(entries) {
|
|
405
|
+
const shown = entries.slice(0, LISTED_ENTRIES).join(", ");
|
|
406
|
+
const more = entries.length - LISTED_ENTRIES;
|
|
407
|
+
return more > 0 ? `${shown} and ${more} more` : shown;
|
|
408
|
+
}
|
|
409
|
+
function listOverflow(entries) {
|
|
410
|
+
return entries.slice(LISTED_ENTRIES);
|
|
411
|
+
}
|
|
412
|
+
function count(n, singular, plural = `${singular}s`) {
|
|
413
|
+
return `${n} ${n === 1 ? singular : plural}`;
|
|
414
|
+
}
|
|
415
|
+
function joinParts(parts) {
|
|
416
|
+
if (parts.length <= 1) {
|
|
417
|
+
return parts.join("");
|
|
418
|
+
}
|
|
419
|
+
return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
|
|
420
|
+
}
|
|
421
|
+
var INCREMENTAL_ADVICE = " Results saved before the change are reused: run once with --force over the whole mutate scope, not only the files named here.";
|
|
422
|
+
function incrementalAdvice(incremental) {
|
|
423
|
+
return incremental ? INCREMENTAL_ADVICE : "";
|
|
424
|
+
}
|
|
425
|
+
var UNSEEN_LOAD_ADVICE = "If the tests do load one of those in a way the runner cannot see (through a package, a worker or a child process), add it to bun.alwaysImport.";
|
|
426
|
+
function leftOutText(summary, imported) {
|
|
427
|
+
const verb = imported === 0 ? "It does not import any of them itself" : `It does not import the other ${summary.left.length} itself`;
|
|
428
|
+
return `${verb}: ${listText(summary.left)}. ${UNSEEN_LOAD_ADVICE}${incrementalAdvice(summary.incremental)}`;
|
|
429
|
+
}
|
|
430
|
+
function importListOneRunMessage(summary, sources) {
|
|
431
|
+
const imported = sources.statically + sources.named + sources.always;
|
|
432
|
+
const parts = [];
|
|
433
|
+
if (sources.statically > 0) {
|
|
434
|
+
parts.push(`${sources.statically} that the test files or preloads import statically`);
|
|
435
|
+
}
|
|
436
|
+
if (sources.named > 0) {
|
|
437
|
+
parts.push(`${sources.named} that they reach only through a literal import() or require()`);
|
|
438
|
+
}
|
|
439
|
+
if (sources.always > 0) {
|
|
440
|
+
parts.push(`${sources.always} kept by bun.alwaysImport`);
|
|
441
|
+
}
|
|
442
|
+
const head = imported === 0 ? `Dry run: of the ${summary.matched} files matched by mutate, the runner imports none before the tests.` : `Dry run: of the ${summary.matched} files matched by mutate, the runner imports ${imported} before the tests: ${joinParts(parts)}.`;
|
|
443
|
+
return `${head} ${leftOutText(summary, imported)}`;
|
|
444
|
+
}
|
|
445
|
+
function importListTwoRunMessage(summary, sources, published, discovery) {
|
|
446
|
+
const imported = sources.observed + sources.always;
|
|
447
|
+
const observed = sources.always === 0 ? `the ${sources.observed}` : `${sources.observed}`;
|
|
448
|
+
const parts = [`${observed} that a ${discovery} run of the tests was seen to load`];
|
|
449
|
+
if (sources.always > 0) {
|
|
450
|
+
parts.push(`${sources.always} kept by bun.alwaysImport`);
|
|
451
|
+
}
|
|
452
|
+
const head = imported === 0 ? `Dry run: of the ${summary.matched} files matched by mutate, the runner imports none before the tests of the ${published} run.` : `Dry run: of the ${summary.matched} files matched by mutate, the runner imports ${imported} before the tests of the ${published} run: ${joinParts(parts)}.`;
|
|
453
|
+
return `${head} ${leftOutText(summary, imported)}`;
|
|
454
|
+
}
|
|
455
|
+
var SCAN_NEXT = {
|
|
456
|
+
full: "One run of the tests, with every file matched by mutate imported first.",
|
|
457
|
+
static: "One run of the tests, with those files imported first and the rest watched.",
|
|
458
|
+
dynamic: "A plain run of the tests is observed first, then the run that publishes results."
|
|
459
|
+
};
|
|
460
|
+
function scanMessage(scan) {
|
|
461
|
+
const sets = `${scan.statically.length} imported statically [${scan.statically.join(", ")}], ${scan.named.length} named in import() or require() [${scan.named.join(", ")}], ${scan.always.length} kept by bun.alwaysImport [${scan.always.join(", ")}]`;
|
|
462
|
+
const reasons = scan.reasons.length === 0 ? "" : `; reasons: ${escapeControlCharacters(scan.reasons.join("; "))}`;
|
|
463
|
+
const notes = scan.notes.length === 0 ? "" : `; notes: ${escapeControlCharacters(scan.notes.join("; "))}`;
|
|
464
|
+
return `Import scan: ${scan.answer} in ${Math.round(scan.wallMs)} ms over ${scan.scannedFiles} files; of the ${scan.matched} files matched by mutate, ${sets}${reasons}${notes}. ${SCAN_NEXT[scan.next]}`;
|
|
465
|
+
}
|
|
466
|
+
function scanUnusableMessage(reason, started) {
|
|
467
|
+
const what = started ? "The import scan gave no usable answer" : "The import scan was not started";
|
|
468
|
+
return `${what}: ${escapeControlCharacters(reason)}. ${SCAN_NEXT.dynamic}`;
|
|
469
|
+
}
|
|
470
|
+
var MISS_DISCARDED = "The run is discarded, and the dry run starts again with a plain run of the tests that observes what they load; if that run is accepted, the runner attempts a third run to publish the results.";
|
|
471
|
+
function missMessage(files, testFiles, incremental) {
|
|
472
|
+
const sentences = [];
|
|
473
|
+
if (files.length === 1) {
|
|
474
|
+
sentences.push(`${files[0]} was loaded during the dry run, but the scan of the test files' imports found no route to it.`);
|
|
475
|
+
} else if (files.length > 0) {
|
|
476
|
+
sentences.push(`${files.length} files matched by mutate were loaded during the dry run, but the scan of the test files' imports found no route to them: ${listText(files)}.`);
|
|
477
|
+
}
|
|
478
|
+
if (testFiles.length === 1) {
|
|
479
|
+
sentences.push(`${testFiles[0]} ran tests but was not among the test files the runner scanned.`);
|
|
480
|
+
} else if (testFiles.length > 0) {
|
|
481
|
+
sentences.push(`${testFiles.length} test files ran tests but were not among the test files the runner scanned: ${listText(testFiles)}.`);
|
|
482
|
+
}
|
|
483
|
+
sentences.push(MISS_DISCARDED);
|
|
484
|
+
if (files.length > 0) {
|
|
485
|
+
const which = files.length === 1 ? "the file" : "those files";
|
|
486
|
+
sentences.push(`To avoid that, add ${which} to bun.alwaysImport or set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`);
|
|
487
|
+
} else {
|
|
488
|
+
sentences.push(`To avoid that, set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`);
|
|
489
|
+
}
|
|
490
|
+
return sentences.join(" ");
|
|
491
|
+
}
|
|
492
|
+
function namedMessage(namedCount, notLoaded, kept, incremental) {
|
|
493
|
+
const head = `The first run of the dry run failed while the runner imported first, among others, ${count(namedCount, "file")} that test files or preloads reach only through a literal import() or require().`;
|
|
494
|
+
if (notLoaded.length === 0) {
|
|
495
|
+
return `${head} A plain run of the tests then passed, loading every one of them, so importing them is not shown to be the cause. This took three runs.`;
|
|
496
|
+
}
|
|
497
|
+
let imports = notLoaded.length === 1 ? "The runner no longer imports it." : "The runner no longer imports them.";
|
|
498
|
+
if (kept.length === notLoaded.length) {
|
|
499
|
+
imports = `bun.alwaysImport keeps ${notLoaded.length === 1 ? "it" : "them"}, so the runner still imports ${notLoaded.length === 1 ? "it" : "them"} first.`;
|
|
500
|
+
} else if (kept.length > 0) {
|
|
501
|
+
imports = `The runner no longer imports them, except ${kept.length} that bun.alwaysImport keeps: ${listText(kept)}.`;
|
|
502
|
+
}
|
|
503
|
+
return `${head} A plain run of the tests then passed without loading ${notLoaded.length} of them, the likely cause: ${listText(notLoaded)}. ${imports} ` + `This took three runs; remove the import() or require() that never runs, or set bun.importDiscovery to 'run'.${incrementalAdvice(incremental)}`;
|
|
504
|
+
}
|
|
505
|
+
function discoveryFailedMessage(discovery, reasons) {
|
|
506
|
+
const next = discovery === "first" ? "second" : "third";
|
|
507
|
+
return `stryker-bun-runner: the ${discovery} run of the dry run (a plain run of the tests, with no mutated file imported first) did not complete cleanly: ${reasons.join("; ")}. The ${next} run was not made.`;
|
|
508
|
+
}
|
|
509
|
+
function discoveryAfterFailedRunMessage(reasons) {
|
|
510
|
+
return "The second run of the dry run (a plain run of the tests, with no mutated file imported first, made because the first run failed) " + `did not complete cleanly either: ${reasons.join("; ")}. The first run's result is returned.`;
|
|
511
|
+
}
|
|
512
|
+
function publishedFailedMessage(published, discovery, imported, observed, failures) {
|
|
513
|
+
if (imported.length === 0) {
|
|
514
|
+
return `The ${published} run of the dry run failed although the ${discovery}, a plain run of the same tests, passed. ` + "It imported no mutated file first, so the difference is not an import: a test that does not pass on every run can do this.";
|
|
515
|
+
}
|
|
516
|
+
const always = imported.length - observed;
|
|
517
|
+
const which = always === 0 ? `the ${count(observed, "mutated file")} the plain run loaded` : `${count(observed, "mutated file")} the plain run loaded and ${count(always, "file")} kept by bun.alwaysImport`;
|
|
518
|
+
const threw = failures.length === 0 ? "" : ` Imports that threw: ${listText(failures)}.`;
|
|
519
|
+
return `The ${published} run of the dry run failed although the ${discovery}, a plain run of the same tests, passed. ` + `The ${published} run imports ${which} before the tests, so that their module-level code is not credited to whichever test loads them first; ` + `one of those imports probably broke the tests: ${listText(imported)}.${threw} Make that file importable before the tests, or remove it from mutate.`;
|
|
520
|
+
}
|
|
521
|
+
function loadedByListMessage(files) {
|
|
522
|
+
const cause = "(a file imported first, including one only bun.alwaysImport keeps, or a preload can cause this)";
|
|
523
|
+
if (files.length === 1) {
|
|
524
|
+
return `${files[0]} was not loaded in the plain run of the tests, but in the run that publishes it was loaded before the tests, while the runner imported its list first ${cause}. ` + "It ran before the tests, as in earlier versions.";
|
|
525
|
+
}
|
|
526
|
+
return `${listText(files)} were not loaded in the plain run of the tests, but in the run that publishes they were loaded before the tests, while the runner imported its list first ${cause}. ` + "They ran before the tests, as in earlier versions.";
|
|
527
|
+
}
|
|
528
|
+
function lateWhere(load) {
|
|
529
|
+
if (load.test !== null) {
|
|
530
|
+
return `inside test ${quoted(load.test)}`;
|
|
531
|
+
}
|
|
532
|
+
return load.sensor === "header" ? "after the imports, outside a test" : "after the imports";
|
|
533
|
+
}
|
|
534
|
+
function lateLoadEntries(loads) {
|
|
535
|
+
return loads.map((load) => `${load.file} (${lateWhere(load)})`);
|
|
536
|
+
}
|
|
537
|
+
function lateLoadMessage(loads, published, discovery, incremental) {
|
|
538
|
+
if (loads.length === 1) {
|
|
539
|
+
return `stryker-bun-runner: ${loads[0].file} was loaded during the ${published} run of the dry run (${lateWhere(loads[0])}) but not during the ${discovery}, ` + `so the runner had not imported it before the tests. Add it to bun.alwaysImport. No mutant was scored.${incrementalAdvice(incremental)}`;
|
|
540
|
+
}
|
|
541
|
+
const listed = listText(lateLoadEntries(loads));
|
|
542
|
+
return `stryker-bun-runner: ${loads.length} files matched by mutate were loaded during the ${published} run of the dry run but not during the ${discovery}, ` + `so the runner had not imported them before the tests: ${listed}. Add them to bun.alwaysImport. No mutant was scored.${incrementalAdvice(incremental)}`;
|
|
543
|
+
}
|
|
544
|
+
function eagerFailureMessage(file, error) {
|
|
545
|
+
return `Importing ${file} before the tests failed: ${displayError(error)}. The dry run continued, as earlier versions did without saying so. A test that loads this file afterwards gets the same error.`;
|
|
546
|
+
}
|
|
547
|
+
function lostImportedText(report) {
|
|
548
|
+
if (report.always === 0) {
|
|
549
|
+
return `the ${count(report.imported, "file")} the tests load ${report.imported === 1 ? "was" : "were"}`;
|
|
550
|
+
}
|
|
551
|
+
return `${count(report.imported - report.always, "file")} the tests load and ${count(report.always, "file")} kept by bun.alwaysImport were`;
|
|
552
|
+
}
|
|
553
|
+
function lostMessage(report) {
|
|
554
|
+
const where = report.files.length === 0 ? "" : ` in ${listText(report.files)}`;
|
|
555
|
+
const verb = report.ids.length === 1 ? "was" : "were";
|
|
556
|
+
return `stryker-bun-runner: ${count(report.ids.length, "mutant")}${where} (ids ${listText(report.ids)}) ${verb} reached when the tests ran on their own, ` + `and not reached when ${lostImportedText(report)} imported first, in the ${report.published} run. ` + `${count(report.leftOut.length, "file")} matched by mutate ${report.leftOut.length === 1 ? "was" : "were"} left out of that import because the run of the tests on their own did not load ${report.leftOut.length === 1 ? "it" : "them"}: ${listText(report.leftOut)}. ` + "Either module-level code depends on one of the files left out (add it to bun.alwaysImport), or the tests do not execute the same code on every run " + "(a random order without a seed can do this). bun.alwaysImport: 'all' imports every mutated file first, in one run, as earlier versions did. " + `No mutant was scored.${incrementalAdvice(report.incremental)}`;
|
|
557
|
+
}
|
|
558
|
+
function refuseMessage(problems, incremental) {
|
|
559
|
+
return `stryker-bun-runner: cannot tell which mutated files the tests load: ${problems.join("; ")}. ` + `Set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did. No mutant was scored.${incrementalAdvice(incremental)}`;
|
|
560
|
+
}
|
|
561
|
+
function unpublishedCampaignMessage(file, cause, watched) {
|
|
562
|
+
return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}). The mutant runs need it to watch the ${count(watched, "file")} matched by mutate that the dry run ` + "neither imported before the tests nor saw load, so the dry run stops here. No mutant was scored. " + "Make the run's temporary directory writable, or set bun.alwaysImport to 'all' to import every mutated file first, as earlier versions did.";
|
|
563
|
+
}
|
|
564
|
+
function staleRegistryMessage(file, cause, registry) {
|
|
565
|
+
return `stryker-bun-runner: cannot write ${escapeControlCharacters(file)} (${displayError(cause)}), so ${escapeControlCharacters(registry)} still holds an earlier dry run's test names, ` + "test file selection, durations and coverage by test file. The mutant runs of the other workers would use them for this run, so the dry run stops here. No mutant was scored. " + `Make the run's temporary directory writable, or remove ${escapeControlCharacters(registry)}.`;
|
|
566
|
+
}
|
|
567
|
+
function seconds(ms) {
|
|
568
|
+
return (ms / 1000).toFixed(1);
|
|
569
|
+
}
|
|
570
|
+
function budgetMessage(usedMs, remainingMs, budgetMinutes, suggestedMinutes) {
|
|
571
|
+
return `The dry run has used ${seconds(usedMs)} s and ${seconds(remainingMs)} s remain of dryRunTimeoutMinutes (${budgetMinutes}); it now runs the tests again. ` + `If the initial test run times out, raise dryRunTimeoutMinutes to at least ${suggestedMinutes}.`;
|
|
572
|
+
}
|
|
573
|
+
function witnessMessage(report) {
|
|
574
|
+
const one = report.files.length === 1;
|
|
575
|
+
const files = listText(report.files);
|
|
576
|
+
const force = report.incremental ? " with --force over the whole mutate scope, not only the files named here" : "";
|
|
577
|
+
return `stryker-bun-runner: ${files} ${one ? "was" : "were"} present in bun's module cache in this mutant run (mutant ${report.mutantId}, tests: ${report.scope}) when the mutant first executed, ` + `and the dry run neither imported ${one ? "it" : "them"} before the tests nor saw ${one ? "it" : "them"} load. ` + "The coverage plan for this run may be incomplete, so the run is stopped: Stryker writes no final report and no incremental file for it " + "(results already reported for earlier mutants, and files from earlier runs, are left as they are). " + `Add ${files} to bun.alwaysImport, or set bun.importDiscovery to 'run', and run again${force}; ` + `a mock.module() of ${one ? "that file" : "those files"} that only some tests make has the same effect and the same remedy.`;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// src/coverage/dry-run-plan.ts
|
|
581
|
+
import path4 from "node:path";
|
|
582
|
+
import picomatch from "picomatch";
|
|
583
|
+
|
|
584
|
+
// src/coverage/preload-logic.ts
|
|
585
|
+
import { appendFileSync, closeSync, constants, openSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
586
|
+
var COVERAGE_KEYS_ONLY_ENV = "__STRYKER_COVERAGE_KEYS_ONLY__";
|
|
587
|
+
var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
|
|
588
|
+
var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
|
|
589
|
+
var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
|
|
590
|
+
function readPreloadTimings(stderr) {
|
|
591
|
+
const start = stderr.lastIndexOf(`
|
|
592
|
+
${PRELOAD_TIMINGS_PREFIX}`);
|
|
593
|
+
if (start === -1) {
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const jsonStart = start + 1 + PRELOAD_TIMINGS_PREFIX.length;
|
|
597
|
+
const end = stderr.indexOf(`
|
|
598
|
+
`, jsonStart);
|
|
599
|
+
try {
|
|
600
|
+
const parsed = JSON.parse(stderr.slice(jsonStart, end === -1 ? stderr.length : end));
|
|
601
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
|
|
605
|
+
} catch {
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
|
|
610
|
+
var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
|
|
611
|
+
var DRY_RUN_PLAN_ENV = "__STRYKER_DRY_RUN_PLAN__";
|
|
612
|
+
var PLAN_FIELDS = new Set(["mode", "eager", "candidates", "recordFile", "nonce"]);
|
|
613
|
+
function latestSightings(observations) {
|
|
614
|
+
const kept = new Map;
|
|
615
|
+
for (const sighting of observations) {
|
|
616
|
+
const known = kept.get(sighting.file);
|
|
617
|
+
if (known === undefined || known.time === "by-eager-end" && sighting.time === "later") {
|
|
618
|
+
kept.set(sighting.file, sighting);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return observations.filter((sighting) => kept.get(sighting.file) === sighting);
|
|
622
|
+
}
|
|
623
|
+
var PRIVATE_CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
|
|
624
|
+
var WATCH_LIST_ENV = "__STRYKER_WATCH_LIST__";
|
|
625
|
+
var WITNESS_SENTINEL = "__STRYKER_UNIMPORTED_LOADED__";
|
|
626
|
+
var WATCH_LIST_PROBLEM_SENTINEL = "__STRYKER_WATCH_LIST_UNREADABLE__";
|
|
627
|
+
var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
|
|
628
|
+
|
|
629
|
+
// src/coverage/dry-run-plan.ts
|
|
630
|
+
function selectAlways(eagerList, option, projectDir) {
|
|
631
|
+
if (option === "all") {
|
|
632
|
+
return { files: [...eagerList], unmatched: [] };
|
|
633
|
+
}
|
|
634
|
+
const patterns = option ?? [];
|
|
635
|
+
const relative = eagerList.map((file) => path4.relative(projectDir, file).split(path4.sep).join("/"));
|
|
636
|
+
const matched = new Set;
|
|
637
|
+
const unmatched = [];
|
|
638
|
+
for (const pattern of patterns) {
|
|
639
|
+
const matches = picomatch(pattern, { dot: true });
|
|
640
|
+
const hits = eagerList.filter((_file, index) => matches(relative[index]));
|
|
641
|
+
if (hits.length === 0) {
|
|
642
|
+
unmatched.push(pattern);
|
|
643
|
+
}
|
|
644
|
+
for (const file of hits) {
|
|
645
|
+
matched.add(file);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return { files: eagerList.filter((file) => matched.has(file)), unmatched };
|
|
649
|
+
}
|
|
650
|
+
function selectList(eagerList, sets) {
|
|
651
|
+
return eagerList.filter((file) => sets.some((set) => set.has(file)));
|
|
652
|
+
}
|
|
653
|
+
function legacyReason(eagerList, always) {
|
|
654
|
+
if (eagerList.length === 0) {
|
|
655
|
+
return "empty";
|
|
656
|
+
}
|
|
657
|
+
const kept = new Set(always);
|
|
658
|
+
return eagerList.every((file) => kept.has(file)) ? "always-covers" : null;
|
|
659
|
+
}
|
|
660
|
+
function decideFromScan(scan, eagerList, always, importDiscovery) {
|
|
661
|
+
const legacy = legacyReason(eagerList, always);
|
|
662
|
+
if (legacy !== null) {
|
|
663
|
+
return { kind: "legacy", reason: legacy };
|
|
664
|
+
}
|
|
665
|
+
const mandatory = new Set(scan.mandatory);
|
|
666
|
+
const named = new Set(scan.named);
|
|
667
|
+
const kept = new Set(always);
|
|
668
|
+
const sources = {
|
|
669
|
+
statically: eagerList.filter((file) => mandatory.has(file)),
|
|
670
|
+
named: eagerList.filter((file) => named.has(file) && !mandatory.has(file)),
|
|
671
|
+
always: eagerList.filter((file) => kept.has(file) && !mandatory.has(file) && !named.has(file))
|
|
672
|
+
};
|
|
673
|
+
const list = selectList(eagerList, [mandatory, named, kept]);
|
|
674
|
+
if (list.length === eagerList.length) {
|
|
675
|
+
return { kind: "full", list, sources };
|
|
676
|
+
}
|
|
677
|
+
if (scan.answer !== "static" || scan.reasons.length > 0) {
|
|
678
|
+
const reasons = scan.reasons.length > 0 ? scan.reasons : [`the scan answered ${scan.answer} without a reason`];
|
|
679
|
+
return { kind: "dynamic", cause: "scan", reasons, sources };
|
|
680
|
+
}
|
|
681
|
+
if (importDiscovery === "run") {
|
|
682
|
+
return { kind: "dynamic", cause: "importDiscovery", reasons: ["bun.importDiscovery is 'run'"], sources };
|
|
683
|
+
}
|
|
684
|
+
return { kind: "static", list, sources };
|
|
685
|
+
}
|
|
686
|
+
function publishPlan(eagerList, list, recordFile, nonce) {
|
|
687
|
+
const imported = new Set(list);
|
|
688
|
+
const candidates = eagerList.filter((file) => !imported.has(file));
|
|
689
|
+
if (candidates.length === 0) {
|
|
690
|
+
return list.length === 0 ? { mode: "publish", eager: [], candidates: null, recordFile: null, nonce: null } : { mode: "publish", eager: [...list], candidates: null, recordFile, nonce };
|
|
691
|
+
}
|
|
692
|
+
return { mode: "publish", eager: [...list], candidates, recordFile, nonce };
|
|
693
|
+
}
|
|
694
|
+
function discoveryPlan(eagerList, recordFile, nonce) {
|
|
695
|
+
return { mode: "discover", eager: [], candidates: [...eagerList], recordFile, nonce };
|
|
696
|
+
}
|
|
697
|
+
function outsideCandidates(observations, list) {
|
|
698
|
+
const imported = new Set(list);
|
|
699
|
+
const kept = latestSightings(observations.filter((observation) => !imported.has(observation.file)));
|
|
700
|
+
return {
|
|
701
|
+
byEagerEnd: kept.filter((observation) => observation.time === "by-eager-end"),
|
|
702
|
+
later: kept.filter((observation) => observation.time === "later")
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function lostIds(reachedInDiscovery, rawCoverage) {
|
|
706
|
+
const hit = new Set;
|
|
707
|
+
for (const counts of [rawCoverage.static, ...Object.values(rawCoverage.perTest)]) {
|
|
708
|
+
for (const [id, count] of Object.entries(counts)) {
|
|
709
|
+
if (count > 0) {
|
|
710
|
+
hit.add(id);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return [...new Set(reachedInDiscovery)].filter((id) => !hit.has(id));
|
|
715
|
+
}
|
|
716
|
+
function watchList(eagerList, list, seen) {
|
|
717
|
+
const known = new Set([...list, ...seen]);
|
|
718
|
+
return eagerList.filter((file) => !known.has(file));
|
|
719
|
+
}
|
|
720
|
+
function isDuration(value) {
|
|
721
|
+
return Number.isFinite(value) && value >= 0;
|
|
722
|
+
}
|
|
723
|
+
function timeoutCorrection(extraMs, elapsedMs, publishedTestDurations) {
|
|
724
|
+
if (!isDuration(extraMs) || !isDuration(elapsedMs) || extraMs > elapsedMs || !publishedTestDurations.every((duration) => isDuration(duration))) {
|
|
725
|
+
return 0;
|
|
726
|
+
}
|
|
727
|
+
const testsMs = publishedTestDurations.reduce((sum, duration) => sum + duration, 0);
|
|
728
|
+
const overheadMs = Math.max(0, elapsedMs - testsMs);
|
|
729
|
+
return Math.floor(Math.min(extraMs, overheadMs));
|
|
730
|
+
}
|
|
731
|
+
function signedPayloads(stderr, marker, token) {
|
|
732
|
+
const payloads = [];
|
|
733
|
+
if (token === "") {
|
|
734
|
+
return payloads;
|
|
735
|
+
}
|
|
736
|
+
const prefix = `${marker} ${token} `;
|
|
737
|
+
let from = 0;
|
|
738
|
+
for (;; ) {
|
|
739
|
+
const at = stderr.indexOf(prefix, from);
|
|
740
|
+
if (at === -1) {
|
|
741
|
+
return payloads;
|
|
742
|
+
}
|
|
743
|
+
const end = stderr.indexOf(`
|
|
744
|
+
`, at);
|
|
745
|
+
if (at === 0 || stderr[at - 1] === `
|
|
746
|
+
`) {
|
|
747
|
+
payloads.push(stderr.slice(at + prefix.length, end === -1 ? stderr.length : end));
|
|
748
|
+
}
|
|
749
|
+
from = at + prefix.length;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function readWitnessReport(stderr, token, watched) {
|
|
753
|
+
for (const payload of signedPayloads(stderr, WITNESS_SENTINEL, token)) {
|
|
754
|
+
let value;
|
|
755
|
+
try {
|
|
756
|
+
value = JSON.parse(payload);
|
|
757
|
+
} catch {}
|
|
758
|
+
if (Array.isArray(value) && value.length > 0 && value.every((file) => watched.has(file))) {
|
|
759
|
+
return value;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
function readWatchListProblem(stderr, token) {
|
|
765
|
+
for (const payload of signedPayloads(stderr, WATCH_LIST_PROBLEM_SENTINEL, token)) {
|
|
766
|
+
try {
|
|
767
|
+
const value = JSON.parse(payload);
|
|
768
|
+
if (typeof value === "string") {
|
|
769
|
+
return value;
|
|
770
|
+
}
|
|
771
|
+
} catch {}
|
|
772
|
+
}
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
var isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
776
|
+
function isCount(value) {
|
|
777
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
778
|
+
}
|
|
779
|
+
function isObservation(value, eager) {
|
|
780
|
+
if (!isPlainRecord(value)) {
|
|
781
|
+
return false;
|
|
782
|
+
}
|
|
783
|
+
const { file, time, sensor, testKey } = value;
|
|
784
|
+
return typeof file === "string" && eager.has(file) && (time === "by-eager-end" || time === "later") && (sensor === "header" || sensor === "cache") && (testKey === null || typeof testKey === "string");
|
|
785
|
+
}
|
|
786
|
+
function isEagerFailure(value, eager) {
|
|
787
|
+
if (!isPlainRecord(value)) {
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
const { file, error } = value;
|
|
791
|
+
return typeof file === "string" && eager.has(file) && typeof error === "string";
|
|
792
|
+
}
|
|
793
|
+
function recordObject(text) {
|
|
794
|
+
let value;
|
|
795
|
+
try {
|
|
796
|
+
value = JSON.parse(text);
|
|
797
|
+
} catch {
|
|
798
|
+
return { problem: "is not valid JSON" };
|
|
799
|
+
}
|
|
800
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
801
|
+
return { problem: "is not a JSON object" };
|
|
802
|
+
}
|
|
803
|
+
return { value };
|
|
804
|
+
}
|
|
805
|
+
function observationProblem(value, eager) {
|
|
806
|
+
if (typeof value.nonce !== "string" || value.nonce === "") {
|
|
807
|
+
return "has no nonce";
|
|
808
|
+
}
|
|
809
|
+
if (value.complete !== true) {
|
|
810
|
+
return "is not marked complete";
|
|
811
|
+
}
|
|
812
|
+
if (!Array.isArray(value.observed) || !value.observed.every((entry) => isObservation(entry, eager))) {
|
|
813
|
+
return "has an observed list that is not a list of sightings of files matched by mutate";
|
|
814
|
+
}
|
|
815
|
+
if (!isStringList(value.problems)) {
|
|
816
|
+
return "has problems that are not a list of strings";
|
|
817
|
+
}
|
|
818
|
+
if (!Array.isArray(value.eagerFailures) || !value.eagerFailures.every((entry) => isEagerFailure(entry, eager))) {
|
|
819
|
+
return "has eagerFailures that are not a list of failed imports of files matched by mutate";
|
|
820
|
+
}
|
|
821
|
+
if (!Number.isFinite(value.sensorMs) || value.sensorMs < 0) {
|
|
822
|
+
return "has a sensorMs that is not a non-negative number";
|
|
823
|
+
}
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
function readObservationRecord(text, eagerList) {
|
|
827
|
+
const parsed = recordObject(text);
|
|
828
|
+
if ("problem" in parsed) {
|
|
829
|
+
return parsed;
|
|
830
|
+
}
|
|
831
|
+
const problem = observationProblem(parsed.value, new Set(eagerList));
|
|
832
|
+
return problem === undefined ? { record: parsed.value } : { problem };
|
|
833
|
+
}
|
|
834
|
+
function ownRecord(read, nonce) {
|
|
835
|
+
return "problem" in read || read.record.nonce === nonce ? read : { problem: "carries another launch's nonce" };
|
|
836
|
+
}
|
|
837
|
+
function readDiscoveryRecord(text, eagerList) {
|
|
838
|
+
const observation = readObservationRecord(text, eagerList);
|
|
839
|
+
if ("problem" in observation) {
|
|
840
|
+
return observation;
|
|
841
|
+
}
|
|
842
|
+
const { startedTests, reached } = observation.record;
|
|
843
|
+
if (!isCount(startedTests)) {
|
|
844
|
+
return { problem: "has a startedTests that is not a count" };
|
|
845
|
+
}
|
|
846
|
+
if (!isStringList(reached)) {
|
|
847
|
+
return { problem: "has a reached list that is not a list of mutant ids" };
|
|
848
|
+
}
|
|
849
|
+
return { record: observation.record };
|
|
850
|
+
}
|
|
851
|
+
function endReasons(facts) {
|
|
852
|
+
if (facts.spawnError !== undefined) {
|
|
853
|
+
return [`bun test could not be started (${facts.spawnError})`];
|
|
854
|
+
}
|
|
855
|
+
if (facts.timedOut) {
|
|
856
|
+
return [facts.memoryLimitExceeded ? "the runner killed it for exceeding bun.maxChildRss" : "the runner killed it at bun.timeout"];
|
|
857
|
+
}
|
|
858
|
+
if (facts.signal !== null) {
|
|
859
|
+
return [`it was terminated by signal ${facts.signal}`];
|
|
860
|
+
}
|
|
861
|
+
return facts.exitCode === 0 ? [] : [`bun exited with code ${String(facts.exitCode)}`];
|
|
862
|
+
}
|
|
863
|
+
function summaryReasons(facts) {
|
|
864
|
+
if (!facts.summaryPrinted) {
|
|
865
|
+
return ["bun printed no summary"];
|
|
866
|
+
}
|
|
867
|
+
const reasons = [];
|
|
868
|
+
if (facts.summaryFailed > 0) {
|
|
869
|
+
reasons.push(`${facts.summaryFailed} failing test(s)`);
|
|
870
|
+
}
|
|
871
|
+
if (facts.summaryErrors > 0) {
|
|
872
|
+
reasons.push(`${facts.summaryErrors} error(s) outside tests`);
|
|
873
|
+
}
|
|
874
|
+
return reasons;
|
|
875
|
+
}
|
|
876
|
+
function recordReasons(facts) {
|
|
877
|
+
if ("problem" in facts.record) {
|
|
878
|
+
return [`no completion record of this run (the record ${facts.record.problem})`];
|
|
879
|
+
}
|
|
880
|
+
const { nonce, startedTests } = facts.record.record;
|
|
881
|
+
if (nonce !== facts.nonce) {
|
|
882
|
+
return ["no completion record of this run (the record carries another launch's nonce)"];
|
|
883
|
+
}
|
|
884
|
+
if (facts.summaryPrinted && startedTests < facts.summaryPassed) {
|
|
885
|
+
return [`the completion record counts ${startedTests} test start(s), fewer than bun's ${facts.summaryPassed} passing test(s)`];
|
|
886
|
+
}
|
|
887
|
+
return [];
|
|
888
|
+
}
|
|
889
|
+
function acceptDiscovery(facts) {
|
|
890
|
+
const reasons = [...endReasons(facts), ...summaryReasons(facts), ...recordReasons(facts)];
|
|
891
|
+
if (reasons.length > 0) {
|
|
892
|
+
return { kind: "rejected", reasons };
|
|
893
|
+
}
|
|
894
|
+
const { record } = facts.record;
|
|
895
|
+
return record.problems.length > 0 ? { kind: "refused", problems: record.problems } : { kind: "accepted", record };
|
|
896
|
+
}
|
|
897
|
+
function sensorProblems(facts) {
|
|
898
|
+
if (facts.record === undefined) {
|
|
899
|
+
return [];
|
|
900
|
+
}
|
|
901
|
+
if ("problem" in facts.record) {
|
|
902
|
+
return facts.watched && facts.green ? [`the published run's observation record ${facts.record.problem}`] : [];
|
|
903
|
+
}
|
|
904
|
+
return [...facts.record.record.problems];
|
|
905
|
+
}
|
|
906
|
+
function outsideOf(facts) {
|
|
907
|
+
return facts.record === undefined || "problem" in facts.record ? { byEagerEnd: [], later: [] } : outsideCandidates(facts.record.record.observed, facts.list);
|
|
908
|
+
}
|
|
909
|
+
function eagerFailuresOf(record) {
|
|
910
|
+
return record === undefined || "problem" in record ? [] : record.record.eagerFailures;
|
|
911
|
+
}
|
|
912
|
+
function oneRunOutcome(facts, unscanned, named) {
|
|
913
|
+
const problems = sensorProblems(facts);
|
|
914
|
+
if (problems.length > 0) {
|
|
915
|
+
return { kind: "refuse", problems };
|
|
916
|
+
}
|
|
917
|
+
const outside = outsideOf(facts);
|
|
918
|
+
const files = [...outside.byEagerEnd, ...outside.later];
|
|
919
|
+
if (files.length > 0 || unscanned.length > 0) {
|
|
920
|
+
return { kind: "miss", files, testFiles: [...unscanned] };
|
|
921
|
+
}
|
|
922
|
+
if (!facts.green) {
|
|
923
|
+
return { kind: "failed", discover: named.length > 0 };
|
|
924
|
+
}
|
|
925
|
+
return { kind: "publish" };
|
|
926
|
+
}
|
|
927
|
+
function twoRunOutcome(facts, lost) {
|
|
928
|
+
const problems = sensorProblems(facts);
|
|
929
|
+
if (problems.length > 0) {
|
|
930
|
+
return { kind: "refuse", problems };
|
|
931
|
+
}
|
|
932
|
+
const outside = outsideOf(facts);
|
|
933
|
+
if (outside.later.length > 0) {
|
|
934
|
+
return { kind: "late", files: outside.later };
|
|
935
|
+
}
|
|
936
|
+
if (!facts.green) {
|
|
937
|
+
return { kind: "failed" };
|
|
938
|
+
}
|
|
939
|
+
if (lost.length > 0) {
|
|
940
|
+
return { kind: "lost", ids: [...lost] };
|
|
941
|
+
}
|
|
942
|
+
return { kind: "publish", early: outside.byEagerEnd };
|
|
943
|
+
}
|
|
944
|
+
function unscannedTestFiles(testFiles, roots, projectDir) {
|
|
945
|
+
const scanned = new Set(roots);
|
|
946
|
+
const unscanned = new Set;
|
|
947
|
+
for (const file of testFiles) {
|
|
948
|
+
if (file !== undefined && !scanned.has(path4.resolve(projectDir, file))) {
|
|
949
|
+
unscanned.add(file);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return [...unscanned];
|
|
953
|
+
}
|
|
954
|
+
var SCAN_NEUTRAL_FLAGS = new Set([
|
|
955
|
+
"--bail",
|
|
956
|
+
"--dots",
|
|
957
|
+
"--expose-gc",
|
|
958
|
+
"--isolate",
|
|
959
|
+
"--no-deprecation",
|
|
960
|
+
"--no-install",
|
|
961
|
+
"--no-isolate",
|
|
962
|
+
"--no-macros",
|
|
963
|
+
"--no-orphans",
|
|
964
|
+
"--only",
|
|
965
|
+
"--only-failures",
|
|
966
|
+
"--prefer-latest",
|
|
967
|
+
"--prefer-offline",
|
|
968
|
+
"--randomize",
|
|
969
|
+
"--silent",
|
|
970
|
+
"--smol",
|
|
971
|
+
"--throw-deprecation",
|
|
972
|
+
"--todo",
|
|
973
|
+
"--update-timings",
|
|
974
|
+
"--zero-fill-buffers"
|
|
975
|
+
]);
|
|
976
|
+
var SCAN_NEUTRAL_VALUE_FLAGS = new Set([
|
|
977
|
+
"--bail",
|
|
978
|
+
"--console-depth",
|
|
979
|
+
"--dns-result-order",
|
|
980
|
+
"--elide-lines",
|
|
981
|
+
"--env-file",
|
|
982
|
+
"--max-http-header-size",
|
|
983
|
+
"--reporter",
|
|
984
|
+
"--reporter-outfile",
|
|
985
|
+
"--seed",
|
|
986
|
+
"--timeout",
|
|
987
|
+
"--timings",
|
|
988
|
+
"--title",
|
|
989
|
+
"--unhandled-rejections"
|
|
990
|
+
]);
|
|
991
|
+
var PRELOAD_FLAGS = ["--preload", "--require", "--import", "-r"];
|
|
992
|
+
var NODE_LOADING_FLAGS = ["--require", "-r", "--import", "--loader", "--experimental-loader", "--conditions", "-C"];
|
|
993
|
+
function preloadAt(args, index) {
|
|
994
|
+
const arg = args[index];
|
|
995
|
+
if (PRELOAD_FLAGS.includes(arg)) {
|
|
996
|
+
const value = args.at(index + 1);
|
|
997
|
+
return { file: value === undefined || value.startsWith("-") ? undefined : value, tokens: 2 };
|
|
998
|
+
}
|
|
999
|
+
const flag = PRELOAD_FLAGS.find((spelling) => arg.startsWith(spelling.startsWith("--") ? `${spelling}=` : spelling));
|
|
1000
|
+
if (flag === undefined) {
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
const value = arg.slice(flag.length).replace(/^=/, "");
|
|
1004
|
+
return { file: value === "" ? undefined : value, tokens: 1 };
|
|
1005
|
+
}
|
|
1006
|
+
function neutralTokens(args, index) {
|
|
1007
|
+
const arg = args[index];
|
|
1008
|
+
if (SCAN_NEUTRAL_FLAGS.has(arg)) {
|
|
1009
|
+
return 1;
|
|
1010
|
+
}
|
|
1011
|
+
if (SCAN_NEUTRAL_VALUE_FLAGS.has(arg)) {
|
|
1012
|
+
return 2;
|
|
1013
|
+
}
|
|
1014
|
+
const equals = arg.indexOf("=");
|
|
1015
|
+
return equals !== -1 && SCAN_NEUTRAL_VALUE_FLAGS.has(arg.slice(0, equals)) ? 1 : 0;
|
|
1016
|
+
}
|
|
1017
|
+
function readScanArguments(args, source, cwd) {
|
|
1018
|
+
const preloads = [];
|
|
1019
|
+
for (let index = 0;index < args.length; ) {
|
|
1020
|
+
const preload = preloadAt(args, index);
|
|
1021
|
+
if (preload !== undefined) {
|
|
1022
|
+
if (preload.file === undefined) {
|
|
1023
|
+
return { problem: `${source} contains "${args[index]}" without a file the import scan can name` };
|
|
1024
|
+
}
|
|
1025
|
+
preloads.push(path4.resolve(cwd, preload.file));
|
|
1026
|
+
index += preload.tokens;
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
const tokens = neutralTokens(args, index);
|
|
1030
|
+
if (tokens === 0) {
|
|
1031
|
+
return { problem: `${source} contains "${args[index]}", which can change what the tests load or how their imports resolve, and the import scan cannot account for it` };
|
|
1032
|
+
}
|
|
1033
|
+
index += tokens;
|
|
1034
|
+
}
|
|
1035
|
+
return { preloads };
|
|
1036
|
+
}
|
|
1037
|
+
function scanLaunchArguments(bunArgs, env, cwd) {
|
|
1038
|
+
const bunOptions = (env.BUN_OPTIONS ?? "").split(/\s/).filter((token) => token !== "");
|
|
1039
|
+
const fromEnv = readScanArguments(bunOptions, "the BUN_OPTIONS environment variable", cwd);
|
|
1040
|
+
if ("problem" in fromEnv) {
|
|
1041
|
+
return fromEnv;
|
|
1042
|
+
}
|
|
1043
|
+
if (fromEnv.preloads.length > 0) {
|
|
1044
|
+
return { problem: "the BUN_OPTIONS environment variable adds a preload, which the import scan cannot account for" };
|
|
1045
|
+
}
|
|
1046
|
+
const nodeOptions = env.NODE_OPTIONS ?? "";
|
|
1047
|
+
const nodeOption = nodeOptions.split(/\s/).find((token) => NODE_LOADING_FLAGS.some((flag) => token === flag || token.startsWith(`${flag}=`)));
|
|
1048
|
+
if (nodeOption !== undefined) {
|
|
1049
|
+
return { problem: `the NODE_OPTIONS environment variable contains "${nodeOption}", which the import scan cannot account for` };
|
|
1050
|
+
}
|
|
1051
|
+
return readScanArguments(bunArgs, "bun.bunArgs", cwd);
|
|
1052
|
+
}
|
|
1053
|
+
function correctStrykerTimeout(strykerTimeoutMs, correctionMs) {
|
|
1054
|
+
const correction = correctionMs;
|
|
1055
|
+
if (Number.isFinite(correction) && correction >= 0 && correction < strykerTimeoutMs) {
|
|
1056
|
+
return { timeoutMs: strykerTimeoutMs - correction, applied: true };
|
|
1057
|
+
}
|
|
1058
|
+
return { timeoutMs: strykerTimeoutMs, applied: false };
|
|
1059
|
+
}
|
|
1060
|
+
function budgetWarning(usedMs, budgetMs) {
|
|
1061
|
+
const budget = budgetMs;
|
|
1062
|
+
if (!Number.isFinite(budget) || budget <= 0 || !Number.isFinite(usedMs)) {
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
const remainingMs = budget - usedMs;
|
|
1066
|
+
if (remainingMs >= usedMs) {
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
return { usedMs, remainingMs: Math.max(0, remainingMs), suggestedMinutes: Math.ceil(2 * usedMs / 60000) };
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// src/coverage/import-scan-runner.ts
|
|
1073
|
+
import { spawn } from "node:child_process";
|
|
1074
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1075
|
+
import { rm as rm3 } from "node:fs/promises";
|
|
1076
|
+
import path5 from "node:path";
|
|
1077
|
+
import { fileURLToPath } from "node:url";
|
|
1078
|
+
var IMPORT_SCAN_TIMEOUT_MS = 5000;
|
|
1079
|
+
var STDERR_EXCERPT_CHARS = 2000;
|
|
1080
|
+
var IMPORT_SCAN_STDERR_LIMIT_BYTES = 64 * 1024;
|
|
1081
|
+
var STDOUT_BASE_BYTES = 1024 * 1024;
|
|
1082
|
+
function scanOutputLimits(input) {
|
|
1083
|
+
const eagerBytes = input.eager.reduce((sum, file) => sum + Buffer.byteLength(file) + 3, 0);
|
|
1084
|
+
return { stdout: STDOUT_BASE_BYTES + 6 * eagerBytes, stderr: IMPORT_SCAN_STDERR_LIMIT_BYTES };
|
|
1085
|
+
}
|
|
1086
|
+
function resolveBunExecutable(bunPath, cwd) {
|
|
1087
|
+
const hasDirectory = bunPath.includes("/") || path5.sep === "\\" && bunPath.includes("\\");
|
|
1088
|
+
return hasDirectory && !path5.isAbsolute(bunPath) ? path5.resolve(cwd, bunPath) : bunPath;
|
|
1089
|
+
}
|
|
1090
|
+
var PRELOADING_ENV = ["BUN_OPTIONS", "NODE_OPTIONS"];
|
|
1091
|
+
function resolveImportScanScript(moduleDir) {
|
|
1092
|
+
const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
|
|
1093
|
+
return isBundled ? path5.join(moduleDir, "templates/import-scan.js") : path5.join(moduleDir, "import-scan.ts");
|
|
1094
|
+
}
|
|
1095
|
+
function failedScanResult(reason) {
|
|
1096
|
+
return { answer: "dynamic", mandatory: [], named: [], reasons: [reason], notes: [], scannedFiles: 0, elapsedMs: 0 };
|
|
1097
|
+
}
|
|
1098
|
+
var isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
1099
|
+
function parseImportScanOutput(stdout, eagerList) {
|
|
1100
|
+
let value;
|
|
1101
|
+
try {
|
|
1102
|
+
value = JSON.parse(stdout);
|
|
1103
|
+
} catch (error) {
|
|
1104
|
+
return { problem: `its output is not JSON (${error.message})` };
|
|
1105
|
+
}
|
|
1106
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1107
|
+
return { problem: "its output is not a JSON object" };
|
|
1108
|
+
}
|
|
1109
|
+
const output = value;
|
|
1110
|
+
const problem = outputProblem(output, new Set(eagerList));
|
|
1111
|
+
if (problem !== undefined) {
|
|
1112
|
+
return { problem };
|
|
1113
|
+
}
|
|
1114
|
+
const { answer, mandatory, named, reasons, notes, scannedFiles, elapsedMs } = output;
|
|
1115
|
+
const mandatorySet = new Set(mandatory);
|
|
1116
|
+
const namedSet = new Set(named);
|
|
1117
|
+
return {
|
|
1118
|
+
result: {
|
|
1119
|
+
answer,
|
|
1120
|
+
mandatory: eagerList.filter((file) => mandatorySet.has(file)),
|
|
1121
|
+
named: eagerList.filter((file) => namedSet.has(file)),
|
|
1122
|
+
reasons,
|
|
1123
|
+
notes,
|
|
1124
|
+
scannedFiles,
|
|
1125
|
+
elapsedMs
|
|
1126
|
+
}
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
function outputProblem(output, eager) {
|
|
1130
|
+
if (output.answer !== "full" && output.answer !== "static" && output.answer !== "dynamic") {
|
|
1131
|
+
return `its answer ${JSON.stringify(output.answer)} is not full, static or dynamic`;
|
|
1132
|
+
}
|
|
1133
|
+
for (const name of ["mandatory", "named"]) {
|
|
1134
|
+
const list = output[name];
|
|
1135
|
+
if (!isStringArray(list) || !list.every((file) => eager.has(file))) {
|
|
1136
|
+
return `its ${name} list is not a list of files of the eager list`;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
for (const name of ["reasons", "notes"]) {
|
|
1140
|
+
if (!isStringArray(output[name])) {
|
|
1141
|
+
return `its ${name} are not a list of strings`;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
for (const name of ["scannedFiles", "elapsedMs"]) {
|
|
1145
|
+
const value = output[name];
|
|
1146
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
1147
|
+
return `its ${name} is not a non-negative number`;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
class BoundedStream {
|
|
1154
|
+
limit;
|
|
1155
|
+
chunks = [];
|
|
1156
|
+
bytes = 0;
|
|
1157
|
+
constructor(limit) {
|
|
1158
|
+
this.limit = limit;
|
|
1159
|
+
}
|
|
1160
|
+
add(chunk) {
|
|
1161
|
+
this.bytes += chunk.length;
|
|
1162
|
+
if (this.bytes > this.limit) {
|
|
1163
|
+
return false;
|
|
1164
|
+
}
|
|
1165
|
+
this.chunks.push(chunk);
|
|
1166
|
+
return true;
|
|
1167
|
+
}
|
|
1168
|
+
text() {
|
|
1169
|
+
return Buffer.concat(this.chunks).toString("utf8");
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function runHelper(bunPath, args, cwd, timeoutMs, maxBytes) {
|
|
1173
|
+
const env = { ...process.env };
|
|
1174
|
+
for (const name of PRELOADING_ENV) {
|
|
1175
|
+
delete env[name];
|
|
1176
|
+
}
|
|
1177
|
+
return new Promise((resolve) => {
|
|
1178
|
+
const streams = { stdout: new BoundedStream(maxBytes.stdout), stderr: new BoundedStream(maxBytes.stderr) };
|
|
1179
|
+
let timedOut = false;
|
|
1180
|
+
let overflow;
|
|
1181
|
+
let error;
|
|
1182
|
+
const ended = (exitCode, signal) => {
|
|
1183
|
+
resolve({ stdout: streams.stdout.text(), stderr: streams.stderr.text(), exitCode, signal, timedOut, overflow, error });
|
|
1184
|
+
};
|
|
1185
|
+
let child;
|
|
1186
|
+
try {
|
|
1187
|
+
child = spawn(bunPath, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
|
|
1188
|
+
} catch (spawnError) {
|
|
1189
|
+
error = spawnError instanceof Error ? spawnError : new Error(String(spawnError));
|
|
1190
|
+
ended(null, null);
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
const abandon = () => {
|
|
1194
|
+
child.kill("SIGKILL");
|
|
1195
|
+
child.stdout?.destroy();
|
|
1196
|
+
child.stderr?.destroy();
|
|
1197
|
+
ended(null, null);
|
|
1198
|
+
};
|
|
1199
|
+
const timer = setTimeout(() => {
|
|
1200
|
+
timedOut = true;
|
|
1201
|
+
abandon();
|
|
1202
|
+
}, timeoutMs);
|
|
1203
|
+
const collect = (name) => (chunk) => {
|
|
1204
|
+
if (!streams[name].add(chunk) && overflow === undefined) {
|
|
1205
|
+
overflow = name;
|
|
1206
|
+
clearTimeout(timer);
|
|
1207
|
+
abandon();
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
child.stdout?.on("data", collect("stdout"));
|
|
1211
|
+
child.stderr?.on("data", collect("stderr"));
|
|
1212
|
+
child.on("error", (spawnError) => {
|
|
1213
|
+
error = spawnError;
|
|
1214
|
+
});
|
|
1215
|
+
child.on("close", (exitCode, signal) => {
|
|
1216
|
+
clearTimeout(timer);
|
|
1217
|
+
ended(exitCode, signal);
|
|
1218
|
+
});
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
function helperFailure(exit, timeoutMs, maxBytes) {
|
|
1222
|
+
if (exit.error !== undefined) {
|
|
1223
|
+
return `the scan helper could not be started (${exit.error.message})`;
|
|
1224
|
+
}
|
|
1225
|
+
if (exit.overflow !== undefined) {
|
|
1226
|
+
return `the scan helper printed more than ${maxBytes[exit.overflow]} bytes on ${exit.overflow}`;
|
|
1227
|
+
}
|
|
1228
|
+
if (exit.timedOut) {
|
|
1229
|
+
return `the scan helper did not finish within ${timeoutMs} ms`;
|
|
1230
|
+
}
|
|
1231
|
+
if (exit.exitCode !== 0) {
|
|
1232
|
+
const how = exit.exitCode === null ? `was ended by ${exit.signal}` : `exited with code ${exit.exitCode}`;
|
|
1233
|
+
const said = exit.stderr.trim().slice(0, STDERR_EXCERPT_CHARS);
|
|
1234
|
+
return said === "" ? `the scan helper ${how}` : `the scan helper ${how}: ${said}`;
|
|
1235
|
+
}
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
async function runImportScan(input, launch) {
|
|
1239
|
+
const started = performance.now();
|
|
1240
|
+
const timeoutMs = launch.timeoutMs ?? IMPORT_SCAN_TIMEOUT_MS;
|
|
1241
|
+
const maxBytes = launch.maxBytes ?? scanOutputLimits(input);
|
|
1242
|
+
const scriptPath = launch.scriptPath ?? resolveImportScanScript(path5.dirname(fileURLToPath(import.meta.url)));
|
|
1243
|
+
const stem = path5.join(launch.workDir, `import-scan-${process.pid}-${randomBytes2(8).toString("hex")}`);
|
|
1244
|
+
const inputFile = `${stem}.json`;
|
|
1245
|
+
const configFile = `${stem}.bunfig.toml`;
|
|
1246
|
+
const report = (result, failure) => ({ result, failure, wallMs: performance.now() - started });
|
|
1247
|
+
const fail = (failure) => report(failedScanResult(failure), failure);
|
|
1248
|
+
try {
|
|
1249
|
+
try {
|
|
1250
|
+
await ensurePrivateDir(launch.workDir);
|
|
1251
|
+
await writePrivateFile(inputFile, JSON.stringify(input));
|
|
1252
|
+
await writePrivateFile(configFile, "");
|
|
1253
|
+
} catch (error) {
|
|
1254
|
+
return fail(`the scan's input could not be written (${error.message})`);
|
|
1255
|
+
}
|
|
1256
|
+
const bunPath = resolveBunExecutable(launch.bunPath, process.cwd());
|
|
1257
|
+
const exit = await runHelper(bunPath, ["--no-macros", "--no-install", `--config=${configFile}`, scriptPath, inputFile], launch.workDir, timeoutMs, maxBytes);
|
|
1258
|
+
const failure = helperFailure(exit, timeoutMs, maxBytes);
|
|
1259
|
+
if (failure !== undefined) {
|
|
1260
|
+
return fail(failure);
|
|
1261
|
+
}
|
|
1262
|
+
const parsed = parseImportScanOutput(exit.stdout, input.eager);
|
|
1263
|
+
return "problem" in parsed ? fail(`the scan helper's answer cannot be used: ${parsed.problem}`) : report(parsed.result, null);
|
|
1264
|
+
} finally {
|
|
1265
|
+
await Promise.all([inputFile, configFile].map((file) => rm3(file).catch(() => {
|
|
1266
|
+
return;
|
|
1267
|
+
})));
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// src/coverage/preload-generator.ts
|
|
1272
|
+
import { unlink, readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
|
|
1273
|
+
import path6 from "node:path";
|
|
1274
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
1275
|
+
import { glob } from "tinyglobby";
|
|
1276
|
+
|
|
272
1277
|
// src/utils/test-name-pattern.ts
|
|
273
1278
|
var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
|
|
274
1279
|
var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.(?:[jt]sx?|[mc][jt]s)`;
|
|
@@ -334,7 +1339,7 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
|
|
|
334
1339
|
const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
|
|
335
1340
|
const dtsRe = /\.d\.[cm]?ts$/;
|
|
336
1341
|
const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
|
|
337
|
-
const resolved = filtered.map((p) =>
|
|
1342
|
+
const resolved = filtered.map((p) => path6.resolve(p));
|
|
338
1343
|
resolved.sort((a, b) => a.localeCompare(b));
|
|
339
1344
|
return resolved;
|
|
340
1345
|
}
|
|
@@ -342,44 +1347,48 @@ function resolvePreloadTemplate(moduleDir) {
|
|
|
342
1347
|
const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
|
|
343
1348
|
if (isBundled) {
|
|
344
1349
|
return {
|
|
345
|
-
templatePath:
|
|
1350
|
+
templatePath: path6.join(moduleDir, "templates/coverage-preload.js"),
|
|
346
1351
|
preloadLogicPath: undefined,
|
|
347
1352
|
extension: "js"
|
|
348
1353
|
};
|
|
349
1354
|
}
|
|
350
1355
|
return {
|
|
351
|
-
templatePath:
|
|
352
|
-
preloadLogicPath:
|
|
1356
|
+
templatePath: path6.join(moduleDir, "../templates/coverage-preload.ts"),
|
|
1357
|
+
preloadLogicPath: path6.join(moduleDir, "preload-logic.ts"),
|
|
353
1358
|
extension: "ts"
|
|
354
1359
|
};
|
|
355
1360
|
}
|
|
356
|
-
async function generatePreloadScript(options, moduleDir =
|
|
1361
|
+
async function generatePreloadScript(options, moduleDir = path6.dirname(fileURLToPath2(import.meta.url))) {
|
|
357
1362
|
await ensurePrivateDir(options.tempDir);
|
|
358
1363
|
const { templatePath, preloadLogicPath, extension } = resolvePreloadTemplate(moduleDir);
|
|
359
|
-
const preloadPath =
|
|
360
|
-
const template = await
|
|
361
|
-
const
|
|
362
|
-
const eagerModulesFile = eagerModules.length > 0 ? eagerModulesFileFor(preloadPath) : null;
|
|
363
|
-
const withLogic = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
|
|
364
|
-
const content = withLogic.replace("__EAGER_MODULES_FILE__", () => JSON.stringify(eagerModulesFile));
|
|
1364
|
+
const preloadPath = path6.join(options.tempDir, `stryker-coverage-preload-${process.pid}.${extension}`);
|
|
1365
|
+
const template = await readFile2(templatePath, "utf8");
|
|
1366
|
+
const content = preloadLogicPath === undefined ? template : template.replace("__PRELOAD_LOGIC_PATH__", () => preloadLogicPath);
|
|
365
1367
|
await writePrivateFile(preloadPath, content);
|
|
366
|
-
if (
|
|
367
|
-
await
|
|
1368
|
+
if (options.dryRunPlan !== undefined) {
|
|
1369
|
+
await writeDryRunPlan(dryRunPlanFileFor(preloadPath), options.dryRunPlan);
|
|
368
1370
|
}
|
|
369
1371
|
return preloadPath;
|
|
370
1372
|
}
|
|
371
|
-
function
|
|
372
|
-
|
|
1373
|
+
async function writeDryRunPlan(file, plan) {
|
|
1374
|
+
await writePrivateFile(file, JSON.stringify(plan));
|
|
1375
|
+
}
|
|
1376
|
+
async function writeWatchList(file, paths, resolve = realpath2) {
|
|
1377
|
+
const entries = await Promise.all(paths.map(async (watched) => ({ file: watched, realpath: await resolve(watched).catch(() => watched) })));
|
|
1378
|
+
await writePrivateFile(file, JSON.stringify(entries));
|
|
1379
|
+
}
|
|
1380
|
+
function dryRunPlanFileFor(preloadPath) {
|
|
1381
|
+
return `${preloadPath.replace(/\.[jt]s$/, "")}.dry-run-plan.json`;
|
|
373
1382
|
}
|
|
374
1383
|
async function cleanupPreloadScript(preloadPath) {
|
|
375
|
-
for (const file of [preloadPath,
|
|
1384
|
+
for (const file of [preloadPath, dryRunPlanFileFor(preloadPath)]) {
|
|
376
1385
|
try {
|
|
377
1386
|
await unlink(file);
|
|
378
1387
|
} catch {}
|
|
379
1388
|
}
|
|
380
1389
|
}
|
|
381
1390
|
// src/coverage/collector.ts
|
|
382
|
-
import { readFile as
|
|
1391
|
+
import { readFile as readFile3, unlink as unlink2 } from "node:fs/promises";
|
|
383
1392
|
function addHitCounts(into, from) {
|
|
384
1393
|
for (const [mutantId, count] of Object.entries(from)) {
|
|
385
1394
|
into[mutantId] = (into[mutantId] ?? 0) + count;
|
|
@@ -429,7 +1438,7 @@ async function readCoverageFileDataShared(coverageFile, logger) {
|
|
|
429
1438
|
}
|
|
430
1439
|
async function readCoverageFileData(coverageFile, logger) {
|
|
431
1440
|
try {
|
|
432
|
-
const content = await
|
|
1441
|
+
const content = await readFile3(coverageFile, "utf8");
|
|
433
1442
|
const trimmed = content.trim();
|
|
434
1443
|
const lines = trimmed.split(`
|
|
435
1444
|
`).filter((line) => line.length > 0);
|
|
@@ -585,6 +1594,15 @@ function sumHitsByMutant(coverage) {
|
|
|
585
1594
|
}
|
|
586
1595
|
return totals;
|
|
587
1596
|
}
|
|
1597
|
+
function reachedOnly(coverage) {
|
|
1598
|
+
const reached = {};
|
|
1599
|
+
for (const [mutantId, total] of sumHitsByMutant(coverage)) {
|
|
1600
|
+
if (total > 0) {
|
|
1601
|
+
reached[mutantId] = total;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
return { static: reached, perTest: {} };
|
|
1605
|
+
}
|
|
588
1606
|
function restoreHitTotals(rawCoverage, mapped) {
|
|
589
1607
|
const rawTotals = sumHitsByMutant(rawCoverage);
|
|
590
1608
|
const result = {
|
|
@@ -706,9 +1724,7 @@ function buildMappedCoverage(counterIds, resolved, rawCoverage, testHierarchy) {
|
|
|
706
1724
|
creditHits(incoming, writable, staticIds, staticCounts);
|
|
707
1725
|
}
|
|
708
1726
|
const perTest = nonEmptyTests(creditedByName, orphaned.length > 0);
|
|
709
|
-
|
|
710
|
-
creditOrphanedHits(orphaned, staticCounts, perTest);
|
|
711
|
-
}
|
|
1727
|
+
creditOrphanedHits(orphaned, staticCounts, perTest);
|
|
712
1728
|
return { static: staticCounts, perTest };
|
|
713
1729
|
}
|
|
714
1730
|
function creditHits(incoming, credited, staticIds, staticCounts) {
|
|
@@ -738,7 +1754,7 @@ function holdsAny(counts, mutantIds) {
|
|
|
738
1754
|
}
|
|
739
1755
|
return false;
|
|
740
1756
|
}
|
|
741
|
-
function
|
|
1757
|
+
function firstHolders(staticCounts, perTest) {
|
|
742
1758
|
const firstHolder = new Map;
|
|
743
1759
|
for (const counts of [staticCounts, ...Object.values(perTest)]) {
|
|
744
1760
|
for (const mutantId of Object.keys(counts)) {
|
|
@@ -747,7 +1763,12 @@ function creditOrphanedHits(orphaned, staticCounts, perTest) {
|
|
|
747
1763
|
}
|
|
748
1764
|
}
|
|
749
1765
|
}
|
|
1766
|
+
return firstHolder;
|
|
1767
|
+
}
|
|
1768
|
+
function creditOrphanedHits(orphaned, staticCounts, perTest) {
|
|
1769
|
+
let firstHolder;
|
|
750
1770
|
for (const counts of orphaned) {
|
|
1771
|
+
firstHolder ??= firstHolders(staticCounts, perTest);
|
|
751
1772
|
for (const mutantId of Object.keys(counts)) {
|
|
752
1773
|
const holder = firstHolder.get(mutantId);
|
|
753
1774
|
if (holder) {
|
|
@@ -873,34 +1894,6 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
|
|
|
873
1894
|
orphanedKeyCount: counterIds.length - creditedKeyCount
|
|
874
1895
|
};
|
|
875
1896
|
}
|
|
876
|
-
// src/coverage/preload-logic.ts
|
|
877
|
-
import { appendFileSync, closeSync, constants, openSync, writeSync } from "node:fs";
|
|
878
|
-
var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
|
|
879
|
-
var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
|
|
880
|
-
var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
|
|
881
|
-
function readPreloadTimings(stderr) {
|
|
882
|
-
const start = stderr.lastIndexOf(`
|
|
883
|
-
${PRELOAD_TIMINGS_PREFIX}`);
|
|
884
|
-
if (start === -1) {
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
const jsonStart = start + 1 + PRELOAD_TIMINGS_PREFIX.length;
|
|
888
|
-
const end = stderr.indexOf(`
|
|
889
|
-
`, jsonStart);
|
|
890
|
-
try {
|
|
891
|
-
const parsed = JSON.parse(stderr.slice(jsonStart, end === -1 ? stderr.length : end));
|
|
892
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
893
|
-
return;
|
|
894
|
-
}
|
|
895
|
-
return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
|
|
896
|
-
} catch {
|
|
897
|
-
return;
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
|
|
901
|
-
var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
|
|
902
|
-
var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
|
|
903
|
-
|
|
904
1897
|
// src/inspector/types.ts
|
|
905
1898
|
var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
|
|
906
1899
|
function isTestReporterFoundEvent(message) {
|
|
@@ -1350,10 +2343,10 @@ class InspectorClient {
|
|
|
1350
2343
|
}
|
|
1351
2344
|
}
|
|
1352
2345
|
// src/parsers/console-parser.ts
|
|
1353
|
-
import
|
|
2346
|
+
import path9 from "node:path";
|
|
1354
2347
|
|
|
1355
2348
|
// src/process-runner.ts
|
|
1356
|
-
import { spawn as
|
|
2349
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
1357
2350
|
|
|
1358
2351
|
// src/utils/process-group.ts
|
|
1359
2352
|
function killProcessGroup(pid, signal) {
|
|
@@ -1366,8 +2359,8 @@ function killProcessGroup(pid, signal) {
|
|
|
1366
2359
|
}
|
|
1367
2360
|
|
|
1368
2361
|
// src/utils/process-rss.ts
|
|
1369
|
-
import { spawn } from "node:child_process";
|
|
1370
|
-
import { readFile as
|
|
2362
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2363
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
1371
2364
|
async function getProcessRssBytes(pid) {
|
|
1372
2365
|
return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
|
|
1373
2366
|
}
|
|
@@ -1377,7 +2370,7 @@ function parseVmRss(statusContent) {
|
|
|
1377
2370
|
}
|
|
1378
2371
|
async function getLinuxRss(pid) {
|
|
1379
2372
|
try {
|
|
1380
|
-
const status = await
|
|
2373
|
+
const status = await readFile4(`/proc/${pid}/status`, "utf8");
|
|
1381
2374
|
return parseVmRss(status);
|
|
1382
2375
|
} catch {
|
|
1383
2376
|
return null;
|
|
@@ -1395,7 +2388,7 @@ async function getPsRss(pid) {
|
|
|
1395
2388
|
return new Promise((resolve) => {
|
|
1396
2389
|
let child;
|
|
1397
2390
|
try {
|
|
1398
|
-
child =
|
|
2391
|
+
child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
|
|
1399
2392
|
} catch {
|
|
1400
2393
|
resolve(null);
|
|
1401
2394
|
return;
|
|
@@ -1413,21 +2406,40 @@ async function getPsRss(pid) {
|
|
|
1413
2406
|
});
|
|
1414
2407
|
}
|
|
1415
2408
|
|
|
2409
|
+
// src/utils/project-dir.ts
|
|
2410
|
+
import path7 from "node:path";
|
|
2411
|
+
var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
|
|
2412
|
+
var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
|
|
2413
|
+
function recordProjectDirectory() {
|
|
2414
|
+
const inherited = process.env[PROJECT_DIR_ENV];
|
|
2415
|
+
const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
|
|
2416
|
+
if (isWorker && inherited !== undefined && path7.isAbsolute(inherited)) {
|
|
2417
|
+
return inherited;
|
|
2418
|
+
}
|
|
2419
|
+
const here = process.cwd();
|
|
2420
|
+
process.env[PROJECT_DIR_ENV] = here;
|
|
2421
|
+
return here;
|
|
2422
|
+
}
|
|
2423
|
+
var projectDirectory = recordProjectDirectory();
|
|
2424
|
+
function resolveAgainstProject(file) {
|
|
2425
|
+
return path7.resolve(projectDirectory, file);
|
|
2426
|
+
}
|
|
2427
|
+
|
|
1416
2428
|
// src/utils/test-file-args.ts
|
|
1417
|
-
import
|
|
2429
|
+
import path8 from "node:path";
|
|
1418
2430
|
var MAX_TEST_FILE_ARGS_BYTES = 131072;
|
|
1419
2431
|
var ENTRY_OVERHEAD_BYTES = 1 + 8;
|
|
1420
2432
|
var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
|
|
1421
2433
|
function shortestSpelling(absolute, cwd) {
|
|
1422
|
-
const relative =
|
|
2434
|
+
const relative = path8.relative(cwd, absolute);
|
|
1423
2435
|
if (relative === "" || relative === "..") {
|
|
1424
2436
|
return absolute;
|
|
1425
2437
|
}
|
|
1426
|
-
const spelled = relative.startsWith(`..${
|
|
2438
|
+
const spelled = relative.startsWith(`..${path8.sep}`) ? relative : `.${path8.sep}${relative}`;
|
|
1427
2439
|
return spelled.length < absolute.length ? spelled : absolute;
|
|
1428
2440
|
}
|
|
1429
2441
|
function computeTestFileArgs(files, cwd, budget) {
|
|
1430
|
-
const absolute = files.map((file) =>
|
|
2442
|
+
const absolute = files.map((file) => path8.resolve(cwd, file));
|
|
1431
2443
|
const absoluteBytes = bytesOf(absolute);
|
|
1432
2444
|
if (absoluteBytes <= budget) {
|
|
1433
2445
|
return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
|
|
@@ -1441,7 +2453,7 @@ function sameEntries(a, b) {
|
|
|
1441
2453
|
}
|
|
1442
2454
|
var lastBuild;
|
|
1443
2455
|
function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
|
|
1444
|
-
if (!
|
|
2456
|
+
if (!path8.isAbsolute(cwd)) {
|
|
1445
2457
|
return computeTestFileArgs(files, cwd, budget);
|
|
1446
2458
|
}
|
|
1447
2459
|
const cached = lastBuild;
|
|
@@ -1569,8 +2581,11 @@ function buildChildEnv(options, spawnDepth) {
|
|
|
1569
2581
|
__STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
|
|
1570
2582
|
__STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
|
|
1571
2583
|
__STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
|
|
2584
|
+
[COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
|
|
1572
2585
|
__STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
|
|
1573
2586
|
[SYNC_TOKEN_ENV]: options.syncToken,
|
|
2587
|
+
[DRY_RUN_PLAN_ENV]: options.dryRunPlan,
|
|
2588
|
+
[WATCH_LIST_ENV]: options.watchList,
|
|
1574
2589
|
[LIFELINE_FD_ENV]: String(LIFELINE_FD)
|
|
1575
2590
|
};
|
|
1576
2591
|
for (const [name, value] of Object.entries(preloadVars)) {
|
|
@@ -1581,6 +2596,7 @@ function buildChildEnv(options, spawnDepth) {
|
|
|
1581
2596
|
}
|
|
1582
2597
|
}
|
|
1583
2598
|
env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
|
|
2599
|
+
delete env[PROJECT_DIR_ENV];
|
|
1584
2600
|
if (options.profile) {
|
|
1585
2601
|
delete env[PROFILE_ENV];
|
|
1586
2602
|
}
|
|
@@ -1644,7 +2660,10 @@ async function spawnBunTests(options, spawnDepth) {
|
|
|
1644
2660
|
cwd: process.cwd(),
|
|
1645
2661
|
detached: true
|
|
1646
2662
|
};
|
|
1647
|
-
|
|
2663
|
+
try {
|
|
2664
|
+
options.onSpawn?.([options.bunPath, ...args]);
|
|
2665
|
+
} catch {}
|
|
2666
|
+
const childProcess = spawn3(options.bunPath, args, spawnOpts);
|
|
1648
2667
|
profile?.mark("spawned");
|
|
1649
2668
|
liveChildren.add(childProcess);
|
|
1650
2669
|
ensureSignalCleanup();
|
|
@@ -1788,11 +2807,11 @@ function headerFilter(lines, testFiles) {
|
|
|
1788
2807
|
if (testFiles === undefined) {
|
|
1789
2808
|
return () => true;
|
|
1790
2809
|
}
|
|
1791
|
-
const roots = new Set(testFiles.map((file) =>
|
|
2810
|
+
const roots = new Set(testFiles.map((file) => path9.resolve(file)));
|
|
1792
2811
|
const isRunFile = (file) => {
|
|
1793
|
-
let candidate =
|
|
2812
|
+
let candidate = path9.resolve(file);
|
|
1794
2813
|
while (!roots.has(candidate)) {
|
|
1795
|
-
const parent =
|
|
2814
|
+
const parent = path9.dirname(candidate);
|
|
1796
2815
|
if (parent === candidate) {
|
|
1797
2816
|
return false;
|
|
1798
2817
|
}
|
|
@@ -2004,7 +3023,7 @@ ${stderr}`;
|
|
|
2004
3023
|
blockStart: 0,
|
|
2005
3024
|
lastFailed: undefined
|
|
2006
3025
|
};
|
|
2007
|
-
for (
|
|
3026
|
+
for (const index of lines.keys()) {
|
|
2008
3027
|
readLine(reader, index);
|
|
2009
3028
|
}
|
|
2010
3029
|
const summaryCounts = parseSummaryLines(output);
|
|
@@ -2026,9 +3045,303 @@ ${stderr}`;
|
|
|
2026
3045
|
};
|
|
2027
3046
|
}
|
|
2028
3047
|
|
|
3048
|
+
// src/parsers/unhandled-errors.ts
|
|
3049
|
+
var MAX_BLOCKS_SHOWN = 20;
|
|
3050
|
+
var MAX_DIAGNOSTIC_CHARS = 16000;
|
|
3051
|
+
var MAX_SNIPPET_LINE_CHARS = 300;
|
|
3052
|
+
var MAX_NAMED = 3;
|
|
3053
|
+
var MAX_NAME_CHARS = 200;
|
|
3054
|
+
var BLOCK_MARKER = "# Unhandled error between tests";
|
|
3055
|
+
var BLOCK_RULE = "-".repeat(31);
|
|
3056
|
+
var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
|
|
3057
|
+
var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
|
|
3058
|
+
var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
|
|
3059
|
+
var SNIPPET_LINE_RE = /^\s*\d+ \|/;
|
|
3060
|
+
var SNIPPET_CARET_RE = /^\s*\^+$/;
|
|
3061
|
+
var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
|
|
3062
|
+
function pathKey(path) {
|
|
3063
|
+
return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
|
|
3064
|
+
}
|
|
3065
|
+
function percentDecode(text) {
|
|
3066
|
+
try {
|
|
3067
|
+
return decodeURIComponent(text);
|
|
3068
|
+
} catch {
|
|
3069
|
+
return text;
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
function locationPath(location) {
|
|
3073
|
+
if (/^file:\/\//i.test(location)) {
|
|
3074
|
+
const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
|
|
3075
|
+
return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
|
|
3076
|
+
}
|
|
3077
|
+
return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
|
|
3078
|
+
}
|
|
3079
|
+
function frameFile(line) {
|
|
3080
|
+
const trimmed = line.trim();
|
|
3081
|
+
if (!trimmed.startsWith("at ")) {
|
|
3082
|
+
return;
|
|
3083
|
+
}
|
|
3084
|
+
let location = trimmed.slice(3).trim();
|
|
3085
|
+
const open = location.lastIndexOf(" (");
|
|
3086
|
+
if (open !== -1 && location.endsWith(")")) {
|
|
3087
|
+
location = location.slice(open + 2, -1);
|
|
3088
|
+
}
|
|
3089
|
+
const file = FRAME_LOCATION_RE.exec(location)?.[1];
|
|
3090
|
+
return file === undefined ? undefined : locationPath(file);
|
|
3091
|
+
}
|
|
3092
|
+
function buildBlock(printed, headerFile) {
|
|
3093
|
+
const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
|
|
3094
|
+
const errorLine = body.find((line) => line.startsWith("error: "));
|
|
3095
|
+
return {
|
|
3096
|
+
headerFile,
|
|
3097
|
+
lines: body,
|
|
3098
|
+
frames: body.flatMap((line) => {
|
|
3099
|
+
const path = frameFile(line);
|
|
3100
|
+
return path === undefined ? [] : [{ path, line }];
|
|
3101
|
+
}),
|
|
3102
|
+
lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
|
|
3103
|
+
};
|
|
3104
|
+
}
|
|
3105
|
+
function parseUnhandledErrorBlocks(stderr, secrets = []) {
|
|
3106
|
+
const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
|
|
3107
|
+
const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
|
|
3108
|
+
const blocks = [];
|
|
3109
|
+
let headerFile;
|
|
3110
|
+
let scanned = 0;
|
|
3111
|
+
for (const [n, start] of starts.entries()) {
|
|
3112
|
+
for (const line of lines.slice(scanned, start)) {
|
|
3113
|
+
headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
|
|
3114
|
+
}
|
|
3115
|
+
const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
|
|
3116
|
+
const closingRule = following.indexOf(BLOCK_RULE);
|
|
3117
|
+
blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
|
|
3118
|
+
scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
|
|
3119
|
+
}
|
|
3120
|
+
return blocks;
|
|
3121
|
+
}
|
|
3122
|
+
var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
|
|
3123
|
+
function renderBlock(block, index, total) {
|
|
3124
|
+
const heading = ` Unhandled error block ${index + 1} of ${total}:`;
|
|
3125
|
+
if (block.lines.length === 0) {
|
|
3126
|
+
const empty = `${heading}
|
|
3127
|
+
(empty)`;
|
|
3128
|
+
return { full: empty, bare: empty };
|
|
3129
|
+
}
|
|
3130
|
+
const full = [];
|
|
3131
|
+
const bare = [];
|
|
3132
|
+
let omittedRun = 0;
|
|
3133
|
+
const endRun = () => {
|
|
3134
|
+
if (omittedRun > 0) {
|
|
3135
|
+
bare.push(` ... [${omittedRun} source line(s) omitted]`);
|
|
3136
|
+
omittedRun = 0;
|
|
3137
|
+
}
|
|
3138
|
+
};
|
|
3139
|
+
for (const line of block.lines) {
|
|
3140
|
+
if (isSnippetLine(line)) {
|
|
3141
|
+
omittedRun++;
|
|
3142
|
+
full.push(line.length > MAX_SNIPPET_LINE_CHARS ? ` ${line.slice(0, MAX_SNIPPET_LINE_CHARS)}... [${line.length - MAX_SNIPPET_LINE_CHARS} more character(s) of this line omitted]` : ` ${line}`);
|
|
3143
|
+
} else {
|
|
3144
|
+
endRun();
|
|
3145
|
+
full.push(` ${line}`);
|
|
3146
|
+
bare.push(` ${line}`);
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
endRun();
|
|
3150
|
+
return { full: [heading, ...full].join(`
|
|
3151
|
+
`), bare: [heading, ...bare].join(`
|
|
3152
|
+
`) };
|
|
3153
|
+
}
|
|
3154
|
+
function nameOf(text, secrets) {
|
|
3155
|
+
const redacted = redactSecrets(text, secrets);
|
|
3156
|
+
return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
|
|
3157
|
+
}
|
|
3158
|
+
function nameList(names) {
|
|
3159
|
+
const shown = names.slice(0, MAX_NAMED).join(", ");
|
|
3160
|
+
return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
|
|
3161
|
+
}
|
|
3162
|
+
function matchesHeader(framePath, header) {
|
|
3163
|
+
const frame = pathKey(framePath);
|
|
3164
|
+
const wanted = pathKey(header).replace(/^\.\//, "");
|
|
3165
|
+
return frame === wanted || frame.endsWith(`/${wanted}`);
|
|
3166
|
+
}
|
|
3167
|
+
function testFileFrame(block) {
|
|
3168
|
+
const { headerFile, frames } = block;
|
|
3169
|
+
const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
|
|
3170
|
+
return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
|
|
3171
|
+
}
|
|
3172
|
+
function lateCalls(blocks, secrets) {
|
|
3173
|
+
const seen = new Set;
|
|
3174
|
+
return blocks.flatMap((block, index) => {
|
|
3175
|
+
if (block.lateCall === undefined) {
|
|
3176
|
+
return [];
|
|
3177
|
+
}
|
|
3178
|
+
const frame = testFileFrame(block);
|
|
3179
|
+
const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
|
|
3180
|
+
const call = nameOf(block.lateCall, secrets);
|
|
3181
|
+
const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
|
|
3182
|
+
if (seen.has(key)) {
|
|
3183
|
+
return [];
|
|
3184
|
+
}
|
|
3185
|
+
seen.add(key);
|
|
3186
|
+
return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
|
|
3187
|
+
});
|
|
3188
|
+
}
|
|
3189
|
+
function eagerClaims(blocks, eagerModules, secrets) {
|
|
3190
|
+
const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
|
|
3191
|
+
const seen = new Set;
|
|
3192
|
+
return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
|
|
3193
|
+
const module = eagerByKey.get(pathKey(frame.path));
|
|
3194
|
+
if (module === undefined || seen.has(module)) {
|
|
3195
|
+
return [];
|
|
3196
|
+
}
|
|
3197
|
+
seen.add(module);
|
|
3198
|
+
return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
|
|
3199
|
+
}) : []);
|
|
3200
|
+
}
|
|
3201
|
+
function describeLateCall(late) {
|
|
3202
|
+
const error = `\`Cannot call ${late.call}() after the test run has completed\``;
|
|
3203
|
+
if (late.frame !== undefined) {
|
|
3204
|
+
return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
|
|
3205
|
+
}
|
|
3206
|
+
if (late.header !== undefined) {
|
|
3207
|
+
return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
|
|
3208
|
+
}
|
|
3209
|
+
return `${error} (block ${late.block + 1})`;
|
|
3210
|
+
}
|
|
3211
|
+
var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
|
|
3212
|
+
function lateCallSentences(lates, blocks) {
|
|
3213
|
+
if (lates.length === 0) {
|
|
3214
|
+
return [];
|
|
3215
|
+
}
|
|
3216
|
+
const named = lates.slice(0, MAX_NAMED);
|
|
3217
|
+
const fileKnown = named.every((late) => late.frame !== undefined);
|
|
3218
|
+
const consequence = fileKnown ? "bun had already ended that file's run when the call was made, so tests registered from that point were not run." : "bun's message says the call came after the test run had completed, so tests registered from that point were not run.";
|
|
3219
|
+
const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
|
|
3220
|
+
return [
|
|
3221
|
+
[
|
|
3222
|
+
`bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
|
|
3223
|
+
consequence,
|
|
3224
|
+
...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
|
|
3225
|
+
].join(" ")
|
|
3226
|
+
];
|
|
3227
|
+
}
|
|
3228
|
+
function eagerSentences(modules) {
|
|
3229
|
+
if (modules.length === 0) {
|
|
3230
|
+
return [];
|
|
3231
|
+
}
|
|
3232
|
+
const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
|
|
3233
|
+
return [
|
|
3234
|
+
`Stack frames point at ${named}. The module(s) named here are in the list of files this run's coverage preload imports before any test runs: ` + "files matched by your Stryker 'mutate' globs that the tests load or name in import() or require(), and any that bun.alwaysImport keeps. " + "If no test needs one of them imported first (typically an entry point with top-level side effects), take it out of bun.alwaysImport, " + "remove the import() or require() of it that never runs, or exclude it from 'mutate' (add a '!<path>' glob) and re-run."
|
|
3235
|
+
];
|
|
3236
|
+
}
|
|
3237
|
+
var CUT_NOTE_RESERVE = 200;
|
|
3238
|
+
var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
|
|
3239
|
+
function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
|
|
3240
|
+
const blocks = parseUnhandledErrorBlocks(stderr, secrets);
|
|
3241
|
+
if (blocks.length === 0) {
|
|
3242
|
+
return;
|
|
3243
|
+
}
|
|
3244
|
+
const lates = lateCalls(blocks, secrets);
|
|
3245
|
+
const modules = eagerClaims(blocks, eagerModules, secrets);
|
|
3246
|
+
const dropped = new Set;
|
|
3247
|
+
for (let attempt = 0;attempt < 8; attempt++) {
|
|
3248
|
+
const claims = {
|
|
3249
|
+
lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
|
|
3250
|
+
modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
|
|
3251
|
+
};
|
|
3252
|
+
const result = layOut(blocks, claims);
|
|
3253
|
+
const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
|
|
3254
|
+
if (lost.length === 0) {
|
|
3255
|
+
return result.text;
|
|
3256
|
+
}
|
|
3257
|
+
for (const claim of lost) {
|
|
3258
|
+
dropped.add(keyOf(claim));
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
|
|
3262
|
+
}
|
|
3263
|
+
function selectBlocks(blockCount, required) {
|
|
3264
|
+
const shown = new Set(required);
|
|
3265
|
+
for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
|
|
3266
|
+
shown.add(i);
|
|
3267
|
+
}
|
|
3268
|
+
return [...shown].toSorted((a, b) => a - b);
|
|
3269
|
+
}
|
|
3270
|
+
function cutBlock(text, share) {
|
|
3271
|
+
const [heading, ...body] = text.split(`
|
|
3272
|
+
`);
|
|
3273
|
+
const kept = [heading];
|
|
3274
|
+
let used = heading.length;
|
|
3275
|
+
for (const line of body) {
|
|
3276
|
+
if (used + 1 + line.length > share) {
|
|
3277
|
+
if (kept.length === 1) {
|
|
3278
|
+
const head = Math.max(0, share - used - 1);
|
|
3279
|
+
kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
|
|
3280
|
+
}
|
|
3281
|
+
break;
|
|
3282
|
+
}
|
|
3283
|
+
used += 1 + line.length;
|
|
3284
|
+
kept.push(line);
|
|
3285
|
+
}
|
|
3286
|
+
const left = body.length - (kept.length - 1);
|
|
3287
|
+
return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
|
|
3288
|
+
`) : kept.join(`
|
|
3289
|
+
`);
|
|
3290
|
+
}
|
|
3291
|
+
function layOut(blocks, claims) {
|
|
3292
|
+
const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
|
|
3293
|
+
const required = new Set([0, ...named]);
|
|
3294
|
+
const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
|
|
3295
|
+
let selected = selectBlocks(blocks.length, required);
|
|
3296
|
+
const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
|
|
3297
|
+
const noSnippets = new Set;
|
|
3298
|
+
const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
|
|
3299
|
+
const summary = [
|
|
3300
|
+
...lateCallSentences(claims.lates, blocks),
|
|
3301
|
+
...eagerSentences(claims.modules)
|
|
3302
|
+
];
|
|
3303
|
+
const parts = () => {
|
|
3304
|
+
const omitted = blocks.length - selected.length;
|
|
3305
|
+
return [
|
|
3306
|
+
intro,
|
|
3307
|
+
...selected.map((index) => shownText(index)),
|
|
3308
|
+
...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
|
|
3309
|
+
...summary
|
|
3310
|
+
];
|
|
3311
|
+
};
|
|
3312
|
+
const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
|
|
3313
|
+
for (const index of selected.toReversed()) {
|
|
3314
|
+
if (fits()) {
|
|
3315
|
+
break;
|
|
3316
|
+
}
|
|
3317
|
+
noSnippets.add(index);
|
|
3318
|
+
}
|
|
3319
|
+
for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
|
|
3320
|
+
if (fits()) {
|
|
3321
|
+
break;
|
|
3322
|
+
}
|
|
3323
|
+
selected = selected.filter((index) => index !== dropped);
|
|
3324
|
+
}
|
|
3325
|
+
if (!fits()) {
|
|
3326
|
+
const outside = parts().filter((_, position) => position === 0 || position > selected.length);
|
|
3327
|
+
const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
|
|
3328
|
+
for (const index of selected) {
|
|
3329
|
+
const text = texts.get(index).bare;
|
|
3330
|
+
texts.set(index, { full: text, bare: cutBlock(text, share) });
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
|
|
3334
|
+
`))]));
|
|
3335
|
+
return {
|
|
3336
|
+
text: parts().join(`
|
|
3337
|
+
`),
|
|
3338
|
+
shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
|
|
3339
|
+
};
|
|
3340
|
+
}
|
|
3341
|
+
|
|
2029
3342
|
// src/run-profile.ts
|
|
2030
3343
|
import { appendFileSync as appendFileSync2 } from "node:fs";
|
|
2031
|
-
import
|
|
3344
|
+
import path10 from "node:path";
|
|
2032
3345
|
import { StringDecoder } from "node:string_decoder";
|
|
2033
3346
|
var PROFILE_FORMAT_VERSION = 1;
|
|
2034
3347
|
var SPAWN_MARKS = ["spawnStart", "spawned", "firstStderr", "inspector", "firstFile", "decisive", "exit", "close"];
|
|
@@ -2162,6 +3475,7 @@ class RunProfile {
|
|
|
2162
3475
|
scope;
|
|
2163
3476
|
files;
|
|
2164
3477
|
patternBytes;
|
|
3478
|
+
launches = 0;
|
|
2165
3479
|
constructor(owner, kind, mutantId, clock) {
|
|
2166
3480
|
this.owner = owner;
|
|
2167
3481
|
this.kind = kind;
|
|
@@ -2170,6 +3484,15 @@ class RunProfile {
|
|
|
2170
3484
|
this.requestedAt = clock.now();
|
|
2171
3485
|
this.scope = kind === "dry" ? "dry" : undefined;
|
|
2172
3486
|
}
|
|
3487
|
+
countLaunch() {
|
|
3488
|
+
this.launches++;
|
|
3489
|
+
}
|
|
3490
|
+
restartLaunch() {
|
|
3491
|
+
this.spawnStates.length = 0;
|
|
3492
|
+
for (const name of Object.keys(this.details)) {
|
|
3493
|
+
delete this.details[name];
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
2173
3496
|
setScope(scope) {
|
|
2174
3497
|
this.scope = scope;
|
|
2175
3498
|
}
|
|
@@ -2282,6 +3605,7 @@ class RunProfile {
|
|
|
2282
3605
|
files: this.files,
|
|
2283
3606
|
patternBytes: this.patternBytes,
|
|
2284
3607
|
spawns: this.spawnStates.length,
|
|
3608
|
+
launches: this.kind === "dry" ? this.launches : undefined,
|
|
2285
3609
|
bail: last?.bail,
|
|
2286
3610
|
decisive: last?.decisive,
|
|
2287
3611
|
fileHeaders: last?.fileHeaders,
|
|
@@ -2375,7 +3699,7 @@ function createWorkerProfiler(logger, env = process.env) {
|
|
|
2375
3699
|
if (value === undefined || value === "" || value === "0" || value === "false") {
|
|
2376
3700
|
return;
|
|
2377
3701
|
}
|
|
2378
|
-
if (!
|
|
3702
|
+
if (!path10.isAbsolute(value)) {
|
|
2379
3703
|
logger.warn("%s must be the absolute path of a JSONL file to append to (got %s); profiling is off", PROFILE_ENV, value);
|
|
2380
3704
|
return;
|
|
2381
3705
|
}
|
|
@@ -2474,7 +3798,7 @@ function assertSupportedBunArgs(bunArgs) {
|
|
|
2474
3798
|
throw new Error(`stryker-bun-runner: bun.bunArgs contains unsupported flags: ${list}. Remove them.`);
|
|
2475
3799
|
}
|
|
2476
3800
|
// src/utils/bun-version.ts
|
|
2477
|
-
import { spawn as
|
|
3801
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
2478
3802
|
var MIN_BUN_VERSION = "1.4.0";
|
|
2479
3803
|
var VERSION_CHECK_TIMEOUT_MS = 1e4;
|
|
2480
3804
|
function parseBunVersion(output) {
|
|
@@ -2493,7 +3817,7 @@ function compareVersions(a, b) {
|
|
|
2493
3817
|
function probeBunVersion(bunPath, env, timeoutMs) {
|
|
2494
3818
|
return new Promise((resolve) => {
|
|
2495
3819
|
try {
|
|
2496
|
-
const child =
|
|
3820
|
+
const child = spawn4(bunPath, ["--version"], {
|
|
2497
3821
|
env: { ...process.env, ...env },
|
|
2498
3822
|
stdio: ["ignore", "pipe", "pipe"]
|
|
2499
3823
|
});
|
|
@@ -2540,7 +3864,7 @@ async function checkBunVersion(bunPath, env, timeoutMs = VERSION_CHECK_TIMEOUT_M
|
|
|
2540
3864
|
return version;
|
|
2541
3865
|
}
|
|
2542
3866
|
// src/utils/sync-server.ts
|
|
2543
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
3867
|
+
import { randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
2544
3868
|
import { createRequire } from "node:module";
|
|
2545
3869
|
import { WebSocketServer, WebSocket as WebSocket3 } from "ws";
|
|
2546
3870
|
var { createServer } = createRequire(import.meta.url)("node:http");
|
|
@@ -2559,7 +3883,7 @@ function rawDataToString(data) {
|
|
|
2559
3883
|
}
|
|
2560
3884
|
|
|
2561
3885
|
class SyncServer {
|
|
2562
|
-
token =
|
|
3886
|
+
token = randomBytes3(16).toString("hex");
|
|
2563
3887
|
httpServer = null;
|
|
2564
3888
|
wss = null;
|
|
2565
3889
|
clients = new Set;
|
|
@@ -2650,7 +3974,14 @@ class SyncServer {
|
|
|
2650
3974
|
this.pendingDrainClients.add(ws);
|
|
2651
3975
|
return;
|
|
2652
3976
|
}
|
|
2653
|
-
this.drainInFlight
|
|
3977
|
+
if (this.drainInFlight === null) {
|
|
3978
|
+
const started = this.drainHandler();
|
|
3979
|
+
this.drainInFlight = started;
|
|
3980
|
+
const settled = () => {
|
|
3981
|
+
this.drainInFlight = null;
|
|
3982
|
+
};
|
|
3983
|
+
started.then(settled).catch(settled);
|
|
3984
|
+
}
|
|
2654
3985
|
const inFlight = this.drainInFlight;
|
|
2655
3986
|
(async () => {
|
|
2656
3987
|
try {
|
|
@@ -2696,8 +4027,8 @@ class SyncServer {
|
|
|
2696
4027
|
}
|
|
2697
4028
|
}
|
|
2698
4029
|
// src/utils/bunfig-sanitizer.ts
|
|
2699
|
-
import { readFile as
|
|
2700
|
-
import
|
|
4030
|
+
import { readFile as readFile5, unlink as unlink3 } from "node:fs/promises";
|
|
4031
|
+
import path11 from "node:path";
|
|
2701
4032
|
import { parse, stringify } from "smol-toml";
|
|
2702
4033
|
var SAFE_TEST_KEYS = new Set([
|
|
2703
4034
|
"preload",
|
|
@@ -2731,7 +4062,7 @@ function absolutizePath(value, projectCwd) {
|
|
|
2731
4062
|
if (typeof value !== "string") {
|
|
2732
4063
|
return value;
|
|
2733
4064
|
}
|
|
2734
|
-
return
|
|
4065
|
+
return path11.isAbsolute(value) ? value : path11.resolve(projectCwd, value);
|
|
2735
4066
|
}
|
|
2736
4067
|
function absolutizePathValue(value, projectCwd) {
|
|
2737
4068
|
if (Array.isArray(value)) {
|
|
@@ -2740,9 +4071,9 @@ function absolutizePathValue(value, projectCwd) {
|
|
|
2740
4071
|
return absolutizePath(value, projectCwd);
|
|
2741
4072
|
}
|
|
2742
4073
|
async function readSourceBunfig(projectCwd, sourceBunfig) {
|
|
2743
|
-
const bunfigPath = sourceBunfig === undefined ?
|
|
4074
|
+
const bunfigPath = sourceBunfig === undefined ? path11.join(projectCwd, "bunfig.toml") : path11.resolve(projectCwd, sourceBunfig);
|
|
2744
4075
|
try {
|
|
2745
|
-
const content = await
|
|
4076
|
+
const content = await readFile5(bunfigPath, "utf8");
|
|
2746
4077
|
return parse(content);
|
|
2747
4078
|
} catch (err) {
|
|
2748
4079
|
if (sourceBunfig === undefined && err.code === "ENOENT") {
|
|
@@ -2755,12 +4086,60 @@ async function readSourceBunfig(projectCwd, sourceBunfig) {
|
|
|
2755
4086
|
async function readBunfigTestRoot(projectCwd, sourceBunfig) {
|
|
2756
4087
|
const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
|
|
2757
4088
|
const root = rawConfig.test?.root;
|
|
2758
|
-
return typeof root === "string" ?
|
|
4089
|
+
return typeof root === "string" ? path11.resolve(projectCwd, root) : undefined;
|
|
4090
|
+
}
|
|
4091
|
+
async function readBunfigTestPreloads(projectCwd, sourceBunfig) {
|
|
4092
|
+
return testPreloadsOf(await readSourceBunfig(projectCwd, sourceBunfig), projectCwd);
|
|
4093
|
+
}
|
|
4094
|
+
function testPreloadsOf(rawConfig, projectCwd) {
|
|
4095
|
+
const preload = rawConfig.test?.preload;
|
|
4096
|
+
return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path11.resolve(projectCwd, entry));
|
|
4097
|
+
}
|
|
4098
|
+
var SCAN_NEUTRAL_BUNFIG_KEYS = new Set(["preload", "smol", "logLevel", "telemetry", "env", "console", "serve", "install", "run", "conditions", "test"]);
|
|
4099
|
+
var JSX_BUNFIG_KEYS = new Set(["jsx", "jsxImportSource", "jsxFactory", "jsxFragment"]);
|
|
4100
|
+
function isLiteralDefine(value) {
|
|
4101
|
+
if (typeof value !== "string") {
|
|
4102
|
+
return false;
|
|
4103
|
+
}
|
|
4104
|
+
if (value === "undefined" || /^'[^']*'$/.test(value)) {
|
|
4105
|
+
return true;
|
|
4106
|
+
}
|
|
4107
|
+
try {
|
|
4108
|
+
const parsed = JSON.parse(value);
|
|
4109
|
+
return parsed === null || ["string", "number", "boolean"].includes(typeof parsed);
|
|
4110
|
+
} catch {
|
|
4111
|
+
return false;
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
function topLevelScanProblem(key, value) {
|
|
4115
|
+
if (key === "loader") {
|
|
4116
|
+
return isTable(value) && Object.keys(value).length === 0 ? undefined : "the bunfig's [loader] maps file extensions to loaders, which the import scan does not model";
|
|
4117
|
+
}
|
|
4118
|
+
if (key === "define") {
|
|
4119
|
+
const expression = isTable(value) ? Object.entries(value).find(([, replacement]) => !isLiteralDefine(replacement)) : [key, value];
|
|
4120
|
+
return expression === undefined ? undefined : `the bunfig's define replaces ${JSON.stringify(expression[0])} with ${JSON.stringify(expression[1])}, an expression the import scan does not model`;
|
|
4121
|
+
}
|
|
4122
|
+
if (JSX_BUNFIG_KEYS.has(key)) {
|
|
4123
|
+
return `the bunfig sets ${key}, which chooses the JSX runtime the tests import, and the import scan does not read the bunfig`;
|
|
4124
|
+
}
|
|
4125
|
+
return SCAN_NEUTRAL_BUNFIG_KEYS.has(key) ? undefined : `the bunfig sets ${JSON.stringify(key)}, which the import scan does not know, so it cannot tell whether it changes what the tests load or how their imports resolve`;
|
|
4126
|
+
}
|
|
4127
|
+
function bunfigScanProblem(rawConfig) {
|
|
4128
|
+
for (const [key, value] of Object.entries(rawConfig)) {
|
|
4129
|
+
const problem = topLevelScanProblem(key, value);
|
|
4130
|
+
if (problem !== undefined) {
|
|
4131
|
+
return problem;
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
const ignored = isTable(rawConfig.test) ? rawConfig.test.pathIgnorePatterns : undefined;
|
|
4135
|
+
if (ignored !== undefined && [ignored].flat().length > 0) {
|
|
4136
|
+
return "the bunfig's [test].pathIgnorePatterns makes bun skip matching test files even when the runner names them, and the runner does not reproduce bun's matching";
|
|
4137
|
+
}
|
|
4138
|
+
return;
|
|
2759
4139
|
}
|
|
2760
|
-
async function
|
|
4140
|
+
async function readBunfigForScan(projectCwd, sourceBunfig) {
|
|
2761
4141
|
const rawConfig = await readSourceBunfig(projectCwd, sourceBunfig);
|
|
2762
|
-
|
|
2763
|
-
return [preload].flat().filter((entry) => typeof entry === "string").map((entry) => path6.resolve(projectCwd, entry));
|
|
4142
|
+
return { preloads: testPreloadsOf(rawConfig, projectCwd), problem: bunfigScanProblem(rawConfig) };
|
|
2764
4143
|
}
|
|
2765
4144
|
function sanitizeTestSection(sourceTest, projectCwd, dropped) {
|
|
2766
4145
|
const sanitizedTest = {};
|
|
@@ -2796,7 +4175,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir, sourceBunfig, onDropp
|
|
|
2796
4175
|
dropped.push({ key: `test.${key}`, reason: RANDOM_ORDER_REASON, warn: false, mutantRunsOnly: true });
|
|
2797
4176
|
}
|
|
2798
4177
|
onDropped?.(dropped);
|
|
2799
|
-
const outPath =
|
|
4178
|
+
const outPath = path11.join(tmpDir, `stryker-bun-runner-bunfig-${process.pid}-${Date.now()}.toml`);
|
|
2800
4179
|
await writePrivateFile(outPath, stringify(sanitized));
|
|
2801
4180
|
const mutantRunTest = { ...sanitizedTest, onlyFailures: true };
|
|
2802
4181
|
if (randomOrderKeys.length > 0) {
|
|
@@ -2820,8 +4199,8 @@ async function cleanupSanitizedBunfig(filePath) {
|
|
|
2820
4199
|
await unlinkIfPresent(mutantRunBunfigPath(filePath));
|
|
2821
4200
|
}
|
|
2822
4201
|
// src/utils/test-file-discovery.ts
|
|
2823
|
-
import * as
|
|
2824
|
-
import
|
|
4202
|
+
import * as fsPromises2 from "node:fs/promises";
|
|
4203
|
+
import path12 from "node:path";
|
|
2825
4204
|
function isExcludedDirName(name) {
|
|
2826
4205
|
return name.startsWith(".") || name.toLowerCase() === "node_modules";
|
|
2827
4206
|
}
|
|
@@ -2831,14 +4210,14 @@ function hasExcludedAncestor(absolutePath) {
|
|
|
2831
4210
|
}
|
|
2832
4211
|
async function tryRealpath(p) {
|
|
2833
4212
|
try {
|
|
2834
|
-
return await
|
|
4213
|
+
return await fsPromises2.realpath(p);
|
|
2835
4214
|
} catch {
|
|
2836
4215
|
return;
|
|
2837
4216
|
}
|
|
2838
4217
|
}
|
|
2839
4218
|
async function tryStat(p) {
|
|
2840
4219
|
try {
|
|
2841
|
-
return await
|
|
4220
|
+
return await fsPromises2.stat(p);
|
|
2842
4221
|
} catch {
|
|
2843
4222
|
return;
|
|
2844
4223
|
}
|
|
@@ -2867,7 +4246,7 @@ async function handleSymlinkFile(fullPath, entryName, ctx) {
|
|
|
2867
4246
|
}
|
|
2868
4247
|
const resolvedTarget = await tryRealpath(fullPath);
|
|
2869
4248
|
if (resolvedTarget && !hasExcludedAncestor(resolvedTarget)) {
|
|
2870
|
-
ctx.results.push(
|
|
4249
|
+
ctx.results.push(path12.relative(ctx.cwd, fullPath));
|
|
2871
4250
|
}
|
|
2872
4251
|
}
|
|
2873
4252
|
async function handleSymlink(fullPath, entryName, ctx) {
|
|
@@ -2883,7 +4262,7 @@ async function handleSymlink(fullPath, entryName, ctx) {
|
|
|
2883
4262
|
}
|
|
2884
4263
|
}
|
|
2885
4264
|
async function processEntry(entry, dir, ctx) {
|
|
2886
|
-
const fullPath =
|
|
4265
|
+
const fullPath = path12.join(dir, entry.name);
|
|
2887
4266
|
if (entry.isDirectory()) {
|
|
2888
4267
|
if (!isExcludedDirName(entry.name)) {
|
|
2889
4268
|
await ctx.walk(fullPath);
|
|
@@ -2891,10 +4270,20 @@ async function processEntry(entry, dir, ctx) {
|
|
|
2891
4270
|
} else if (entry.isSymbolicLink()) {
|
|
2892
4271
|
await handleSymlink(fullPath, entry.name, ctx);
|
|
2893
4272
|
} else if (entry.isFile() && TEST_FILE_SUFFIX_RE.test(entry.name)) {
|
|
2894
|
-
ctx.results.push(
|
|
4273
|
+
ctx.results.push(path12.relative(ctx.cwd, fullPath));
|
|
2895
4274
|
}
|
|
2896
4275
|
}
|
|
2897
4276
|
async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
|
|
4277
|
+
const walkRoot = await readBunfigTestRoot(cwd, sourceBunfig) ?? cwd;
|
|
4278
|
+
const results = await walkTestFiles(walkRoot, cwd, logger);
|
|
4279
|
+
if (results.length === 0) {
|
|
4280
|
+
logger?.warn("discoverTestFiles: no test files found in %s; falling back to Bun discovery", walkRoot);
|
|
4281
|
+
return;
|
|
4282
|
+
}
|
|
4283
|
+
logger?.debug("discoverTestFiles: found %d test files in %s", results.length, cwd);
|
|
4284
|
+
return results;
|
|
4285
|
+
}
|
|
4286
|
+
async function walkTestFiles(walkRoot, cwd, logger) {
|
|
2898
4287
|
const results = [];
|
|
2899
4288
|
const visitedRealPaths = new Set;
|
|
2900
4289
|
const ctx = { cwd, results, visitedRealPaths, logger, walk };
|
|
@@ -2910,7 +4299,7 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
|
|
|
2910
4299
|
visitedRealPaths.add(realDir);
|
|
2911
4300
|
let entries;
|
|
2912
4301
|
try {
|
|
2913
|
-
entries = await
|
|
4302
|
+
entries = await fsPromises2.readdir(dir, { withFileTypes: true });
|
|
2914
4303
|
} catch {
|
|
2915
4304
|
return;
|
|
2916
4305
|
}
|
|
@@ -2919,16 +4308,29 @@ async function discoverTestFiles(cwd = process.cwd(), logger, sourceBunfig) {
|
|
|
2919
4308
|
await processEntry(entry, dir, ctx);
|
|
2920
4309
|
}
|
|
2921
4310
|
}
|
|
2922
|
-
const walkRoot = await readBunfigTestRoot(cwd, sourceBunfig) ?? cwd;
|
|
2923
4311
|
await walk(walkRoot);
|
|
2924
|
-
if (results.length === 0) {
|
|
2925
|
-
logger?.warn("discoverTestFiles: no test files found in %s; falling back to Bun discovery", walkRoot);
|
|
2926
|
-
return;
|
|
2927
|
-
}
|
|
2928
4312
|
results.sort((a, b) => a.localeCompare(b));
|
|
2929
|
-
logger?.debug("discoverTestFiles: found %d test files in %s", results.length, cwd);
|
|
2930
4313
|
return results;
|
|
2931
4314
|
}
|
|
4315
|
+
async function expandTestFileEntries(entries, cwd, logger) {
|
|
4316
|
+
const expanded = await Promise.all(entries.map(async (entry) => {
|
|
4317
|
+
const absolute = path12.resolve(cwd, entry);
|
|
4318
|
+
const stat = await tryStat(absolute);
|
|
4319
|
+
if (stat?.isFile()) {
|
|
4320
|
+
return [absolute];
|
|
4321
|
+
}
|
|
4322
|
+
if (stat?.isDirectory()) {
|
|
4323
|
+
const found = await walkTestFiles(absolute, cwd, logger);
|
|
4324
|
+
return found.map((file) => path12.resolve(cwd, file));
|
|
4325
|
+
}
|
|
4326
|
+
return entry;
|
|
4327
|
+
}));
|
|
4328
|
+
const missing = expanded.find((item) => typeof item === "string");
|
|
4329
|
+
if (missing !== undefined) {
|
|
4330
|
+
return { problem: `the test file entry ${missing} is neither an existing file nor an existing directory` };
|
|
4331
|
+
}
|
|
4332
|
+
return { files: [...new Set(expanded.flat())] };
|
|
4333
|
+
}
|
|
2932
4334
|
// src/utils/mutant-warn-aggregator.ts
|
|
2933
4335
|
var MAX_LISTED_MUTANT_IDS = 5;
|
|
2934
4336
|
|
|
@@ -2958,7 +4360,7 @@ class MutantWarnAggregator {
|
|
|
2958
4360
|
}
|
|
2959
4361
|
}
|
|
2960
4362
|
// src/utils/likely-killer-order.ts
|
|
2961
|
-
import
|
|
4363
|
+
import path13 from "node:path";
|
|
2962
4364
|
var MUTANT_SWITCH_RE = /stryMutAct_9fa48\("([^"\\]+)"\)/g;
|
|
2963
4365
|
function mutantIdsInInstrumentedSource(code) {
|
|
2964
4366
|
return new Set(Array.from(code.matchAll(MUTANT_SWITCH_RE), (match) => match[1]));
|
|
@@ -3033,8 +4435,8 @@ function namedAfter(sourceFile) {
|
|
|
3033
4435
|
if (sourceFile === undefined) {
|
|
3034
4436
|
return () => false;
|
|
3035
4437
|
}
|
|
3036
|
-
const sourceStem =
|
|
3037
|
-
return (testFile) =>
|
|
4438
|
+
const sourceStem = path13.parse(sourceFile).name.toLowerCase();
|
|
4439
|
+
return (testFile) => path13.basename(testFile).replace(TEST_FILE_SUFFIX_RE, "").toLowerCase() === sourceStem;
|
|
3038
4440
|
}
|
|
3039
4441
|
function compareKillerRanks(a, b) {
|
|
3040
4442
|
return a.coverage - b.coverage || b.sourceMutants - a.sourceMutants || Number(b.namedAfter) - Number(a.namedAfter);
|
|
@@ -3043,6 +4445,134 @@ function orderLikelyKillersFirst(files, rankOf) {
|
|
|
3043
4445
|
const ranks = new Map(files.map((file) => [file, rankOf(file)]));
|
|
3044
4446
|
return files.toSorted((a, b) => compareKillerRanks(ranks.get(a), ranks.get(b)));
|
|
3045
4447
|
}
|
|
4448
|
+
// src/utils/dry-run-output-log.ts
|
|
4449
|
+
import { randomUUID } from "node:crypto";
|
|
4450
|
+
import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, rm as rm4 } from "node:fs/promises";
|
|
4451
|
+
import path14 from "node:path";
|
|
4452
|
+
var MAX_LOG_STREAM_CHARS = 16 * 1024 * 1024;
|
|
4453
|
+
var MAX_LOG_COMMAND_CHARS = 4000;
|
|
4454
|
+
function capStream(text, max) {
|
|
4455
|
+
if (text.length <= max) {
|
|
4456
|
+
return { text, cut: 0 };
|
|
4457
|
+
}
|
|
4458
|
+
const head = Math.floor(max / 2);
|
|
4459
|
+
const tail = max - head;
|
|
4460
|
+
const cut = text.length - max;
|
|
4461
|
+
return { text: `${text.slice(0, head)}
|
|
4462
|
+
[... ${cut} characters omitted here: the size cap is ${max} characters per stream; the first ${head} and the last ${tail} are kept ...]
|
|
4463
|
+
${text.slice(-tail)}`, cut };
|
|
4464
|
+
}
|
|
4465
|
+
var quoteArg = (arg) => /^[\w@%+=:,./-]+$/.test(arg) ? arg : JSON.stringify(arg);
|
|
4466
|
+
function describeStream(name, original, cut, max, incomplete) {
|
|
4467
|
+
const parts = [`${original} characters${incomplete ? " captured" : ""}`];
|
|
4468
|
+
if (incomplete) {
|
|
4469
|
+
parts.push("INCOMPLETE capture (not the whole output)");
|
|
4470
|
+
}
|
|
4471
|
+
if (cut > 0) {
|
|
4472
|
+
parts.push(`CUT to ${max} (${cut} omitted from the middle, see the marker in the text)`);
|
|
4473
|
+
}
|
|
4474
|
+
if (!incomplete && cut === 0) {
|
|
4475
|
+
parts.push("saved in full");
|
|
4476
|
+
}
|
|
4477
|
+
return `${name}: ${parts.join(", ")}`;
|
|
4478
|
+
}
|
|
4479
|
+
function formatDryRunOutputLog(output, now, maxStreamChars = MAX_LOG_STREAM_CHARS) {
|
|
4480
|
+
const clean = (text) => cleanDiagnosticText(text, output.secrets);
|
|
4481
|
+
const stdout = clean(output.stdout);
|
|
4482
|
+
const stderr = clean(output.stderr);
|
|
4483
|
+
const cappedStdout = capStream(stdout, maxStreamChars);
|
|
4484
|
+
const cappedStderr = capStream(stderr, maxStreamChars);
|
|
4485
|
+
const incomplete = output.outputIncomplete === true;
|
|
4486
|
+
const fullCommand = (output.command ?? []).map((arg) => quoteArg(clean(arg))).join(" ") || "(not recorded)";
|
|
4487
|
+
const command = fullCommand.length > MAX_LOG_COMMAND_CHARS ? `${fullCommand.slice(0, MAX_LOG_COMMAND_CHARS)}... [${fullCommand.length - MAX_LOG_COMMAND_CHARS} more characters omitted]` : fullCommand;
|
|
4488
|
+
const ended = output.signal ? `terminated by signal ${output.signal}` : `exit code ${output.exitCode ?? "none"}`;
|
|
4489
|
+
return [
|
|
4490
|
+
"stryker-bun-runner: output of the dry run's bun test process",
|
|
4491
|
+
"Written because the dry run's data-completeness check failed and the bun.dryRunOutputFile option is set; the next such failure replaces this file. The error message holds only a bounded part of this.",
|
|
4492
|
+
`Time: ${now.toISOString()}`,
|
|
4493
|
+
`Bun version: ${output.bunVersion ?? "unknown"}`,
|
|
4494
|
+
`Working directory: ${clean(output.cwd)}`,
|
|
4495
|
+
`Command: ${command}`,
|
|
4496
|
+
`Ended: ${ended}`,
|
|
4497
|
+
...incomplete ? ["Output capture: INCOMPLETE. bun test exited, but its stdout or stderr was still held open by a process it started, so the runner stopped reading; the text below may be missing its end."] : [],
|
|
4498
|
+
"Removed from this file: ANSI colour codes, the paths of inspector ws:// addresses, the fragment of debug.bun.sh links and this run's tokens. Nothing else: whatever the tests or the command line print, credentials included, is here as printed.",
|
|
4499
|
+
describeStream("stdout", stdout.length, cappedStdout.cut, maxStreamChars, incomplete),
|
|
4500
|
+
describeStream("stderr", stderr.length, cappedStderr.cut, maxStreamChars, incomplete),
|
|
4501
|
+
"",
|
|
4502
|
+
"===== stdout =====",
|
|
4503
|
+
cappedStdout.text,
|
|
4504
|
+
"",
|
|
4505
|
+
"===== stderr =====",
|
|
4506
|
+
cappedStderr.text,
|
|
4507
|
+
""
|
|
4508
|
+
].join(`
|
|
4509
|
+
`);
|
|
4510
|
+
}
|
|
4511
|
+
async function checkTarget(file) {
|
|
4512
|
+
let existing;
|
|
4513
|
+
try {
|
|
4514
|
+
existing = await lstat2(file);
|
|
4515
|
+
} catch (error) {
|
|
4516
|
+
if (error.code === "ENOENT") {
|
|
4517
|
+
return;
|
|
4518
|
+
}
|
|
4519
|
+
throw error;
|
|
4520
|
+
}
|
|
4521
|
+
if (existing.isSymbolicLink()) {
|
|
4522
|
+
throw new Error(`refusing to write through a symbolic link at ${file}`);
|
|
4523
|
+
}
|
|
4524
|
+
if (!existing.isFile()) {
|
|
4525
|
+
throw new Error(`${file} exists and is not a regular file`);
|
|
4526
|
+
}
|
|
4527
|
+
}
|
|
4528
|
+
function throwIfAbandoned(signal) {
|
|
4529
|
+
if (signal?.aborted) {
|
|
4530
|
+
throw new Error("saving was abandoned");
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
function errorText(error) {
|
|
4534
|
+
try {
|
|
4535
|
+
return error instanceof Error ? error.message : String(error);
|
|
4536
|
+
} catch {
|
|
4537
|
+
return "an error that cannot be converted to text";
|
|
4538
|
+
}
|
|
4539
|
+
}
|
|
4540
|
+
function oneLine(error) {
|
|
4541
|
+
return escapeControlCharacters(errorText(error).replaceAll(/\s+/g, " ").trim());
|
|
4542
|
+
}
|
|
4543
|
+
async function saveDryRunOutput(file, output, options = {}) {
|
|
4544
|
+
try {
|
|
4545
|
+
const text = formatDryRunOutputLog(output, new Date(options.now ?? Date.now()), options.maxStreamChars);
|
|
4546
|
+
const directory = path14.dirname(file);
|
|
4547
|
+
await mkdir2(directory, { recursive: true });
|
|
4548
|
+
throwIfAbandoned(options.signal);
|
|
4549
|
+
await checkTarget(file);
|
|
4550
|
+
const temporary = path14.join(directory, `.stryker-bun-runner-output-${randomUUID()}.tmp`);
|
|
4551
|
+
const handle = await open(temporary, "wx", 384);
|
|
4552
|
+
try {
|
|
4553
|
+
try {
|
|
4554
|
+
await (options.write ?? ((target, data) => target.writeFile(data, "utf8")))(handle, text);
|
|
4555
|
+
await handle.chmod(384).catch(() => {
|
|
4556
|
+
return;
|
|
4557
|
+
});
|
|
4558
|
+
} finally {
|
|
4559
|
+
await handle.close().catch(() => {
|
|
4560
|
+
return;
|
|
4561
|
+
});
|
|
4562
|
+
}
|
|
4563
|
+
throwIfAbandoned(options.signal);
|
|
4564
|
+
await rename2(temporary, file);
|
|
4565
|
+
} catch (error) {
|
|
4566
|
+
await rm4(temporary).catch(() => {
|
|
4567
|
+
return;
|
|
4568
|
+
});
|
|
4569
|
+
throw error;
|
|
4570
|
+
}
|
|
4571
|
+
return { path: file };
|
|
4572
|
+
} catch (error) {
|
|
4573
|
+
return { error: redactSecrets(oneLine(error), output.secrets) };
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
3046
4576
|
// src/bun-test-runner.ts
|
|
3047
4577
|
function createInspectorUrlWaiter() {
|
|
3048
4578
|
let url = null;
|
|
@@ -3112,7 +4642,7 @@ function formatDrainSettleReason(reason) {
|
|
|
3112
4642
|
function formatSpawnErrorMessage(spawnError) {
|
|
3113
4643
|
return `could not start bun test: ${spawnError}`;
|
|
3114
4644
|
}
|
|
3115
|
-
function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
|
|
4645
|
+
function formatInspectorTimeoutMessage(inspectorTimeoutMs, child, secrets) {
|
|
3116
4646
|
if (child.spawnError !== undefined) {
|
|
3117
4647
|
return formatSpawnErrorMessage(child.spawnError);
|
|
3118
4648
|
}
|
|
@@ -3121,10 +4651,10 @@ function formatInspectorTimeoutMessage(inspectorTimeoutMs, child) {
|
|
|
3121
4651
|
ended = "killed by the runner after the run timeout (bun.timeout)";
|
|
3122
4652
|
}
|
|
3123
4653
|
const prefix = `Timeout waiting for inspector URL after ${inspectorTimeoutMs}ms (raise bun.inspectorTimeout if bun is slow to start)`;
|
|
3124
|
-
return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child)}`;
|
|
4654
|
+
return `${prefix}; bun test ${ended}; last stderr: ${formatStderrTail(child, secrets)}`;
|
|
3125
4655
|
}
|
|
3126
|
-
function formatStderrTail(child) {
|
|
3127
|
-
const tail = child.stderr.trim().slice(-1000) || "(empty)";
|
|
4656
|
+
function formatStderrTail(child, secrets) {
|
|
4657
|
+
const tail = cleanDiagnosticText(child.stderr, secrets).trim().slice(-1000) || "(empty)";
|
|
3128
4658
|
return child.outputIncomplete ? `${tail} (possibly cut short: ${formatOutputIncomplete()})` : tail;
|
|
3129
4659
|
}
|
|
3130
4660
|
function redactInspectorUrl(url) {
|
|
@@ -3134,8 +4664,8 @@ function redactInspectorUrl(url) {
|
|
|
3134
4664
|
function formatOutputIncomplete() {
|
|
3135
4665
|
return `bun test exited, but its output was still held open ${STDIO_CLOSE_GRACE_MS}ms later by a process it started, so the run did not wait for the rest`;
|
|
3136
4666
|
}
|
|
3137
|
-
function formatInspectorConnectMessage(error, child) {
|
|
3138
|
-
return `Failed to connect to Bun inspector: ${error}; last stderr: ${formatStderrTail(child)}`;
|
|
4667
|
+
function formatInspectorConnectMessage(error, child, secrets) {
|
|
4668
|
+
return `Failed to connect to Bun inspector: ${error}; last stderr: ${formatStderrTail(child, secrets)}`;
|
|
3139
4669
|
}
|
|
3140
4670
|
function collectAbnormalDrainProblems(data) {
|
|
3141
4671
|
const problems = [];
|
|
@@ -3151,6 +4681,32 @@ function collectAbnormalDrainProblems(data) {
|
|
|
3151
4681
|
}
|
|
3152
4682
|
return problems;
|
|
3153
4683
|
}
|
|
4684
|
+
function nonEmptyString(value) {
|
|
4685
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
4686
|
+
}
|
|
4687
|
+
var SAVE_TIME_LIMIT_MS = 5000;
|
|
4688
|
+
var OUTPUT_FILE_HINT = "To save the full output of the bun test process when this happens, set the bun.dryRunOutputFile option to a file path in your Stryker configuration and run again.";
|
|
4689
|
+
var REGISTRY_FILE = "registry.json";
|
|
4690
|
+
|
|
4691
|
+
class WriteFailure extends Error {
|
|
4692
|
+
file;
|
|
4693
|
+
constructor(file, cause) {
|
|
4694
|
+
super(errorText(cause), { cause });
|
|
4695
|
+
this.file = file;
|
|
4696
|
+
}
|
|
4697
|
+
}
|
|
4698
|
+
async function writingTo(file, write) {
|
|
4699
|
+
try {
|
|
4700
|
+
return await write();
|
|
4701
|
+
} catch (error) {
|
|
4702
|
+
throw new WriteFailure(file, error);
|
|
4703
|
+
}
|
|
4704
|
+
}
|
|
4705
|
+
var MISSING_COVERAGE_FOR_RULE_3_3 = "the run that publishes left no coverage data, so the runner cannot check that it reached every mutant the plain run of the tests reached";
|
|
4706
|
+
var RUN_ORDINALS = ["first", "second", "third"];
|
|
4707
|
+
function isGreen(result) {
|
|
4708
|
+
return result.status === DryRunStatus.Complete && !result.tests.some((test) => test.status === TestStatus.Failed);
|
|
4709
|
+
}
|
|
3154
4710
|
function buildTestNameIndex(tests, bunNames) {
|
|
3155
4711
|
const testNameIndex = new Map;
|
|
3156
4712
|
for (const [i, test] of tests.entries()) {
|
|
@@ -3162,6 +4718,17 @@ function buildTestNameIndex(tests, bunNames) {
|
|
|
3162
4718
|
return testNameIndex;
|
|
3163
4719
|
}
|
|
3164
4720
|
var ZERO_MATCH_TEST_PATTERN_RE = /matched 0 tests\./;
|
|
4721
|
+
var CHILD_EXIT_WAIT_MS = 5000;
|
|
4722
|
+
async function awaitChildExit(child, limitMs) {
|
|
4723
|
+
let timer;
|
|
4724
|
+
try {
|
|
4725
|
+
await Promise.race([child, new Promise((resolve) => {
|
|
4726
|
+
timer = setTimeout(resolve, limitMs);
|
|
4727
|
+
})]);
|
|
4728
|
+
} catch {} finally {
|
|
4729
|
+
clearTimeout(timer);
|
|
4730
|
+
}
|
|
4731
|
+
}
|
|
3165
4732
|
function defaultFailureMessage(testInfo) {
|
|
3166
4733
|
return testInfo.status === "timeout" ? "Test timed out" : "Test failed";
|
|
3167
4734
|
}
|
|
@@ -3236,7 +4803,7 @@ function emptyMutantRunCounts() {
|
|
|
3236
4803
|
};
|
|
3237
4804
|
}
|
|
3238
4805
|
function newHitLimitToken() {
|
|
3239
|
-
return
|
|
4806
|
+
return randomBytes4(16).toString("hex");
|
|
3240
4807
|
}
|
|
3241
4808
|
function readReportedHitCount(stderr, token) {
|
|
3242
4809
|
const match = new RegExp(String.raw`^${HIT_LIMIT_SENTINEL} ${token} (\d+)$`, "m").exec(stderr);
|
|
@@ -3276,6 +4843,7 @@ class BunTestRunner {
|
|
|
3276
4843
|
maxChildRss;
|
|
3277
4844
|
rssCheckIntervalMs;
|
|
3278
4845
|
maxSpawnDepth;
|
|
4846
|
+
dryRunOutputFile;
|
|
3279
4847
|
coverageAnalysis;
|
|
3280
4848
|
preloadScriptPath;
|
|
3281
4849
|
coverageFilePath;
|
|
@@ -3305,6 +4873,14 @@ class BunTestRunner {
|
|
|
3305
4873
|
mutantRunsByStatus = emptyMutantRunCounts();
|
|
3306
4874
|
fullSuiteFallbacks = 0;
|
|
3307
4875
|
profiler;
|
|
4876
|
+
alwaysImport;
|
|
4877
|
+
importDiscovery;
|
|
4878
|
+
incremental;
|
|
4879
|
+
inPlace;
|
|
4880
|
+
timeoutCorrectionMs;
|
|
4881
|
+
loggedUnusableCorrection = false;
|
|
4882
|
+
campaign;
|
|
4883
|
+
warnedWatchListProblem = false;
|
|
3308
4884
|
currentAbortController;
|
|
3309
4885
|
constructor(logger, options) {
|
|
3310
4886
|
this.logger = logger;
|
|
@@ -3322,6 +4898,7 @@ class BunTestRunner {
|
|
|
3322
4898
|
this.maxChildRss = bunOptions.maxChildRss;
|
|
3323
4899
|
this.rssCheckIntervalMs = bunOptions.rssCheckIntervalMs;
|
|
3324
4900
|
this.maxSpawnDepth = bunOptions.maxSpawnDepth;
|
|
4901
|
+
this.dryRunOutputFile = nonEmptyString(bunOptions.dryRunOutputFile);
|
|
3325
4902
|
if (bunOptions.testFiles?.length === 0) {
|
|
3326
4903
|
this.logger.warn("bun.testFiles was set to an empty array — treating as undefined and falling back to auto-discovery");
|
|
3327
4904
|
this.testFilesOverride = undefined;
|
|
@@ -3331,6 +4908,10 @@ class BunTestRunner {
|
|
|
3331
4908
|
this.mutateGlobs = options.mutate ?? [];
|
|
3332
4909
|
this.coverageAnalysis = options.coverageAnalysis;
|
|
3333
4910
|
this.disableBail = options.disableBail;
|
|
4911
|
+
this.incremental = options.incremental === true;
|
|
4912
|
+
this.inPlace = options.inPlace === true;
|
|
4913
|
+
this.alwaysImport = bunOptions.alwaysImport;
|
|
4914
|
+
this.importDiscovery = bunOptions.importDiscovery;
|
|
3334
4915
|
this.mutantWarnings = new MutantWarnAggregator(logger);
|
|
3335
4916
|
this.profiler = createWorkerProfiler(logger);
|
|
3336
4917
|
this.logger.debug("BunTestRunner initialized with options: %o", {
|
|
@@ -3342,9 +4923,10 @@ class BunTestRunner {
|
|
|
3342
4923
|
smol: this.smol,
|
|
3343
4924
|
maxChildRss: this.maxChildRss,
|
|
3344
4925
|
rssCheckIntervalMs: this.rssCheckIntervalMs,
|
|
3345
|
-
maxSpawnDepth: this.maxSpawnDepth
|
|
4926
|
+
maxSpawnDepth: this.maxSpawnDepth,
|
|
4927
|
+
dryRunOutputFile: this.dryRunOutputFile
|
|
3346
4928
|
});
|
|
3347
|
-
if (this.testFilesOverride?.some((p) =>
|
|
4929
|
+
if (this.testFilesOverride?.some((p) => path15.isAbsolute(p))) {
|
|
3348
4930
|
const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
|
|
3349
4931
|
if (isSandbox) {
|
|
3350
4932
|
this.logger.warn("bun.testFiles contains absolute path(s) and the current working directory appears to be a Stryker sandbox (%s). " + "Absolute paths point at the ORIGINAL (unmutated) source files — mutations will be silently bypassed. " + "Use relative paths so that Bun resolves them against the sandbox copy.", process.cwd());
|
|
@@ -3353,7 +4935,7 @@ class BunTestRunner {
|
|
|
3353
4935
|
}
|
|
3354
4936
|
async resolveRegistryPath() {
|
|
3355
4937
|
this.assertRunOwnerIsParent();
|
|
3356
|
-
return
|
|
4938
|
+
return path15.join(await resolveRunTempDir(), REGISTRY_FILE);
|
|
3357
4939
|
}
|
|
3358
4940
|
assertRunOwnerIsParent() {
|
|
3359
4941
|
if (this.runOwnerPid !== undefined && process.ppid !== this.runOwnerPid) {
|
|
@@ -3445,7 +5027,7 @@ class BunTestRunner {
|
|
|
3445
5027
|
}
|
|
3446
5028
|
let mutantIds = new Set;
|
|
3447
5029
|
try {
|
|
3448
|
-
mutantIds = mutantIdsInInstrumentedSource(await
|
|
5030
|
+
mutantIds = mutantIdsInInstrumentedSource(await fsPromises3.readFile(sandboxFileName, "utf8"));
|
|
3449
5031
|
} catch (error) {
|
|
3450
5032
|
this.logger.debug("Could not read %s for its mutant ids (%s); its full-suite runs rank test files without same-file coverage", sandboxFileName, error instanceof Error ? error.message : String(error));
|
|
3451
5033
|
}
|
|
@@ -3484,7 +5066,7 @@ class BunTestRunner {
|
|
|
3484
5066
|
this.logger.debug("Stryker passed an empty testFiles array; ignoring it");
|
|
3485
5067
|
}
|
|
3486
5068
|
} else {
|
|
3487
|
-
const files = [...new Set(requested.map((file) =>
|
|
5069
|
+
const files = [...new Set(requested.map((file) => path15.resolve(cwd, file)))].toSorted((a, b) => a.localeCompare(b));
|
|
3488
5070
|
this.strykerTestFiles = { cwd, files };
|
|
3489
5071
|
this.warnIfTestFilesOverridden(files, cwd);
|
|
3490
5072
|
}
|
|
@@ -3546,7 +5128,7 @@ class BunTestRunner {
|
|
|
3546
5128
|
if (this.warnedTestFilesConflict || this.testFilesOverride === undefined) {
|
|
3547
5129
|
return;
|
|
3548
5130
|
}
|
|
3549
|
-
const configured = [...new Set(this.testFilesOverride.map((file) =>
|
|
5131
|
+
const configured = [...new Set(this.testFilesOverride.map((file) => path15.resolve(cwd, file)))];
|
|
3550
5132
|
const selectedSet = new Set(selected);
|
|
3551
5133
|
if (configured.length === selectedSet.size && configured.every((file) => selectedSet.has(file))) {
|
|
3552
5134
|
return;
|
|
@@ -3619,7 +5201,7 @@ class BunTestRunner {
|
|
|
3619
5201
|
this.runOwnerPid ??= process.ppid;
|
|
3620
5202
|
const tempDir = await this.ensureRunTempDir();
|
|
3621
5203
|
this.tempDirTouchedAt = Date.now();
|
|
3622
|
-
this.coverageFilePath =
|
|
5204
|
+
this.coverageFilePath = path15.join(tempDir, `coverage-${Date.now()}.json`);
|
|
3623
5205
|
this.logger.debug("Generating coverage preload script...");
|
|
3624
5206
|
const eagerCwd = process.cwd();
|
|
3625
5207
|
const testFilesPending = this.getOrDiscoverTestFiles();
|
|
@@ -3631,16 +5213,35 @@ class BunTestRunner {
|
|
|
3631
5213
|
this.cachedEagerModulesCwd = eagerCwd;
|
|
3632
5214
|
this.logger.debug("Resolved %d eager modules from mutate globs", this.cachedEagerModules.length);
|
|
3633
5215
|
}
|
|
5216
|
+
if (this.coverageAnalysis !== "off") {
|
|
5217
|
+
await this.rejectIfCampaignStopped(tempDir, this.cachedEagerModules);
|
|
5218
|
+
}
|
|
3634
5219
|
this.preloadScriptPath = await generatePreloadScript({
|
|
3635
5220
|
tempDir,
|
|
3636
|
-
coverageFile: this.coverageFilePath
|
|
3637
|
-
eagerModules: this.cachedEagerModules
|
|
5221
|
+
coverageFile: this.coverageFilePath
|
|
3638
5222
|
});
|
|
3639
5223
|
this.logger.debug("Preload script generated at: %s", this.preloadScriptPath);
|
|
3640
5224
|
await this.ensureSanitizedBunfig();
|
|
3641
5225
|
const testFiles = await testFilesPending;
|
|
3642
5226
|
this.logStartSummary(testFiles);
|
|
3643
5227
|
}
|
|
5228
|
+
async rejectIfCampaignStopped(runDir, eager) {
|
|
5229
|
+
const marker = await readAbortMarker(runDir);
|
|
5230
|
+
if (marker === undefined) {
|
|
5231
|
+
return;
|
|
5232
|
+
}
|
|
5233
|
+
const campaign = await readRegistryCampaign(path15.join(runDir, REGISTRY_FILE));
|
|
5234
|
+
if (campaign?.generation !== marker.generation) {
|
|
5235
|
+
this.logger.debug("Ignoring the abort marker in %s: it belongs to an earlier campaign", runDir);
|
|
5236
|
+
return;
|
|
5237
|
+
}
|
|
5238
|
+
if (campaign.fingerprint !== null && campaign.fingerprint !== await campaignFingerprint(eager)) {
|
|
5239
|
+
this.logger.debug("Ignoring the abort marker in %s: the files matched by mutate changed since its campaign's dry run, so this is a new campaign", runDir);
|
|
5240
|
+
return;
|
|
5241
|
+
}
|
|
5242
|
+
this.logger.error("%s", marker.message);
|
|
5243
|
+
throw new Error(marker.message);
|
|
5244
|
+
}
|
|
3644
5245
|
async ensureRunTempDir() {
|
|
3645
5246
|
this.assertRunOwnerIsParent();
|
|
3646
5247
|
this.tempDir = await resolveRunTempDir();
|
|
@@ -3682,7 +5283,7 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
|
|
|
3682
5283
|
async loadRegistryFile(mutantId) {
|
|
3683
5284
|
const registryPath = await this.resolveRegistryPath();
|
|
3684
5285
|
try {
|
|
3685
|
-
const raw = await
|
|
5286
|
+
const raw = await fsPromises3.readFile(registryPath, "utf8");
|
|
3686
5287
|
const parsed = JSON.parse(raw);
|
|
3687
5288
|
if (parsed.version !== 2) {
|
|
3688
5289
|
this.mutantWarnings.warn(MUTANT_WARN_KIND.registryVersion, mutantId, "dryRun registry file has unexpected version %s; skipping", String(parsed.version));
|
|
@@ -3705,6 +5306,11 @@ ${lines}`, ...ignored.flatMap((d) => [d.key.replace(/^test\./, "[test]."), d.rea
|
|
|
3705
5306
|
}
|
|
3706
5307
|
this.testFileDurations = parseTestFileDurations(parsed.testFileDurations);
|
|
3707
5308
|
this.setTestFileCoverage(TestFileCoverage.fromJson(parsed.mutantTestFiles));
|
|
5309
|
+
if (this.coverageAnalysis !== "off") {
|
|
5310
|
+
this.timeoutCorrectionMs = parsed.timeoutCorrectionMs;
|
|
5311
|
+
const campaign = parseCampaignState(parsed.campaign);
|
|
5312
|
+
this.campaign = campaign === undefined ? undefined : { ...campaign, dir: path15.dirname(registryPath), watched: new Set(campaign.watchList) };
|
|
5313
|
+
}
|
|
3708
5314
|
this.logger.debug("Loaded dryRun registry from %s (%d entries)", registryPath, this.cachedTestNames.size);
|
|
3709
5315
|
} catch (err) {
|
|
3710
5316
|
const code = err.code;
|
|
@@ -3838,11 +5444,494 @@ ${stack}` : baseFailureMessage;
|
|
|
3838
5444
|
return result;
|
|
3839
5445
|
}
|
|
3840
5446
|
async executeDryRun(options, profile) {
|
|
5447
|
+
const startedAt = performance.now();
|
|
3841
5448
|
const coverageAnalysis = this.resolveCoverageAnalysis(options);
|
|
3842
5449
|
this.applyDryRunTestFiles(options);
|
|
3843
5450
|
this.logger.debug("Running dry run with inspector-based coverage collection...");
|
|
5451
|
+
const cwd = process.cwd();
|
|
5452
|
+
const eager = this.cachedEagerModules ?? [];
|
|
5453
|
+
const launchContext = {
|
|
5454
|
+
options,
|
|
5455
|
+
coverageAnalysis,
|
|
5456
|
+
cwd,
|
|
5457
|
+
eager,
|
|
5458
|
+
runDir: this.tempDir ?? tmpdir2(),
|
|
5459
|
+
startedAt,
|
|
5460
|
+
profile,
|
|
5461
|
+
extraMs: 0,
|
|
5462
|
+
launches: 0
|
|
5463
|
+
};
|
|
5464
|
+
if (this.inPlace && this.tempDir !== undefined) {
|
|
5465
|
+
await removeQuietly(path15.join(this.tempDir, ABORT_MARKER_FILE));
|
|
5466
|
+
}
|
|
5467
|
+
if (coverageAnalysis === "off") {
|
|
5468
|
+
return this.runWithoutCoverage(launchContext);
|
|
5469
|
+
}
|
|
5470
|
+
const always = this.selectAlwaysImported(eager, cwd);
|
|
5471
|
+
const ctx = { ...launchContext, always };
|
|
5472
|
+
const legacy = legacyReason(eager, always);
|
|
5473
|
+
if (legacy !== null) {
|
|
5474
|
+
this.logger.debug("Dry run: %s, so the runner imports all of them before the tests, with no import scan", legacy === "empty" ? "mutate matches no file" : "bun.alwaysImport keeps every file mutate matches");
|
|
5475
|
+
const launch = await this.runPublished(ctx, eager);
|
|
5476
|
+
this.warnEagerFailures(ctx, launch.record);
|
|
5477
|
+
return this.publishDryRun(ctx, launch);
|
|
5478
|
+
}
|
|
5479
|
+
const { decision, roots } = await this.decideShape(ctx);
|
|
5480
|
+
if (decision.kind === "full") {
|
|
5481
|
+
return this.runFullShape(ctx, decision);
|
|
5482
|
+
}
|
|
5483
|
+
if (decision.kind === "static") {
|
|
5484
|
+
return this.runStaticShape(ctx, decision, roots);
|
|
5485
|
+
}
|
|
5486
|
+
return this.runTwoRuns(ctx, { kind: "scan" });
|
|
5487
|
+
}
|
|
5488
|
+
async runWithoutCoverage(ctx) {
|
|
5489
|
+
this.logger.debug("Dry run: coverageAnalysis is 'off', so the runner imports nothing before the tests, records no mutant coverage and runs the tests once");
|
|
5490
|
+
this.noteOptionsWithoutEffect();
|
|
5491
|
+
this.beforeLaunch(ctx);
|
|
5492
|
+
const imported = [];
|
|
5493
|
+
const pass = await this.runInspectedPass(ctx, imported, undefined);
|
|
5494
|
+
return this.publishDryRun(ctx, { ...pass, list: imported, record: undefined, elapsedMs: 0 });
|
|
5495
|
+
}
|
|
5496
|
+
noteOptionsWithoutEffect() {
|
|
5497
|
+
const set = [
|
|
5498
|
+
...this.alwaysImport === undefined ? [] : ["bun.alwaysImport"],
|
|
5499
|
+
...this.importDiscovery === undefined ? [] : ["bun.importDiscovery"]
|
|
5500
|
+
];
|
|
5501
|
+
if (set.length > 0) {
|
|
5502
|
+
this.logger.info("%s %s no effect with coverageAnalysis 'off': its dry run imports no mutated file before the tests", set.join(" and "), set.length === 1 ? "has" : "have");
|
|
5503
|
+
}
|
|
5504
|
+
}
|
|
5505
|
+
selectAlwaysImported(eager, cwd) {
|
|
5506
|
+
const selection = selectAlways(eager, this.alwaysImport, cwd);
|
|
5507
|
+
for (const pattern of selection.unmatched) {
|
|
5508
|
+
this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
|
|
5509
|
+
}
|
|
5510
|
+
return selection.files;
|
|
5511
|
+
}
|
|
5512
|
+
projectPathsOf(ctx, files) {
|
|
5513
|
+
return files.map((file) => shownPath(file, ctx.cwd));
|
|
5514
|
+
}
|
|
5515
|
+
logListed(level, message, lists) {
|
|
5516
|
+
this.logger[level]("%s", message);
|
|
5517
|
+
for (const [what, entries] of lists) {
|
|
5518
|
+
const overflow = listOverflow(entries);
|
|
5519
|
+
if (overflow.length > 0) {
|
|
5520
|
+
this.logger.debug("The rest of %s: %s", what, overflow.join(", "));
|
|
5521
|
+
}
|
|
5522
|
+
}
|
|
5523
|
+
}
|
|
5524
|
+
async decideShape(ctx) {
|
|
5525
|
+
const started = performance.now();
|
|
5526
|
+
try {
|
|
5527
|
+
const input = await this.importScanInput(ctx);
|
|
5528
|
+
if ("problem" in input) {
|
|
5529
|
+
this.logger.debug("%s", scanUnusableMessage(input.problem, false));
|
|
5530
|
+
return { decision: decideFromScan(failedScanResult(input.problem), ctx.eager, ctx.always, this.importDiscovery), roots: [] };
|
|
5531
|
+
}
|
|
5532
|
+
const report = await runImportScan(input.input, { bunPath: this.bunPath, workDir: ctx.runDir });
|
|
5533
|
+
const decision = decideFromScan(report.result, ctx.eager, ctx.always, this.importDiscovery);
|
|
5534
|
+
if (report.failure === null) {
|
|
5535
|
+
this.logger.debug("%s", scanMessage({
|
|
5536
|
+
answer: report.result.answer,
|
|
5537
|
+
wallMs: report.wallMs,
|
|
5538
|
+
scannedFiles: report.result.scannedFiles,
|
|
5539
|
+
matched: ctx.eager.length,
|
|
5540
|
+
statically: this.projectPathsOf(ctx, decision.sources.statically),
|
|
5541
|
+
named: this.projectPathsOf(ctx, decision.sources.named),
|
|
5542
|
+
always: this.projectPathsOf(ctx, decision.sources.always),
|
|
5543
|
+
reasons: decision.kind === "dynamic" ? decision.reasons : report.result.reasons,
|
|
5544
|
+
notes: report.result.notes,
|
|
5545
|
+
next: decision.kind
|
|
5546
|
+
}));
|
|
5547
|
+
} else {
|
|
5548
|
+
this.logger.info("%s", scanUnusableMessage(report.failure, true));
|
|
5549
|
+
}
|
|
5550
|
+
return { decision, roots: input.input.roots };
|
|
5551
|
+
} finally {
|
|
5552
|
+
ctx.extraMs += performance.now() - started;
|
|
5553
|
+
}
|
|
5554
|
+
}
|
|
5555
|
+
async importScanInput(ctx) {
|
|
5556
|
+
const { testFiles } = await this.dryRunFiles(ctx.cwd);
|
|
5557
|
+
if (testFiles === undefined) {
|
|
5558
|
+
return { problem: "the dry run hands bun no list of test files (bun finds them itself), so the runner cannot name the test files to scan" };
|
|
5559
|
+
}
|
|
5560
|
+
const launch = scanLaunchArguments(this.bunArgs ?? [], { ...process.env, ...this.env }, ctx.cwd);
|
|
5561
|
+
if ("problem" in launch) {
|
|
5562
|
+
return launch;
|
|
5563
|
+
}
|
|
5564
|
+
const expanded = await expandTestFileEntries(testFiles, ctx.cwd, this.logger);
|
|
5565
|
+
if ("problem" in expanded) {
|
|
5566
|
+
return expanded;
|
|
5567
|
+
}
|
|
5568
|
+
let bunfig;
|
|
5569
|
+
try {
|
|
5570
|
+
bunfig = await readBunfigForScan(ctx.cwd, this.sourceBunfig);
|
|
5571
|
+
} catch (error) {
|
|
5572
|
+
return { problem: `the bunfig's [test].preload cannot be read (${errorText(error)})` };
|
|
5573
|
+
}
|
|
5574
|
+
if (bunfig.problem !== undefined) {
|
|
5575
|
+
return { problem: bunfig.problem };
|
|
5576
|
+
}
|
|
5577
|
+
const { preloads } = bunfig;
|
|
5578
|
+
return {
|
|
5579
|
+
input: {
|
|
5580
|
+
eager: ctx.eager,
|
|
5581
|
+
roots: [...new Set([...expanded.files, ...preloads, ...launch.preloads])],
|
|
5582
|
+
always: ctx.always,
|
|
5583
|
+
tsconfig: await this.applicableTsconfig(ctx.cwd),
|
|
5584
|
+
projectDir: ctx.cwd
|
|
5585
|
+
}
|
|
5586
|
+
};
|
|
5587
|
+
}
|
|
5588
|
+
async applicableTsconfig(cwd) {
|
|
5589
|
+
for (const name of ["tsconfig.json", "jsconfig.json"]) {
|
|
5590
|
+
const file = path15.join(cwd, name);
|
|
5591
|
+
const stat = await fsPromises3.stat(file).catch(() => {
|
|
5592
|
+
return;
|
|
5593
|
+
});
|
|
5594
|
+
if (stat?.isFile()) {
|
|
5595
|
+
return file;
|
|
5596
|
+
}
|
|
5597
|
+
}
|
|
5598
|
+
return null;
|
|
5599
|
+
}
|
|
5600
|
+
async dryRunFiles(cwd) {
|
|
5601
|
+
const bunfigPath = await this.ensureSanitizedBunfig();
|
|
5602
|
+
const listed = this.testFilesCacheHit(cwd) ?? await this.getOrDiscoverTestFiles();
|
|
5603
|
+
return { bunfigPath, testFiles: this.fitTestFiles(listed, this.explicitTestFilesSource(cwd)) };
|
|
5604
|
+
}
|
|
5605
|
+
beforeLaunch(ctx) {
|
|
5606
|
+
const budgetMs = ctx.options?.timeout;
|
|
5607
|
+
const warning = ctx.launches === 0 ? undefined : budgetWarning(performance.now() - ctx.startedAt, budgetMs);
|
|
5608
|
+
if (warning !== undefined) {
|
|
5609
|
+
this.logger.warn("%s", budgetMessage(warning.usedMs, warning.remainingMs, budgetMs / 60000, warning.suggestedMinutes));
|
|
5610
|
+
}
|
|
5611
|
+
ctx.launches++;
|
|
5612
|
+
ctx.profile?.countLaunch();
|
|
5613
|
+
}
|
|
5614
|
+
async runPublished(ctx, list) {
|
|
5615
|
+
this.beforeLaunch(ctx);
|
|
5616
|
+
const started = performance.now();
|
|
5617
|
+
const files = this.launchFiles(ctx);
|
|
5618
|
+
const nonce = newGeneration();
|
|
5619
|
+
const plan = publishPlan(ctx.eager, list, files.recordFile, nonce);
|
|
5620
|
+
try {
|
|
5621
|
+
const written = plan.eager.length === 0 && plan.candidates === null ? { planFile: undefined } : await this.writePlan(files.planFile, plan);
|
|
5622
|
+
if ("result" in written) {
|
|
5623
|
+
return { result: written.result, list, record: undefined, elapsedMs: performance.now() - started };
|
|
5624
|
+
}
|
|
5625
|
+
const pass = await this.runInspectedPass(ctx, list, written.planFile);
|
|
5626
|
+
const record = plan.recordFile === null ? undefined : ownRecord(await this.readRecord(plan.recordFile, (text) => readObservationRecord(text, ctx.eager)), nonce);
|
|
5627
|
+
return { ...pass, list, record, elapsedMs: performance.now() - started };
|
|
5628
|
+
} finally {
|
|
5629
|
+
await this.removeLaunchFiles(files);
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
launchFiles(ctx) {
|
|
5633
|
+
return {
|
|
5634
|
+
planFile: this.preloadScriptPath === undefined ? undefined : newLaunchFile(path15.dirname(this.preloadScriptPath), "dry-run-plan"),
|
|
5635
|
+
recordFile: newRecordFile(ctx.runDir)
|
|
5636
|
+
};
|
|
5637
|
+
}
|
|
5638
|
+
async removeLaunchFiles(files) {
|
|
5639
|
+
const plan = files.planFile === undefined ? [] : [files.planFile];
|
|
5640
|
+
await Promise.all([...plan, files.recordFile, `${files.recordFile}.tmp`].map(async (file) => removeQuietly(file)));
|
|
5641
|
+
}
|
|
5642
|
+
async writePlan(planFile, plan) {
|
|
5643
|
+
if (planFile === undefined) {
|
|
5644
|
+
return { planFile };
|
|
5645
|
+
}
|
|
5646
|
+
try {
|
|
5647
|
+
await writeDryRunPlan(planFile, plan);
|
|
5648
|
+
return { planFile };
|
|
5649
|
+
} catch (error) {
|
|
5650
|
+
const errorMessage = `stryker-bun-runner: cannot write the dry-run plan ${planFile} (${errorText(error)})`;
|
|
5651
|
+
this.logger.error("%s", errorMessage);
|
|
5652
|
+
return { result: { status: DryRunStatus.Error, errorMessage } };
|
|
5653
|
+
}
|
|
5654
|
+
}
|
|
5655
|
+
async readRecord(file, parse) {
|
|
5656
|
+
const read = await readRecordFile(file);
|
|
5657
|
+
await removeQuietly(file);
|
|
5658
|
+
return "problem" in read ? read : parse(read.text);
|
|
5659
|
+
}
|
|
5660
|
+
launchFacts(ctx, launch) {
|
|
5661
|
+
return { list: launch.list, watched: launch.list.length < ctx.eager.length, record: launch.record, green: isGreen(launch.result) };
|
|
5662
|
+
}
|
|
5663
|
+
warnEagerFailures(ctx, record) {
|
|
5664
|
+
const failures = eagerFailuresOf(record);
|
|
5665
|
+
for (const failure of failures.slice(0, LISTED_ENTRIES)) {
|
|
5666
|
+
this.logger.warn("%s", eagerFailureMessage(shownPath(failure.file, ctx.cwd), failure.error));
|
|
5667
|
+
}
|
|
5668
|
+
const rest = failures.slice(LISTED_ENTRIES);
|
|
5669
|
+
if (rest.length > 0) {
|
|
5670
|
+
this.logger.warn("%d more imports before the tests failed (listed at debug)", rest.length);
|
|
5671
|
+
this.logger.debug("The other imports before the tests that failed: %s", rest.map((failure) => `${shownPath(failure.file, ctx.cwd)}: ${displayError(failure.error)}`).join("; "));
|
|
5672
|
+
}
|
|
5673
|
+
}
|
|
5674
|
+
async runFullShape(ctx, decision) {
|
|
5675
|
+
const launch = await this.runPublished(ctx, decision.list);
|
|
5676
|
+
if (isGreen(launch.result) || decision.sources.named.length === 0) {
|
|
5677
|
+
this.warnEagerFailures(ctx, launch.record);
|
|
5678
|
+
return this.publishDryRun(ctx, launch);
|
|
5679
|
+
}
|
|
5680
|
+
ctx.extraMs += launch.elapsedMs;
|
|
5681
|
+
return this.runTwoRuns(ctx, { kind: "failed", attempt: launch, named: decision.sources.named });
|
|
5682
|
+
}
|
|
5683
|
+
async runStaticShape(ctx, decision, roots) {
|
|
5684
|
+
const launch = await this.runPublished(ctx, decision.list);
|
|
5685
|
+
const testFiles = launch.result.status === DryRunStatus.Complete ? launch.result.tests.map((test) => test.fileName) : [];
|
|
5686
|
+
const outcome = oneRunOutcome(this.launchFacts(ctx, launch), unscannedTestFiles(testFiles, roots, ctx.cwd), decision.sources.named);
|
|
5687
|
+
if (outcome.kind === "refuse") {
|
|
5688
|
+
return this.refuseDryRun(outcome.problems);
|
|
5689
|
+
}
|
|
5690
|
+
if (outcome.kind === "miss") {
|
|
5691
|
+
const files = this.projectPathsOf(ctx, outcome.files.map((observation) => observation.file));
|
|
5692
|
+
const unscanned = outcome.testFiles.map((file) => displayName(file));
|
|
5693
|
+
this.logListed("warn", missMessage(files, unscanned, this.incremental), [["the files loaded outside the list", files], ["the test files the runner did not scan", unscanned]]);
|
|
5694
|
+
ctx.extraMs += launch.elapsedMs;
|
|
5695
|
+
return this.runTwoRuns(ctx, { kind: "miss" });
|
|
5696
|
+
}
|
|
5697
|
+
if (outcome.kind === "failed" && outcome.discover) {
|
|
5698
|
+
ctx.extraMs += launch.elapsedMs;
|
|
5699
|
+
return this.runTwoRuns(ctx, { kind: "failed", attempt: launch, named: decision.sources.named });
|
|
5700
|
+
}
|
|
5701
|
+
this.warnEagerFailures(ctx, launch.record);
|
|
5702
|
+
if (outcome.kind === "publish") {
|
|
5703
|
+
const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !decision.list.includes(file)));
|
|
5704
|
+
this.logListed("info", importListOneRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { statically: decision.sources.statically.length, named: decision.sources.named.length, always: decision.sources.always.length }), [["the files the runner does not import", left]]);
|
|
5705
|
+
}
|
|
5706
|
+
return this.publishDryRun(ctx, launch);
|
|
5707
|
+
}
|
|
5708
|
+
async runTwoRuns(ctx, cause) {
|
|
5709
|
+
this.beforeLaunch(ctx);
|
|
5710
|
+
const discoveryOrdinal = RUN_ORDINALS[ctx.launches - 1];
|
|
5711
|
+
const started = performance.now();
|
|
5712
|
+
const files = this.launchFiles(ctx);
|
|
5713
|
+
const nonce = newGeneration();
|
|
5714
|
+
let discovery;
|
|
5715
|
+
try {
|
|
5716
|
+
const written = await this.writePlan(files.planFile, discoveryPlan(ctx.eager, files.recordFile, nonce));
|
|
5717
|
+
if ("result" in written) {
|
|
5718
|
+
return written.result;
|
|
5719
|
+
}
|
|
5720
|
+
discovery = await this.runDiscovery(ctx, written.planFile, files.recordFile, nonce);
|
|
5721
|
+
} finally {
|
|
5722
|
+
await this.removeLaunchFiles(files);
|
|
5723
|
+
ctx.extraMs += performance.now() - started;
|
|
5724
|
+
}
|
|
5725
|
+
if (discovery.verdict.kind === "refused") {
|
|
5726
|
+
return this.refuseDryRun(discovery.verdict.problems);
|
|
5727
|
+
}
|
|
5728
|
+
if (discovery.verdict.kind === "rejected") {
|
|
5729
|
+
if (cause.kind === "failed") {
|
|
5730
|
+
this.logger.warn("%s", discoveryAfterFailedRunMessage(discovery.verdict.reasons));
|
|
5731
|
+
this.warnEagerFailures(ctx, cause.attempt.record);
|
|
5732
|
+
return this.publishDryRun(ctx, cause.attempt);
|
|
5733
|
+
}
|
|
5734
|
+
return this.discoveryError(ctx, discovery, discoveryOrdinal, discovery.verdict.reasons);
|
|
5735
|
+
}
|
|
5736
|
+
return this.runAfterDiscovery(ctx, cause, discovery.verdict.record, discoveryOrdinal);
|
|
5737
|
+
}
|
|
5738
|
+
async runAfterDiscovery(ctx, cause, discovered, discoveryOrdinal) {
|
|
5739
|
+
const observed = new Set(discovered.observed.map((observation) => observation.file));
|
|
5740
|
+
const list = selectList(ctx.eager, [observed, new Set(ctx.always)]);
|
|
5741
|
+
const launch = await this.runPublished(ctx, list);
|
|
5742
|
+
const publishedOrdinal = RUN_ORDINALS[ctx.launches - 1];
|
|
5743
|
+
const facts = this.launchFacts(ctx, launch);
|
|
5744
|
+
const rawCoverage = launch.publication?.rawCoverage;
|
|
5745
|
+
const lost = facts.watched && rawCoverage !== undefined ? lostIds(discovered.reached, rawCoverage) : [];
|
|
5746
|
+
const outcome = twoRunOutcome(facts, lost);
|
|
5747
|
+
if (outcome.kind === "refuse") {
|
|
5748
|
+
return this.refuseDryRun(outcome.problems);
|
|
5749
|
+
}
|
|
5750
|
+
if (outcome.kind === "late") {
|
|
5751
|
+
return this.lateLoadError(ctx, launch, outcome.files, publishedOrdinal, discoveryOrdinal);
|
|
5752
|
+
}
|
|
5753
|
+
if (outcome.kind === "failed") {
|
|
5754
|
+
const failures = eagerFailuresOf(launch.record).map((failure) => `${shownPath(failure.file, ctx.cwd)}: ${displayError(failure.error)}`);
|
|
5755
|
+
const imported = this.projectPathsOf(ctx, list);
|
|
5756
|
+
const fromObservation = list.filter((file) => observed.has(file)).length;
|
|
5757
|
+
this.logListed("error", publishedFailedMessage(publishedOrdinal, discoveryOrdinal, imported, fromObservation, failures), [["the files imported first", imported], ["the imports that threw", failures]]);
|
|
5758
|
+
this.warnEagerFailures(ctx, launch.record);
|
|
5759
|
+
return this.publishDryRun(ctx, launch);
|
|
5760
|
+
}
|
|
5761
|
+
if (outcome.kind === "lost") {
|
|
5762
|
+
return this.lostError(ctx, outcome.ids, list, list.filter((file) => !observed.has(file)).length, publishedOrdinal);
|
|
5763
|
+
}
|
|
5764
|
+
if (facts.watched && rawCoverage === undefined) {
|
|
5765
|
+
return this.refuseDryRun([MISSING_COVERAGE_FOR_RULE_3_3]);
|
|
5766
|
+
}
|
|
5767
|
+
const early = outcome.early.map((observation) => observation.file);
|
|
5768
|
+
this.reportTwoRunPublication(ctx, { cause, list, observed, early, watched: facts.watched }, publishedOrdinal, discoveryOrdinal);
|
|
5769
|
+
this.warnEagerFailures(ctx, launch.record);
|
|
5770
|
+
return this.publishDryRun(ctx, launch, early);
|
|
5771
|
+
}
|
|
5772
|
+
reportTwoRunPublication(ctx, run, publishedOrdinal, discoveryOrdinal) {
|
|
5773
|
+
if (run.early.length > 0) {
|
|
5774
|
+
const files = this.projectPathsOf(ctx, run.early);
|
|
5775
|
+
this.logListed("warn", loadedByListMessage(files), [["the files loaded before the tests", files]]);
|
|
5776
|
+
}
|
|
5777
|
+
const kept = new Set(run.list);
|
|
5778
|
+
if (run.watched) {
|
|
5779
|
+
const left = this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file)));
|
|
5780
|
+
const fromObservation = run.list.filter((file) => run.observed.has(file)).length;
|
|
5781
|
+
this.logListed("info", importListTwoRunMessage({ matched: ctx.eager.length, left, incremental: this.incremental }, { observed: fromObservation, always: run.list.length - fromObservation }, publishedOrdinal, discoveryOrdinal), [["the files the runner does not import", left]]);
|
|
5782
|
+
}
|
|
5783
|
+
if (run.cause.kind === "failed") {
|
|
5784
|
+
const unloaded = run.cause.named.filter((file) => !run.observed.has(file));
|
|
5785
|
+
const notLoaded = this.projectPathsOf(ctx, unloaded);
|
|
5786
|
+
const keptAnyway = this.projectPathsOf(ctx, unloaded.filter((file) => kept.has(file)));
|
|
5787
|
+
this.logListed("warn", namedMessage(run.cause.named.length, notLoaded, keptAnyway, this.incremental), [
|
|
5788
|
+
["the named files the plain run did not load", notLoaded],
|
|
5789
|
+
["the named files bun.alwaysImport keeps", keptAnyway]
|
|
5790
|
+
]);
|
|
5791
|
+
}
|
|
5792
|
+
}
|
|
5793
|
+
async runDiscovery(ctx, planFile, recordFile, nonce) {
|
|
5794
|
+
const { bunfigPath, testFiles } = await this.dryRunFiles(ctx.cwd);
|
|
5795
|
+
const abortController = new AbortController;
|
|
5796
|
+
this.currentAbortController = abortController;
|
|
5797
|
+
const spawned = {};
|
|
5798
|
+
let result;
|
|
5799
|
+
try {
|
|
5800
|
+
result = await runBunTests({
|
|
5801
|
+
bunPath: this.bunPath,
|
|
5802
|
+
timeout: this.timeout,
|
|
5803
|
+
env: this.env,
|
|
5804
|
+
bunArgs: this.bunArgs,
|
|
5805
|
+
bunfigPath,
|
|
5806
|
+
preloadScript: this.preloadScriptPath,
|
|
5807
|
+
dryRunPlan: planFile,
|
|
5808
|
+
sequentialMode: true,
|
|
5809
|
+
testFiles,
|
|
5810
|
+
signal: abortController.signal,
|
|
5811
|
+
smol: this.smol,
|
|
5812
|
+
maxChildRss: this.maxChildRss,
|
|
5813
|
+
rssCheckIntervalMs: this.rssCheckIntervalMs,
|
|
5814
|
+
maxSpawnDepth: this.maxSpawnDepth,
|
|
5815
|
+
onMemoryLimitExceeded: (rssBytes) => {
|
|
5816
|
+
this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during the dry run's plain run of the tests — killing it", rssBytes);
|
|
5817
|
+
},
|
|
5818
|
+
onSpawn: (command) => {
|
|
5819
|
+
spawned.command = command;
|
|
5820
|
+
}
|
|
5821
|
+
});
|
|
5822
|
+
} finally {
|
|
5823
|
+
if (this.currentAbortController === abortController) {
|
|
5824
|
+
this.currentAbortController = undefined;
|
|
5825
|
+
}
|
|
5826
|
+
}
|
|
5827
|
+
const parsed = parseBunTestOutput(result.stdout, result.stderr);
|
|
5828
|
+
const record = await this.readRecord(recordFile, (text) => readDiscoveryRecord(text, ctx.eager));
|
|
5829
|
+
const verdict = acceptDiscovery({
|
|
5830
|
+
exitCode: result.exitCode,
|
|
5831
|
+
signal: result.signal ?? null,
|
|
5832
|
+
timedOut: result.timedOut,
|
|
5833
|
+
memoryLimitExceeded: result.memoryLimitExceeded === true,
|
|
5834
|
+
spawnError: result.spawnError,
|
|
5835
|
+
summaryPrinted: parsed.summaryPrinted,
|
|
5836
|
+
summaryPassed: parsed.summaryPassed,
|
|
5837
|
+
summaryFailed: parsed.summaryFailed,
|
|
5838
|
+
summaryErrors: parsed.summaryErrors,
|
|
5839
|
+
record,
|
|
5840
|
+
nonce
|
|
5841
|
+
});
|
|
5842
|
+
this.logger.debug("Dry run: the plain run of the tests ended with exit code %s (%d pass, %d fail): %s", String(result.exitCode), parsed.summaryPassed, parsed.summaryFailed, verdict.kind);
|
|
5843
|
+
return { result, verdict, command: spawned.command };
|
|
5844
|
+
}
|
|
5845
|
+
refuseDryRun(problems) {
|
|
5846
|
+
const errorMessage = refuseMessage(problems, this.incremental);
|
|
5847
|
+
this.logger.error("%s", errorMessage);
|
|
5848
|
+
return { status: DryRunStatus.Error, errorMessage };
|
|
5849
|
+
}
|
|
5850
|
+
async discoveryError(ctx, discovery, ordinal, reasons) {
|
|
5851
|
+
const { result } = discovery;
|
|
5852
|
+
const unhandled = describeUnhandledErrors(result.stderr, [], []);
|
|
5853
|
+
const tail = cleanDiagnosticText([result.stdout, result.stderr].join(`
|
|
5854
|
+
`)).trim().slice(-500) || "(empty)";
|
|
5855
|
+
const output = unhandled ?? `Last 500 chars of its output:
|
|
5856
|
+
${tail}`;
|
|
5857
|
+
const outputLine = await this.saveFailedDryRunOutput(result, { command: discovery.command, cwd: ctx.cwd, syncToken: "" });
|
|
5858
|
+
const errorMessage = `${discoveryFailedMessage(ordinal, reasons)}
|
|
5859
|
+
${output}
|
|
5860
|
+
${outputLine}`;
|
|
5861
|
+
this.logger.error("%s", errorMessage);
|
|
5862
|
+
return { status: DryRunStatus.Error, errorMessage };
|
|
5863
|
+
}
|
|
5864
|
+
lateLoadError(ctx, launch, late, published, discovery) {
|
|
5865
|
+
const names = launch.publication?.testNames;
|
|
5866
|
+
const loads = late.map((observation) => ({
|
|
5867
|
+
file: shownPath(observation.file, ctx.cwd),
|
|
5868
|
+
test: observation.testKey === null ? null : names?.get(observation.testKey) ?? observation.testKey,
|
|
5869
|
+
sensor: observation.sensor
|
|
5870
|
+
}));
|
|
5871
|
+
const errorMessage = lateLoadMessage(loads, published, discovery, this.incremental);
|
|
5872
|
+
this.logListed("error", errorMessage, [["the files loaded late", lateLoadEntries(loads)]]);
|
|
5873
|
+
return { status: DryRunStatus.Error, errorMessage };
|
|
5874
|
+
}
|
|
5875
|
+
async lostError(ctx, ids, list, always, published) {
|
|
5876
|
+
const lost = new Set(ids);
|
|
5877
|
+
const holding = await Promise.all(ctx.eager.map(async (file) => {
|
|
5878
|
+
const read = fsPromises3.readFile(file, "utf8");
|
|
5879
|
+
const content = await read.catch(() => "");
|
|
5880
|
+
return [...mutantIdsInInstrumentedSource(content)].some((id) => lost.has(id));
|
|
5881
|
+
}));
|
|
5882
|
+
const kept = new Set(list);
|
|
5883
|
+
const report = {
|
|
5884
|
+
ids,
|
|
5885
|
+
files: this.projectPathsOf(ctx, ctx.eager.filter((_file, index) => holding[index])),
|
|
5886
|
+
imported: list.length,
|
|
5887
|
+
always,
|
|
5888
|
+
leftOut: this.projectPathsOf(ctx, ctx.eager.filter((file) => !kept.has(file))),
|
|
5889
|
+
published,
|
|
5890
|
+
incremental: this.incremental
|
|
5891
|
+
};
|
|
5892
|
+
const errorMessage = lostMessage(report);
|
|
5893
|
+
this.logListed("error", errorMessage, [["the lost mutant ids", ids], ["the files of the lost mutants", report.files], ["the files left out", report.leftOut]]);
|
|
5894
|
+
return { status: DryRunStatus.Error, errorMessage };
|
|
5895
|
+
}
|
|
5896
|
+
async publishDryRun(ctx, launch, seen = []) {
|
|
5897
|
+
const { publication } = launch;
|
|
5898
|
+
if (publication === undefined) {
|
|
5899
|
+
return launch.result;
|
|
5900
|
+
}
|
|
5901
|
+
const { tests, testNameIndex, testFileCoverage, processResult, parsed, totalElapsedMs } = publication;
|
|
5902
|
+
const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
|
|
5903
|
+
ctx.profile?.at("coverageChecked");
|
|
5904
|
+
const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
|
|
5905
|
+
const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, eager: ctx.eager } : undefined;
|
|
5906
|
+
const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
|
|
5907
|
+
ctx.profile?.at("registryWritten");
|
|
5908
|
+
if (unpublished !== undefined) {
|
|
5909
|
+
this.logger.error("%s", unpublished);
|
|
5910
|
+
return { status: DryRunStatus.Error, errorMessage: unpublished };
|
|
5911
|
+
}
|
|
5912
|
+
this.warnOnUnidentifiedDryRunFailure(processResult, parsed, tests);
|
|
5913
|
+
this.warnOnTightDryRunTimeout(totalElapsedMs);
|
|
5914
|
+
return launch.result;
|
|
5915
|
+
}
|
|
5916
|
+
async runInspectedPass(ctx, list, planFile) {
|
|
3844
5917
|
const abortController = new AbortController;
|
|
3845
5918
|
this.currentAbortController = abortController;
|
|
5919
|
+
ctx.profile?.restartLaunch();
|
|
5920
|
+
const coverageFile = this.coverageFilePath === undefined ? undefined : newLaunchFile(path15.dirname(this.coverageFilePath), "coverage");
|
|
5921
|
+
const launched = {};
|
|
5922
|
+
try {
|
|
5923
|
+
return await this.runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched);
|
|
5924
|
+
} catch (error) {
|
|
5925
|
+
await awaitChildExit(launched.child, CHILD_EXIT_WAIT_MS);
|
|
5926
|
+
throw error;
|
|
5927
|
+
} finally {
|
|
5928
|
+
if (coverageFile !== undefined) {
|
|
5929
|
+
await cleanupCoverageFile(coverageFile);
|
|
5930
|
+
}
|
|
5931
|
+
}
|
|
5932
|
+
}
|
|
5933
|
+
async runInspectedChild(ctx, list, planFile, coverageFile, abortController, launched) {
|
|
5934
|
+
const { coverageAnalysis, profile } = ctx;
|
|
3846
5935
|
const syncServer = new SyncServer;
|
|
3847
5936
|
let syncPort;
|
|
3848
5937
|
try {
|
|
@@ -3853,8 +5942,10 @@ ${stack}` : baseFailureMessage;
|
|
|
3853
5942
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
3854
5943
|
this.logger.error("Failed to start sync server: %s", errorMsg);
|
|
3855
5944
|
return {
|
|
3856
|
-
|
|
3857
|
-
|
|
5945
|
+
result: {
|
|
5946
|
+
status: DryRunStatus.Error,
|
|
5947
|
+
errorMessage: `Failed to start sync server: ${errorMsg}`
|
|
5948
|
+
}
|
|
3858
5949
|
};
|
|
3859
5950
|
}
|
|
3860
5951
|
const startTime = Date.now();
|
|
@@ -3866,6 +5957,7 @@ ${stack}` : baseFailureMessage;
|
|
|
3866
5957
|
const listed = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
|
|
3867
5958
|
this.logTestFilesSource(listed, cwd);
|
|
3868
5959
|
const testFiles = this.fitTestFiles(listed, this.explicitTestFilesSource(cwd));
|
|
5960
|
+
const spawned = {};
|
|
3869
5961
|
const testProcess = runBunTests({
|
|
3870
5962
|
bunPath: this.bunPath,
|
|
3871
5963
|
timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
|
|
@@ -3873,7 +5965,9 @@ ${stack}` : baseFailureMessage;
|
|
|
3873
5965
|
bunArgs: this.bunArgs,
|
|
3874
5966
|
bunfigPath,
|
|
3875
5967
|
preloadScript: this.preloadScriptPath,
|
|
3876
|
-
|
|
5968
|
+
dryRunPlan: planFile,
|
|
5969
|
+
coverageFile,
|
|
5970
|
+
coverageKeysOnly: coverageAnalysis === "off",
|
|
3877
5971
|
inspect: true,
|
|
3878
5972
|
sequentialMode: true,
|
|
3879
5973
|
syncPort,
|
|
@@ -3888,14 +5982,19 @@ ${stack}` : baseFailureMessage;
|
|
|
3888
5982
|
this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during dryRun — killing and reporting as a timeout for this run", rssBytes);
|
|
3889
5983
|
},
|
|
3890
5984
|
onInspectorReady: inspectorUrlWaiter.onReady,
|
|
5985
|
+
onSpawn: (command) => {
|
|
5986
|
+
spawned.command = command;
|
|
5987
|
+
},
|
|
3891
5988
|
profile
|
|
3892
5989
|
});
|
|
5990
|
+
launched.child = testProcess;
|
|
3893
5991
|
const inspectorUrl = await inspectorUrlWaiter.wait(testProcess, this.inspectorTimeout);
|
|
3894
5992
|
if (!inspectorUrl) {
|
|
3895
5993
|
await syncServer.close();
|
|
3896
5994
|
const diagnosticResult = await testProcess;
|
|
3897
|
-
const
|
|
3898
|
-
const
|
|
5995
|
+
const secrets = [syncServer.token];
|
|
5996
|
+
const stdoutPreview = cleanDiagnosticText(diagnosticResult.stdout, secrets).slice(0, 1000);
|
|
5997
|
+
const stderrPreview = cleanDiagnosticText(diagnosticResult.stderr, secrets).slice(0, 1000);
|
|
3899
5998
|
this.logger.error(`Failed to get inspector URL within timeout (%dms).
|
|
3900
5999
|
exit=%s timedOut=%s
|
|
3901
6000
|
` + `--- STDOUT (first 1000 chars) ---
|
|
@@ -3903,8 +6002,10 @@ exit=%s timedOut=%s
|
|
|
3903
6002
|
` + `--- STDERR (first 1000 chars) ---
|
|
3904
6003
|
%s`, this.inspectorTimeout, String(diagnosticResult.exitCode), String(diagnosticResult.timedOut), stdoutPreview || "(empty)", stderrPreview || "(empty)");
|
|
3905
6004
|
return {
|
|
3906
|
-
|
|
3907
|
-
|
|
6005
|
+
result: {
|
|
6006
|
+
status: DryRunStatus.Error,
|
|
6007
|
+
errorMessage: formatInspectorTimeoutMessage(this.inspectorTimeout, diagnosticResult, secrets)
|
|
6008
|
+
}
|
|
3908
6009
|
};
|
|
3909
6010
|
}
|
|
3910
6011
|
this.logger.debug("Inspector URL: %s", redactInspectorUrl(inspectorUrl));
|
|
@@ -3917,7 +6018,7 @@ exit=%s timedOut=%s
|
|
|
3917
6018
|
this.logger.warn("Inspector error: %s", error.message);
|
|
3918
6019
|
},
|
|
3919
6020
|
onUnexpectedClose: (context) => {
|
|
3920
|
-
this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s closeCode=%s closeReason=%s closeWasClean=%s msFromLastFrameToClose=%s) — often benign; see
|
|
6021
|
+
this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s closeCode=%s closeReason=%s closeWasClean=%s msFromLastFrameToClose=%s) — often benign; see findCompletenessProblems", context.wsClosed, context.closeExpected, context.isClosing, String(context.closeCode), String(context.closeReason), String(context.closeWasClean), String(context.msFromLastFrameToClose));
|
|
3921
6022
|
},
|
|
3922
6023
|
onRequestStall: (info) => {
|
|
3923
6024
|
this.logger.warn("Inspector request unanswered after %dms even though other frames are still arriving (last frame %dms ago): %s (id=%d) — possible protocol-level stall distinct from total silence", info.msUnanswered, info.msSinceLastFrame, info.method, info.id);
|
|
@@ -3931,14 +6032,16 @@ exit=%s timedOut=%s
|
|
|
3931
6032
|
profile?.mark("inspector");
|
|
3932
6033
|
this.logger.debug("Inspector connected and TestReporter enabled");
|
|
3933
6034
|
} catch (error) {
|
|
3934
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
6035
|
+
const errorMsg = cleanDiagnosticText(error instanceof Error ? error.message : String(error), [syncServer.token]);
|
|
3935
6036
|
this.logger.error("Failed to connect inspector: %s", errorMsg);
|
|
3936
6037
|
abortController.abort();
|
|
3937
6038
|
await inspector.close();
|
|
3938
6039
|
const child = await testProcess;
|
|
3939
6040
|
return {
|
|
3940
|
-
|
|
3941
|
-
|
|
6041
|
+
result: {
|
|
6042
|
+
status: DryRunStatus.Error,
|
|
6043
|
+
errorMessage: formatInspectorConnectMessage(errorMsg, child, [syncServer.token])
|
|
6044
|
+
}
|
|
3942
6045
|
};
|
|
3943
6046
|
}
|
|
3944
6047
|
let drainSettleReason;
|
|
@@ -4003,11 +6106,11 @@ exit=%s timedOut=%s
|
|
|
4003
6106
|
});
|
|
4004
6107
|
const parsed = parseBunTestOutput(result.stdout, result.stderr);
|
|
4005
6108
|
markStep("outputParsed");
|
|
4006
|
-
const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
|
|
6109
|
+
const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy, [syncServer.token]);
|
|
4007
6110
|
if (earlyResult) {
|
|
4008
|
-
return earlyResult;
|
|
6111
|
+
return { result: earlyResult };
|
|
4009
6112
|
}
|
|
4010
|
-
return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, coverageAnalysis, profile);
|
|
6113
|
+
return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, { wasClosedUnexpectedly, closeInfo, duplicateFoundIdCount: collisionStats.duplicateFoundIdCount }, { coverageAnalysis, imported: list, coverageFile }, { command: spawned.command, cwd, syncToken: syncServer.token }, profile);
|
|
4011
6114
|
} finally {
|
|
4012
6115
|
abortController.abort();
|
|
4013
6116
|
if (this.currentAbortController === abortController) {
|
|
@@ -4025,8 +6128,8 @@ exit=%s timedOut=%s
|
|
|
4025
6128
|
this.logger.warn("Inspector data looks abnormal after the dry run: %s — test results may be incomplete; enable debug logging for the full drain/close/collision diagnostics", problems.join("; "));
|
|
4026
6129
|
}
|
|
4027
6130
|
}
|
|
4028
|
-
async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState,
|
|
4029
|
-
const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage } = await this.collectAndRemapCoverage(testHierarchy, executionOrder, profile);
|
|
6131
|
+
async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, inspectorState, run, spawnInfo, profile) {
|
|
6132
|
+
const { coverage: mutantCoverage, inspectorIdToProjectFile, coverageKeys, testFileCoverage, rawCoverage, counterKeyToTestName } = await this.collectAndRemapCoverage(run.coverageFile, testHierarchy, executionOrder, run.coverageAnalysis, profile);
|
|
4030
6133
|
profile?.at("coverageMapped");
|
|
4031
6134
|
const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, [...new Set(executionOrder)], parsed, totalElapsedMs, inspectorIdToProjectFile);
|
|
4032
6135
|
tests.sort((a, b) => a.name.localeCompare(b.name));
|
|
@@ -4040,30 +6143,38 @@ exit=%s timedOut=%s
|
|
|
4040
6143
|
resultTestIds: tests.map((t) => t.id),
|
|
4041
6144
|
duplicateFoundIdCount: inspectorState.duplicateFoundIdCount
|
|
4042
6145
|
};
|
|
4043
|
-
const
|
|
6146
|
+
const gateReasons = this.findCompletenessProblems(facts, parsed.summaryFailed, tests, result.stderr, run.imported, [spawnInfo.syncToken]);
|
|
4044
6147
|
profile?.at("gateChecked");
|
|
4045
|
-
if (
|
|
4046
|
-
|
|
6148
|
+
if (gateReasons.length > 0) {
|
|
6149
|
+
const outputLine = await this.saveFailedDryRunOutput(result, spawnInfo);
|
|
6150
|
+
return { result: this.completenessError(gateReasons, inspectorState.wasClosedUnexpectedly, inspectorState.closeInfo, outputLine) };
|
|
4047
6151
|
}
|
|
4048
|
-
const coverageResult = this.checkCoverageData(mutantCoverage, tests, coverageAnalysis, result.stderr);
|
|
6152
|
+
const coverageResult = this.checkCoverageData(mutantCoverage, tests, run.coverageAnalysis, result.stderr, run.coverageFile);
|
|
4049
6153
|
if (coverageResult) {
|
|
4050
|
-
return coverageResult;
|
|
6154
|
+
return { result: coverageResult };
|
|
6155
|
+
}
|
|
6156
|
+
const off = run.coverageAnalysis === "off";
|
|
6157
|
+
const complete = { status: DryRunStatus.Complete, tests };
|
|
6158
|
+
if (mutantCoverage !== undefined && !off) {
|
|
6159
|
+
complete.mutantCoverage = run.coverageAnalysis === "all" ? reachedOnly(mutantCoverage) : mutantCoverage;
|
|
4051
6160
|
}
|
|
4052
|
-
profile?.at("coverageChecked");
|
|
4053
|
-
await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage);
|
|
4054
|
-
profile?.at("registryWritten");
|
|
4055
|
-
this.warnOnUnidentifiedDryRunFailure(result, parsed, tests);
|
|
4056
|
-
this.warnOnTightDryRunTimeout(totalElapsedMs);
|
|
4057
6161
|
return {
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
6162
|
+
result: complete,
|
|
6163
|
+
publication: {
|
|
6164
|
+
tests,
|
|
6165
|
+
testNameIndex,
|
|
6166
|
+
testFileCoverage: off ? undefined : testFileCoverage,
|
|
6167
|
+
rawCoverage,
|
|
6168
|
+
testNames: counterKeyToTestName,
|
|
6169
|
+
processResult: result,
|
|
6170
|
+
parsed,
|
|
6171
|
+
totalElapsedMs
|
|
6172
|
+
}
|
|
4061
6173
|
};
|
|
4062
6174
|
}
|
|
4063
|
-
checkCoverageData(coverage, tests, coverageAnalysis, stderr) {
|
|
6175
|
+
checkCoverageData(coverage, tests, coverageAnalysis, stderr, coverageFile) {
|
|
4064
6176
|
const preloadLines = extractPreloadCoverageDiagnostics(stderr);
|
|
4065
|
-
|
|
4066
|
-
if (!coverageMissing || tests.some((t) => t.status === TestStatus.Failed)) {
|
|
6177
|
+
if (coverage !== undefined || tests.some((t) => t.status === TestStatus.Failed)) {
|
|
4067
6178
|
if (preloadLines.length > 0) {
|
|
4068
6179
|
this.logger.warn(`The coverage preload reported problems on the dry-run child's stderr:
|
|
4069
6180
|
%s`, preloadLines.join(`
|
|
@@ -4074,20 +6185,29 @@ exit=%s timedOut=%s
|
|
|
4074
6185
|
}
|
|
4075
6186
|
return null;
|
|
4076
6187
|
}
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
if (preloadLines.length > 0) {
|
|
4085
|
-
parts.push(`Coverage preload diagnostics from the child's stderr:
|
|
6188
|
+
return this.missingCoverageResult(coverageAnalysis, preloadLines, coverageFile);
|
|
6189
|
+
}
|
|
6190
|
+
missingCoverageResult(coverageAnalysis, preloadLines, coverageFile) {
|
|
6191
|
+
const file = coverageFile ?? "(none configured)";
|
|
6192
|
+
const coverageDir = coverageFile === undefined ? tmpdir2() : path15.dirname(coverageFile);
|
|
6193
|
+
const causes = "Likely causes: the coverage preload never ran (check for a [test].preload in bunfig.toml or bun.bunArgs that replaces or bypasses it), " + `${coverageDir} is not writable, or the bun test child exited before its final afterAll hook wrote the file (e.g. a test calls process.exit).`;
|
|
6194
|
+
const diagnostics = preloadLines.length > 0 ? [`Coverage preload diagnostics from the child's stderr:
|
|
4086
6195
|
${preloadLines.join(`
|
|
4087
|
-
`)}`
|
|
6196
|
+
`)}`] : [];
|
|
6197
|
+
if (coverageAnalysis === "off") {
|
|
6198
|
+
const what = `stryker-bun-runner: the dry run's record of which test file ran each test, ${file}, was missing, unreadable or empty, ` + "so each test is named after the file bun reports for it: a test that a shared helper file defines is credited to that file, not to the test file that ran it.";
|
|
6199
|
+
this.logger.warn("%s", [what, causes, ...diagnostics].join(" "));
|
|
6200
|
+
return null;
|
|
4088
6201
|
}
|
|
4089
|
-
const
|
|
4090
|
-
|
|
6202
|
+
const fails = coverageAnalysis === "perTest" || coverageAnalysis === "all";
|
|
6203
|
+
const what = `stryker-bun-runner: the dry run produced no mutant coverage data — the coverage file ${file} was missing, unreadable or empty. ` + "Without it Stryker runs the full test suite for every mutant, which is far slower than running each mutant's covering tests.";
|
|
6204
|
+
const message = [
|
|
6205
|
+
what,
|
|
6206
|
+
causes,
|
|
6207
|
+
...fails ? [`Failing the dry run because coverageAnalysis is '${coverageAnalysis}'; set coverageAnalysis to 'off' to run without coverage instead.`] : [],
|
|
6208
|
+
...diagnostics
|
|
6209
|
+
].join(" ");
|
|
6210
|
+
if (fails) {
|
|
4091
6211
|
this.logger.error("%s", message);
|
|
4092
6212
|
return { status: DryRunStatus.Error, errorMessage: message };
|
|
4093
6213
|
}
|
|
@@ -4099,7 +6219,7 @@ ${preloadLines.join(`
|
|
|
4099
6219
|
this.logger.warn("The dry run took %dms, more than 80%% of bun.timeout (%dms). bun.timeout bounds the dry run (mutant runs use Stryker's per-mutant timeout instead); a dry run that outgrows bun.timeout plus the drain-handshake allowance is killed — raise bun.timeout", elapsedMs, this.timeout);
|
|
4100
6220
|
}
|
|
4101
6221
|
}
|
|
4102
|
-
async buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage) {
|
|
6222
|
+
async buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaignInput) {
|
|
4103
6223
|
this.cachedTestNames = new Set(tests.map((t) => t.name));
|
|
4104
6224
|
if (tests.length !== this.cachedTestNames.size) {
|
|
4105
6225
|
const nameCount = new Map;
|
|
@@ -4125,27 +6245,85 @@ ${preloadLines.join(`
|
|
|
4125
6245
|
this.testFileDurations = sumDurationsByFile(tests);
|
|
4126
6246
|
this.logger.debug("Recorded dry-run durations for %d test file(s) to order mutant runs cheapest-first", this.testFileDurations.size);
|
|
4127
6247
|
this.setTestFileCoverage(testFileCoverage);
|
|
6248
|
+
this.timeoutCorrectionMs = campaignInput?.timeoutCorrectionMs;
|
|
6249
|
+
if (campaignInput !== undefined) {
|
|
6250
|
+
this.logger.debug("Mutant runs take %d ms off Stryker's per-mutant timeout for the dry run's extra work", campaignInput.timeoutCorrectionMs);
|
|
6251
|
+
}
|
|
6252
|
+
this.campaign = undefined;
|
|
4128
6253
|
try {
|
|
4129
|
-
const
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
|
|
6254
|
+
const indexes = { cachedTestNames: this.cachedTestNames, baseNameIndex: this.baseNameIndex, testNameIndex, testFileDurations: this.testFileDurations };
|
|
6255
|
+
await this.writeRegistry(indexes, testFileCoverage, campaignInput);
|
|
6256
|
+
return;
|
|
6257
|
+
} catch (error) {
|
|
6258
|
+
return this.registryWriteFailed(error, campaignInput);
|
|
6259
|
+
}
|
|
6260
|
+
}
|
|
6261
|
+
async registryWriteFailed(failure, campaignInput) {
|
|
6262
|
+
const watched = campaignInput?.watched.length ?? 0;
|
|
6263
|
+
if (watched > 0) {
|
|
6264
|
+
return failure instanceof WriteFailure ? unpublishedCampaignMessage(failure.file, failure.message, watched) : unpublishedCampaignMessage("the run's temporary directory", errorText(failure), watched);
|
|
6265
|
+
}
|
|
6266
|
+
if (campaignInput !== undefined && failure instanceof WriteFailure) {
|
|
6267
|
+
const registryPath = path15.join(path15.dirname(failure.file), REGISTRY_FILE);
|
|
6268
|
+
const earlier = await fsPromises3.lstat(registryPath).catch(() => {
|
|
6269
|
+
return;
|
|
4140
6270
|
});
|
|
4141
|
-
|
|
6271
|
+
if (earlier !== undefined) {
|
|
6272
|
+
return staleRegistryMessage(failure.file, failure.message, registryPath);
|
|
6273
|
+
}
|
|
6274
|
+
}
|
|
6275
|
+
this.warnRegistryWriteFailed(errorText(failure));
|
|
6276
|
+
return;
|
|
6277
|
+
}
|
|
6278
|
+
async writeRegistry(indexes, testFileCoverage, campaignInput) {
|
|
6279
|
+
const registryPath = await this.resolveRegistryPath();
|
|
6280
|
+
const runDir = path15.dirname(registryPath);
|
|
6281
|
+
const campaign = campaignInput === undefined ? undefined : await this.writeCampaignFiles(runDir, campaignInput);
|
|
6282
|
+
const tmpPath = `${registryPath}.tmp`;
|
|
6283
|
+
const registryData = JSON.stringify({
|
|
6284
|
+
version: 2,
|
|
6285
|
+
writtenAt: Date.now(),
|
|
6286
|
+
cachedTestNames: [...indexes.cachedTestNames],
|
|
6287
|
+
baseNameIndex: [...indexes.baseNameIndex.entries()],
|
|
6288
|
+
testNameIndex: [...indexes.testNameIndex.entries()],
|
|
6289
|
+
testFiles: this.selectedTestFilesFor(process.cwd()),
|
|
6290
|
+
testFileDurations: [...indexes.testFileDurations.entries()],
|
|
6291
|
+
mutantTestFiles: testFileCoverage?.toJSON(),
|
|
6292
|
+
timeoutCorrectionMs: campaignInput?.timeoutCorrectionMs,
|
|
6293
|
+
campaign
|
|
6294
|
+
});
|
|
6295
|
+
try {
|
|
6296
|
+
await writingTo(tmpPath, async () => writePrivateFile(tmpPath, registryData));
|
|
4142
6297
|
this.lastRegistryTmpPath = tmpPath;
|
|
4143
|
-
await
|
|
4144
|
-
this.lastRegistryTmpPath = undefined;
|
|
4145
|
-
this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, this.cachedTestNames.size);
|
|
6298
|
+
await writingTo(registryPath, async () => fsPromises3.rename(tmpPath, registryPath));
|
|
4146
6299
|
} catch (error) {
|
|
4147
|
-
|
|
6300
|
+
if (campaign?.watchListFile) {
|
|
6301
|
+
await removeQuietly(path15.join(runDir, campaign.watchListFile));
|
|
6302
|
+
}
|
|
6303
|
+
throw error;
|
|
4148
6304
|
}
|
|
6305
|
+
this.lastRegistryTmpPath = undefined;
|
|
6306
|
+
if (campaign !== undefined) {
|
|
6307
|
+
await removeQuietly(path15.join(runDir, ABORT_MARKER_FILE));
|
|
6308
|
+
this.campaign = { ...campaign, dir: runDir, watched: new Set(campaign.watchList) };
|
|
6309
|
+
}
|
|
6310
|
+
this.logger.debug("Wrote dryRun registry to %s (%d entries)", registryPath, indexes.cachedTestNames.size);
|
|
6311
|
+
}
|
|
6312
|
+
async writeCampaignFiles(runDir, campaignInput) {
|
|
6313
|
+
const { watched } = campaignInput;
|
|
6314
|
+
const generation = newGeneration();
|
|
6315
|
+
const watchListFile = watched.length === 0 ? null : watchListFileFor(generation);
|
|
6316
|
+
const campaign = {
|
|
6317
|
+
generation,
|
|
6318
|
+
watchList: [...watched],
|
|
6319
|
+
watchListFile,
|
|
6320
|
+
fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.eager)
|
|
6321
|
+
};
|
|
6322
|
+
if (watchListFile !== null) {
|
|
6323
|
+
const file = path15.join(runDir, watchListFile);
|
|
6324
|
+
await writingTo(file, async () => writeWatchList(file, watched));
|
|
6325
|
+
}
|
|
6326
|
+
return campaign;
|
|
4149
6327
|
}
|
|
4150
6328
|
warnRegistryWriteFailed(message) {
|
|
4151
6329
|
if (this.selectedTestFilesFor(process.cwd()) === undefined) {
|
|
@@ -4191,7 +6369,7 @@ ${preloadLines.join(`
|
|
|
4191
6369
|
this.logRandomizeOffOnce();
|
|
4192
6370
|
this.effectiveTestFiles = await this.getOrDiscoverTestFiles();
|
|
4193
6371
|
const strykerTimeoutMs = isUsableTimeout(options.timeout) ? options.timeout : undefined;
|
|
4194
|
-
const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(strykerTimeoutMs);
|
|
6372
|
+
const limitMs = strykerTimeoutMs === undefined ? this.timeout : limitFromStrykerTimeout(this.correctedStrykerTimeout(strykerTimeoutMs));
|
|
4195
6373
|
const sourceCoverage = this.ordersLikelyKillersFirst(options, filterIds.length) ? await this.sourceCoverageFor(options.sandboxFileName) : undefined;
|
|
4196
6374
|
const result = await this.executeMutantRun({
|
|
4197
6375
|
options,
|
|
@@ -4209,6 +6387,64 @@ ${preloadLines.join(`
|
|
|
4209
6387
|
profile?.finish(result.status);
|
|
4210
6388
|
return result;
|
|
4211
6389
|
}
|
|
6390
|
+
correctedStrykerTimeout(strykerTimeoutMs) {
|
|
6391
|
+
const corrected = correctStrykerTimeout(strykerTimeoutMs, this.timeoutCorrectionMs);
|
|
6392
|
+
if (!corrected.applied && !this.loggedUnusableCorrection) {
|
|
6393
|
+
this.loggedUnusableCorrection = true;
|
|
6394
|
+
this.logger.debug("No usable dry-run timeout correction (%s); mutant runs use Stryker's per-mutant timeout unchanged", String(this.timeoutCorrectionMs));
|
|
6395
|
+
}
|
|
6396
|
+
return corrected.timeoutMs;
|
|
6397
|
+
}
|
|
6398
|
+
watchListForMutantRuns() {
|
|
6399
|
+
const { campaign } = this;
|
|
6400
|
+
return campaign?.watchListFile ? path15.join(campaign.dir, campaign.watchListFile) : undefined;
|
|
6401
|
+
}
|
|
6402
|
+
async enforceWitness(stderr, hitLimitToken, ctx, testNamePattern) {
|
|
6403
|
+
const { campaign } = this;
|
|
6404
|
+
if (campaign === undefined) {
|
|
6405
|
+
return;
|
|
6406
|
+
}
|
|
6407
|
+
const problem = readWatchListProblem(stderr, hitLimitToken);
|
|
6408
|
+
if (problem !== undefined && !this.warnedWatchListProblem) {
|
|
6409
|
+
this.warnedWatchListProblem = true;
|
|
6410
|
+
this.logger.warn("A mutant run could not use its watch list (%s), so it could not check for files the dry run missed; its result stands. This warning is shown once.", displayError(problem));
|
|
6411
|
+
}
|
|
6412
|
+
const loaded = readWitnessReport(stderr, hitLimitToken, campaign.watched);
|
|
6413
|
+
if (loaded === undefined) {
|
|
6414
|
+
return;
|
|
6415
|
+
}
|
|
6416
|
+
const cwd = process.cwd();
|
|
6417
|
+
const files = loaded.map((file) => shownPath(file, cwd));
|
|
6418
|
+
const scope = this.witnessScope(ctx, testNamePattern);
|
|
6419
|
+
const message = witnessMessage({
|
|
6420
|
+
files,
|
|
6421
|
+
mutantId: ctx.options.activeMutant.id,
|
|
6422
|
+
scope: scope.text,
|
|
6423
|
+
incremental: this.incremental
|
|
6424
|
+
});
|
|
6425
|
+
const lists = [["the watched files found loaded", files]];
|
|
6426
|
+
if (scope.tests !== undefined) {
|
|
6427
|
+
lists.push(["the covering tests", scope.tests]);
|
|
6428
|
+
}
|
|
6429
|
+
this.logListed("error", message, lists);
|
|
6430
|
+
try {
|
|
6431
|
+
await writeAbortMarker(campaign.dir, { generation: campaign.generation, message });
|
|
6432
|
+
} catch (error) {
|
|
6433
|
+
this.logger.error("Could not write the abort marker in %s (%s): a worker Stryker starts in this one's place will not know the campaign was stopped", campaign.dir, errorText(error));
|
|
6434
|
+
}
|
|
6435
|
+
throw new Error(message);
|
|
6436
|
+
}
|
|
6437
|
+
witnessScope(ctx, testNamePattern) {
|
|
6438
|
+
if (ctx.testFileScope !== undefined) {
|
|
6439
|
+
return { text: `the tests of ${ctx.testFileScope.length} file(s) Stryker's testFiles option selected` };
|
|
6440
|
+
}
|
|
6441
|
+
if (testNamePattern === undefined) {
|
|
6442
|
+
return { text: ctx.coveringTestCount === 0 ? "the whole suite" : `the whole suite, in place of its ${ctx.coveringTestCount} covering test(s)` };
|
|
6443
|
+
}
|
|
6444
|
+
const ids = ctx.options.testFilter ?? [];
|
|
6445
|
+
const tests = ids.map((id) => displayName(id));
|
|
6446
|
+
return { text: `${tests.length} covering test(s): ${listText(tests)}`, tests };
|
|
6447
|
+
}
|
|
4212
6448
|
async resolveTestFileFilter(filter) {
|
|
4213
6449
|
if (filter.length === 0) {
|
|
4214
6450
|
return;
|
|
@@ -4221,7 +6457,7 @@ ${preloadLines.join(`
|
|
|
4221
6457
|
const cwd = process.cwd();
|
|
4222
6458
|
const exist = await Promise.all(entries.map(async (entry) => {
|
|
4223
6459
|
try {
|
|
4224
|
-
const stat = await
|
|
6460
|
+
const stat = await fsPromises3.stat(path15.resolve(cwd, entry));
|
|
4225
6461
|
return stat.isFile();
|
|
4226
6462
|
} catch {
|
|
4227
6463
|
return false;
|
|
@@ -4249,6 +6485,7 @@ ${preloadLines.join(`
|
|
|
4249
6485
|
activeMutant: options.activeMutant.id,
|
|
4250
6486
|
hitLimit: options.hitLimit,
|
|
4251
6487
|
hitLimitToken,
|
|
6488
|
+
watchList: this.watchListForMutantRuns(),
|
|
4252
6489
|
bail: !options.disableBail,
|
|
4253
6490
|
sequentialMode: true,
|
|
4254
6491
|
preloadScript: this.preloadScriptPath,
|
|
@@ -4269,6 +6506,7 @@ ${preloadLines.join(`
|
|
|
4269
6506
|
this.currentAbortController = undefined;
|
|
4270
6507
|
}
|
|
4271
6508
|
}
|
|
6509
|
+
await this.enforceWitness(result.stderr, hitLimitToken, ctx, testNamePattern);
|
|
4272
6510
|
const runawayResult = this.classifyRunawayMutantRun(result, ctx, testNamePattern, hitLimitToken);
|
|
4273
6511
|
if (runawayResult) {
|
|
4274
6512
|
return runawayResult;
|
|
@@ -4404,7 +6642,7 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
|
|
|
4404
6642
|
this.mutantWarnings.warn(MUTANT_WARN_KIND.earlyExit, mutantId, "Mutant %s: %s — scoring as Error rather than Survived", mutantId, errorMessage);
|
|
4405
6643
|
return { status: MutantRunStatus.Error, errorMessage };
|
|
4406
6644
|
}
|
|
4407
|
-
checkDryRunProcessResult(result, parsed, testHierarchy) {
|
|
6645
|
+
checkDryRunProcessResult(result, parsed, testHierarchy, secrets) {
|
|
4408
6646
|
if (result.timedOut) {
|
|
4409
6647
|
if (result.memoryLimitExceeded !== true) {
|
|
4410
6648
|
this.logger.warn("Dry run timed out: bun.timeout is %dms, and the dry-run child was killed at its %dms limit (bun.timeout plus the drain-handshake allowance) — raise bun.timeout above your full suite's run time", this.timeout, this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS);
|
|
@@ -4415,7 +6653,7 @@ ${result.stderr}`).trim().slice(-500) || "(no output)";
|
|
|
4415
6653
|
return {
|
|
4416
6654
|
status: DryRunStatus.Error,
|
|
4417
6655
|
errorMessage: `${formatSpawnErrorMessage(result.spawnError)}
|
|
4418
|
-
${result.stderr}`
|
|
6656
|
+
${cleanDiagnosticText(result.stderr, secrets)}`
|
|
4419
6657
|
};
|
|
4420
6658
|
}
|
|
4421
6659
|
if (result.exitCode !== 0 && parsed.failed === 0) {
|
|
@@ -4424,7 +6662,7 @@ ${result.stderr}`
|
|
|
4424
6662
|
if (failureDetails) {
|
|
4425
6663
|
messageParts.push(failureDetails);
|
|
4426
6664
|
}
|
|
4427
|
-
messageParts.push(result.stderr);
|
|
6665
|
+
messageParts.push(cleanDiagnosticText(result.stderr, secrets));
|
|
4428
6666
|
return {
|
|
4429
6667
|
status: DryRunStatus.Error,
|
|
4430
6668
|
errorMessage: messageParts.join(`
|
|
@@ -4465,51 +6703,103 @@ ${lines.join(`
|
|
|
4465
6703
|
%s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
|
|
4466
6704
|
}
|
|
4467
6705
|
}
|
|
4468
|
-
|
|
6706
|
+
async saveFailedDryRunOutput(result, spawnInfo) {
|
|
6707
|
+
const secrets = [spawnInfo.syncToken];
|
|
6708
|
+
const couldNotSave = (reason) => `Full output of the bun test process could not be saved: ${escapeControlCharacters(redactSecrets(reason, secrets))}.`;
|
|
6709
|
+
let timer;
|
|
6710
|
+
try {
|
|
6711
|
+
if (this.dryRunOutputFile === undefined) {
|
|
6712
|
+
return OUTPUT_FILE_HINT;
|
|
6713
|
+
}
|
|
6714
|
+
const abandon = new AbortController;
|
|
6715
|
+
const expired = new Promise((resolve) => {
|
|
6716
|
+
timer = setTimeout(() => {
|
|
6717
|
+
abandon.abort();
|
|
6718
|
+
resolve("expired");
|
|
6719
|
+
}, SAVE_TIME_LIMIT_MS);
|
|
6720
|
+
});
|
|
6721
|
+
const saved = await Promise.race([
|
|
6722
|
+
saveDryRunOutput(resolveAgainstProject(this.dryRunOutputFile), {
|
|
6723
|
+
stdout: result.stdout,
|
|
6724
|
+
stderr: result.stderr,
|
|
6725
|
+
command: spawnInfo.command,
|
|
6726
|
+
cwd: spawnInfo.cwd,
|
|
6727
|
+
bunVersion: this.bunVersion,
|
|
6728
|
+
exitCode: result.exitCode,
|
|
6729
|
+
signal: result.signal,
|
|
6730
|
+
outputIncomplete: result.outputIncomplete === true,
|
|
6731
|
+
secrets
|
|
6732
|
+
}, { signal: abandon.signal }),
|
|
6733
|
+
expired
|
|
6734
|
+
]);
|
|
6735
|
+
if (saved === "expired") {
|
|
6736
|
+
return couldNotSave(`saving took longer than ${SAVE_TIME_LIMIT_MS / 1000} seconds`);
|
|
6737
|
+
}
|
|
6738
|
+
return "path" in saved ? `Full output of the bun test process was saved to ${escapeControlCharacters(redactSecrets(saved.path, secrets))}.` : couldNotSave(saved.error);
|
|
6739
|
+
} catch (error) {
|
|
6740
|
+
return couldNotSave(errorText(error).replaceAll(/\s+/g, " ").trim());
|
|
6741
|
+
} finally {
|
|
6742
|
+
clearTimeout(timer);
|
|
6743
|
+
}
|
|
6744
|
+
}
|
|
6745
|
+
findCompletenessProblems(facts, summaryFailed, tests, stderr, eagerModules, secrets = []) {
|
|
4469
6746
|
if (tests.some((t) => t.status === TestStatus.Failed)) {
|
|
4470
|
-
return
|
|
6747
|
+
return [];
|
|
4471
6748
|
}
|
|
4472
6749
|
const reasons = findDryRunDataLoss(facts);
|
|
4473
6750
|
if (summaryFailed > 0) {
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
6751
|
+
const unattributed = `bun's console summary reported ${summaryFailed} failing test(s), but none of them could be attributed to an individual test`;
|
|
6752
|
+
const unhandled = describeUnhandledErrors(stderr, eagerModules, secrets);
|
|
6753
|
+
if (unhandled === undefined) {
|
|
6754
|
+
reasons.push(`${unattributed} — a whole spec file that fails to load (e.g. an unresolvable import) can produce this shape, ` + `but no "Unhandled error between tests" block was found in bun's stderr to say what happened. ` + `Last 500 chars of stderr:
|
|
6755
|
+
${cleanDiagnosticText(stderr, secrets).slice(-500)}`);
|
|
6756
|
+
} else {
|
|
6757
|
+
reasons.push(`${unattributed}. ${unhandled}`);
|
|
6758
|
+
}
|
|
4479
6759
|
}
|
|
6760
|
+
return reasons;
|
|
6761
|
+
}
|
|
6762
|
+
completenessError(problems, wasClosedUnexpectedly, closeInfo, outputLine) {
|
|
6763
|
+
const reasons = [...problems];
|
|
4480
6764
|
if (wasClosedUnexpectedly) {
|
|
4481
6765
|
const closeDetail = closeInfo.code === undefined ? "close code/reason not captured" : `close code=${closeInfo.code} reason=${JSON.stringify(closeInfo.reason ?? "")} wasClean=${String(closeInfo.wasClean)}, ${String(closeInfo.msFromLastFrameToClose)}ms after the last received frame`;
|
|
4482
6766
|
reasons.push(`the inspector WebSocket also closed unexpectedly (${closeDetail}), which is routine on its own and listed only as context`);
|
|
4483
6767
|
}
|
|
4484
|
-
const
|
|
6768
|
+
const joined = reasons.map((reason, position) => position < reasons.length - 1 && reason.endsWith(".") ? reason.slice(0, -1) : reason).join("; ");
|
|
6769
|
+
const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${joined}${joined.endsWith(".") ? "" : "."} Completing this dry run would hand Stryker test results or coverage that are silently ` + "missing or credited to the wrong tests, so it is reported as an error instead, and the test registry has NOT " + "been persisted. If a cause named above is in your test suite, fix it there; otherwise re-run the dry run, and " + "if this recurs, please report it at https://github.com/hughescr/stryker-bun-runner/issues with this message, " + `your bun version and a debug log (logLevel: 'debug').
|
|
6770
|
+
${outputLine}`;
|
|
4485
6771
|
this.logger.error("%s", errorMessage);
|
|
4486
6772
|
return {
|
|
4487
6773
|
status: DryRunStatus.Error,
|
|
4488
6774
|
errorMessage
|
|
4489
6775
|
};
|
|
4490
6776
|
}
|
|
4491
|
-
async collectAndRemapCoverage(testHierarchy, executionOrder, profile) {
|
|
6777
|
+
async collectAndRemapCoverage(coverageFile, testHierarchy, executionOrder, coverageAnalysis, profile) {
|
|
4492
6778
|
const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
|
|
4493
|
-
if (!
|
|
4494
|
-
return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
|
|
6779
|
+
if (!coverageFile) {
|
|
6780
|
+
return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
|
|
4495
6781
|
}
|
|
4496
6782
|
const [rawCoverage, lateHits] = await Promise.all([
|
|
4497
|
-
collectCoverage(
|
|
4498
|
-
collectLateHits(
|
|
6783
|
+
collectCoverage(coverageFile, this.logger),
|
|
6784
|
+
collectLateHits(coverageFile, this.logger)
|
|
4499
6785
|
]);
|
|
4500
6786
|
profile?.at("coverageRead");
|
|
4501
|
-
await cleanupCoverageFile(
|
|
6787
|
+
await cleanupCoverageFile(coverageFile);
|
|
4502
6788
|
if (!rawCoverage) {
|
|
4503
|
-
return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined };
|
|
6789
|
+
return { coverage: undefined, inspectorIdToProjectFile: new Map, coverageKeys: undefined, counterKeyToTestName: new Map };
|
|
4504
6790
|
}
|
|
4505
6791
|
const testFileCoverage = TestFileCoverage.fromPerTest(rawCoverage.perTest);
|
|
4506
6792
|
const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
|
|
4507
|
-
|
|
6793
|
+
if (coverageAnalysis !== "all" && coverageAnalysis !== "off") {
|
|
6794
|
+
this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
|
|
6795
|
+
}
|
|
4508
6796
|
return {
|
|
4509
6797
|
coverage,
|
|
4510
6798
|
inspectorIdToProjectFile,
|
|
4511
6799
|
coverageKeys: { keyCount: rawKeyCount, unmatchedKeyCount: orphanedKeyCount },
|
|
4512
|
-
testFileCoverage
|
|
6800
|
+
testFileCoverage,
|
|
6801
|
+
rawCoverage,
|
|
6802
|
+
counterKeyToTestName
|
|
4513
6803
|
};
|
|
4514
6804
|
}
|
|
4515
6805
|
emitCoverageBleedWarnings(lateHits, counterKeyToTestName) {
|
|
@@ -4622,7 +6912,7 @@ ${stderr.slice(-500)}`);
|
|
|
4622
6912
|
}
|
|
4623
6913
|
if (this.lastRegistryTmpPath) {
|
|
4624
6914
|
try {
|
|
4625
|
-
await
|
|
6915
|
+
await fsPromises3.unlink(this.lastRegistryTmpPath);
|
|
4626
6916
|
} catch (err) {
|
|
4627
6917
|
if (err.code !== "ENOENT") {
|
|
4628
6918
|
this.logger.debug("Failed to clean registry tmp file: %s", err instanceof Error ? err.message : String(err));
|
|
@@ -4632,9 +6922,9 @@ ${stderr.slice(-500)}`);
|
|
|
4632
6922
|
}
|
|
4633
6923
|
}
|
|
4634
6924
|
// src/checker-tsconfig.ts
|
|
4635
|
-
import { readFile as
|
|
6925
|
+
import { readFile as readFile7, rename as rename4, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
|
|
4636
6926
|
import { createRequire as createRequire2 } from "node:module";
|
|
4637
|
-
import
|
|
6927
|
+
import path16 from "node:path";
|
|
4638
6928
|
import { glob as glob2 } from "tinyglobby";
|
|
4639
6929
|
var DEFAULT_MUTATE_PATTERNS = ["{src,lib}/**"];
|
|
4640
6930
|
var MUTATION_RANGE_RE = /:\d+(?::\d+)?-\d+(?::\d+)?$/;
|
|
@@ -4644,7 +6934,7 @@ var LOG_PREFIX = "[Stryker] withTestFilesExcludedFromTypeCheck: ";
|
|
|
4644
6934
|
var MAX_QUOTED_ERRORS = 3;
|
|
4645
6935
|
function loadTypeScript(cwd) {
|
|
4646
6936
|
try {
|
|
4647
|
-
return createRequire2(
|
|
6937
|
+
return createRequire2(path16.join(cwd, "package.json"))("typescript");
|
|
4648
6938
|
} catch {
|
|
4649
6939
|
return;
|
|
4650
6940
|
}
|
|
@@ -4671,7 +6961,7 @@ async function findTestFiles(config, cwd) {
|
|
|
4671
6961
|
for (const relativeFiles of [await discoverTestFiles(cwd, undefined, sourceBunfig), bun.testFiles]) {
|
|
4672
6962
|
if (relativeFiles) {
|
|
4673
6963
|
for (const file of relativeFiles) {
|
|
4674
|
-
testFiles.add(
|
|
6964
|
+
testFiles.add(path16.resolve(cwd, file));
|
|
4675
6965
|
}
|
|
4676
6966
|
}
|
|
4677
6967
|
}
|
|
@@ -4714,7 +7004,7 @@ function findNewErrors(derived, original, testFiles) {
|
|
|
4714
7004
|
async function updateDerivedFile(derivedPath, shown, text) {
|
|
4715
7005
|
const temp = `${derivedPath}.${process.pid}.tmp`;
|
|
4716
7006
|
try {
|
|
4717
|
-
const existing = await
|
|
7007
|
+
const existing = await readFile7(derivedPath, "utf8").catch((error) => {
|
|
4718
7008
|
if (error.code === "ENOENT") {
|
|
4719
7009
|
return;
|
|
4720
7010
|
}
|
|
@@ -4727,10 +7017,10 @@ async function updateDerivedFile(derivedPath, shown, text) {
|
|
|
4727
7017
|
return `${shown} exists and was not generated by this helper (rename or delete it)`;
|
|
4728
7018
|
}
|
|
4729
7019
|
await writeFile2(temp, text);
|
|
4730
|
-
await
|
|
7020
|
+
await rename4(temp, derivedPath);
|
|
4731
7021
|
return;
|
|
4732
7022
|
} catch (error) {
|
|
4733
|
-
await
|
|
7023
|
+
await rm5(temp, { force: true });
|
|
4734
7024
|
return `cannot update ${shown}: ${error instanceof Error ? error.message : String(error)}`;
|
|
4735
7025
|
}
|
|
4736
7026
|
}
|
|
@@ -4749,12 +7039,12 @@ function derivedHeader(source) {
|
|
|
4749
7039
|
`);
|
|
4750
7040
|
}
|
|
4751
7041
|
function renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints) {
|
|
4752
|
-
const source =
|
|
7042
|
+
const source = path16.basename(sourcePath);
|
|
4753
7043
|
const body = {
|
|
4754
7044
|
extends: `./${source}`,
|
|
4755
7045
|
...project.options.declarationDir !== undefined && { compilerOptions: { declarationDir: null } },
|
|
4756
7046
|
include: [],
|
|
4757
|
-
files: entryPoints.map((file) =>
|
|
7047
|
+
files: entryPoints.map((file) => path16.relative(path16.dirname(derivedPath), file))
|
|
4758
7048
|
};
|
|
4759
7049
|
return `${derivedHeader(source)}${JSON.stringify(body, null, 2)}
|
|
4760
7050
|
`;
|
|
@@ -4768,8 +7058,8 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
|
|
|
4768
7058
|
if (!ts) {
|
|
4769
7059
|
return leaveUnchanged(config, `typescript cannot be loaded from ${cwd}; install it there`);
|
|
4770
7060
|
}
|
|
4771
|
-
const sourcePath =
|
|
4772
|
-
const shownSource =
|
|
7061
|
+
const sourcePath = path16.resolve(cwd, config.tsconfigFile ?? "tsconfig.json");
|
|
7062
|
+
const shownSource = path16.relative(cwd, sourcePath);
|
|
4773
7063
|
const read = readProject(ts, sourcePath, shownSource);
|
|
4774
7064
|
if ("problem" in read) {
|
|
4775
7065
|
return leaveUnchanged(config, read.problem);
|
|
@@ -4786,10 +7076,10 @@ async function withTestFilesExcludedFromTypeCheck(config, { cwd = process.cwd()
|
|
|
4786
7076
|
if (entryPoints.length === 0) {
|
|
4787
7077
|
return leaveUnchanged(config, `${shownSource} would have no files left once test files are excluded`);
|
|
4788
7078
|
}
|
|
4789
|
-
const derivedPath =
|
|
4790
|
-
const shownDerived =
|
|
7079
|
+
const derivedPath = path16.join(path16.dirname(sourcePath), `${path16.basename(sourcePath, ".json")}${DERIVED_SUFFIX}`);
|
|
7080
|
+
const shownDerived = path16.relative(cwd, derivedPath);
|
|
4791
7081
|
const text = renderDerivedTsconfig(sourcePath, derivedPath, project, entryPoints);
|
|
4792
|
-
const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys,
|
|
7082
|
+
const derivedProject = ts.parseJsonSourceFileConfigFileContent(ts.parseJsonText(derivedPath, text), ts.sys, path16.dirname(derivedPath), undefined, derivedPath);
|
|
4793
7083
|
const derived = createProgram(ts, derivedProject, original);
|
|
4794
7084
|
const newErrors = findNewErrors(derived, original, testFiles);
|
|
4795
7085
|
if (newErrors.length > 0) {
|
|
@@ -4883,6 +7173,31 @@ var strykerValidationSchema = {
|
|
|
4883
7173
|
minimum: 1,
|
|
4884
7174
|
description: "Maximum `bun test` spawn nesting depth before the runner refuses to spawn (default: 1). Guards against runaway recursion when a run spawned by this runner ends up spawning another one. Raise to 2 only if your own tests drive this runner.",
|
|
4885
7175
|
default: 1
|
|
7176
|
+
},
|
|
7177
|
+
dryRunOutputFile: {
|
|
7178
|
+
type: "string",
|
|
7179
|
+
minLength: 1,
|
|
7180
|
+
description: "A file to write the dry run's complete `bun test` output (stdout and stderr) to when the dry run's data-completeness check fails; without it nothing is written. A relative path resolves against the directory Stryker was started in, not the sandbox. The file is replaced by each failure and created with mode 0600. Colour codes, inspector addresses and this run's tokens are removed from it; anything else the tests print is saved as printed, so check it before sharing it."
|
|
7181
|
+
},
|
|
7182
|
+
alwaysImport: {
|
|
7183
|
+
description: "Files matched by mutate that the dry run imports before the tests even when no test loads them, so that their module-level code runs before any test. 'all' imports every file mutate matches, in one run of the tests. A list holds glob patterns, matched against the project-relative paths of the files mutate matches (dot paths included); a file is kept when any pattern matches it. Negated patterns (!...) are not supported. A pattern that matches none of those files is reported at warn.",
|
|
7184
|
+
oneOf: [
|
|
7185
|
+
{ type: "string", enum: ["all"] },
|
|
7186
|
+
{
|
|
7187
|
+
type: "array",
|
|
7188
|
+
items: {
|
|
7189
|
+
type: "string",
|
|
7190
|
+
minLength: 1,
|
|
7191
|
+
pattern: "^[^!]"
|
|
7192
|
+
}
|
|
7193
|
+
}
|
|
7194
|
+
]
|
|
7195
|
+
},
|
|
7196
|
+
importDiscovery: {
|
|
7197
|
+
type: "string",
|
|
7198
|
+
enum: ["scan", "run"],
|
|
7199
|
+
description: "How the dry run establishes which mutated files the tests load. 'scan' (default): the runner reads the imports of the test files and preloads, and runs the tests once when that settles it; otherwise it first observes a plain run of the tests. 'run': a plain run of the tests is always observed first, unless the files the tests import, with alwaysImport, already cover every mutated file.",
|
|
7200
|
+
default: "scan"
|
|
4886
7201
|
}
|
|
4887
7202
|
},
|
|
4888
7203
|
additionalProperties: false
|