@hughescr/stryker-bun-runner 1.7.0 → 1.7.2

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/dist/index.js CHANGED
@@ -1274,9 +1274,14 @@ import path6 from "node:path";
1274
1274
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1275
1275
  import { glob } from "tinyglobby";
1276
1276
 
1277
+ // src/utils/code-files.ts
1278
+ var CODE_EXTENSION_PATTERN = String.raw`(?:[jt]sx?|[mc][jt]s)`;
1279
+ var CODE_FILE_RE = new RegExp(String.raw`\.${CODE_EXTENSION_PATTERN}$`);
1280
+ var DECLARATION_FILE_RE = /\.d\.[mc]?ts$/;
1281
+
1277
1282
  // src/utils/test-name-pattern.ts
1278
1283
  var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
1279
- var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.(?:[jt]sx?|[mc][jt]s)`;
1284
+ var TEST_FILE_SUFFIX_PATTERN = String.raw`[._](?:test|spec)\.${CODE_EXTENSION_PATTERN}`;
1280
1285
  var TEST_FILE_SUFFIX_RE = new RegExp(`${TEST_FILE_SUFFIX_PATTERN}$`, "i");
1281
1286
  var dedupSuffixRe = / \[\d+\]$/;
1282
1287
  var metaRe = /[.*+?^${}()|[\]\\/]/g;
@@ -1336,13 +1341,24 @@ async function resolveEagerModulesFromGlobs(mutateGlobs, cwd = process.cwd()) {
1336
1341
  ignore: negativePatterns,
1337
1342
  expandDirectories: false
1338
1343
  });
1339
- const sourceFileRe = /\.(?:tsx?|[cm]?js)$/;
1340
- const dtsRe = /\.d\.[cm]?ts$/;
1341
- const filtered = paths.filter((p) => sourceFileRe.test(p) && !dtsRe.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1344
+ const filtered = paths.filter((p) => CODE_FILE_RE.test(p) && !DECLARATION_FILE_RE.test(p) && !TEST_FILE_SUFFIX_RE.test(p));
1342
1345
  const resolved = filtered.map((p) => path6.resolve(p));
1343
1346
  resolved.sort((a, b) => a.localeCompare(b));
1344
1347
  return resolved;
1345
1348
  }
1349
+ async function withoutSelectedTestFiles(eager, testFiles, resolve = realpath2) {
1350
+ if (testFiles.length === 0) {
1351
+ return { kept: [...eager], removed: [] };
1352
+ }
1353
+ const real = async (files) => Promise.all(files.map(async (file) => resolve(file).catch(() => file)));
1354
+ const [eagerReal, testReal] = await Promise.all([real(eager), real(testFiles)]);
1355
+ const tests = new Set([...testFiles, ...testReal]);
1356
+ const isTest = eager.map((file, index) => tests.has(file) || tests.has(eagerReal[index]));
1357
+ return {
1358
+ kept: eager.filter((_file, index) => !isTest[index]),
1359
+ removed: eager.filter((_file, index) => isTest[index])
1360
+ };
1361
+ }
1346
1362
  function resolvePreloadTemplate(moduleDir) {
1347
1363
  const isBundled = moduleDir.endsWith("dist") || moduleDir.includes("dist/");
1348
1364
  if (isBundled) {
@@ -1894,6 +1910,185 @@ function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger
1894
1910
  orphanedKeyCount: counterIds.length - creditedKeyCount
1895
1911
  };
1896
1912
  }
1913
+ // src/drain-handshake.ts
1914
+ var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
1915
+ var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
1916
+ var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
1917
+ var MAX_GAP_IDS_LISTED = 20;
1918
+
1919
+ class DrainWaitTimeoutError extends Error {
1920
+ reason;
1921
+ constructor(message, reason) {
1922
+ super(message);
1923
+ this.name = "DrainWaitTimeoutError";
1924
+ this.reason = reason;
1925
+ }
1926
+ }
1927
+
1928
+ class InspectorClosedError extends Error {
1929
+ }
1930
+ function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs) {
1931
+ const startedAt = Date.now();
1932
+ let timer;
1933
+ const promise = new Promise((_resolve, reject) => {
1934
+ timer = setInterval(() => {
1935
+ const sinceLastFrame = inspector.getMsSinceLastFrame();
1936
+ const totalElapsed = Date.now() - startedAt;
1937
+ if (totalElapsed >= absoluteCeilingMs) {
1938
+ reject(new DrainWaitTimeoutError(`${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
1939
+ } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
1940
+ reject(new DrainWaitTimeoutError(`${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
1941
+ }
1942
+ }, DRAIN_SILENCE_POLL_INTERVAL_MS);
1943
+ });
1944
+ return { promise, cancel: () => clearInterval(timer) };
1945
+ }
1946
+ function formatGapIdList(gaps) {
1947
+ if (gaps.length === 0) {
1948
+ return "";
1949
+ }
1950
+ const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
1951
+ return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
1952
+ }
1953
+ function isProof(reason) {
1954
+ return reason === "ack" || reason === "events";
1955
+ }
1956
+ var nothingToStop = () => {
1957
+ return;
1958
+ };
1959
+
1960
+ class DrainHandshake {
1961
+ inspector;
1962
+ logger;
1963
+ profile;
1964
+ silenceMs;
1965
+ settlements = [];
1966
+ rejection;
1967
+ requests = 0;
1968
+ dropped = 0;
1969
+ expectedStarts = 0;
1970
+ unprovenSince;
1971
+ constructor(inspector, logger, profile, silenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS) {
1972
+ this.inspector = inspector;
1973
+ this.logger = logger;
1974
+ this.profile = profile;
1975
+ this.silenceMs = silenceMs;
1976
+ }
1977
+ get proven() {
1978
+ return this.requests > 0 && this.dropped === 0 && this.settlements.length === this.requests && this.settlements.every((reason) => isProof(reason));
1979
+ }
1980
+ describe() {
1981
+ const served = this.describeServed();
1982
+ return this.dropped === 0 ? served : `${served}; ${this.dropped} dropped unserved`;
1983
+ }
1984
+ describeServed() {
1985
+ if (this.requests === 0) {
1986
+ return "never requested";
1987
+ }
1988
+ if (this.requests === 1) {
1989
+ return this.settlements.length === 1 ? `settled via ${this.settlements[0]}` : "requested, not settled";
1990
+ }
1991
+ const counts = new Map;
1992
+ for (const reason of this.settlements) {
1993
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
1994
+ }
1995
+ const unsettled = this.requests - this.settlements.length;
1996
+ if (unsettled > 0) {
1997
+ counts.set("not settled", unsettled);
1998
+ }
1999
+ const byReason = [...counts].map(([how, count]) => `${how} (${count})`);
2000
+ return `${this.requests} requests: ${byReason.join(", ")}`;
2001
+ }
2002
+ requestDropped(request) {
2003
+ this.dropped++;
2004
+ this.unprovenSince ??= "a drain request was dropped unserved";
2005
+ this.logger.debug("Drain request dropped unserved (its client went away first), with a count of %s: no later request of this launch can be proven from the test events", String(request.startedTests));
2006
+ }
2007
+ async handle(request) {
2008
+ const receivedAt = Date.now();
2009
+ this.profile?.at("drainRequest");
2010
+ this.requests++;
2011
+ const startedTests = request?.startedTests;
2012
+ this.expectedStarts = this.expectedStarts === undefined || startedTests === undefined ? undefined : this.expectedStarts + startedTests;
2013
+ const countsAtRequest = this.inspector.getEventCounts();
2014
+ const gapsAtRequest = this.inspector.getFoundIdGaps();
2015
+ this.logger.debug("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
2016
+ const reason = await this.prove();
2017
+ this.profile?.at("drainSettled");
2018
+ this.settlements.push(reason);
2019
+ if (!isProof(reason)) {
2020
+ this.unprovenSince ??= `drain-request ${this.requests} settled via ${reason}`;
2021
+ }
2022
+ this.inspector.startProgressWindow();
2023
+ const countsAtSettle = this.inspector.getEventCounts();
2024
+ const gapsAtSettle = this.inspector.getFoundIdGaps();
2025
+ this.logger.debug("Drain handler settled via %s after %dms; events during wait +%d/+%d/+%d found/start/end; found-id gaps %d -> %d%s", reason, Date.now() - receivedAt, countsAtSettle.found - countsAtRequest.found, countsAtSettle.start - countsAtRequest.start, countsAtSettle.end - countsAtRequest.end, gapsAtRequest.length, gapsAtSettle.length, isProof(reason) && gapsAtSettle.length > 0 ? ` — ${reason} resolved but gaps remain: the ${reason} may under-prove drain` : "");
2026
+ }
2027
+ async prove() {
2028
+ const first = this.requests === 1;
2029
+ const provable = this.unprovenSince === undefined;
2030
+ if (!first) {
2031
+ const progress = this.inspector.getTestProgress();
2032
+ this.logger.debug("Drain-request %d of this launch (bun evaluated the preload again, as --isolate does for each test file, and answers no inspector command after the first file): " + "%s: %s test start(s) expected, %d received, %d test(s) running, %d of %d test(s) found since the previous request without an end", this.requests, provable ? "proving it from the test events" : `not proving it from the test events, since ${this.unprovenSince}; waiting for the silence bound instead`, String(this.expectedStarts), progress.testStarts, progress.testsRunning, progress.unendedTests, progress.foundTests);
2033
+ if (provable && this.eventsProveDrain()) {
2034
+ return "events";
2035
+ }
2036
+ }
2037
+ const { promise: silence, cancel } = raceAgainstSilence(this.inspector, this.silenceMs, DRAIN_ACK_ABSOLUTE_CEILING_MS);
2038
+ const proof = first ? this.roundTrip() : this.waitForEvents(provable);
2039
+ try {
2040
+ return await Promise.race([proof.promise, silence]);
2041
+ } catch (error) {
2042
+ return this.giveUpReason(error);
2043
+ } finally {
2044
+ cancel();
2045
+ proof.stop();
2046
+ }
2047
+ }
2048
+ giveUpReason(error) {
2049
+ if (error instanceof DrainWaitTimeoutError) {
2050
+ this.logger.debug("Inspector drain wait gave up: %s", error.message);
2051
+ return error.reason;
2052
+ }
2053
+ if (error instanceof InspectorClosedError) {
2054
+ this.logger.debug("Inspector connection closed before the test events proved drain-request %d", this.requests);
2055
+ return "closed";
2056
+ }
2057
+ this.rejection = error instanceof Error ? error.message : String(error);
2058
+ this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", this.rejection);
2059
+ return "send-rejected";
2060
+ }
2061
+ roundTrip() {
2062
+ return {
2063
+ promise: this.inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000).then(() => "ack"),
2064
+ stop: nothingToStop
2065
+ };
2066
+ }
2067
+ waitForEvents(provable) {
2068
+ let stop = nothingToStop;
2069
+ const promise = new Promise((resolve, reject) => {
2070
+ const check = () => {
2071
+ if (provable && this.eventsProveDrain()) {
2072
+ resolve("events");
2073
+ } else if (this.inspector.hasClosed) {
2074
+ reject(new InspectorClosedError);
2075
+ }
2076
+ };
2077
+ stop = this.inspector.onProgress(check);
2078
+ check();
2079
+ });
2080
+ return { promise, stop: () => stop() };
2081
+ }
2082
+ eventsProveDrain() {
2083
+ const expected = this.expectedStarts;
2084
+ if (expected === undefined) {
2085
+ return false;
2086
+ }
2087
+ const progress = this.inspector.getTestProgress();
2088
+ return progress.testStarts >= expected && progress.testsRunning === 0 && progress.foundTests > 0 && progress.unendedTests === 0;
2089
+ }
2090
+ }
2091
+
1897
2092
  // src/inspector/types.ts
1898
2093
  var TEST_STATUSES = ["pass", "fail", "timeout", "skip", "todo", "skipped_because_label"];
1899
2094
  function isTestReporterFoundEvent(message) {
@@ -2034,6 +2229,10 @@ class InspectorClient {
2034
2229
  foundCount = 0;
2035
2230
  startCount = 0;
2036
2231
  endCount = 0;
2232
+ windowTests = 0;
2233
+ windowUnended = new Set;
2234
+ runningTests = new Set;
2235
+ progressListeners = new Set;
2037
2236
  closeCode = undefined;
2038
2237
  closeReason = undefined;
2039
2238
  closeWasClean = undefined;
@@ -2129,6 +2328,21 @@ class InspectorClient {
2129
2328
  this.ws.close();
2130
2329
  }
2131
2330
  this.ws = null;
2331
+ this.notifyProgress();
2332
+ }
2333
+ get hasClosed() {
2334
+ return this.wsClosed || this.isClosing;
2335
+ }
2336
+ onProgress(listener) {
2337
+ this.progressListeners.add(listener);
2338
+ return () => {
2339
+ this.progressListeners.delete(listener);
2340
+ };
2341
+ }
2342
+ notifyProgress() {
2343
+ for (const listener of this.progressListeners) {
2344
+ listener();
2345
+ }
2132
2346
  }
2133
2347
  expectClose() {
2134
2348
  this.closeExpected = true;
@@ -2176,6 +2390,18 @@ class InspectorClient {
2176
2390
  getEventCounts() {
2177
2391
  return { found: this.foundCount, start: this.startCount, end: this.endCount };
2178
2392
  }
2393
+ getTestProgress() {
2394
+ return {
2395
+ testStarts: this.executionOrder.length,
2396
+ testsRunning: this.runningTests.size,
2397
+ foundTests: this.windowTests,
2398
+ unendedTests: this.windowUnended.size
2399
+ };
2400
+ }
2401
+ startProgressWindow() {
2402
+ this.windowTests = 0;
2403
+ this.windowUnended.clear();
2404
+ }
2179
2405
  getCloseInfo() {
2180
2406
  return {
2181
2407
  code: this.closeCode,
@@ -2228,6 +2454,7 @@ class InspectorClient {
2228
2454
  } else if (isTestReporterEndEvent(message)) {
2229
2455
  this.handleTestEnd(message.params);
2230
2456
  }
2457
+ this.notifyProgress();
2231
2458
  } catch (error) {
2232
2459
  this.handleError(error instanceof Error ? error : new Error(String(error)));
2233
2460
  }
@@ -2246,6 +2473,10 @@ class InspectorClient {
2246
2473
  line: params.line
2247
2474
  };
2248
2475
  this.testHierarchy.set(params.id, testInfo);
2476
+ if (testInfo.type === "test") {
2477
+ this.windowTests++;
2478
+ this.windowUnended.add(testInfo);
2479
+ }
2249
2480
  if (this.handlers.onTestFound) {
2250
2481
  this.handlers.onTestFound(testInfo);
2251
2482
  }
@@ -2259,6 +2490,7 @@ class InspectorClient {
2259
2490
  }
2260
2491
  if (testInfo.type === "test") {
2261
2492
  this.executionOrder.push(params.id);
2493
+ this.runningTests.add(params.id);
2262
2494
  }
2263
2495
  if (this.handlers.onTestStart) {
2264
2496
  this.handlers.onTestStart(testInfo);
@@ -2271,6 +2503,8 @@ class InspectorClient {
2271
2503
  this.handleError(new Error(`Test end event for unknown test ID: ${params.id}`));
2272
2504
  return;
2273
2505
  }
2506
+ this.runningTests.delete(params.id);
2507
+ this.windowUnended.delete(testInfo);
2274
2508
  testInfo.status = params.status;
2275
2509
  testInfo.elapsed = params.elapsed;
2276
2510
  if (params.error) {
@@ -2313,6 +2547,7 @@ class InspectorClient {
2313
2547
  for (const finish of waiters) {
2314
2548
  finish();
2315
2549
  }
2550
+ this.notifyProgress();
2316
2551
  if (this.isClosing || this.closeExpected) {
2317
2552
  return;
2318
2553
  }
@@ -2343,1000 +2578,1002 @@ class InspectorClient {
2343
2578
  }
2344
2579
  }
2345
2580
  // src/parsers/console-parser.ts
2346
- import path9 from "node:path";
2347
-
2348
- // src/process-runner.ts
2349
- import { spawn as spawn3 } from "node:child_process";
2581
+ import path7 from "node:path";
2350
2582
 
2351
- // src/utils/process-group.ts
2352
- function killProcessGroup(pid, signal) {
2353
- try {
2354
- process.kill(-pid, signal);
2355
- return true;
2356
- } catch {
2357
- return false;
2358
- }
2583
+ // src/utils/strip-ansi.ts
2584
+ function stripAnsi(text) {
2585
+ return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
2359
2586
  }
2360
2587
 
2361
- // src/utils/process-rss.ts
2362
- import { spawn as spawn2 } from "node:child_process";
2363
- import { readFile as readFile4 } from "node:fs/promises";
2364
- async function getProcessRssBytes(pid) {
2365
- return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
2366
- }
2367
- function parseVmRss(statusContent) {
2368
- const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
2369
- return match ? Number(match[1]) * 1024 : null;
2370
- }
2371
- async function getLinuxRss(pid) {
2372
- try {
2373
- const status = await readFile4(`/proc/${pid}/status`, "utf8");
2374
- return parseVmRss(status);
2375
- } catch {
2376
- return null;
2377
- }
2588
+ // src/parsers/console-parser.ts
2589
+ var fileHeaderRe = new RegExp(String.raw`^(?:::group::)?([^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2590
+ var workflowCommandRe = /^::(?:group|endgroup|error|warning|notice|debug|add-mask|add-matcher|remove-matcher)(?:::|\s|$)/;
2591
+ function parseFilePath(line) {
2592
+ const fileMatch = fileHeaderRe.exec(line);
2593
+ return fileMatch ? fileMatch[1] : null;
2378
2594
  }
2379
- function parsePsRssOutput(output) {
2380
- const trimmed = output.trim();
2381
- if (trimmed === "") {
2382
- return null;
2595
+ function headerFilter(lines, testFiles) {
2596
+ if (testFiles === undefined) {
2597
+ return () => true;
2383
2598
  }
2384
- const kb = Number(trimmed);
2385
- return Number.isFinite(kb) ? kb * 1024 : null;
2386
- }
2387
- async function getPsRss(pid) {
2388
- return new Promise((resolve) => {
2389
- let child;
2390
- try {
2391
- child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
2392
- } catch {
2393
- resolve(null);
2394
- return;
2599
+ const roots = new Set(testFiles.map((file) => path7.resolve(file)));
2600
+ const isRunFile = (file) => {
2601
+ let candidate = path7.resolve(file);
2602
+ while (!roots.has(candidate)) {
2603
+ const parent = path7.dirname(candidate);
2604
+ if (parent === candidate) {
2605
+ return false;
2606
+ }
2607
+ candidate = parent;
2395
2608
  }
2396
- let output = "";
2397
- child.stdout.on("data", (data) => {
2398
- output += data.toString();
2399
- });
2400
- child.on("close", (code) => {
2401
- resolve(code === 0 ? parsePsRssOutput(output) : null);
2402
- });
2403
- child.on("error", () => {
2404
- resolve(null);
2405
- });
2609
+ return true;
2610
+ };
2611
+ const namesRunFile = lines.some((line) => {
2612
+ const file = parseFilePath(line);
2613
+ return file !== null && isRunFile(file);
2406
2614
  });
2615
+ return namesRunFile ? isRunFile : () => true;
2407
2616
  }
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;
2617
+ function isWorkflowCommandLine(line) {
2618
+ return workflowCommandRe.test(line);
2422
2619
  }
2423
- var projectDirectory = recordProjectDirectory();
2424
- function resolveAgainstProject(file) {
2425
- return path7.resolve(projectDirectory, file);
2620
+ var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2621
+ function buildTestName(testName, currentFile) {
2622
+ return currentFile ? `${currentFile} > ${testName}` : testName;
2426
2623
  }
2427
-
2428
- // src/utils/test-file-args.ts
2429
- import path8 from "node:path";
2430
- var MAX_TEST_FILE_ARGS_BYTES = 131072;
2431
- var ENTRY_OVERHEAD_BYTES = 1 + 8;
2432
- var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
2433
- function shortestSpelling(absolute, cwd) {
2434
- const relative = path8.relative(cwd, absolute);
2435
- if (relative === "" || relative === "..") {
2436
- return absolute;
2624
+ function parseTestLine(line, currentFile) {
2625
+ const passMatch = /^✓ +(\S.*?) \[([0-9.]+)ms\]$/.exec(line);
2626
+ if (passMatch) {
2627
+ return {
2628
+ test: {
2629
+ name: buildTestName(passMatch[1].trim(), currentFile),
2630
+ file: currentFile,
2631
+ status: "passed",
2632
+ duration: Number.parseFloat(passMatch[2])
2633
+ }
2634
+ };
2437
2635
  }
2438
- const spelled = relative.startsWith(`..${path8.sep}`) ? relative : `.${path8.sep}${relative}`;
2439
- return spelled.length < absolute.length ? spelled : absolute;
2440
- }
2441
- function computeTestFileArgs(files, cwd, budget) {
2442
- const absolute = files.map((file) => path8.resolve(cwd, file));
2443
- const absoluteBytes = bytesOf(absolute);
2444
- if (absoluteBytes <= budget) {
2445
- return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
2636
+ const failMatch = /^✗ +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2637
+ if (failMatch) {
2638
+ return {
2639
+ test: {
2640
+ name: buildTestName(failMatch[1].trim(), currentFile),
2641
+ file: currentFile,
2642
+ status: "failed",
2643
+ duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
2644
+ }
2645
+ };
2446
2646
  }
2447
- const relative = absolute.map((file) => shortestSpelling(file, cwd));
2448
- const relativeBytes = bytesOf(relative);
2449
- return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
2450
- }
2451
- function sameEntries(a, b) {
2452
- return a.length === b.length && a.every((entry, index) => entry === b[index]);
2453
- }
2454
- var lastBuild;
2455
- function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
2456
- if (!path8.isAbsolute(cwd)) {
2457
- return computeTestFileArgs(files, cwd, budget);
2647
+ const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2648
+ if (bailFailMatch) {
2649
+ return {
2650
+ test: {
2651
+ name: buildTestName(bailFailMatch[1].trim(), currentFile),
2652
+ file: currentFile,
2653
+ status: "failed",
2654
+ duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
2655
+ }
2656
+ };
2458
2657
  }
2459
- const cached = lastBuild;
2460
- if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
2461
- return { ...cached.result, args: [...cached.result.args] };
2658
+ const skipMatch = /^⏭ +(\S.*)$/.exec(line);
2659
+ if (skipMatch) {
2660
+ return {
2661
+ test: {
2662
+ name: buildTestName(skipMatch[1].trim(), currentFile),
2663
+ file: currentFile,
2664
+ status: "skipped"
2665
+ }
2666
+ };
2462
2667
  }
2463
- const result = computeTestFileArgs(files, cwd, budget);
2464
- lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
2465
- return result;
2668
+ return {};
2466
2669
  }
2467
-
2468
- // src/process-runner.ts
2469
- var KILL_GRACE_PERIOD_MS = 500;
2470
- var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
2471
- var LIFELINE_FD = 3;
2472
- var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
2473
- var DEFAULT_MAX_SPAWN_DEPTH = 1;
2474
- var PROFILE_ENV = "STRYKER_BUN_PROFILE";
2475
- function stripAnsi(text) {
2476
- return text.replaceAll(/\u001B\[[0-9;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/g, "");
2670
+ var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2671
+ var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2672
+ var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2673
+ var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2674
+ function capFailureMessage(message) {
2675
+ return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2676
+ … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2477
2677
  }
2478
- function readSpawnDepth(raw) {
2479
- const parsed = Number(raw);
2480
- return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
2678
+ function readFailureBlock(block) {
2679
+ const lines = block.filter((line) => !isWorkflowCommandLine(line));
2680
+ const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2681
+ const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2682
+ const text = lines.slice(Math.max(start, 0)).join(`
2683
+ `).trim();
2684
+ return { text: text === "" ? undefined : text, reported: start !== -1 };
2481
2685
  }
2482
- function stripBailArgs(bunArgs) {
2483
- const sanitized = [];
2484
- for (let i = 0;i < bunArgs.length; i++) {
2485
- const arg = bunArgs[i];
2486
- if (arg === "--bail" || arg.startsWith("--bail=")) {
2487
- if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
2488
- i += 1;
2489
- }
2490
- continue;
2491
- }
2492
- sanitized.push(arg);
2686
+ function failureMessageFrom(block, notes) {
2687
+ const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
2688
+ const parts = report === undefined ? notes : [report, ...notes];
2689
+ return parts.length === 0 ? undefined : parts.join(`
2690
+ `);
2691
+ }
2692
+ function setFailureMessage(test, block, notes) {
2693
+ const failureMessage = failureMessageFrom(block, notes);
2694
+ if (failureMessage !== undefined) {
2695
+ test.failureMessage = failureMessage;
2493
2696
  }
2494
- return sanitized;
2495
2697
  }
2496
- var liveChildren = new Set;
2497
- function killAllLiveChildren() {
2498
- for (const child of liveChildren) {
2499
- killProcessTree(child, "SIGKILL");
2698
+ function recordTest(reader, test, index) {
2699
+ if (test.status === "failed") {
2700
+ const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
2701
+ setFailureMessage(test, block, []);
2702
+ reader.lastFailed = { test, block, notes: [] };
2500
2703
  }
2501
- liveChildren.clear();
2704
+ reader.tests.push(test);
2705
+ reader.counters[test.status]++;
2706
+ reader.blockStart = index + 1;
2502
2707
  }
2503
- var CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2504
- var onCleanupSignal = (signal) => {
2505
- killAllLiveChildren();
2506
- removeSignalCleanup();
2507
- process.kill(process.pid, signal);
2508
- };
2509
- function ensureSignalCleanup() {
2510
- if (process.listeners(CLEANUP_SIGNALS[0]).includes(onCleanupSignal)) {
2511
- return false;
2708
+ function readLine(reader, index) {
2709
+ const line = reader.lines[index];
2710
+ const filePath = parseFilePath(line);
2711
+ if (filePath && reader.isHeaderFile(filePath)) {
2712
+ reader.currentFile = filePath;
2713
+ reader.blockStart = index + 1;
2714
+ reader.lastFailed = undefined;
2715
+ return;
2512
2716
  }
2513
- for (const s of CLEANUP_SIGNALS) {
2514
- process.on(s, onCleanupSignal);
2717
+ if (isWorkflowCommandLine(line)) {
2718
+ return;
2515
2719
  }
2516
- return true;
2517
- }
2518
- function removeSignalCleanup() {
2519
- for (const s of CLEANUP_SIGNALS) {
2520
- process.off(s, onCleanupSignal);
2720
+ if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
2721
+ const { test, block, notes } = reader.lastFailed;
2722
+ notes.push(line.trim());
2723
+ setFailureMessage(test, block, notes);
2724
+ reader.blockStart = index + 1;
2725
+ return;
2521
2726
  }
2522
- }
2523
- function killProcessTree(childProcess, signal) {
2524
- const pid = childProcess.pid;
2525
- if (pid === undefined || !killProcessGroup(pid, signal)) {
2526
- childProcess.kill(signal);
2527
- return false;
2727
+ reader.lastFailed = undefined;
2728
+ const { test } = parseTestLine(line, reader.currentFile);
2729
+ if (test) {
2730
+ recordTest(reader, test, index);
2731
+ } else if (NON_FAILING_RESULT_LINE.test(line)) {
2732
+ reader.blockStart = index + 1;
2528
2733
  }
2529
- return true;
2530
2734
  }
2531
- function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
2532
- const pid = childProcess.pid;
2533
- const signalledGroup = killProcessTree(childProcess, "SIGTERM");
2534
- let hasEscalated = false;
2535
- const escalationHandle = setTimeout(() => {
2536
- if (!isClosed()) {
2537
- hasEscalated = true;
2538
- killProcessTree(childProcess, "SIGKILL");
2735
+ var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
2736
+ var PASS_LINE = /^\s*\d+\s+pass\s*$/;
2737
+ var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
2738
+ var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
2739
+ function lastLineMatching(lines, from, pattern, stopAtBlank) {
2740
+ for (let index = from;index >= 0; index--) {
2741
+ const match = pattern.exec(lines[index]);
2742
+ if (match) {
2743
+ return { index, match };
2539
2744
  }
2540
- }, gracePeriodMs);
2541
- return () => {
2542
- clearTimeout(escalationHandle);
2543
- if (!hasEscalated && signalledGroup && pid !== undefined) {
2544
- hasEscalated = true;
2545
- killProcessGroup(pid, "SIGKILL");
2745
+ if (stopAtBlank && !lines[index].trim()) {
2746
+ return;
2546
2747
  }
2547
- };
2548
- }
2549
- async function runBunTests(options) {
2550
- const spawnDepth = readSpawnDepth(process.env[SPAWN_DEPTH_ENV]);
2551
- const maxSpawnDepth = options.maxSpawnDepth ?? DEFAULT_MAX_SPAWN_DEPTH;
2552
- if (!Number.isSafeInteger(maxSpawnDepth) || maxSpawnDepth < 1) {
2553
- return {
2554
- stdout: "",
2555
- stderr: `stryker-bun-runner: invalid maxSpawnDepth=${String(maxSpawnDepth)}; expected a positive integer.`,
2556
- exitCode: 1,
2557
- signal: null,
2558
- timedOut: false,
2559
- memoryLimitExceeded: false
2560
- };
2561
- }
2562
- if (spawnDepth >= maxSpawnDepth) {
2563
- return {
2564
- stdout: "",
2565
- stderr: `stryker-bun-runner: refusing to spawn \`bun test\` at nesting depth ${spawnDepth} (maxSpawnDepth=${maxSpawnDepth}). A test run spawned by this runner tried to spawn another one; this is almost always runaway recursion. See the bun.maxSpawnDepth option.`,
2566
- exitCode: 1,
2567
- signal: null,
2568
- timedOut: false,
2569
- memoryLimitExceeded: false
2570
- };
2571
2748
  }
2572
- return spawnBunTests(options, spawnDepth);
2749
+ return;
2573
2750
  }
2574
- function buildChildEnv(options, spawnDepth) {
2575
- const env = {
2576
- ...process.env,
2577
- ...options.env
2578
- };
2579
- const preloadVars = {
2580
- __STRYKER_ACTIVE_MUTANT__: options.activeMutant === "" ? undefined : options.activeMutant,
2581
- __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
2582
- __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
2583
- __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
2584
- [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
2585
- __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
2586
- [SYNC_TOKEN_ENV]: options.syncToken,
2587
- [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
2588
- [WATCH_LIST_ENV]: options.watchList,
2589
- [LIFELINE_FD_ENV]: String(LIFELINE_FD)
2751
+ function readBunSummary(output) {
2752
+ const lines = stripAnsi(output).split(`
2753
+ `);
2754
+ const lastIndex = lines.length - 1;
2755
+ const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
2756
+ const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
2757
+ const summary = {
2758
+ pass: 0,
2759
+ skip: 0,
2760
+ todo: 0,
2761
+ fail: 0,
2762
+ error: 0,
2763
+ ran: ran && Number.parseInt(ran.match[1], 10),
2764
+ bailed: undefined,
2765
+ printed: ran !== undefined || pass !== undefined
2590
2766
  };
2591
- for (const [name, value] of Object.entries(preloadVars)) {
2592
- if (value === undefined) {
2593
- delete env[name];
2594
- } else {
2595
- env[name] = value;
2767
+ if (pass) {
2768
+ for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
2769
+ const match = COUNT_LINE.exec(line);
2770
+ if (match) {
2771
+ summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
2772
+ }
2596
2773
  }
2597
2774
  }
2598
- env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
2599
- delete env[PROJECT_DIR_ENV];
2600
- if (options.profile) {
2601
- delete env[PROFILE_ENV];
2602
- }
2603
- if (options.profile && options.syncPort) {
2604
- env[PRELOAD_TIMINGS_ENV] = "1";
2605
- } else {
2606
- delete env[PRELOAD_TIMINGS_ENV];
2775
+ for (const line of lines.slice(ran?.index ?? 0)) {
2776
+ const match = BAIL_LINE.exec(line);
2777
+ if (match) {
2778
+ summary.bailed = Number.parseInt(match[1], 10);
2779
+ }
2607
2780
  }
2608
- return env;
2781
+ return summary;
2609
2782
  }
2610
- async function spawnBunTests(options, spawnDepth) {
2611
- const profile = options.profile;
2612
- profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
2613
- const args = ["test"];
2614
- if (options.inspect) {
2615
- args.push("--inspect=127.0.0.1:0");
2616
- }
2617
- if (options.bunfigPath) {
2618
- args.push(`--config=${options.bunfigPath}`);
2619
- }
2620
- if (options.preloadScript) {
2621
- args.push("--preload", options.preloadScript);
2622
- }
2623
- if (options.testNamePattern) {
2624
- args.push("--test-name-pattern", options.testNamePattern);
2625
- }
2626
- if (options.bail) {
2627
- args.push("--bail");
2628
- }
2629
- if (options.sequentialMode) {
2630
- args.push("--max-concurrency=1");
2631
- }
2632
- if (options.smol) {
2633
- args.push("--smol");
2783
+ function parseSummaryLines(output) {
2784
+ const bun = readBunSummary(output);
2785
+ const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
2786
+ if (bun.bailed !== undefined) {
2787
+ counts.failed = Math.max(counts.failed, bun.bailed);
2634
2788
  }
2635
- if (options.bunArgs && options.bunArgs.length > 0) {
2636
- args.push(...stripBailArgs(options.bunArgs));
2789
+ const genuinePassed = counts.passed;
2790
+ const genuineFailed = counts.failed;
2791
+ if (bun.ran !== undefined) {
2792
+ const totalParsed = counts.passed + counts.failed + counts.skipped;
2793
+ if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
2794
+ counts.passed = bun.ran;
2795
+ }
2637
2796
  }
2638
- if (options.testFiles && options.testFiles.length > 0) {
2639
- args.push(...buildTestFileArgs(options.testFiles).args);
2797
+ return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
2798
+ }
2799
+ function parseBunTestOutput(stdout, stderr, testFiles) {
2800
+ const tests = [];
2801
+ const counters = { passed: 0, failed: 0, skipped: 0 };
2802
+ const output = `${stdout}
2803
+ ${stderr}`;
2804
+ const lines = output.split(`
2805
+ `).map((line) => stripAnsi(line));
2806
+ const reader = {
2807
+ lines,
2808
+ isHeaderFile: headerFilter(lines, testFiles),
2809
+ tests,
2810
+ counters,
2811
+ currentFile: undefined,
2812
+ blockStart: 0,
2813
+ lastFailed: undefined
2814
+ };
2815
+ for (const index of lines.keys()) {
2816
+ readLine(reader, index);
2640
2817
  }
2641
- const env = buildChildEnv(options, spawnDepth);
2642
- return new Promise((resolve) => {
2643
- const stdoutChunks = [];
2644
- const stderrChunks = [];
2645
- let timedOut = false;
2646
- let processKilled = false;
2647
- let memoryLimitExceeded = false;
2648
- let hasClosed = false;
2649
- let rssIntervalHandle;
2650
- let stdioCloseHandle;
2651
- let onLeaderExitDuringTermination;
2652
- let onAbort;
2653
- if (options.signal?.aborted) {
2654
- resolve({ stdout: "", stderr: "", exitCode: null, signal: null, timedOut: true, memoryLimitExceeded: false });
2655
- return;
2656
- }
2657
- const spawnOpts = {
2658
- env,
2659
- stdio: ["ignore", "pipe", "pipe", "pipe"],
2660
- cwd: process.cwd(),
2661
- detached: true
2662
- };
2663
- try {
2664
- options.onSpawn?.([options.bunPath, ...args]);
2665
- } catch {}
2666
- const childProcess = spawn3(options.bunPath, args, spawnOpts);
2667
- profile?.mark("spawned");
2668
- liveChildren.add(childProcess);
2669
- ensureSignalCleanup();
2670
- const beginTermination = () => {
2671
- if (processKilled) {
2672
- return false;
2673
- }
2674
- processKilled = true;
2675
- timedOut = true;
2676
- onLeaderExitDuringTermination = killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
2677
- return true;
2678
- };
2679
- const timeoutHandle = setTimeout(() => {
2680
- beginTermination();
2681
- }, options.timeout);
2682
- if (options.signal) {
2683
- onAbort = () => {
2684
- beginTermination();
2685
- };
2686
- options.signal.addEventListener("abort", onAbort, { once: true });
2687
- }
2688
- if (options.maxChildRss !== undefined) {
2689
- const rssLimit = options.maxChildRss;
2690
- const checkMemoryCeiling = async () => {
2691
- if (hasClosed || processKilled) {
2692
- return;
2693
- }
2694
- const pid = childProcess.pid;
2695
- if (pid === undefined) {
2696
- return;
2697
- }
2698
- const rssBytes = await getProcessRssBytes(pid);
2699
- if (rssBytes === null || hasClosed) {
2700
- return;
2701
- }
2702
- if (rssBytes > rssLimit) {
2703
- if (!beginTermination()) {
2704
- return;
2705
- }
2706
- memoryLimitExceeded = true;
2707
- if (rssIntervalHandle) {
2708
- clearInterval(rssIntervalHandle);
2709
- }
2710
- options.onMemoryLimitExceeded?.(rssBytes);
2711
- }
2712
- };
2713
- rssIntervalHandle = setInterval(() => {
2714
- checkMemoryCeiling();
2715
- }, options.rssCheckIntervalMs ?? 1000);
2716
- rssIntervalHandle.unref();
2717
- }
2718
- if (childProcess.stdout) {
2719
- childProcess.stdout.on("data", (data) => {
2720
- stdoutChunks.push(data);
2721
- });
2722
- }
2723
- let inspectorUrlExtracted = false;
2724
- if (childProcess.stderr) {
2725
- childProcess.stderr.on("data", (data) => {
2726
- stderrChunks.push(data);
2727
- profile?.onStderr(data);
2728
- if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
2729
- const text = Buffer.concat(stderrChunks).toString();
2730
- const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
2731
- if (match) {
2732
- inspectorUrlExtracted = true;
2733
- options.onInspectorReady(match[1]);
2734
- }
2735
- }
2736
- });
2737
- }
2738
- const release = () => {
2739
- liveChildren.delete(childProcess);
2740
- clearTimeout(timeoutHandle);
2741
- clearTimeout(stdioCloseHandle);
2742
- if (options.signal && onAbort) {
2743
- options.signal.removeEventListener("abort", onAbort);
2744
- }
2745
- if (rssIntervalHandle) {
2746
- clearInterval(rssIntervalHandle);
2747
- }
2748
- };
2749
- childProcess.on("exit", (code, signal) => {
2750
- profile?.mark("exit");
2751
- onLeaderExitDuringTermination?.();
2752
- stdioCloseHandle = setTimeout(() => {
2753
- release();
2754
- resolve({
2755
- stdout: Buffer.concat(stdoutChunks).toString(),
2756
- stderr: Buffer.concat(stderrChunks).toString(),
2757
- exitCode: processKilled ? null : code,
2758
- signal: signal ?? null,
2759
- timedOut,
2760
- memoryLimitExceeded,
2761
- outputIncomplete: true
2762
- });
2763
- }, STDIO_CLOSE_GRACE_MS);
2764
- });
2765
- childProcess.on("close", (code, signal) => {
2766
- profile?.mark("close");
2767
- hasClosed = true;
2768
- onLeaderExitDuringTermination?.();
2769
- release();
2770
- resolve({
2771
- stdout: Buffer.concat(stdoutChunks).toString(),
2772
- stderr: Buffer.concat(stderrChunks).toString(),
2773
- exitCode: processKilled ? null : code,
2774
- signal: signal ?? null,
2775
- timedOut,
2776
- memoryLimitExceeded
2777
- });
2778
- });
2779
- childProcess.on("error", (error) => {
2780
- profile?.mark("close");
2781
- hasClosed = true;
2782
- onLeaderExitDuringTermination?.();
2783
- release();
2784
- const stderrOutput = Buffer.concat(stderrChunks).toString();
2785
- resolve({
2786
- stdout: Buffer.concat(stdoutChunks).toString(),
2787
- stderr: `${stderrOutput}
2788
- Process error: ${error.message}`,
2789
- exitCode: null,
2790
- signal: null,
2791
- timedOut,
2792
- memoryLimitExceeded,
2793
- spawnError: error.message
2794
- });
2795
- });
2796
- });
2818
+ const summaryCounts = parseSummaryLines(output);
2819
+ counters.passed = Math.max(counters.passed, summaryCounts.passed);
2820
+ counters.failed = Math.max(counters.failed, summaryCounts.failed);
2821
+ counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
2822
+ return {
2823
+ tests,
2824
+ totalTests: counters.passed + counters.failed + counters.skipped,
2825
+ passed: counters.passed,
2826
+ failed: counters.failed,
2827
+ skipped: counters.skipped,
2828
+ summaryPassed: summaryCounts.genuinePassed,
2829
+ summaryFailed: summaryCounts.genuineFailed,
2830
+ summarySkipped: summaryCounts.skipped,
2831
+ summaryTodo: summaryCounts.todo,
2832
+ summaryErrors: summaryCounts.errors,
2833
+ summaryPrinted: summaryCounts.printed
2834
+ };
2797
2835
  }
2798
2836
 
2799
- // src/parsers/console-parser.ts
2800
- var fileHeaderRe = new RegExp(String.raw`^(?:::group::)?([^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2801
- var workflowCommandRe = /^::(?:group|endgroup|error|warning|notice|debug|add-mask|add-matcher|remove-matcher)(?:::|\s|$)/;
2802
- function parseFilePath(line) {
2803
- const fileMatch = fileHeaderRe.exec(line);
2804
- return fileMatch ? fileMatch[1] : null;
2837
+ // src/parsers/unhandled-errors.ts
2838
+ var MAX_BLOCKS_SHOWN = 20;
2839
+ var MAX_DIAGNOSTIC_CHARS = 16000;
2840
+ var MAX_SNIPPET_LINE_CHARS = 300;
2841
+ var MAX_NAMED = 3;
2842
+ var MAX_NAME_CHARS = 200;
2843
+ var BLOCK_MARKER = "# Unhandled error between tests";
2844
+ var BLOCK_RULE = "-".repeat(31);
2845
+ var LATE_CALL_RE = /^error: Cannot call ([\w$.]+)\(\) after the test run has completed\.?$/;
2846
+ var FILE_HEADER_RE = new RegExp(String.raw`^(?:::group::)?((?:[a-z]:)?[^:]+${TEST_FILE_SUFFIX_PATTERN}):$`, "i");
2847
+ var FRAME_LOCATION_RE = /^(.+):\d+:\d+$/;
2848
+ var SNIPPET_LINE_RE = /^\s*\d+ \|/;
2849
+ var SNIPPET_CARET_RE = /^\s*\^+$/;
2850
+ var isDrivePath = (path) => /^[a-z]:[\\/]/i.test(path);
2851
+ function pathKey(path) {
2852
+ return isDrivePath(path) ? `${path.charAt(0).toLowerCase()}${path.slice(1).replaceAll("\\", "/")}` : path;
2805
2853
  }
2806
- function headerFilter(lines, testFiles) {
2807
- if (testFiles === undefined) {
2808
- return () => true;
2854
+ function percentDecode(text) {
2855
+ try {
2856
+ return decodeURIComponent(text);
2857
+ } catch {
2858
+ return text;
2809
2859
  }
2810
- const roots = new Set(testFiles.map((file) => path9.resolve(file)));
2811
- const isRunFile = (file) => {
2812
- let candidate = path9.resolve(file);
2813
- while (!roots.has(candidate)) {
2814
- const parent = path9.dirname(candidate);
2815
- if (parent === candidate) {
2816
- return false;
2817
- }
2818
- candidate = parent;
2819
- }
2820
- return true;
2821
- };
2822
- const namesRunFile = lines.some((line) => {
2823
- const file = parseFilePath(line);
2824
- return file !== null && isRunFile(file);
2825
- });
2826
- return namesRunFile ? isRunFile : () => true;
2827
- }
2828
- function isWorkflowCommandLine(line) {
2829
- return workflowCommandRe.test(line);
2830
2860
  }
2831
- var MAX_FAILURE_MESSAGE_LENGTH = 4000;
2832
- function buildTestName(testName, currentFile) {
2833
- return currentFile ? `${currentFile} > ${testName}` : testName;
2861
+ function locationPath(location) {
2862
+ if (/^file:\/\//i.test(location)) {
2863
+ const path = percentDecode(location.slice("file://".length).replace(/^localhost(?=\/)/i, "").replace(/\?.*/s, ""));
2864
+ return /^\/[a-z]:[\\/]/i.test(path) ? path.slice(1) : path;
2865
+ }
2866
+ return /^[a-z][\w+.-]+:/i.test(location) && !isDrivePath(location) ? undefined : location;
2834
2867
  }
2835
- function parseTestLine(line, currentFile) {
2836
- const passMatch = /^✓ +(\S.*?) \[([0-9.]+)ms\]$/.exec(line);
2837
- if (passMatch) {
2838
- return {
2839
- test: {
2840
- name: buildTestName(passMatch[1].trim(), currentFile),
2841
- file: currentFile,
2842
- status: "passed",
2843
- duration: Number.parseFloat(passMatch[2])
2844
- }
2845
- };
2868
+ function frameFile(line) {
2869
+ const trimmed = line.trim();
2870
+ if (!trimmed.startsWith("at ")) {
2871
+ return;
2846
2872
  }
2847
- const failMatch = /^✗ +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2848
- if (failMatch) {
2849
- return {
2850
- test: {
2851
- name: buildTestName(failMatch[1].trim(), currentFile),
2852
- file: currentFile,
2853
- status: "failed",
2854
- duration: failMatch[2] ? Number.parseFloat(failMatch[2]) : undefined
2855
- }
2856
- };
2873
+ let location = trimmed.slice(3).trim();
2874
+ const open = location.lastIndexOf(" (");
2875
+ if (open !== -1 && location.endsWith(")")) {
2876
+ location = location.slice(open + 2, -1);
2857
2877
  }
2858
- const bailFailMatch = /^\(fail\) +(\S.*?)(?: \[([0-9.]+)ms\])?$/.exec(line);
2859
- if (bailFailMatch) {
2860
- return {
2861
- test: {
2862
- name: buildTestName(bailFailMatch[1].trim(), currentFile),
2863
- file: currentFile,
2864
- status: "failed",
2865
- duration: bailFailMatch[2] ? Number.parseFloat(bailFailMatch[2]) : undefined
2866
- }
2867
- };
2878
+ const file = FRAME_LOCATION_RE.exec(location)?.[1];
2879
+ return file === undefined ? undefined : locationPath(file);
2880
+ }
2881
+ function buildBlock(printed, headerFile) {
2882
+ const body = printed.slice(printed.findIndex((line) => line !== ""), printed.findLastIndex((line) => line !== "") + 1);
2883
+ const errorLine = body.find((line) => line.startsWith("error: "));
2884
+ return {
2885
+ headerFile,
2886
+ lines: body,
2887
+ frames: body.flatMap((line) => {
2888
+ const path = frameFile(line);
2889
+ return path === undefined ? [] : [{ path, line }];
2890
+ }),
2891
+ lateCall: errorLine === undefined ? undefined : LATE_CALL_RE.exec(errorLine)?.[1]
2892
+ };
2893
+ }
2894
+ function parseUnhandledErrorBlocks(stderr, secrets = []) {
2895
+ const lines = cleanDiagnosticText(stderr, secrets).split(/\r?\n/).map((line) => line.trimEnd());
2896
+ const starts = lines.flatMap((line, i) => line === BLOCK_MARKER && lines[i + 1] === BLOCK_RULE ? [i] : []);
2897
+ const blocks = [];
2898
+ let headerFile;
2899
+ let scanned = 0;
2900
+ for (const [n, start] of starts.entries()) {
2901
+ for (const line of lines.slice(scanned, start)) {
2902
+ headerFile = FILE_HEADER_RE.exec(line)?.[1] ?? headerFile;
2903
+ }
2904
+ const following = lines.slice(start + 2, starts[n + 1] ?? lines.length);
2905
+ const closingRule = following.indexOf(BLOCK_RULE);
2906
+ blocks.push(buildBlock(closingRule === -1 ? following : following.slice(0, closingRule), headerFile));
2907
+ scanned = closingRule === -1 ? start + 2 + following.length : start + 2 + closingRule + 1;
2868
2908
  }
2869
- const skipMatch = /^⏭ +(\S.*)$/.exec(line);
2870
- if (skipMatch) {
2871
- return {
2872
- test: {
2873
- name: buildTestName(skipMatch[1].trim(), currentFile),
2874
- file: currentFile,
2875
- status: "skipped"
2876
- }
2877
- };
2909
+ return blocks;
2910
+ }
2911
+ var isSnippetLine = (line) => SNIPPET_LINE_RE.test(line) || SNIPPET_CARET_RE.test(line);
2912
+ function renderBlock(block, index, total) {
2913
+ const heading = ` Unhandled error block ${index + 1} of ${total}:`;
2914
+ if (block.lines.length === 0) {
2915
+ const empty = `${heading}
2916
+ (empty)`;
2917
+ return { full: empty, bare: empty };
2878
2918
  }
2879
- return {};
2919
+ const full = [];
2920
+ const bare = [];
2921
+ let omittedRun = 0;
2922
+ const endRun = () => {
2923
+ if (omittedRun > 0) {
2924
+ bare.push(` ... [${omittedRun} source line(s) omitted]`);
2925
+ omittedRun = 0;
2926
+ }
2927
+ };
2928
+ for (const line of block.lines) {
2929
+ if (isSnippetLine(line)) {
2930
+ omittedRun++;
2931
+ 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}`);
2932
+ } else {
2933
+ endRun();
2934
+ full.push(` ${line}`);
2935
+ bare.push(` ${line}`);
2936
+ }
2937
+ }
2938
+ endRun();
2939
+ return { full: [heading, ...full].join(`
2940
+ `), bare: [heading, ...bare].join(`
2941
+ `) };
2942
+ }
2943
+ function nameOf(text, secrets) {
2944
+ const redacted = redactSecrets(text, secrets);
2945
+ return redacted.length > MAX_NAME_CHARS ? `${redacted.slice(0, MAX_NAME_CHARS)}... [${redacted.length - MAX_NAME_CHARS} more character(s) omitted]` : redacted;
2946
+ }
2947
+ function nameList(names) {
2948
+ const shown = names.slice(0, MAX_NAMED).join(", ");
2949
+ return names.length > MAX_NAMED ? `${shown} and ${names.length - MAX_NAMED} more` : shown;
2880
2950
  }
2881
- var NON_FAILING_RESULT_LINE = /^(?:\((?:pass|skip|todo)\)|[✓»✎⏭]) +\S/;
2882
- var CODE_FRAME_LINE = /^\s*\d+ \|(?: |$)/;
2883
- var ERROR_HEADING_LINE = /^(?:error|\w*Error)(?: \[[^\]]*\])?: /;
2884
- var AFTER_FAIL_NOTE_LINE = /^\s+\^ \S/;
2885
- function capFailureMessage(message) {
2886
- return message.length > MAX_FAILURE_MESSAGE_LENGTH ? `${message.slice(0, MAX_FAILURE_MESSAGE_LENGTH)}
2887
- … (${message.length - MAX_FAILURE_MESSAGE_LENGTH} more characters)` : message;
2951
+ function matchesHeader(framePath, header) {
2952
+ const frame = pathKey(framePath);
2953
+ const wanted = pathKey(header).replace(/^\.\//, "");
2954
+ return frame === wanted || frame.endsWith(`/${wanted}`);
2888
2955
  }
2889
- function readFailureBlock(block) {
2890
- const lines = block.filter((line) => !isWorkflowCommandLine(line));
2891
- const frameStart = lines.findIndex((line) => CODE_FRAME_LINE.test(line));
2892
- const start = frameStart === -1 ? lines.findIndex((line) => ERROR_HEADING_LINE.test(line)) : frameStart;
2893
- const text = lines.slice(Math.max(start, 0)).join(`
2894
- `).trim();
2895
- return { text: text === "" ? undefined : text, reported: start !== -1 };
2956
+ function testFileFrame(block) {
2957
+ const { headerFile, frames } = block;
2958
+ const inEffect = headerFile === undefined ? undefined : frames.find((frame) => matchesHeader(frame.path, headerFile));
2959
+ return inEffect ?? frames.find((frame) => TEST_FILE_SUFFIX_RE.test(frame.path));
2896
2960
  }
2897
- function failureMessageFrom(block, notes) {
2898
- const report = block.text !== undefined && (block.reported || notes.length === 0) ? capFailureMessage(block.text) : undefined;
2899
- const parts = report === undefined ? notes : [report, ...notes];
2900
- return parts.length === 0 ? undefined : parts.join(`
2901
- `);
2961
+ function lateCalls(blocks, secrets) {
2962
+ const seen = new Set;
2963
+ return blocks.flatMap((block, index) => {
2964
+ if (block.lateCall === undefined) {
2965
+ return [];
2966
+ }
2967
+ const frame = testFileFrame(block);
2968
+ const header = block.headerFile === undefined ? undefined : nameOf(block.headerFile, secrets);
2969
+ const call = nameOf(block.lateCall, secrets);
2970
+ const key = `${call}\x00${frame?.path ?? ""}\x00${frame === undefined ? header ?? "" : ""}`;
2971
+ if (seen.has(key)) {
2972
+ return [];
2973
+ }
2974
+ seen.add(key);
2975
+ return [{ call, block: index, header, frame: frame === undefined ? undefined : { block: index, name: nameOf(frame.path, secrets), line: frame.line } }];
2976
+ });
2902
2977
  }
2903
- function setFailureMessage(test, block, notes) {
2904
- const failureMessage = failureMessageFrom(block, notes);
2905
- if (failureMessage !== undefined) {
2906
- test.failureMessage = failureMessage;
2907
- }
2978
+ function eagerClaims(blocks, eagerModules, secrets) {
2979
+ const eagerByKey = new Map(eagerModules.map((module) => [pathKey(module), module]));
2980
+ const seen = new Set;
2981
+ return blocks.flatMap((block, index) => block.lateCall === undefined ? block.frames.flatMap((frame) => {
2982
+ const module = eagerByKey.get(pathKey(frame.path));
2983
+ if (module === undefined || seen.has(module)) {
2984
+ return [];
2985
+ }
2986
+ seen.add(module);
2987
+ return [{ block: index, name: nameOf(module, secrets), line: frame.line }];
2988
+ }) : []);
2908
2989
  }
2909
- function recordTest(reader, test, index) {
2910
- if (test.status === "failed") {
2911
- const block = readFailureBlock(reader.lines.slice(reader.blockStart, index));
2912
- setFailureMessage(test, block, []);
2913
- reader.lastFailed = { test, block, notes: [] };
2990
+ function describeLateCall(late) {
2991
+ const error = `\`Cannot call ${late.call}() after the test run has completed\``;
2992
+ if (late.frame !== undefined) {
2993
+ return `${error} for test file ${late.frame.name} (block ${late.block + 1})`;
2914
2994
  }
2915
- reader.tests.push(test);
2916
- reader.counters[test.status]++;
2917
- reader.blockStart = index + 1;
2995
+ if (late.header !== undefined) {
2996
+ return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
2997
+ }
2998
+ return `${error} (block ${late.block + 1})`;
2918
2999
  }
2919
- function readLine(reader, index) {
2920
- const line = reader.lines[index];
2921
- const filePath = parseFilePath(line);
2922
- if (filePath && reader.isHeaderFile(filePath)) {
2923
- reader.currentFile = filePath;
2924
- reader.blockStart = index + 1;
2925
- reader.lastFailed = undefined;
2926
- return;
3000
+ var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3001
+ function lateCallSentences(lates, blocks) {
3002
+ if (lates.length === 0) {
3003
+ return [];
2927
3004
  }
2928
- if (isWorkflowCommandLine(line)) {
2929
- return;
3005
+ const named = lates.slice(0, MAX_NAMED);
3006
+ const fileKnown = named.every((late) => late.frame !== undefined);
3007
+ 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.";
3008
+ const precededByOtherBlock = blocks.findIndex((block) => block.lateCall !== undefined) > 0;
3009
+ return [
3010
+ [
3011
+ `bun reported ${nameList(lates.map((late) => describeLateCall(late)))}.`,
3012
+ consequence,
3013
+ ...precededByOtherBlock ? ["An error raised outside any test, such as those in the blocks shown, is what makes bun end a run early."] : []
3014
+ ].join(" ")
3015
+ ];
3016
+ }
3017
+ function eagerSentences(modules) {
3018
+ if (modules.length === 0) {
3019
+ return [];
2930
3020
  }
2931
- if (reader.lastFailed && AFTER_FAIL_NOTE_LINE.test(line)) {
2932
- const { test, block, notes } = reader.lastFailed;
2933
- notes.push(line.trim());
2934
- setFailureMessage(test, block, notes);
2935
- reader.blockStart = index + 1;
3021
+ const named = nameList(modules.map((claim) => `${claim.name} (block ${claim.block + 1})`));
3022
+ return [
3023
+ `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."
3024
+ ];
3025
+ }
3026
+ var CUT_NOTE_RESERVE = 200;
3027
+ var joinedLength = (parts) => parts.reduce((sum, part) => sum + part.length, 0) + Math.max(0, parts.length - 1);
3028
+ function describeUnhandledErrors(stderr, eagerModules, secrets = []) {
3029
+ const blocks = parseUnhandledErrorBlocks(stderr, secrets);
3030
+ if (blocks.length === 0) {
2936
3031
  return;
2937
3032
  }
2938
- reader.lastFailed = undefined;
2939
- const { test } = parseTestLine(line, reader.currentFile);
2940
- if (test) {
2941
- recordTest(reader, test, index);
2942
- } else if (NON_FAILING_RESULT_LINE.test(line)) {
2943
- reader.blockStart = index + 1;
2944
- }
2945
- }
2946
- var RAN_LINE = /^\s*Ran\s+(\d+)\s+tests?\b/;
2947
- var PASS_LINE = /^\s*\d+\s+pass\s*$/;
2948
- var COUNT_LINE = /^\s*(\d+)\s+(pass|skip|todo|fail|errors?)\s*$/;
2949
- var BAIL_LINE = /^\s*Bailed out after (\d+) failures?\s*$/;
2950
- function lastLineMatching(lines, from, pattern, stopAtBlank) {
2951
- for (let index = from;index >= 0; index--) {
2952
- const match = pattern.exec(lines[index]);
2953
- if (match) {
2954
- return { index, match };
3033
+ const lates = lateCalls(blocks, secrets);
3034
+ const modules = eagerClaims(blocks, eagerModules, secrets);
3035
+ const dropped = new Set;
3036
+ for (let attempt = 0;attempt < 8; attempt++) {
3037
+ const claims = {
3038
+ lates: lates.map((late) => late.frame !== undefined && dropped.has(keyOf(late.frame)) ? { ...late, frame: undefined } : late),
3039
+ modules: modules.filter((claim) => !dropped.has(keyOf(claim)))
3040
+ };
3041
+ const result = layOut(blocks, claims);
3042
+ const lost = [...claims.lates.slice(0, MAX_NAMED).flatMap((late) => late.frame ?? []), ...claims.modules.slice(0, MAX_NAMED)].filter((claim) => !result.shown(claim));
3043
+ if (lost.length === 0) {
3044
+ return result.text;
2955
3045
  }
2956
- if (stopAtBlank && !lines[index].trim()) {
2957
- return;
3046
+ for (const claim of lost) {
3047
+ dropped.add(keyOf(claim));
2958
3048
  }
2959
3049
  }
2960
- return;
3050
+ return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
2961
3051
  }
2962
- function readBunSummary(output) {
2963
- const lines = stripAnsi(output).split(`
2964
- `);
2965
- const lastIndex = lines.length - 1;
2966
- const ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
2967
- const pass = ran ? lastLineMatching(lines, ran.index - 1, PASS_LINE, true) : lastLineMatching(lines, lastIndex, PASS_LINE, false);
2968
- const summary = {
2969
- pass: 0,
2970
- skip: 0,
2971
- todo: 0,
2972
- fail: 0,
2973
- error: 0,
2974
- ran: ran && Number.parseInt(ran.match[1], 10),
2975
- bailed: undefined,
2976
- printed: ran !== undefined || pass !== undefined
2977
- };
2978
- if (pass) {
2979
- for (const line of lines.slice(pass.index, ran?.index ?? lines.length)) {
2980
- const match = COUNT_LINE.exec(line);
2981
- if (match) {
2982
- summary[match[2] === "errors" ? "error" : match[2]] = Number.parseInt(match[1], 10);
2983
- }
2984
- }
2985
- }
2986
- for (const line of lines.slice(ran?.index ?? 0)) {
2987
- const match = BAIL_LINE.exec(line);
2988
- if (match) {
2989
- summary.bailed = Number.parseInt(match[1], 10);
2990
- }
3052
+ function selectBlocks(blockCount, required) {
3053
+ const shown = new Set(required);
3054
+ for (let i = 0;i < blockCount && shown.size < MAX_BLOCKS_SHOWN; i++) {
3055
+ shown.add(i);
2991
3056
  }
2992
- return summary;
3057
+ return [...shown].toSorted((a, b) => a - b);
2993
3058
  }
2994
- function parseSummaryLines(output) {
2995
- const bun = readBunSummary(output);
2996
- const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
2997
- if (bun.bailed !== undefined) {
2998
- counts.failed = Math.max(counts.failed, bun.bailed);
2999
- }
3000
- const genuinePassed = counts.passed;
3001
- const genuineFailed = counts.failed;
3002
- if (bun.ran !== undefined) {
3003
- const totalParsed = counts.passed + counts.failed + counts.skipped;
3004
- if (totalParsed !== bun.ran && counts.passed === 0 && counts.failed === 0) {
3005
- counts.passed = bun.ran;
3059
+ function cutBlock(text, share) {
3060
+ const [heading, ...body] = text.split(`
3061
+ `);
3062
+ const kept = [heading];
3063
+ let used = heading.length;
3064
+ for (const line of body) {
3065
+ if (used + 1 + line.length > share) {
3066
+ if (kept.length === 1) {
3067
+ const head = Math.max(0, share - used - 1);
3068
+ kept.push(`${line.slice(0, head)}... [${line.length - head} more character(s) of this line omitted]`);
3069
+ }
3070
+ break;
3006
3071
  }
3072
+ used += 1 + line.length;
3073
+ kept.push(line);
3007
3074
  }
3008
- return { ...counts, todo: bun.todo, errors: bun.error, printed: bun.printed, genuinePassed, genuineFailed };
3075
+ const left = body.length - (kept.length - 1);
3076
+ return left > 0 ? [...kept, ` ... [${left} more line(s) of this block omitted]`].join(`
3077
+ `) : kept.join(`
3078
+ `);
3009
3079
  }
3010
- function parseBunTestOutput(stdout, stderr, testFiles) {
3011
- const tests = [];
3012
- const counters = { passed: 0, failed: 0, skipped: 0 };
3013
- const output = `${stdout}
3014
- ${stderr}`;
3015
- const lines = output.split(`
3016
- `).map((line) => stripAnsi(line));
3017
- const reader = {
3018
- lines,
3019
- isHeaderFile: headerFilter(lines, testFiles),
3020
- tests,
3021
- counters,
3022
- currentFile: undefined,
3023
- blockStart: 0,
3024
- lastFailed: undefined
3080
+ function layOut(blocks, claims) {
3081
+ const named = [...claims.lates.slice(0, MAX_NAMED).map((late) => late.block), ...claims.modules.slice(0, MAX_NAMED).map((claim) => claim.block)];
3082
+ const required = new Set([0, ...named]);
3083
+ const intro = `bun's stderr holds ${blocks.length} "Unhandled error between tests" block(s), errors raised outside any individual test:`;
3084
+ let selected = selectBlocks(blocks.length, required);
3085
+ const texts = new Map(selected.map((index) => [index, renderBlock(blocks[index], index, blocks.length)]));
3086
+ const noSnippets = new Set;
3087
+ const shownText = (index) => noSnippets.has(index) ? texts.get(index).bare : texts.get(index).full;
3088
+ const summary = [
3089
+ ...lateCallSentences(claims.lates, blocks),
3090
+ ...eagerSentences(claims.modules)
3091
+ ];
3092
+ const parts = () => {
3093
+ const omitted = blocks.length - selected.length;
3094
+ return [
3095
+ intro,
3096
+ ...selected.map((index) => shownText(index)),
3097
+ ...omitted > 0 ? [` ... [${omitted} more block(s) omitted]`] : [],
3098
+ ...summary
3099
+ ];
3025
3100
  };
3026
- for (const index of lines.keys()) {
3027
- readLine(reader, index);
3101
+ const fits = () => joinedLength(parts()) <= MAX_DIAGNOSTIC_CHARS;
3102
+ for (const index of selected.toReversed()) {
3103
+ if (fits()) {
3104
+ break;
3105
+ }
3106
+ noSnippets.add(index);
3028
3107
  }
3029
- const summaryCounts = parseSummaryLines(output);
3030
- counters.passed = Math.max(counters.passed, summaryCounts.passed);
3031
- counters.failed = Math.max(counters.failed, summaryCounts.failed);
3032
- counters.skipped = Math.max(counters.skipped, summaryCounts.skipped);
3108
+ for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3109
+ if (fits()) {
3110
+ break;
3111
+ }
3112
+ selected = selected.filter((index) => index !== dropped);
3113
+ }
3114
+ if (!fits()) {
3115
+ const outside = parts().filter((_, position) => position === 0 || position > selected.length);
3116
+ const share = Math.max(0, Math.floor((MAX_DIAGNOSTIC_CHARS - joinedLength(outside) - selected.length) / selected.length) - CUT_NOTE_RESERVE);
3117
+ for (const index of selected) {
3118
+ const text = texts.get(index).bare;
3119
+ texts.set(index, { full: text, bare: cutBlock(text, share) });
3120
+ }
3121
+ }
3122
+ const shownLines = new Map(selected.map((index) => [index, new Set(shownText(index).split(`
3123
+ `))]));
3033
3124
  return {
3034
- tests,
3035
- totalTests: counters.passed + counters.failed + counters.skipped,
3036
- passed: counters.passed,
3037
- failed: counters.failed,
3038
- skipped: counters.skipped,
3039
- summaryPassed: summaryCounts.genuinePassed,
3040
- summaryFailed: summaryCounts.genuineFailed,
3041
- summarySkipped: summaryCounts.skipped,
3042
- summaryTodo: summaryCounts.todo,
3043
- summaryErrors: summaryCounts.errors,
3044
- summaryPrinted: summaryCounts.printed
3125
+ text: parts().join(`
3126
+ `),
3127
+ shown: (claim) => shownLines.get(claim.block).has(` ${claim.line}`)
3045
3128
  };
3046
3129
  }
3047
3130
 
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) {
3131
+ // src/process-runner.ts
3132
+ import { spawn as spawn3 } from "node:child_process";
3133
+
3134
+ // src/utils/process-group.ts
3135
+ function killProcessGroup(pid, signal) {
3066
3136
  try {
3067
- return decodeURIComponent(text);
3137
+ process.kill(-pid, signal);
3138
+ return true;
3068
3139
  } catch {
3069
- return text;
3140
+ return false;
3070
3141
  }
3071
3142
  }
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;
3143
+
3144
+ // src/utils/process-rss.ts
3145
+ import { spawn as spawn2 } from "node:child_process";
3146
+ import { readFile as readFile4 } from "node:fs/promises";
3147
+ async function getProcessRssBytes(pid) {
3148
+ return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
3078
3149
  }
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);
3150
+ function parseVmRss(statusContent) {
3151
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
3152
+ return match ? Number(match[1]) * 1024 : null;
3153
+ }
3154
+ async function getLinuxRss(pid) {
3155
+ try {
3156
+ const status = await readFile4(`/proc/${pid}/status`, "utf8");
3157
+ return parseVmRss(status);
3158
+ } catch {
3159
+ return null;
3088
3160
  }
3089
- const file = FRAME_LOCATION_RE.exec(location)?.[1];
3090
- return file === undefined ? undefined : locationPath(file);
3091
3161
  }
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
- };
3162
+ function parsePsRssOutput(output) {
3163
+ const trimmed = output.trim();
3164
+ if (trimmed === "") {
3165
+ return null;
3166
+ }
3167
+ const kb = Number(trimmed);
3168
+ return Number.isFinite(kb) ? kb * 1024 : null;
3104
3169
  }
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;
3170
+ async function getPsRss(pid) {
3171
+ return new Promise((resolve) => {
3172
+ let child;
3173
+ try {
3174
+ child = spawn2("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
3175
+ } catch {
3176
+ resolve(null);
3177
+ return;
3114
3178
  }
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;
3179
+ let output = "";
3180
+ child.stdout.on("data", (data) => {
3181
+ output += data.toString();
3182
+ });
3183
+ child.on("close", (code) => {
3184
+ resolve(code === 0 ? parsePsRssOutput(output) : null);
3185
+ });
3186
+ child.on("error", () => {
3187
+ resolve(null);
3188
+ });
3189
+ });
3121
3190
  }
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 };
3191
+
3192
+ // src/utils/project-dir.ts
3193
+ import path8 from "node:path";
3194
+ var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3195
+ var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3196
+ function recordProjectDirectory() {
3197
+ const inherited = process.env[PROJECT_DIR_ENV];
3198
+ const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3199
+ if (isWorker && inherited !== undefined && path8.isAbsolute(inherited)) {
3200
+ return inherited;
3129
3201
  }
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
- }
3202
+ const here = process.cwd();
3203
+ process.env[PROJECT_DIR_ENV] = here;
3204
+ return here;
3205
+ }
3206
+ var projectDirectory = recordProjectDirectory();
3207
+ function resolveAgainstProject(file) {
3208
+ return path8.resolve(projectDirectory, file);
3209
+ }
3210
+
3211
+ // src/utils/test-file-args.ts
3212
+ import path9 from "node:path";
3213
+ var MAX_TEST_FILE_ARGS_BYTES = 131072;
3214
+ var ENTRY_OVERHEAD_BYTES = 1 + 8;
3215
+ var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3216
+ function shortestSpelling(absolute, cwd) {
3217
+ const relative = path9.relative(cwd, absolute);
3218
+ if (relative === "" || relative === "..") {
3219
+ return absolute;
3148
3220
  }
3149
- endRun();
3150
- return { full: [heading, ...full].join(`
3151
- `), bare: [heading, ...bare].join(`
3152
- `) };
3221
+ const spelled = relative.startsWith(`..${path9.sep}`) ? relative : `.${path9.sep}${relative}`;
3222
+ return spelled.length < absolute.length ? spelled : absolute;
3153
3223
  }
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;
3224
+ function computeTestFileArgs(files, cwd, budget) {
3225
+ const absolute = files.map((file) => path9.resolve(cwd, file));
3226
+ const absoluteBytes = bytesOf(absolute);
3227
+ if (absoluteBytes <= budget) {
3228
+ return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
3229
+ }
3230
+ const relative = absolute.map((file) => shortestSpelling(file, cwd));
3231
+ const relativeBytes = bytesOf(relative);
3232
+ return { args: relative, form: "relative", bytes: relativeBytes, fits: relativeBytes <= budget };
3157
3233
  }
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;
3234
+ function sameEntries(a, b) {
3235
+ return a.length === b.length && a.every((entry, index) => entry === b[index]);
3161
3236
  }
3162
- function matchesHeader(framePath, header) {
3163
- const frame = pathKey(framePath);
3164
- const wanted = pathKey(header).replace(/^\.\//, "");
3165
- return frame === wanted || frame.endsWith(`/${wanted}`);
3237
+ var lastBuild;
3238
+ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3239
+ if (!path9.isAbsolute(cwd)) {
3240
+ return computeTestFileArgs(files, cwd, budget);
3241
+ }
3242
+ const cached = lastBuild;
3243
+ if (cached?.cwd === cwd && cached.budget === budget && sameEntries(cached.files, files)) {
3244
+ return { ...cached.result, args: [...cached.result.args] };
3245
+ }
3246
+ const result = computeTestFileArgs(files, cwd, budget);
3247
+ lastBuild = { files: [...files], cwd, budget, result: { ...result, args: [...result.args] } };
3248
+ return result;
3166
3249
  }
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));
3250
+
3251
+ // src/process-runner.ts
3252
+ var KILL_GRACE_PERIOD_MS = 500;
3253
+ var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
3254
+ var LIFELINE_FD = 3;
3255
+ var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
3256
+ var DEFAULT_MAX_SPAWN_DEPTH = 1;
3257
+ var PROFILE_ENV = "STRYKER_BUN_PROFILE";
3258
+ function readSpawnDepth(raw) {
3259
+ const parsed = Number(raw);
3260
+ return Number.isInteger(parsed) ? Math.max(parsed, 0) : 0;
3171
3261
  }
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 [];
3262
+ function stripBailArgs(bunArgs) {
3263
+ const sanitized = [];
3264
+ for (let i = 0;i < bunArgs.length; i++) {
3265
+ const arg = bunArgs[i];
3266
+ if (arg === "--bail" || arg.startsWith("--bail=")) {
3267
+ if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
3268
+ i += 1;
3269
+ }
3270
+ continue;
3184
3271
  }
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
- });
3272
+ sanitized.push(arg);
3273
+ }
3274
+ return sanitized;
3188
3275
  }
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
- }) : []);
3276
+ var liveChildren = new Set;
3277
+ function killAllLiveChildren() {
3278
+ for (const child of liveChildren) {
3279
+ killProcessTree(child, "SIGKILL");
3280
+ }
3281
+ liveChildren.clear();
3200
3282
  }
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})`;
3283
+ var CLEANUP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
3284
+ var onCleanupSignal = (signal) => {
3285
+ killAllLiveChildren();
3286
+ removeSignalCleanup();
3287
+ process.kill(process.pid, signal);
3288
+ };
3289
+ function ensureSignalCleanup() {
3290
+ if (process.listeners(CLEANUP_SIGNALS[0]).includes(onCleanupSignal)) {
3291
+ return false;
3205
3292
  }
3206
- if (late.header !== undefined) {
3207
- return `${error} printed under the header of ${late.header} (block ${late.block + 1})`;
3293
+ for (const s of CLEANUP_SIGNALS) {
3294
+ process.on(s, onCleanupSignal);
3208
3295
  }
3209
- return `${error} (block ${late.block + 1})`;
3296
+ return true;
3210
3297
  }
3211
- var keyOf = (claim) => `${claim.block}\x00${claim.line}`;
3212
- function lateCallSentences(lates, blocks) {
3213
- if (lates.length === 0) {
3214
- return [];
3298
+ function removeSignalCleanup() {
3299
+ for (const s of CLEANUP_SIGNALS) {
3300
+ process.off(s, onCleanupSignal);
3215
3301
  }
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
3302
  }
3228
- function eagerSentences(modules) {
3229
- if (modules.length === 0) {
3230
- return [];
3303
+ function killProcessTree(childProcess, signal) {
3304
+ const pid = childProcess.pid;
3305
+ if (pid === undefined || !killProcessGroup(pid, signal)) {
3306
+ childProcess.kill(signal);
3307
+ return false;
3231
3308
  }
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
- ];
3309
+ return true;
3236
3310
  }
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;
3311
+ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
3312
+ const pid = childProcess.pid;
3313
+ const signalledGroup = killProcessTree(childProcess, "SIGTERM");
3314
+ let hasEscalated = false;
3315
+ const escalationHandle = setTimeout(() => {
3316
+ if (!isClosed()) {
3317
+ hasEscalated = true;
3318
+ killProcessTree(childProcess, "SIGKILL");
3256
3319
  }
3257
- for (const claim of lost) {
3258
- dropped.add(keyOf(claim));
3320
+ }, gracePeriodMs);
3321
+ return () => {
3322
+ clearTimeout(escalationHandle);
3323
+ if (!hasEscalated && signalledGroup && pid !== undefined) {
3324
+ hasEscalated = true;
3325
+ killProcessGroup(pid, "SIGKILL");
3259
3326
  }
3327
+ };
3328
+ }
3329
+ async function runBunTests(options) {
3330
+ const spawnDepth = readSpawnDepth(process.env[SPAWN_DEPTH_ENV]);
3331
+ const maxSpawnDepth = options.maxSpawnDepth ?? DEFAULT_MAX_SPAWN_DEPTH;
3332
+ if (!Number.isSafeInteger(maxSpawnDepth) || maxSpawnDepth < 1) {
3333
+ return {
3334
+ stdout: "",
3335
+ stderr: `stryker-bun-runner: invalid maxSpawnDepth=${String(maxSpawnDepth)}; expected a positive integer.`,
3336
+ exitCode: 1,
3337
+ signal: null,
3338
+ timedOut: false,
3339
+ memoryLimitExceeded: false
3340
+ };
3260
3341
  }
3261
- return layOut(blocks, { lates: lates.map((late) => ({ ...late, frame: undefined })), modules: [] }).text;
3342
+ if (spawnDepth >= maxSpawnDepth) {
3343
+ return {
3344
+ stdout: "",
3345
+ stderr: `stryker-bun-runner: refusing to spawn \`bun test\` at nesting depth ${spawnDepth} (maxSpawnDepth=${maxSpawnDepth}). A test run spawned by this runner tried to spawn another one; this is almost always runaway recursion. See the bun.maxSpawnDepth option.`,
3346
+ exitCode: 1,
3347
+ signal: null,
3348
+ timedOut: false,
3349
+ memoryLimitExceeded: false
3350
+ };
3351
+ }
3352
+ return spawnBunTests(options, spawnDepth);
3262
3353
  }
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);
3354
+ function buildChildEnv(options, spawnDepth) {
3355
+ const env = {
3356
+ ...process.env,
3357
+ ...options.env
3358
+ };
3359
+ const preloadVars = {
3360
+ __STRYKER_ACTIVE_MUTANT__: options.activeMutant === "" ? undefined : options.activeMutant,
3361
+ __STRYKER_HIT_LIMIT__: options.hitLimit === undefined ? undefined : String(options.hitLimit),
3362
+ __STRYKER_HIT_LIMIT_TOKEN__: options.hitLimitToken,
3363
+ __STRYKER_COVERAGE_FILE__: options.coverageFile === "" ? undefined : options.coverageFile,
3364
+ [COVERAGE_KEYS_ONLY_ENV]: options.coverageKeysOnly === true ? "1" : undefined,
3365
+ __STRYKER_SYNC_PORT__: options.syncPort ? String(options.syncPort) : undefined,
3366
+ [SYNC_TOKEN_ENV]: options.syncToken,
3367
+ [DRY_RUN_PLAN_ENV]: options.dryRunPlan,
3368
+ [WATCH_LIST_ENV]: options.watchList,
3369
+ [LIFELINE_FD_ENV]: String(LIFELINE_FD)
3370
+ };
3371
+ for (const [name, value] of Object.entries(preloadVars)) {
3372
+ if (value === undefined) {
3373
+ delete env[name];
3374
+ } else {
3375
+ env[name] = value;
3376
+ }
3267
3377
  }
3268
- return [...shown].toSorted((a, b) => a - b);
3378
+ env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
3379
+ delete env[PROJECT_DIR_ENV];
3380
+ if (options.profile) {
3381
+ delete env[PROFILE_ENV];
3382
+ }
3383
+ if (options.profile && options.syncPort) {
3384
+ env[PRELOAD_TIMINGS_ENV] = "1";
3385
+ } else {
3386
+ delete env[PRELOAD_TIMINGS_ENV];
3387
+ }
3388
+ return env;
3269
3389
  }
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]`);
3390
+ async function spawnBunTests(options, spawnDepth) {
3391
+ const profile = options.profile;
3392
+ profile?.beginSpawn(options.bail === true, options.testFiles, options.testNamePattern);
3393
+ const args = ["test"];
3394
+ if (options.inspect) {
3395
+ args.push("--inspect=127.0.0.1:0");
3396
+ }
3397
+ if (options.bunfigPath) {
3398
+ args.push(`--config=${options.bunfigPath}`);
3399
+ }
3400
+ if (options.preloadScript) {
3401
+ args.push("--preload", options.preloadScript);
3402
+ }
3403
+ if (options.testNamePattern) {
3404
+ args.push("--test-name-pattern", options.testNamePattern);
3405
+ }
3406
+ if (options.bail) {
3407
+ args.push("--bail");
3408
+ }
3409
+ if (options.sequentialMode) {
3410
+ args.push("--max-concurrency=1");
3411
+ }
3412
+ if (options.smol) {
3413
+ args.push("--smol");
3414
+ }
3415
+ if (options.bunArgs && options.bunArgs.length > 0) {
3416
+ args.push(...stripBailArgs(options.bunArgs));
3417
+ }
3418
+ if (options.testFiles && options.testFiles.length > 0) {
3419
+ args.push(...buildTestFileArgs(options.testFiles).args);
3420
+ }
3421
+ const env = buildChildEnv(options, spawnDepth);
3422
+ return new Promise((resolve) => {
3423
+ const stdoutChunks = [];
3424
+ const stderrChunks = [];
3425
+ let timedOut = false;
3426
+ let processKilled = false;
3427
+ let memoryLimitExceeded = false;
3428
+ let hasClosed = false;
3429
+ let rssIntervalHandle;
3430
+ let stdioCloseHandle;
3431
+ let onLeaderExitDuringTermination;
3432
+ let onAbort;
3433
+ if (options.signal?.aborted) {
3434
+ resolve({ stdout: "", stderr: "", exitCode: null, signal: null, timedOut: true, memoryLimitExceeded: false });
3435
+ return;
3436
+ }
3437
+ const spawnOpts = {
3438
+ env,
3439
+ stdio: ["ignore", "pipe", "pipe", "pipe"],
3440
+ cwd: process.cwd(),
3441
+ detached: true
3442
+ };
3443
+ try {
3444
+ options.onSpawn?.([options.bunPath, ...args]);
3445
+ } catch {}
3446
+ const childProcess = spawn3(options.bunPath, args, spawnOpts);
3447
+ profile?.mark("spawned");
3448
+ liveChildren.add(childProcess);
3449
+ ensureSignalCleanup();
3450
+ const beginTermination = () => {
3451
+ if (processKilled) {
3452
+ return false;
3280
3453
  }
3281
- break;
3454
+ processKilled = true;
3455
+ timedOut = true;
3456
+ onLeaderExitDuringTermination = killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
3457
+ return true;
3458
+ };
3459
+ const timeoutHandle = setTimeout(() => {
3460
+ beginTermination();
3461
+ }, options.timeout);
3462
+ if (options.signal) {
3463
+ onAbort = () => {
3464
+ beginTermination();
3465
+ };
3466
+ options.signal.addEventListener("abort", onAbort, { once: true });
3282
3467
  }
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;
3468
+ if (options.maxChildRss !== undefined) {
3469
+ const rssLimit = options.maxChildRss;
3470
+ const checkMemoryCeiling = async () => {
3471
+ if (hasClosed || processKilled) {
3472
+ return;
3473
+ }
3474
+ const pid = childProcess.pid;
3475
+ if (pid === undefined) {
3476
+ return;
3477
+ }
3478
+ const rssBytes = await getProcessRssBytes(pid);
3479
+ if (rssBytes === null || hasClosed) {
3480
+ return;
3481
+ }
3482
+ if (rssBytes > rssLimit) {
3483
+ if (!beginTermination()) {
3484
+ return;
3485
+ }
3486
+ memoryLimitExceeded = true;
3487
+ if (rssIntervalHandle) {
3488
+ clearInterval(rssIntervalHandle);
3489
+ }
3490
+ options.onMemoryLimitExceeded?.(rssBytes);
3491
+ }
3492
+ };
3493
+ rssIntervalHandle = setInterval(() => {
3494
+ checkMemoryCeiling();
3495
+ }, options.rssCheckIntervalMs ?? 1000);
3496
+ rssIntervalHandle.unref();
3316
3497
  }
3317
- noSnippets.add(index);
3318
- }
3319
- for (const dropped of selected.filter((index) => !required.has(index)).toReversed()) {
3320
- if (fits()) {
3321
- break;
3498
+ if (childProcess.stdout) {
3499
+ childProcess.stdout.on("data", (data) => {
3500
+ stdoutChunks.push(data);
3501
+ });
3322
3502
  }
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) });
3503
+ let inspectorUrlExtracted = false;
3504
+ if (childProcess.stderr) {
3505
+ childProcess.stderr.on("data", (data) => {
3506
+ stderrChunks.push(data);
3507
+ profile?.onStderr(data);
3508
+ if (options.inspect && !inspectorUrlExtracted && options.onInspectorReady) {
3509
+ const text = Buffer.concat(stderrChunks).toString();
3510
+ const match = /Listening:[\t\v\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*(ws:\/\/\S+)/.exec(stripAnsi(text));
3511
+ if (match) {
3512
+ inspectorUrlExtracted = true;
3513
+ options.onInspectorReady(match[1]);
3514
+ }
3515
+ }
3516
+ });
3331
3517
  }
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
- };
3518
+ const release = () => {
3519
+ liveChildren.delete(childProcess);
3520
+ clearTimeout(timeoutHandle);
3521
+ clearTimeout(stdioCloseHandle);
3522
+ if (options.signal && onAbort) {
3523
+ options.signal.removeEventListener("abort", onAbort);
3524
+ }
3525
+ if (rssIntervalHandle) {
3526
+ clearInterval(rssIntervalHandle);
3527
+ }
3528
+ };
3529
+ childProcess.on("exit", (code, signal) => {
3530
+ profile?.mark("exit");
3531
+ onLeaderExitDuringTermination?.();
3532
+ stdioCloseHandle = setTimeout(() => {
3533
+ release();
3534
+ resolve({
3535
+ stdout: Buffer.concat(stdoutChunks).toString(),
3536
+ stderr: Buffer.concat(stderrChunks).toString(),
3537
+ exitCode: processKilled ? null : code,
3538
+ signal: signal ?? null,
3539
+ timedOut,
3540
+ memoryLimitExceeded,
3541
+ outputIncomplete: true
3542
+ });
3543
+ }, STDIO_CLOSE_GRACE_MS);
3544
+ });
3545
+ childProcess.on("close", (code, signal) => {
3546
+ profile?.mark("close");
3547
+ hasClosed = true;
3548
+ onLeaderExitDuringTermination?.();
3549
+ release();
3550
+ resolve({
3551
+ stdout: Buffer.concat(stdoutChunks).toString(),
3552
+ stderr: Buffer.concat(stderrChunks).toString(),
3553
+ exitCode: processKilled ? null : code,
3554
+ signal: signal ?? null,
3555
+ timedOut,
3556
+ memoryLimitExceeded
3557
+ });
3558
+ });
3559
+ childProcess.on("error", (error) => {
3560
+ profile?.mark("close");
3561
+ hasClosed = true;
3562
+ onLeaderExitDuringTermination?.();
3563
+ release();
3564
+ const stderrOutput = Buffer.concat(stderrChunks).toString();
3565
+ resolve({
3566
+ stdout: Buffer.concat(stdoutChunks).toString(),
3567
+ stderr: `${stderrOutput}
3568
+ Process error: ${error.message}`,
3569
+ exitCode: null,
3570
+ signal: null,
3571
+ timedOut,
3572
+ memoryLimitExceeded,
3573
+ spawnError: error.message
3574
+ });
3575
+ });
3576
+ });
3340
3577
  }
3341
3578
 
3342
3579
  // src/run-profile.ts
@@ -3881,6 +4118,28 @@ function rawDataToString(data) {
3881
4118
  }
3882
4119
  return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
3883
4120
  }
4121
+ var DRAIN_REQUEST = "drain-request";
4122
+ function parseDrainRequest(text) {
4123
+ if (text === DRAIN_REQUEST) {
4124
+ return { startedTests: undefined };
4125
+ }
4126
+ if (!text.startsWith(`${DRAIN_REQUEST} `)) {
4127
+ return null;
4128
+ }
4129
+ const count = text.slice(DRAIN_REQUEST.length + 1);
4130
+ const startedTests = Number(count);
4131
+ return { startedTests: /^\d+$/.test(count) && Number.isSafeInteger(startedTests) ? startedTests : undefined };
4132
+ }
4133
+ function newDrainState() {
4134
+ return { handler: null, onDropped: null, dropped: [], queue: [], pending: new Set, busy: false, closed: false };
4135
+ }
4136
+ function reportDropped(drain, request) {
4137
+ if (drain.onDropped === null) {
4138
+ drain.dropped.push(request);
4139
+ } else {
4140
+ drain.onDropped(request);
4141
+ }
4142
+ }
3884
4143
 
3885
4144
  class SyncServer {
3886
4145
  token = randomBytes3(16).toString("hex");
@@ -3892,9 +4151,7 @@ class SyncServer {
3892
4151
  createHttpServer;
3893
4152
  WebSocketServerClass;
3894
4153
  webSocketOpenState;
3895
- drainHandler = null;
3896
- drainInFlight = null;
3897
- pendingDrainClients = new Set;
4154
+ drain = newDrainState();
3898
4155
  constructor(options = {}) {
3899
4156
  this.createHttpServer = options.createHttpServer ?? createServer;
3900
4157
  this.WebSocketServerClass = options.WebSocketServerClass ?? WebSocketServer;
@@ -3932,11 +4189,12 @@ class SyncServer {
3932
4189
  }
3933
4190
  ws.on("close", () => {
3934
4191
  this.clients.delete(ws);
3935
- this.pendingDrainClients.delete(ws);
4192
+ this.forgetQueuedDrainRequest(ws);
3936
4193
  });
3937
4194
  ws.on("message", (data) => {
3938
- if (rawDataToString(data) === "drain-request") {
3939
- this.handleDrainRequest(ws);
4195
+ const request = parseDrainRequest(rawDataToString(data));
4196
+ if (request) {
4197
+ this.handleDrainRequest(ws, request);
3940
4198
  }
3941
4199
  });
3942
4200
  });
@@ -3961,46 +4219,69 @@ class SyncServer {
3961
4219
  } catch {}
3962
4220
  }
3963
4221
  }
3964
- setDrainHandler(handler) {
3965
- this.drainHandler = handler;
3966
- const pending = this.pendingDrainClients;
3967
- this.pendingDrainClients = new Set;
3968
- for (const ws of pending) {
3969
- this.handleDrainRequest(ws);
4222
+ setDrainHandler(handler, onDropped) {
4223
+ const drain = this.drain;
4224
+ drain.handler = handler;
4225
+ if (onDropped !== undefined) {
4226
+ drain.onDropped = onDropped;
4227
+ for (const request of drain.dropped.splice(0)) {
4228
+ onDropped(request);
4229
+ }
3970
4230
  }
4231
+ this.serveNextDrainRequest(drain);
3971
4232
  }
3972
- handleDrainRequest(ws) {
3973
- if (!this.drainHandler) {
3974
- this.pendingDrainClients.add(ws);
4233
+ handleDrainRequest(ws, request) {
4234
+ const drain = this.drain;
4235
+ if (drain.pending.has(ws)) {
3975
4236
  return;
3976
4237
  }
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);
4238
+ drain.pending.add(ws);
4239
+ drain.queue.push({ ws, request });
4240
+ this.serveNextDrainRequest(drain);
4241
+ }
4242
+ forgetQueuedDrainRequest(ws) {
4243
+ const drain = this.drain;
4244
+ const index = drain.queue.findIndex((queued) => queued.ws === ws);
4245
+ if (index !== -1) {
4246
+ const [queued] = drain.queue.splice(index, 1);
4247
+ drain.pending.delete(ws);
4248
+ reportDropped(drain, queued.request);
3984
4249
  }
3985
- const inFlight = this.drainInFlight;
3986
- (async () => {
3987
- try {
3988
- await inFlight;
3989
- } catch {
3990
- return;
3991
- }
4250
+ }
4251
+ serveNextDrainRequest(drain) {
4252
+ const handler = drain.handler;
4253
+ if (handler === null || drain.busy || drain.closed) {
4254
+ return;
4255
+ }
4256
+ const next = drain.queue.shift();
4257
+ if (next === undefined) {
4258
+ return;
4259
+ }
4260
+ drain.busy = true;
4261
+ const answer = () => {
3992
4262
  try {
3993
- if (ws.readyState === this.webSocketOpenState) {
3994
- ws.send("drained");
4263
+ if (next.ws.readyState === this.webSocketOpenState) {
4264
+ next.ws.send("drained");
3995
4265
  }
3996
4266
  } catch {}
3997
- })();
4267
+ };
4268
+ const done = () => {
4269
+ drain.pending.delete(next.ws);
4270
+ drain.busy = false;
4271
+ this.serveNextDrainRequest(drain);
4272
+ };
4273
+ handler(next.request).then(answer).catch(() => {
4274
+ return;
4275
+ }).finally(done);
3998
4276
  }
3999
4277
  async close() {
4000
4278
  this.readyLatched = false;
4001
- this.drainHandler = null;
4002
- this.drainInFlight = null;
4003
- this.pendingDrainClients = new Set;
4279
+ const drain = this.drain;
4280
+ drain.closed = true;
4281
+ for (const queued of drain.queue) {
4282
+ reportDropped(drain, queued.request);
4283
+ }
4284
+ this.drain = newDrainState();
4004
4285
  for (const client of this.clients) {
4005
4286
  try {
4006
4287
  client.close();
@@ -4600,45 +4881,6 @@ function createInspectorUrlWaiter() {
4600
4881
  }
4601
4882
  };
4602
4883
  }
4603
- var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
4604
- var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
4605
- var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
4606
- var MAX_GAP_IDS_LISTED = 20;
4607
-
4608
- class DrainWaitTimeoutError extends Error {
4609
- reason;
4610
- constructor(message, reason) {
4611
- super(message);
4612
- this.name = "DrainWaitTimeoutError";
4613
- this.reason = reason;
4614
- }
4615
- }
4616
- function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs) {
4617
- const startedAt = Date.now();
4618
- let timer;
4619
- const promise = new Promise((_resolve, reject) => {
4620
- timer = setInterval(() => {
4621
- const sinceLastFrame = inspector.getMsSinceLastFrame();
4622
- const totalElapsed = Date.now() - startedAt;
4623
- if (totalElapsed >= absoluteCeilingMs) {
4624
- reject(new DrainWaitTimeoutError(`${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
4625
- } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
4626
- reject(new DrainWaitTimeoutError(`${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
4627
- }
4628
- }, DRAIN_SILENCE_POLL_INTERVAL_MS);
4629
- });
4630
- return { promise, cancel: () => clearInterval(timer) };
4631
- }
4632
- function formatGapIdList(gaps) {
4633
- if (gaps.length === 0) {
4634
- return "";
4635
- }
4636
- const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
4637
- return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
4638
- }
4639
- function formatDrainSettleReason(reason) {
4640
- return reason === undefined ? "never requested" : `settled via ${reason}`;
4641
- }
4642
4884
  function formatSpawnErrorMessage(spawnError) {
4643
4885
  return `could not start bun test: ${spawnError}`;
4644
4886
  }
@@ -4669,9 +4911,9 @@ function formatInspectorConnectMessage(error, child, secrets) {
4669
4911
  }
4670
4912
  function collectAbnormalDrainProblems(data) {
4671
4913
  const problems = [];
4672
- if (data.drainSettleReason !== "ack") {
4914
+ if (!data.drainProven) {
4673
4915
  const rejection = data.drainRejection === undefined ? "" : ` (${data.drainRejection})`;
4674
- problems.push(`drain handshake ${formatDrainSettleReason(data.drainSettleReason)}${rejection}`);
4916
+ problems.push(`drain handshake ${data.drainSummary}${rejection}`);
4675
4917
  }
4676
4918
  if (data.finalGaps.length > 0) {
4677
4919
  problems.push(`${data.finalGaps.length} found-id gap(s) remaining${formatGapIdList(data.finalGaps)}`);
@@ -4687,6 +4929,7 @@ function nonEmptyString(value) {
4687
4929
  var SAVE_TIME_LIMIT_MS = 5000;
4688
4930
  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
4931
  var REGISTRY_FILE = "registry.json";
4932
+ var NO_TEST_FILES = { entries: undefined, expanded: undefined };
4690
4933
 
4691
4934
  class WriteFailure extends Error {
4692
4935
  file;
@@ -4882,6 +5125,7 @@ class BunTestRunner {
4882
5125
  campaign;
4883
5126
  warnedWatchListProblem = false;
4884
5127
  currentAbortController;
5128
+ drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
4885
5129
  constructor(logger, options) {
4886
5130
  this.logger = logger;
4887
5131
  const bunOptions = options.bun ?? {};
@@ -5449,12 +5693,13 @@ ${stack}` : baseFailureMessage;
5449
5693
  this.applyDryRunTestFiles(options);
5450
5694
  this.logger.debug("Running dry run with inspector-based coverage collection...");
5451
5695
  const cwd = process.cwd();
5452
- const eager = this.cachedEagerModules ?? [];
5696
+ const matched = this.cachedEagerModules ?? [];
5453
5697
  const launchContext = {
5454
5698
  options,
5455
5699
  coverageAnalysis,
5456
5700
  cwd,
5457
- eager,
5701
+ eager: matched,
5702
+ matched,
5458
5703
  runDir: this.tempDir ?? tmpdir2(),
5459
5704
  startedAt,
5460
5705
  profile,
@@ -5467,8 +5712,10 @@ ${stack}` : baseFailureMessage;
5467
5712
  if (coverageAnalysis === "off") {
5468
5713
  return this.runWithoutCoverage(launchContext);
5469
5714
  }
5470
- const always = this.selectAlwaysImported(eager, cwd);
5471
- const ctx = { ...launchContext, always };
5715
+ const tests = matched.length === 0 ? NO_TEST_FILES : await this.dryRunTestFiles(cwd);
5716
+ const { eager, removed } = await this.withoutTestFilesRun(launchContext, tests);
5717
+ const always = this.selectAlwaysImported(eager, removed, cwd);
5718
+ const ctx = { ...launchContext, eager, always, tests };
5472
5719
  const legacy = legacyReason(eager, always);
5473
5720
  if (legacy !== null) {
5474
5721
  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");
@@ -5502,10 +5749,31 @@ ${stack}` : baseFailureMessage;
5502
5749
  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
5750
  }
5504
5751
  }
5505
- selectAlwaysImported(eager, cwd) {
5752
+ async dryRunTestFiles(cwd) {
5753
+ const { testFiles } = await this.dryRunFiles(cwd);
5754
+ return { entries: testFiles, expanded: testFiles === undefined ? undefined : await expandTestFileEntries(testFiles, cwd, this.logger) };
5755
+ }
5756
+ async withoutTestFilesRun(ctx, tests) {
5757
+ const { expanded } = tests;
5758
+ let selected = [];
5759
+ if (expanded !== undefined) {
5760
+ selected = "files" in expanded ? expanded.files : tests.entries.map((entry) => path15.resolve(ctx.cwd, entry));
5761
+ }
5762
+ const split = await withoutSelectedTestFiles(ctx.matched, selected);
5763
+ if (split.removed.length > 0) {
5764
+ this.logger.debug("Dry run: %d file(s) matched by mutate are test files the dry run runs, so they are never imported before the tests: %s", split.removed.length, split.removed.map((file) => shownPath(file, ctx.cwd)).join(", "));
5765
+ }
5766
+ return { eager: split.kept, removed: split.removed };
5767
+ }
5768
+ selectAlwaysImported(eager, removed, cwd) {
5506
5769
  const selection = selectAlways(eager, this.alwaysImport, cwd);
5507
5770
  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);
5771
+ const tests = selectAlways(removed, [pattern], cwd).files;
5772
+ if (tests.length > 0) {
5773
+ this.logger.warn("bun.alwaysImport pattern %s matches only test files the dry run runs (%s), and a test file is never imported before the tests", JSON.stringify(pattern), listText(tests.map((file) => shownPath(file, cwd))));
5774
+ } else {
5775
+ this.logger.warn("bun.alwaysImport pattern %s matches none of the %d files matched by mutate", JSON.stringify(pattern), eager.length);
5776
+ }
5509
5777
  }
5510
5778
  return selection.files;
5511
5779
  }
@@ -5553,15 +5821,14 @@ ${stack}` : baseFailureMessage;
5553
5821
  }
5554
5822
  }
5555
5823
  async importScanInput(ctx) {
5556
- const { testFiles } = await this.dryRunFiles(ctx.cwd);
5557
- if (testFiles === undefined) {
5824
+ const { expanded } = ctx.tests;
5825
+ if (expanded === undefined) {
5558
5826
  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
5827
  }
5560
5828
  const launch = scanLaunchArguments(this.bunArgs ?? [], { ...process.env, ...this.env }, ctx.cwd);
5561
5829
  if ("problem" in launch) {
5562
5830
  return launch;
5563
5831
  }
5564
- const expanded = await expandTestFileEntries(testFiles, ctx.cwd, this.logger);
5565
5832
  if ("problem" in expanded) {
5566
5833
  return expanded;
5567
5834
  }
@@ -5902,7 +6169,7 @@ ${outputLine}`;
5902
6169
  const correction = timeoutCorrection(ctx.extraMs, performance.now() - ctx.startedAt, tests.map((test) => test.timeSpentMs));
5903
6170
  ctx.profile?.at("coverageChecked");
5904
6171
  const watched = ctx.coverageAnalysis === "off" ? [] : watchList(ctx.eager, launch.list, seen);
5905
- const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, eager: ctx.eager } : undefined;
6172
+ const campaign = isGreen(launch.result) ? { timeoutCorrectionMs: correction, watched, matched: ctx.matched } : undefined;
5906
6173
  const unpublished = await this.buildAndPersistTestRegistry(tests, testNameIndex, testFileCoverage, campaign);
5907
6174
  ctx.profile?.at("registryWritten");
5908
6175
  if (unpublished !== undefined) {
@@ -6044,38 +6311,9 @@ exit=%s timedOut=%s
6044
6311
  }
6045
6312
  };
6046
6313
  }
6047
- let drainSettleReason;
6048
- let drainRejection;
6049
- syncServer.setDrainHandler(async () => {
6050
- const drainRequestReceivedAt = Date.now();
6051
- profile?.at("drainRequest");
6052
- const countsAtRequest = inspector.getEventCounts();
6053
- const gapsAtRequest = inspector.getFoundIdGaps();
6054
- this.logger.debug("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
6055
- const { promise: silencePromise, cancel: cancelSilence } = raceAgainstSilence(inspector, DRAIN_ACK_SILENCE_TIMEOUT_MS, DRAIN_ACK_ABSOLUTE_CEILING_MS);
6056
- try {
6057
- await Promise.race([
6058
- inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000),
6059
- silencePromise
6060
- ]);
6061
- drainSettleReason = "ack";
6062
- } catch (error) {
6063
- if (error instanceof DrainWaitTimeoutError) {
6064
- drainSettleReason = error.reason;
6065
- this.logger.debug("Inspector drain wait gave up: %s", error.message);
6066
- } else {
6067
- drainSettleReason = "send-rejected";
6068
- drainRejection = error instanceof Error ? error.message : String(error);
6069
- this.logger.debug("Inspector drain round-trip rejected before any wait bound was hit: %s", drainRejection);
6070
- }
6071
- } finally {
6072
- profile?.at("drainSettled");
6073
- cancelSilence();
6074
- const elapsedMs = Date.now() - drainRequestReceivedAt;
6075
- const countsAtSettle = inspector.getEventCounts();
6076
- const gapsAtSettle = inspector.getFoundIdGaps();
6077
- this.logger.debug("Drain handler settled via %s after %dms; events during wait +%d/+%d/+%d found/start/end; found-id gaps %d -> %d%s", drainSettleReason, elapsedMs, countsAtSettle.found - countsAtRequest.found, countsAtSettle.start - countsAtRequest.start, countsAtSettle.end - countsAtRequest.end, gapsAtRequest.length, gapsAtSettle.length, drainSettleReason === "ack" && gapsAtSettle.length > 0 ? " — ack resolved but gaps remain: the ack may under-prove drain" : "");
6078
- }
6314
+ const drain = new DrainHandshake(inspector, this.logger, profile, this.drainSilenceMs);
6315
+ syncServer.setDrainHandler(async (request) => drain.handle(request), (request) => {
6316
+ drain.requestDropped(request);
6079
6317
  });
6080
6318
  syncServer.signalReady();
6081
6319
  this.logger.debug("Signaled preload script to proceed");
@@ -6094,13 +6332,14 @@ exit=%s timedOut=%s
6094
6332
  await inspector.close();
6095
6333
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
6096
6334
  const finalGaps = inspector.getFoundIdGaps();
6097
- this.logger.debug("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), formatDrainSettleReason(drainSettleReason));
6335
+ this.logger.debug("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), drain.describe());
6098
6336
  const closeInfo = inspector.getCloseInfo();
6099
6337
  const collisionStats = inspector.getFoundIdCollisionStats();
6100
6338
  this.logger.debug("Post-drain inspector close/collision diagnostics: WS close code=%s reason=%s wasClean=%s msFromLastFrameToClose=%s; " + "found events %d raw / %d unique id(s) / %d duplicate id event(s) (nonzero duplicates = direct evidence of the Bun " + "TestReporter id-collision bug; the found-id-gap count above is density-only — it does NOT prove losslessness under collisions)", String(closeInfo.code), String(closeInfo.reason), String(closeInfo.wasClean), String(closeInfo.msFromLastFrameToClose), collisionStats.rawFoundCount, collisionStats.uniqueFoundIdCount, collisionStats.duplicateFoundIdCount);
6101
6339
  this.warnOnAbnormalDrainData({
6102
- drainSettleReason,
6103
- drainRejection,
6340
+ drainProven: drain.proven,
6341
+ drainSummary: drain.describe(),
6342
+ drainRejection: drain.rejection,
6104
6343
  finalGaps,
6105
6344
  duplicateFoundIdCount: collisionStats.duplicateFoundIdCount
6106
6345
  });
@@ -6317,7 +6556,7 @@ ${preloadLines.join(`
6317
6556
  generation,
6318
6557
  watchList: [...watched],
6319
6558
  watchListFile,
6320
- fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.eager)
6559
+ fingerprint: watchListFile === null || !this.inPlace ? null : await campaignFingerprint(campaignInput.matched)
6321
6560
  };
6322
6561
  if (watchListFile !== null) {
6323
6562
  const file = path15.join(runDir, watchListFile);