mutant-cafe 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -3
- package/dist/bin.js +2044 -343
- package/dist/bin.js.map +4 -4
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -6,6 +6,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
|
6
6
|
|
|
7
7
|
// packages/core/src/Config.ts
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
9
|
+
var DEFAULT_BASELINE_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
9
10
|
var RunConfig = Schema.Struct({
|
|
10
11
|
root: Schema.String,
|
|
11
12
|
tsconfig: Schema.String,
|
|
@@ -14,8 +15,11 @@ var RunConfig = Schema.Struct({
|
|
|
14
15
|
functionFilter: Schema.Array(Schema.String),
|
|
15
16
|
inDiff: Schema.optional(Schema.String),
|
|
16
17
|
exportedOnly: Schema.optional(Schema.Boolean),
|
|
18
|
+
cold: Schema.optional(Schema.Boolean),
|
|
19
|
+
warm: Schema.optional(Schema.Boolean),
|
|
17
20
|
jobs: Schema.Int,
|
|
18
21
|
timeoutMs: Schema.optional(Schema.Int),
|
|
22
|
+
baselineTimeoutMs: Schema.optional(Schema.Int),
|
|
19
23
|
timeoutMultiplier: Schema.Finite,
|
|
20
24
|
minimumTimeoutMs: Schema.Int,
|
|
21
25
|
neverTimeoutMs: Schema.Int,
|
|
@@ -27,7 +31,8 @@ var ConfigFile = Schema.Struct({
|
|
|
27
31
|
functionFilter: Schema.optional(Schema.Array(Schema.String)),
|
|
28
32
|
jobs: Schema.optional(Schema.Int),
|
|
29
33
|
timeoutMultiplier: Schema.optional(Schema.Finite),
|
|
30
|
-
minimumTimeoutMs: Schema.optional(Schema.Int)
|
|
34
|
+
minimumTimeoutMs: Schema.optional(Schema.Int),
|
|
35
|
+
baselineTimeoutMs: Schema.optional(Schema.Int)
|
|
31
36
|
});
|
|
32
37
|
|
|
33
38
|
// packages/core/src/Errors.ts
|
|
@@ -38,12 +43,19 @@ var ProgramLoadError = class extends Schema2.TaggedError()("ProgramLoadError", {
|
|
|
38
43
|
diagnostics: Schema2.Array(Schema2.String)
|
|
39
44
|
}) {
|
|
40
45
|
};
|
|
46
|
+
var formatTestCommand = (command) => command[1]?.endsWith("/launch.mjs") ? `vitest ${command.slice(2).filter((arg) => arg === "--reporter=default" || !arg.startsWith("--reporter=")).join(" ")} (via ${command.join(" ")})` : command.join(" ");
|
|
41
47
|
var BaselineFailed = class extends Schema2.TaggedError()("BaselineFailed", {
|
|
42
48
|
exitCode: Schema2.Int,
|
|
43
49
|
command: Schema2.Array(Schema2.String),
|
|
44
50
|
output: Schema2.String
|
|
45
51
|
}) {
|
|
46
52
|
};
|
|
53
|
+
var BaselineTimedOut = class extends Schema2.TaggedError()("BaselineTimedOut", {
|
|
54
|
+
timeoutMs: Schema2.Int,
|
|
55
|
+
command: Schema2.Array(Schema2.String),
|
|
56
|
+
message: Schema2.String
|
|
57
|
+
}) {
|
|
58
|
+
};
|
|
47
59
|
var ScratchError = class extends Schema2.TaggedError()("ScratchError", {
|
|
48
60
|
operation: Schema2.String,
|
|
49
61
|
path: Schema2.String,
|
|
@@ -51,6 +63,7 @@ var ScratchError = class extends Schema2.TaggedError()("ScratchError", {
|
|
|
51
63
|
}) {
|
|
52
64
|
};
|
|
53
65
|
var TestSpawnError = class extends Schema2.TaggedError()("TestSpawnError", {
|
|
66
|
+
kind: Schema2.optional(Schema2.Literal("reporter")),
|
|
54
67
|
command: Schema2.Array(Schema2.String),
|
|
55
68
|
message: Schema2.String
|
|
56
69
|
}) {
|
|
@@ -115,7 +128,14 @@ var MutantResult = Schema3.Struct({
|
|
|
115
128
|
durationMs: Schema3.Int,
|
|
116
129
|
testCommand: Schema3.Array(Schema3.String),
|
|
117
130
|
diagnostics: Schema3.Array(Schema3.String),
|
|
118
|
-
output: Schema3.optional(Schema3.String)
|
|
131
|
+
output: Schema3.optional(Schema3.String),
|
|
132
|
+
timeoutMs: Schema3.optional(Schema3.Int),
|
|
133
|
+
outerTimeoutMs: Schema3.optional(Schema3.Int),
|
|
134
|
+
backstopMs: Schema3.optional(Schema3.Finite),
|
|
135
|
+
hangBudgetBaseMs: Schema3.optional(Schema3.Finite),
|
|
136
|
+
telemetryWarnings: Schema3.optional(Schema3.Array(Schema3.String)),
|
|
137
|
+
testWorkers: Schema3.optional(Schema3.Int),
|
|
138
|
+
testConcurrency: Schema3.optional(Schema3.Int)
|
|
119
139
|
});
|
|
120
140
|
var SelectionIssue = Schema3.Union([
|
|
121
141
|
Schema3.Struct({ kind: Schema3.Literal("runner"), reason: Schema3.String }),
|
|
@@ -126,7 +146,21 @@ var SelectionIssue = Schema3.Union([
|
|
|
126
146
|
var Baseline = Schema3.Struct({
|
|
127
147
|
durationMs: Schema3.Int,
|
|
128
148
|
testCommand: Schema3.Array(Schema3.String),
|
|
129
|
-
unreliable: Schema3.optional(Schema3.Array(SelectionIssue))
|
|
149
|
+
unreliable: Schema3.optional(Schema3.Array(SelectionIssue)),
|
|
150
|
+
testDurations: Schema3.optional(Schema3.Record(Schema3.String, Schema3.Finite)),
|
|
151
|
+
testTimeouts: Schema3.optional(Schema3.Record(Schema3.String, Schema3.Finite)),
|
|
152
|
+
testWorkers: Schema3.optional(Schema3.Int),
|
|
153
|
+
testConcurrency: Schema3.optional(Schema3.Int),
|
|
154
|
+
testFileDurations: Schema3.optional(Schema3.Record(Schema3.String, Schema3.Finite)),
|
|
155
|
+
startupMs: Schema3.optional(Schema3.Int),
|
|
156
|
+
probeSupported: Schema3.optional(Schema3.Boolean),
|
|
157
|
+
testableMutants: Schema3.optional(Schema3.Int),
|
|
158
|
+
telemetryWarnings: Schema3.optional(Schema3.Array(Schema3.String)),
|
|
159
|
+
hostPid: Schema3.optional(Schema3.Int),
|
|
160
|
+
testTimeoutDetails: Schema3.optional(Schema3.Record(Schema3.String, Schema3.Finite)),
|
|
161
|
+
runnerMode: Schema3.optional(Schema3.Literals(["cold", "warm"])),
|
|
162
|
+
runnerModeReason: Schema3.optional(Schema3.String),
|
|
163
|
+
calibration: Schema3.optional(Schema3.Struct({ coldMs: Schema3.Int, warmMs: Schema3.Int, warmStartupMs: Schema3.Int, overheadMs: Schema3.optional(Schema3.Int), coldStartupMs: Schema3.optional(Schema3.Int), warmRunStartupMs: Schema3.optional(Schema3.Int), testFiles: Schema3.Int, mutants: Schema3.Int }))
|
|
130
164
|
});
|
|
131
165
|
var NotMutated = Schema3.Struct({
|
|
132
166
|
// Optional on decode for existing schemaVersion 2 reports; discovery always supplies it.
|
|
@@ -147,7 +181,17 @@ var MutantList = Schema3.Struct({
|
|
|
147
181
|
notMutated: Schema3.Array(NotMutated),
|
|
148
182
|
counts: SelectionCounts
|
|
149
183
|
});
|
|
184
|
+
var ReachabilityProbe = Schema3.Struct({
|
|
185
|
+
file: Schema3.String,
|
|
186
|
+
status: Schema3.Literals(["unreachable", "reachable", "unsupported"]),
|
|
187
|
+
durationMs: Schema3.Int,
|
|
188
|
+
testCommand: Schema3.Array(Schema3.String),
|
|
189
|
+
output: Schema3.String
|
|
190
|
+
});
|
|
150
191
|
var RunReport = Schema3.Struct({
|
|
192
|
+
hostRestarts: Schema3.optional(Schema3.Int),
|
|
193
|
+
poolResets: Schema3.optional(Schema3.Int),
|
|
194
|
+
reachabilityProbes: Schema3.optional(Schema3.Array(ReachabilityProbe)),
|
|
151
195
|
selected: Schema3.optional(Schema3.Int),
|
|
152
196
|
run: Schema3.optional(Schema3.Int),
|
|
153
197
|
budgetSkipped: Schema3.optional(Schema3.Int),
|
|
@@ -172,6 +216,55 @@ var TestRunner = class extends Context.Service()("mutant.cafe/TestRunner") {
|
|
|
172
216
|
var Reporter = class extends Context.Service()("mutant.cafe/Reporter") {
|
|
173
217
|
};
|
|
174
218
|
|
|
219
|
+
// packages/core/src/Telemetry.ts
|
|
220
|
+
var telemetryInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
221
|
+
var finite = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
222
|
+
var numericRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every(finite);
|
|
223
|
+
var calibration = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && ["coldMs", "warmMs", "warmStartupMs", "testFiles", "mutants"].every((key) => telemetryInteger(Reflect.get(value, key))) && Object.values(value).every((item) => item === void 0 || telemetryInteger(item));
|
|
224
|
+
var validators = {
|
|
225
|
+
durationMs: telemetryInteger,
|
|
226
|
+
timeoutMs: telemetryInteger,
|
|
227
|
+
outerTimeoutMs: telemetryInteger,
|
|
228
|
+
startupMs: telemetryInteger,
|
|
229
|
+
testWorkers: telemetryInteger,
|
|
230
|
+
testConcurrency: telemetryInteger,
|
|
231
|
+
hostPid: telemetryInteger,
|
|
232
|
+
testableMutants: telemetryInteger,
|
|
233
|
+
hostRestarts: telemetryInteger,
|
|
234
|
+
poolResets: telemetryInteger,
|
|
235
|
+
firstTestStart: finite,
|
|
236
|
+
hangBudgetBaseMs: finite,
|
|
237
|
+
testDurations: numericRecord,
|
|
238
|
+
testTimeouts: numericRecord,
|
|
239
|
+
testFileDurations: numericRecord,
|
|
240
|
+
testTimeoutDetails: numericRecord,
|
|
241
|
+
calibration,
|
|
242
|
+
backstopMs: finite,
|
|
243
|
+
runnerModeReason: (value) => typeof value === "string",
|
|
244
|
+
runnerMode: (value) => value === "cold" || value === "warm",
|
|
245
|
+
telemetryWarnings: (value) => Array.isArray(value) && value.every((item) => typeof item === "string")
|
|
246
|
+
};
|
|
247
|
+
var describe = (value) => typeof value === "string" ? JSON.stringify(value.slice(0, 128)) : value === null || typeof value !== "object" ? String(value) : "[object]";
|
|
248
|
+
function cleanTelemetry(input, location, required = ["durationMs"]) {
|
|
249
|
+
const value = { ...input };
|
|
250
|
+
const warnings = [];
|
|
251
|
+
for (const [key, valid] of Object.entries(validators)) {
|
|
252
|
+
const item = Reflect.get(value, key);
|
|
253
|
+
if (item === void 0 || valid(item)) continue;
|
|
254
|
+
warnings.push(`Internal reporter telemetry error: ${location}.${key}=${describe(item)}; ${required.includes(key) ? "using zero" : "omitted"}`);
|
|
255
|
+
if (required.includes(key)) Reflect.set(value, key, 0);
|
|
256
|
+
else Reflect.deleteProperty(value, key);
|
|
257
|
+
}
|
|
258
|
+
return { value, warnings };
|
|
259
|
+
}
|
|
260
|
+
function sanitizeReportTelemetry(report) {
|
|
261
|
+
const root = cleanTelemetry(report, "report", ["timeoutMs"]);
|
|
262
|
+
const baseline = cleanTelemetry(report.baseline, "baseline");
|
|
263
|
+
const results = report.results.map((result5, index) => cleanTelemetry(result5, `results[${index}]`));
|
|
264
|
+
const warnings = [.../* @__PURE__ */ new Set([...root.warnings, ...baseline.warnings, ...baseline.value.telemetryWarnings ?? [], ...results.flatMap((result5) => [...result5.warnings, ...result5.value.telemetryWarnings ?? []])])];
|
|
265
|
+
return { report: { ...root.value, baseline: { ...baseline.value, ...warnings.length ? { telemetryWarnings: warnings } : {} }, results: results.map((result5) => result5.value) }, warnings };
|
|
266
|
+
}
|
|
267
|
+
|
|
175
268
|
// packages/engine/src/index.ts
|
|
176
269
|
import * as Effect from "effect/Effect";
|
|
177
270
|
import * as Layer from "effect/Layer";
|
|
@@ -180,36 +273,36 @@ import * as Schema4 from "effect/Schema";
|
|
|
180
273
|
|
|
181
274
|
// packages/engine/src/Generate.ts
|
|
182
275
|
import { createHash } from "node:crypto";
|
|
183
|
-
function* generateFunction(
|
|
184
|
-
const issue =
|
|
276
|
+
function* generateFunction(fn11) {
|
|
277
|
+
const issue = fn11.generationIssue?.();
|
|
185
278
|
if (issue) return issue;
|
|
186
|
-
const api =
|
|
279
|
+
const api = fn11.api;
|
|
187
280
|
const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
|
|
188
|
-
const pinned = `((): ${
|
|
189
|
-
const text =
|
|
190
|
-
return makeMutant(
|
|
281
|
+
const pinned = `((): ${fn11.returnType} => (${expression}))()`;
|
|
282
|
+
const text = fn11.block ? `{ return ${fn11.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
|
|
283
|
+
return makeMutant(fn11, genre, text, value.synthetic, description);
|
|
191
284
|
};
|
|
192
|
-
const shape =
|
|
285
|
+
const shape = fn11.shape;
|
|
193
286
|
const fits = (value) => new TextEncoder().encode(value.text).byteLength <= 2048;
|
|
194
287
|
const values = "values" in shape ? shape.values.filter(fits) : [];
|
|
195
288
|
switch (shape.kind) {
|
|
196
289
|
case "Effect": {
|
|
197
|
-
const
|
|
198
|
-
if (
|
|
290
|
+
const succeed7 = api("Effect", "succeed");
|
|
291
|
+
if (succeed7) {
|
|
199
292
|
for (const value of values) {
|
|
200
|
-
if (!
|
|
293
|
+
if (!fn11.equivalentValues.includes(value.text) && !(fn11.generator && value.text === fn11.literal)) yield candidate("EffectSucceed", `${succeed7}(${value.text})`, value);
|
|
201
294
|
}
|
|
202
295
|
}
|
|
203
|
-
const
|
|
296
|
+
const fail4 = api("Effect", "fail");
|
|
204
297
|
const catchTag3 = api("Effect", "catchTag");
|
|
205
298
|
for (const error3 of shape.errors) {
|
|
206
|
-
if (
|
|
299
|
+
if (fail4 && fits(error3)) yield candidate("EffectFail", `${fail4}(${error3.text})`, error3, `${fail4}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
|
|
207
300
|
const recoveries = values.length ? shape.enumerateRecoveries ? values : values.slice(0, 1) : [void 0];
|
|
208
|
-
const
|
|
209
|
-
const original =
|
|
301
|
+
const gen11 = api("Effect", "gen");
|
|
302
|
+
const original = fn11.generator ? gen11 && `((): ${fn11.returnType} => ${gen11}(function* () ${fn11.original}))()` : fn11.block ? `((): ${fn11.returnType} => ${fn11.original})()` : `((): ${fn11.returnType} => (${fn11.original}))()`;
|
|
210
303
|
for (const value of recoveries) {
|
|
211
304
|
const die3 = api("Effect", "die");
|
|
212
|
-
const recovery = value &&
|
|
305
|
+
const recovery = value && succeed7 ? `${succeed7}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
|
|
213
306
|
if (catchTag3 && recovery && original) {
|
|
214
307
|
yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag3}(${JSON.stringify(error3.tag)}, () => ${recovery}))` : `turn ${error3.tag} into a defect`);
|
|
215
308
|
}
|
|
@@ -230,52 +323,52 @@ function* generateFunction(fn9) {
|
|
|
230
323
|
}
|
|
231
324
|
case "Stream": {
|
|
232
325
|
const empty = api("Stream", "empty");
|
|
233
|
-
const
|
|
234
|
-
const
|
|
326
|
+
const make11 = api("Stream", "make");
|
|
327
|
+
const fail4 = api("Stream", "fail");
|
|
235
328
|
if (empty) yield candidate("StreamEmpty", empty);
|
|
236
|
-
if (
|
|
237
|
-
if (
|
|
238
|
-
for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${
|
|
329
|
+
if (make11) for (const value of values) yield candidate("StreamOne", `${make11}(${value.text})`, value);
|
|
330
|
+
if (fail4) {
|
|
331
|
+
for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${fail4}(${error3.text})`, error3);
|
|
239
332
|
}
|
|
240
333
|
break;
|
|
241
334
|
}
|
|
242
335
|
case "Layer": {
|
|
243
336
|
const layer2 = api("Layer", "effectContext");
|
|
244
|
-
const
|
|
337
|
+
const fail4 = api("Effect", "fail");
|
|
245
338
|
const die2 = api("Effect", "die");
|
|
246
339
|
if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
|
|
247
|
-
if (layer2 &&
|
|
248
|
-
for (const error3 of shape.errors) if (fits(error3)) yield candidate("LayerFail", `${layer2}(${
|
|
340
|
+
if (layer2 && fail4) {
|
|
341
|
+
for (const error3 of shape.errors) if (fits(error3)) yield candidate("LayerFail", `${layer2}(${fail4}(${error3.text}))`, error3);
|
|
249
342
|
}
|
|
250
343
|
break;
|
|
251
344
|
}
|
|
252
345
|
case "Void":
|
|
253
|
-
yield makeMutant(
|
|
346
|
+
yield makeMutant(fn11, "FnValue", "{}", false, "an empty body");
|
|
254
347
|
break;
|
|
255
348
|
default: {
|
|
256
349
|
const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
|
|
257
350
|
for (const value of values) {
|
|
258
|
-
if (value.text ===
|
|
351
|
+
if (value.text === fn11.literal) continue;
|
|
259
352
|
yield candidate(genre, value.text, value);
|
|
260
353
|
}
|
|
261
354
|
}
|
|
262
355
|
}
|
|
263
356
|
}
|
|
264
|
-
function makeMutant(
|
|
265
|
-
const additions =
|
|
266
|
-
const prefix =
|
|
267
|
-
const insertion =
|
|
268
|
-
const replacement = additions.length &&
|
|
269
|
-
const id = createHash("sha256").update(JSON.stringify([
|
|
357
|
+
function makeMutant(fn11, genre, text, synthetic, description) {
|
|
358
|
+
const additions = fn11.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
|
|
359
|
+
const prefix = fn11.sourcePrefix ?? "";
|
|
360
|
+
const insertion = fn11.importInsertionOffset ?? 0;
|
|
361
|
+
const replacement = additions.length && fn11.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn11.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn11.startOffset, endOffset: fn11.endOffset, text };
|
|
362
|
+
const id = createHash("sha256").update(JSON.stringify([fn11.identityFile ?? fn11.file, fn11.name, fn11.identityOrdinal ?? 0, fn11.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
|
|
270
363
|
return {
|
|
271
364
|
id,
|
|
272
|
-
file:
|
|
273
|
-
functionName:
|
|
274
|
-
returnType:
|
|
275
|
-
displayReturnType:
|
|
365
|
+
file: fn11.file,
|
|
366
|
+
functionName: fn11.name,
|
|
367
|
+
returnType: fn11.returnType,
|
|
368
|
+
displayReturnType: fn11.displayReturnType,
|
|
276
369
|
genre,
|
|
277
|
-
description: `replace ${
|
|
278
|
-
span:
|
|
370
|
+
description: `replace ${fn11.name} -> ${fn11.returnType} with ${description}`,
|
|
371
|
+
span: fn11.span,
|
|
279
372
|
replacement,
|
|
280
373
|
synthetic
|
|
281
374
|
};
|
|
@@ -483,10 +576,10 @@ function makeTypeScriptOracle() {
|
|
|
483
576
|
const found = [];
|
|
484
577
|
visit(source);
|
|
485
578
|
const occurrences = /* @__PURE__ */ new Map();
|
|
486
|
-
for (const
|
|
487
|
-
const ordinal = occurrences.get(
|
|
488
|
-
occurrences.set(
|
|
489
|
-
functions.push({ ...
|
|
579
|
+
for (const fn11 of found) {
|
|
580
|
+
const ordinal = occurrences.get(fn11.name) ?? 0;
|
|
581
|
+
occurrences.set(fn11.name, ordinal + 1);
|
|
582
|
+
functions.push({ ...fn11, identityOrdinal: ordinal });
|
|
490
583
|
}
|
|
491
584
|
}
|
|
492
585
|
const unmatched = config.include.filter((glob) => !matched.has(glob));
|
|
@@ -670,9 +763,9 @@ function functionName(node, checker) {
|
|
|
670
763
|
}
|
|
671
764
|
function wrappedEffect(node, checker) {
|
|
672
765
|
if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
|
|
673
|
-
const
|
|
674
|
-
if (family(
|
|
675
|
-
const signature =
|
|
766
|
+
const result5 = checker.getTypeAtLocation(node.parent);
|
|
767
|
+
if (family(result5, checker)?.kind === "Effect") return result5;
|
|
768
|
+
const signature = result5.getCallSignatures()[0];
|
|
676
769
|
if (!signature) return void 0;
|
|
677
770
|
const returned = checker.getReturnTypeOfSignature(signature);
|
|
678
771
|
return family(returned, checker)?.kind === "Effect" ? returned : void 0;
|
|
@@ -981,11 +1074,11 @@ function smallFinite(type) {
|
|
|
981
1074
|
const members = type.isUnion() ? type.types : [type];
|
|
982
1075
|
return members.length <= 4 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
|
|
983
1076
|
}
|
|
984
|
-
function boundCandidates(candidates,
|
|
1077
|
+
function boundCandidates(candidates, types3, node) {
|
|
985
1078
|
const unique = [...new Map(candidates.map((value) => [valueKey(value.text), value])).values()];
|
|
986
|
-
const members =
|
|
987
|
-
const
|
|
988
|
-
if (
|
|
1079
|
+
const members = types3.flatMap((type) => type.isUnion() ? type.types : [type]);
|
|
1080
|
+
const finite2 = members.length <= 8 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
|
|
1081
|
+
if (finite2 || unique.length <= 6) return { values: unique, omitted: 0 };
|
|
989
1082
|
const absence = unique.find((value) => value.text === "undefined");
|
|
990
1083
|
const defined = unique.filter((value) => value !== absence);
|
|
991
1084
|
const preferred = ["null", '""', "0", "false", "[]", "({ })"].flatMap((text) => {
|
|
@@ -1014,14 +1107,14 @@ function objectDiscriminants(node) {
|
|
|
1014
1107
|
}
|
|
1015
1108
|
function returnedDiscriminants(node) {
|
|
1016
1109
|
if (!isFunction(node) || !node.body) return /* @__PURE__ */ new Set();
|
|
1017
|
-
const
|
|
1110
|
+
const result5 = new Set(objectDiscriminants(node.body));
|
|
1018
1111
|
const visit = (child) => {
|
|
1019
1112
|
if (isFunction(child)) return;
|
|
1020
|
-
if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression))
|
|
1113
|
+
if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression)) result5.add(key);
|
|
1021
1114
|
ts.forEachChild(child, visit);
|
|
1022
1115
|
};
|
|
1023
1116
|
visit(node.body);
|
|
1024
|
-
return
|
|
1117
|
+
return result5;
|
|
1025
1118
|
}
|
|
1026
1119
|
function shapeNotices(shape, type, checker, node) {
|
|
1027
1120
|
const notices = [...shape.synthesisIssues ?? []];
|
|
@@ -1149,9 +1242,9 @@ function makeMutantSource(oracle) {
|
|
|
1149
1242
|
const notMutated = [...discovered.notMutated];
|
|
1150
1243
|
const mutants = [];
|
|
1151
1244
|
const failed = /* @__PURE__ */ new Set();
|
|
1152
|
-
const generatedFunctions = discovered.functions.map((
|
|
1245
|
+
const generatedFunctions = discovered.functions.map((fn11) => {
|
|
1153
1246
|
try {
|
|
1154
|
-
const iterator = generateFunction(
|
|
1247
|
+
const iterator = generateFunction(fn11);
|
|
1155
1248
|
const generated = [];
|
|
1156
1249
|
let step = iterator.next();
|
|
1157
1250
|
while (!step.done) {
|
|
@@ -1159,32 +1252,32 @@ function makeMutantSource(oracle) {
|
|
|
1159
1252
|
step = iterator.next();
|
|
1160
1253
|
}
|
|
1161
1254
|
if (step.value) {
|
|
1162
|
-
failed.add(
|
|
1163
|
-
notMutated.push({ file:
|
|
1164
|
-
return { fn:
|
|
1255
|
+
failed.add(fn11);
|
|
1256
|
+
notMutated.push({ file: fn11.file, functionName: fn11.name, span: fn11.span, reason: step.value });
|
|
1257
|
+
return { fn: fn11, generated: [] };
|
|
1165
1258
|
}
|
|
1166
|
-
return { fn:
|
|
1259
|
+
return { fn: fn11, generated };
|
|
1167
1260
|
} catch (error3) {
|
|
1168
|
-
failed.add(
|
|
1261
|
+
failed.add(fn11);
|
|
1169
1262
|
notMutated.push({
|
|
1170
|
-
file:
|
|
1171
|
-
functionName:
|
|
1172
|
-
span:
|
|
1263
|
+
file: fn11.file,
|
|
1264
|
+
functionName: fn11.name,
|
|
1265
|
+
span: fn11.span,
|
|
1173
1266
|
reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
|
|
1174
1267
|
});
|
|
1175
|
-
return { fn:
|
|
1268
|
+
return { fn: fn11, generated: [] };
|
|
1176
1269
|
}
|
|
1177
1270
|
});
|
|
1178
|
-
for (const { fn:
|
|
1179
|
-
if (failed.has(
|
|
1271
|
+
for (const { fn: fn11, generated } of generatedFunctions) {
|
|
1272
|
+
if (failed.has(fn11)) continue;
|
|
1180
1273
|
{
|
|
1181
|
-
const reasons = [...
|
|
1182
|
-
if (!generated.length && !reasons.length) reasons.push(
|
|
1183
|
-
const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file ===
|
|
1274
|
+
const reasons = [...fn11.notices ?? []];
|
|
1275
|
+
if (!generated.length && !reasons.length) reasons.push(fn11.skipReason ?? `return not synthesizable (type ${fn11.displayReturnType})`);
|
|
1276
|
+
const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file === fn11.file && inner.startOffset > fn11.startOffset && inner.endOffset < fn11.endOffset && generated2.length > 0);
|
|
1184
1277
|
if (innerMutated && !generated.length) {
|
|
1185
1278
|
for (let i = 0; i < reasons.length; i++) if (reasons[i].startsWith("return not synthesizable")) reasons[i] += "; inner functions mutated";
|
|
1186
1279
|
}
|
|
1187
|
-
if (reasons.length) notMutated.push({ file:
|
|
1280
|
+
if (reasons.length) notMutated.push({ file: fn11.file, functionName: fn11.name, span: fn11.span, reason: [...new Set(reasons)].join("; ") });
|
|
1188
1281
|
}
|
|
1189
1282
|
mutants.push(...generated);
|
|
1190
1283
|
}
|
|
@@ -1196,8 +1289,8 @@ function makeMutantSource(oracle) {
|
|
|
1196
1289
|
}
|
|
1197
1290
|
});
|
|
1198
1291
|
return {
|
|
1199
|
-
notMutated: (config) => discover(config).pipe(Effect.map((
|
|
1200
|
-
generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((
|
|
1292
|
+
notMutated: (config) => discover(config).pipe(Effect.map((result5) => result5.notMutated)),
|
|
1293
|
+
generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result5) => Stream.fromIterable(result5.mutants)))),
|
|
1201
1294
|
checkViable: (mutant) => Effect.sync(() => {
|
|
1202
1295
|
try {
|
|
1203
1296
|
return oracle.checkViable(mutant);
|
|
@@ -1215,13 +1308,85 @@ function makeMutantSource(oracle) {
|
|
|
1215
1308
|
|
|
1216
1309
|
// packages/runner/src/Scratch.ts
|
|
1217
1310
|
import * as Effect2 from "effect/Effect";
|
|
1311
|
+
import * as Console from "effect/Console";
|
|
1218
1312
|
import * as FileSystem from "effect/FileSystem";
|
|
1219
1313
|
import * as Layer2 from "effect/Layer";
|
|
1220
1314
|
import * as Path from "effect/Path";
|
|
1315
|
+
|
|
1316
|
+
// packages/runner/src/Poison.ts
|
|
1317
|
+
function prologueEnd(source) {
|
|
1318
|
+
let position = source.charCodeAt(0) === 65279 ? 1 : 0;
|
|
1319
|
+
if (source.startsWith("#!", position)) {
|
|
1320
|
+
const newline = source.indexOf("\n", position);
|
|
1321
|
+
position = newline < 0 ? source.length : newline + 1;
|
|
1322
|
+
}
|
|
1323
|
+
const trivia = (from) => {
|
|
1324
|
+
let at = from;
|
|
1325
|
+
while (at < source.length) {
|
|
1326
|
+
if (/\s/.test(source[at])) {
|
|
1327
|
+
at++;
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
if (source.startsWith("//", at)) {
|
|
1331
|
+
const end = source.indexOf("\n", at);
|
|
1332
|
+
at = end < 0 ? source.length : end + 1;
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (source.startsWith("/*", at)) {
|
|
1336
|
+
const end = source.indexOf("*/", at + 2);
|
|
1337
|
+
at = end < 0 ? source.length : end + 2;
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
break;
|
|
1341
|
+
}
|
|
1342
|
+
return at;
|
|
1343
|
+
};
|
|
1344
|
+
while (position < source.length) {
|
|
1345
|
+
const start = trivia(position);
|
|
1346
|
+
const quote = source[start];
|
|
1347
|
+
if (quote !== '"' && quote !== "'") break;
|
|
1348
|
+
let end = start + 1;
|
|
1349
|
+
while (end < source.length && source[end] !== quote) end += source[end] === "\\" ? 2 : 1;
|
|
1350
|
+
if (end >= source.length) break;
|
|
1351
|
+
end++;
|
|
1352
|
+
const next = trivia(end);
|
|
1353
|
+
if (source[next] === ";") {
|
|
1354
|
+
position = next + 1;
|
|
1355
|
+
continue;
|
|
1356
|
+
}
|
|
1357
|
+
const continuation = /^(?:[([.`+*/%<>=!?:&,|^~\-]|in\b|instanceof\b)/.test(source.slice(next));
|
|
1358
|
+
if (next === source.length || !continuation && /[\r\n]/.test(source.slice(end, next))) {
|
|
1359
|
+
position = next;
|
|
1360
|
+
continue;
|
|
1361
|
+
}
|
|
1362
|
+
break;
|
|
1363
|
+
}
|
|
1364
|
+
return position;
|
|
1365
|
+
}
|
|
1366
|
+
function poisonInsertion(source, signal, token) {
|
|
1367
|
+
return { offset: prologueEnd(source), text: `
|
|
1368
|
+
try { globalThis.process.getBuiltinModule("node:fs").writeFileSync(${JSON.stringify(signal)}, ${JSON.stringify(token)}); }
|
|
1369
|
+
catch { console.error(${JSON.stringify(token)}); }
|
|
1370
|
+
try { globalThis[globalThis.Symbol.for(${JSON.stringify(token)})] = true; } catch {}
|
|
1371
|
+
throw new Error(${JSON.stringify(token)});
|
|
1372
|
+
` };
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
// packages/runner/src/Scratch.ts
|
|
1221
1376
|
var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
1222
1377
|
const fs = yield* FileSystem.FileSystem;
|
|
1223
1378
|
const path = yield* Path.Path;
|
|
1224
1379
|
const failure = (operation, location, error3) => new ScratchError({ operation, path: location, message: error3.message });
|
|
1380
|
+
const skipVanished = (from, to) => (effect5) => effect5.pipe(Effect2.catch((error3) => {
|
|
1381
|
+
if (error3._tag !== "PlatformError" || error3.reason._tag !== "NotFound") return Effect2.fail(error3);
|
|
1382
|
+
return Effect2.gen(function* () {
|
|
1383
|
+
const entry = yield* fs.lstat(from).pipe(Effect2.result);
|
|
1384
|
+
if (entry._tag === "Success") return yield* Effect2.fail(error3);
|
|
1385
|
+
if (entry.failure.reason._tag !== "NotFound") return yield* Effect2.fail(entry.failure);
|
|
1386
|
+
yield* fs.remove(to, { recursive: true, force: true });
|
|
1387
|
+
yield* Effect2.logDebug("Scratch copy skipped a vanished source", { source: from });
|
|
1388
|
+
});
|
|
1389
|
+
}));
|
|
1225
1390
|
return Scratch.of({
|
|
1226
1391
|
acquire: Effect2.fn("Scratch.acquire")(function* (root) {
|
|
1227
1392
|
const source = path.resolve(root);
|
|
@@ -1240,7 +1405,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1240
1405
|
fs.makeTempDirectory({ prefix: "mutant-cafe-" }).pipe(
|
|
1241
1406
|
Effect2.mapError((error3) => failure("create", source, error3))
|
|
1242
1407
|
),
|
|
1243
|
-
(dir2) => fs.remove(dir2, { recursive: true }).pipe(Effect2.
|
|
1408
|
+
(dir2) => fs.remove(dir2, { recursive: true, force: true }).pipe(Effect2.interruptible, Effect2.timeout(3e4), Effect2.catch((error3) => Console.warn(`Warning: scratch removal did not complete within its cleanup budget: ${error3.message}`, { path: dir2 })))
|
|
1244
1409
|
);
|
|
1245
1410
|
const copy = (from, to, ancestors) => Effect2.gen(function* () {
|
|
1246
1411
|
const real = yield* fs.realPath(from);
|
|
@@ -1262,17 +1427,19 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1262
1427
|
if ([".vite", ".vite-temp", ".vitest", ".cache"].includes(name)) continue;
|
|
1263
1428
|
const dependency = path.join(from2, name);
|
|
1264
1429
|
const destination = path.join(to2, name);
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1430
|
+
yield* Effect2.gen(function* () {
|
|
1431
|
+
if (name.startsWith("@")) {
|
|
1432
|
+
yield* linkDependencies(dependency, destination);
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
const realDependency = yield* fs.realPath(dependency);
|
|
1436
|
+
const rel = path.relative(copyRoot, realDependency);
|
|
1437
|
+
const inside = rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) && !rel.split(path.sep).includes("node_modules");
|
|
1438
|
+
yield* fs.symlink(inside ? path.join(temp, rel) : realDependency, destination);
|
|
1439
|
+
}).pipe(skipVanished(dependency, destination));
|
|
1273
1440
|
}
|
|
1274
1441
|
});
|
|
1275
|
-
yield* linkDependencies(src, dest);
|
|
1442
|
+
yield* linkDependencies(src, dest).pipe(skipVanished(src, dest));
|
|
1276
1443
|
} else {
|
|
1277
1444
|
yield* copy(src, dest, [...ancestors, real]);
|
|
1278
1445
|
}
|
|
@@ -1280,7 +1447,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1280
1447
|
} else if (info.type === "File") {
|
|
1281
1448
|
yield* fs.copyFile(from, to);
|
|
1282
1449
|
}
|
|
1283
|
-
}).pipe(Effect2.mapError((error3) => failure("copy", from, error3)));
|
|
1450
|
+
}).pipe(skipVanished(from, to), Effect2.mapError((error3) => failure("copy", from, error3)));
|
|
1284
1451
|
yield* copy(copyRoot, temp, []);
|
|
1285
1452
|
const packageRoot = yield* fs.realPath(path.join(temp, path.relative(copyRoot, source))).pipe(
|
|
1286
1453
|
Effect2.mapError((error3) => failure("resolve", source, error3))
|
|
@@ -1313,6 +1480,13 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1313
1480
|
}
|
|
1314
1481
|
yield* fs.writeFileString(location, original.slice(0, startOffset) + text + original.slice(endOffset));
|
|
1315
1482
|
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((error3) => failure("apply", mutant.file, error3)))),
|
|
1483
|
+
poison: Effect2.fn("Scratch.poison")(function* (mutant, signal, token) {
|
|
1484
|
+
const location = yield* target(mutant);
|
|
1485
|
+
const bytes = yield* fs.readFile(location).pipe(Effect2.mapError((error3) => failure("probe", location, error3)));
|
|
1486
|
+
const original = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
|
|
1487
|
+
const insertion = poisonInsertion(original, signal, token);
|
|
1488
|
+
yield* dir.apply({ ...mutant, replacement: { startOffset: insertion.offset, endOffset: insertion.offset, text: insertion.text } });
|
|
1489
|
+
}),
|
|
1316
1490
|
revert: Effect2.fn("Scratch.revert")(function* (mutant) {
|
|
1317
1491
|
const location = yield* target(mutant);
|
|
1318
1492
|
const bytes = originals.get(location);
|
|
@@ -1328,15 +1502,428 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1328
1502
|
}));
|
|
1329
1503
|
|
|
1330
1504
|
// packages/runner/src/TestRunner.ts
|
|
1331
|
-
import * as
|
|
1332
|
-
import * as
|
|
1505
|
+
import * as Clock4 from "effect/Clock";
|
|
1506
|
+
import * as Console4 from "effect/Console";
|
|
1333
1507
|
|
|
1334
1508
|
// packages/runner/src/Preflight.ts
|
|
1335
|
-
import * as
|
|
1336
|
-
import * as
|
|
1509
|
+
import * as Effect4 from "effect/Effect";
|
|
1510
|
+
import * as Clock2 from "effect/Clock";
|
|
1511
|
+
import * as Schema6 from "effect/Schema";
|
|
1337
1512
|
import * as ChildProcess from "effect/process/ChildProcess";
|
|
1338
1513
|
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
1339
|
-
|
|
1514
|
+
|
|
1515
|
+
// packages/runner/src/ProcessTree.ts
|
|
1516
|
+
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
1517
|
+
import { types } from "xstate";
|
|
1518
|
+
|
|
1519
|
+
// packages/runner/src/ProcessTrace.ts
|
|
1520
|
+
var processTraceSource = String.raw`
|
|
1521
|
+
import { appendFileSync as appendProcessTrace } from "node:fs";
|
|
1522
|
+
const traceProcess = (stage, details = {}) => {
|
|
1523
|
+
const destination = process.env.MUTANT_CAFE_PROCESS_TRACE;
|
|
1524
|
+
if (destination) try {
|
|
1525
|
+
appendProcessTrace(destination, JSON.stringify({ at: Date.now(), pid: process.pid, ppid: process.ppid, stage, ...details }) + "\n");
|
|
1526
|
+
} catch { /* Diagnostics cannot determine a verdict or prevent cleanup. */ }
|
|
1527
|
+
};
|
|
1528
|
+
`;
|
|
1529
|
+
|
|
1530
|
+
// packages/runner/src/ProcessTree.ts
|
|
1531
|
+
import * as Console2 from "effect/Console";
|
|
1532
|
+
import * as Clock from "effect/Clock";
|
|
1533
|
+
import * as Context2 from "effect/Context";
|
|
1534
|
+
import * as Effect3 from "effect/Effect";
|
|
1535
|
+
import * as FileSystem3 from "effect/FileSystem";
|
|
1536
|
+
import * as Result from "effect/Result";
|
|
1537
|
+
import * as Schema5 from "effect/Schema";
|
|
1538
|
+
import * as Semaphore from "effect/Semaphore";
|
|
1539
|
+
import { execFile } from "node:child_process";
|
|
1540
|
+
import { promisify } from "node:util";
|
|
1541
|
+
import { randomUUID } from "node:crypto";
|
|
1542
|
+
import { pathToFileURL } from "node:url";
|
|
1543
|
+
var execute = promisify(execFile);
|
|
1544
|
+
var liveLedgers = /* @__PURE__ */ new Set();
|
|
1545
|
+
var ProcessInspector = Context2.Reference("mutant.cafe/ProcessInspector", { defaultValue: () => ({ inspect: (args) => Effect3.tryPromise({
|
|
1546
|
+
try: (signal) => execute("/bin/ps", [...args], { signal, encoding: "utf8", maxBuffer: 32 * 1024 * 1024, timeout: 2e3, env: { PATH: process.env.PATH, LC_ALL: "C", TZ: "UTC" } }),
|
|
1547
|
+
catch: () => new TestSpawnError({ command: ["ps"], message: "Cannot inspect owned test processes" })
|
|
1548
|
+
}) }) });
|
|
1549
|
+
var PartialCwd = Schema5.Struct({ code: Schema5.Literal(1), stdout: Schema5.String, signal: Schema5.optional(Schema5.Null), killed: Schema5.optional(Schema5.Literal(false)) });
|
|
1550
|
+
var inspectScratchCwd = (pids, probe2 = {
|
|
1551
|
+
live: (pid) => {
|
|
1552
|
+
if (pid <= 0) return false;
|
|
1553
|
+
try {
|
|
1554
|
+
process.kill(pid, 0);
|
|
1555
|
+
return true;
|
|
1556
|
+
} catch {
|
|
1557
|
+
return false;
|
|
1558
|
+
}
|
|
1559
|
+
},
|
|
1560
|
+
read: (pids2, signal) => execute("/usr/sbin/lsof", ["-b", "-w", "-n", "-P", "-a", "-d", "cwd", "-p", pids2.join(","), "-Fpn"], { signal, encoding: "utf8", timeout: 2e3, maxBuffer: 32 * 1024 * 1024, env: { PATH: process.env.PATH, LC_ALL: "C" } })
|
|
1561
|
+
}) => Effect3.tryPromise({
|
|
1562
|
+
// @effect-diagnostics-next-line asyncFunction:off -- Native execFile adapter preserves partial stdout while Effect supplies cancellation.
|
|
1563
|
+
try: async (signal) => {
|
|
1564
|
+
const live2 = pids.filter(probe2.live);
|
|
1565
|
+
if (!live2.length) return { stdout: "" };
|
|
1566
|
+
try {
|
|
1567
|
+
return await probe2.read(live2, signal);
|
|
1568
|
+
} catch (error3) {
|
|
1569
|
+
const partial = Schema5.decodeUnknownOption(PartialCwd)(error3);
|
|
1570
|
+
if (partial._tag === "Some") return { stdout: partial.value.stdout };
|
|
1571
|
+
throw error3;
|
|
1572
|
+
}
|
|
1573
|
+
},
|
|
1574
|
+
catch: () => new TestSpawnError({ command: ["lsof"], message: "Cannot inspect scratch working directories" })
|
|
1575
|
+
});
|
|
1576
|
+
var tokenKey = "MUTANT_CAFE_PROCESS_TOKEN";
|
|
1577
|
+
var ledgerKey = "MUTANT_CAFE_PROCESS_LEDGER";
|
|
1578
|
+
var preloadKey = "MUTANT_CAFE_PROCESS_PRELOAD";
|
|
1579
|
+
var preloadSource = `import cp from "node:child_process";
|
|
1580
|
+
${processTraceSource}
|
|
1581
|
+
import { appendFileSync } from "node:fs";
|
|
1582
|
+
import { syncBuiltinESMExports } from "node:module";
|
|
1583
|
+
const nativeExec = Symbol.for("mutant.cafe.nativeExecFile");
|
|
1584
|
+
const inspect = cp[nativeExec] ?? (cp[nativeExec] = cp.execFile);
|
|
1585
|
+
const ledger = process.env.${ledgerKey};
|
|
1586
|
+
const token = process.env.${tokenKey};
|
|
1587
|
+
const preload = process.env.${preloadKey};
|
|
1588
|
+
traceProcess("preload-start");
|
|
1589
|
+
// Async native inspection plus an independent timer: execFileSync's timeout
|
|
1590
|
+
// still waits for a kernel-blocked helper to exit, freezing the Node thread.
|
|
1591
|
+
const record = pid => new Promise(resolve => {
|
|
1592
|
+
if (!pid || !ledger) return resolve();
|
|
1593
|
+
const began = performance.now();
|
|
1594
|
+
const phase = process.env.MUTANT_CAFE_PROCESS_PHASE;
|
|
1595
|
+
let settled = false; let child;
|
|
1596
|
+
const done = (stage, started = "") => {
|
|
1597
|
+
if (settled) return;
|
|
1598
|
+
settled = true; clearTimeout(timer);
|
|
1599
|
+
if (started) try { appendFileSync(ledger, JSON.stringify({ pid, birth: started, phase }) + "\\n"); } catch {}
|
|
1600
|
+
traceProcess(stage, { targetPid: pid, elapsedMs: performance.now() - began });
|
|
1601
|
+
resolve();
|
|
1602
|
+
};
|
|
1603
|
+
const timer = setTimeout(() => {
|
|
1604
|
+
done("ps-record-timeout");
|
|
1605
|
+
try { child?.kill("SIGKILL"); } catch {}
|
|
1606
|
+
child?.stdout?.destroy(); child?.stderr?.destroy(); child?.unref();
|
|
1607
|
+
}, 1000);
|
|
1608
|
+
traceProcess("ps-record-start", { targetPid: pid });
|
|
1609
|
+
try {
|
|
1610
|
+
child = inspect("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", timeout: 1000, killSignal: "SIGKILL", env: { LC_ALL: "C", TZ: "UTC" } }, (error, stdout) => done(error ? "ps-record-failed" : "ps-record-done", error ? "" : stdout.trim()));
|
|
1611
|
+
} catch { done("ps-record-failed"); }
|
|
1612
|
+
});
|
|
1613
|
+
if (ledger && token && preload) {
|
|
1614
|
+
// Await only our own birth before user code can busy-loop. Child-spawn records
|
|
1615
|
+
// are asynchronous; implicit Node children also record themselves here.
|
|
1616
|
+
await record(process.pid);
|
|
1617
|
+
traceProcess("preload-ready");
|
|
1618
|
+
const environment = node => {
|
|
1619
|
+
const env = { ...process.env };
|
|
1620
|
+
const ownImport = "--import=" + preload;
|
|
1621
|
+
const original = (env.NODE_OPTIONS || "").replaceAll(ownImport, "").trim();
|
|
1622
|
+
if (node && env.${ledgerKey} === ledger && env.${tokenKey} === token) env.NODE_OPTIONS = (original + " " + ownImport).trim();
|
|
1623
|
+
else if (original) env.NODE_OPTIONS = original;
|
|
1624
|
+
else delete env.NODE_OPTIONS;
|
|
1625
|
+
return env;
|
|
1626
|
+
};
|
|
1627
|
+
const options = (value, node) => value?.env !== undefined ? value : ({ ...value, env: environment(node) });
|
|
1628
|
+
for (const name of ["spawn", "fork", "execFile", "exec"]) {
|
|
1629
|
+
const original = cp[name];
|
|
1630
|
+
const wrapped = function (...args) {
|
|
1631
|
+
const index = name === "exec" ? 1 : Array.isArray(args[1]) || (args[1] === undefined && args.length > 2) ? 2 : 1;
|
|
1632
|
+
const value = typeof args[index] === "object" && args[index] !== null ? args[index] : undefined;
|
|
1633
|
+
const node = name === "fork" ? (value?.execPath || process.execPath) === process.execPath : args[0] === process.execPath;
|
|
1634
|
+
if (typeof args[index] === "function") args.splice(index, 0, options(undefined, node));
|
|
1635
|
+
else args[index] = options(value, node);
|
|
1636
|
+
traceProcess("spawn-start", { method: name, node });
|
|
1637
|
+
const child = original.apply(this, args);
|
|
1638
|
+
traceProcess("spawn-return", { method: name, childPid: child.pid, node });
|
|
1639
|
+
child.once("spawn", () => traceProcess("spawn", { method: name, childPid: child.pid, node }));
|
|
1640
|
+
// Exact birth inspection cannot block spawn: a minimal-env child can be
|
|
1641
|
+
// orphaned before this async callback if its parent exits immediately.
|
|
1642
|
+
// Without a birth row, surviving PPID edge or label, it stays warning-only
|
|
1643
|
+
// (cwd/argv backstop). A PID plus approximate spawn time is not reuse proof.
|
|
1644
|
+
void record(child.pid);
|
|
1645
|
+
return child;
|
|
1646
|
+
};
|
|
1647
|
+
const custom = Symbol.for("nodejs.util.promisify.custom");
|
|
1648
|
+
const descriptors = Object.getOwnPropertyDescriptors(original);
|
|
1649
|
+
delete descriptors[custom];
|
|
1650
|
+
Object.defineProperties(wrapped, descriptors);
|
|
1651
|
+
if (name === "exec" || name === "execFile") Object.defineProperty(wrapped, custom, { value: (...args) => {
|
|
1652
|
+
let child;
|
|
1653
|
+
const promise = new Promise((resolve, reject) => {
|
|
1654
|
+
child = wrapped(...args, (error, stdout, stderr) => {
|
|
1655
|
+
if (error) { error.stdout = stdout; error.stderr = stderr; reject(error); }
|
|
1656
|
+
else resolve({ stdout, stderr });
|
|
1657
|
+
});
|
|
1658
|
+
});
|
|
1659
|
+
promise.child = child;
|
|
1660
|
+
return promise;
|
|
1661
|
+
} });
|
|
1662
|
+
cp[name] = wrapped;
|
|
1663
|
+
}
|
|
1664
|
+
syncBuiltinESMExports();
|
|
1665
|
+
}
|
|
1666
|
+
`;
|
|
1667
|
+
var Record2 = Schema5.Struct({ pid: Schema5.Int, birth: Schema5.String });
|
|
1668
|
+
var acquireProcessTree = Effect3.fn("ProcessTree.acquire")(function* (scratch, onBackstop, processesSince) {
|
|
1669
|
+
const fs = yield* FileSystem3.FileSystem;
|
|
1670
|
+
const directory = yield* fs.makeTempDirectory({ prefix: "mutant-processes-" });
|
|
1671
|
+
const ledger = `${directory}/pids.jsonl`;
|
|
1672
|
+
const script = `${directory}/register.mjs`;
|
|
1673
|
+
const token = yield* Effect3.sync(randomUUID);
|
|
1674
|
+
const url = pathToFileURL(script).href;
|
|
1675
|
+
yield* fs.writeFileString(ledger, "");
|
|
1676
|
+
yield* fs.writeFileString(script, preloadSource);
|
|
1677
|
+
liveLedgers.add(ledger);
|
|
1678
|
+
const trace = (stage, details = {}) => {
|
|
1679
|
+
const destination = process.env.MUTANT_CAFE_PROCESS_TRACE;
|
|
1680
|
+
return destination ? Clock.currentTimeMillis.pipe(Effect3.flatMap((at) => fs.writeFileString(destination, JSON.stringify({ at, pid: process.pid, ppid: process.ppid, stage, ...details }) + "\n", { flag: "a" })), Effect3.timeout(100), Effect3.catch(() => Effect3.void)) : Effect3.void;
|
|
1681
|
+
};
|
|
1682
|
+
const roots = /* @__PURE__ */ new Set();
|
|
1683
|
+
const command = ["vitest", "process-cleanup"];
|
|
1684
|
+
const inspector = yield* ProcessInspector;
|
|
1685
|
+
let deadline = Infinity;
|
|
1686
|
+
let lastSnapshot;
|
|
1687
|
+
let ledgerRows = [];
|
|
1688
|
+
const verified = /* @__PURE__ */ new Map();
|
|
1689
|
+
let effectiveKeep = /* @__PURE__ */ new Set();
|
|
1690
|
+
const kill = inspector.signal ?? ((pid, signal2) => {
|
|
1691
|
+
process.kill(pid, signal2);
|
|
1692
|
+
});
|
|
1693
|
+
const bounded = (phase, effect5, limit = 7e3) => Effect3.suspend(() => {
|
|
1694
|
+
const remaining = Math.min(limit, deadline - performance.now());
|
|
1695
|
+
if (remaining <= 0) return Effect3.fail(new TestSpawnError({ command, message: `Cleanup deadline exceeded during ${phase}` }));
|
|
1696
|
+
return effect5.pipe(Effect3.interruptible, Effect3.timeout(remaining), Effect3.mapError(() => new TestSpawnError({ command, message: `Cleanup ${phase} failed or exceeded its ${Math.ceil(remaining)} ms budget` })));
|
|
1697
|
+
});
|
|
1698
|
+
const inspect = (args) => bounded("ps inspection", Effect3.gen(function* () {
|
|
1699
|
+
const began = performance.now();
|
|
1700
|
+
yield* trace("inspect-start", { operation: args[0] ?? "ps" });
|
|
1701
|
+
const result5 = yield* inspector.inspect(args);
|
|
1702
|
+
yield* trace("inspect-done", { elapsedMs: performance.now() - began });
|
|
1703
|
+
return result5;
|
|
1704
|
+
}), 2e3);
|
|
1705
|
+
const snapshot = Effect3.gen(function* () {
|
|
1706
|
+
const result5 = yield* inspect(["-A", "-ww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,args="]);
|
|
1707
|
+
const found = /* @__PURE__ */ new Map();
|
|
1708
|
+
for (const line of result5.stdout.split("\n")) {
|
|
1709
|
+
const match2 = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})(?:\s+(.*))?$/.exec(line);
|
|
1710
|
+
if (!match2) continue;
|
|
1711
|
+
const pid = Number(match2[1]);
|
|
1712
|
+
if (pid !== process.pid && !match2[4].startsWith("Z")) found.set(pid, { pid, ppid: Number(match2[2]), pgid: Number(match2[3]), state: match2[4], birth: match2[5].trim(), argv: match2[6] ?? "" });
|
|
1713
|
+
}
|
|
1714
|
+
for (const [pid, item] of verified) if (found.get(pid)?.birth !== item.birth) verified.delete(pid);
|
|
1715
|
+
lastSnapshot = found;
|
|
1716
|
+
return found;
|
|
1717
|
+
});
|
|
1718
|
+
const discover = (preserved, retained) => Effect3.gen(function* () {
|
|
1719
|
+
const registered = yield* fs.readFileString(ledger).pipe(Effect3.mapError(() => new TestSpawnError({ command, message: "Cannot read the test process ownership ledger" })));
|
|
1720
|
+
ledgerRows = registered.split("\n").flatMap((line) => {
|
|
1721
|
+
const parsed = Schema5.decodeOption(Schema5.fromJsonString(Record2))(line);
|
|
1722
|
+
return parsed._tag === "Some" ? [parsed.value] : [];
|
|
1723
|
+
});
|
|
1724
|
+
const table = yield* snapshot;
|
|
1725
|
+
const keep = new Set(preserved);
|
|
1726
|
+
const subtrees = new Set(retained.filter((item) => table.get(item.pid)?.birth === item.birth).map((item) => item.pid));
|
|
1727
|
+
let keepAdded;
|
|
1728
|
+
do {
|
|
1729
|
+
keepAdded = false;
|
|
1730
|
+
for (const item of table.values()) if (subtrees.has(item.ppid) && !subtrees.has(item.pid)) {
|
|
1731
|
+
subtrees.add(item.pid);
|
|
1732
|
+
keepAdded = true;
|
|
1733
|
+
}
|
|
1734
|
+
} while (keepAdded);
|
|
1735
|
+
for (const pid of subtrees) keep.add(pid);
|
|
1736
|
+
effectiveKeep = keep;
|
|
1737
|
+
const owned = /* @__PURE__ */ new Set();
|
|
1738
|
+
const claim = (pid) => {
|
|
1739
|
+
owned.add(pid);
|
|
1740
|
+
const item = table.get(pid);
|
|
1741
|
+
if (item && !keep.has(pid)) verified.set(pid, item);
|
|
1742
|
+
};
|
|
1743
|
+
const closeDescendants = () => {
|
|
1744
|
+
let added;
|
|
1745
|
+
do {
|
|
1746
|
+
added = false;
|
|
1747
|
+
for (const item of table.values()) if (owned.has(item.ppid) && !owned.has(item.pid)) {
|
|
1748
|
+
claim(item.pid);
|
|
1749
|
+
added = true;
|
|
1750
|
+
}
|
|
1751
|
+
} while (added);
|
|
1752
|
+
};
|
|
1753
|
+
const uncertain = /* @__PURE__ */ new Set();
|
|
1754
|
+
for (const item of ledgerRows) if (table.get(item.pid)?.birth === item.birth) claim(item.pid);
|
|
1755
|
+
closeDescendants();
|
|
1756
|
+
if (process.platform === "linux") {
|
|
1757
|
+
yield* Effect3.forEach([...table.keys()], (pid) => fs.readFileString(`/proc/${pid}/environ`).pipe(
|
|
1758
|
+
Effect3.catch(() => Effect3.succeed("")),
|
|
1759
|
+
Effect3.tap((environment) => Effect3.sync(() => {
|
|
1760
|
+
if (!owned.has(pid) && environment.split("\0").includes(`${tokenKey}=${token}`)) {
|
|
1761
|
+
claim(pid);
|
|
1762
|
+
closeDescendants();
|
|
1763
|
+
}
|
|
1764
|
+
}))
|
|
1765
|
+
), { concurrency: 8, discard: true });
|
|
1766
|
+
} else {
|
|
1767
|
+
const labelled = yield* inspect(["axeww", "-o", "pid=,lstart=,command="]);
|
|
1768
|
+
const label = new RegExp("(?:^|\\s)" + tokenKey + "=" + token + "(?:\\s|$)");
|
|
1769
|
+
const rows = [...labelled.stdout.matchAll(/^\s*(\d+)\s+((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s/gm)];
|
|
1770
|
+
for (const [index, row] of rows.entries()) {
|
|
1771
|
+
const pid = Number(row[1]);
|
|
1772
|
+
const record = labelled.stdout.slice(row.index, rows[index + 1]?.index);
|
|
1773
|
+
if (owned.has(pid) || table.get(pid)?.birth !== row[2]?.trim() || !label.test(record)) continue;
|
|
1774
|
+
const argv = yield* inspect(["ww", "-p", String(pid), "-o", "command="]).pipe(Effect3.result);
|
|
1775
|
+
const environment = yield* inspect(["eww", "-p", String(pid), "-o", "command="]).pipe(Effect3.result);
|
|
1776
|
+
const after = yield* inspect(["ww", "-p", String(pid), "-o", "command="]).pipe(Effect3.result);
|
|
1777
|
+
if (Result.isFailure(argv) || Result.isFailure(environment) || Result.isFailure(after)) continue;
|
|
1778
|
+
const prefix = argv.success.stdout.trimEnd();
|
|
1779
|
+
if (prefix && prefix === after.success.stdout.trimEnd() && environment.success.stdout.startsWith(prefix + " ") && label.test(environment.success.stdout.slice(prefix.length))) uncertain.add(pid);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
closeDescendants();
|
|
1783
|
+
const unverified = [...uncertain].filter((pid) => !owned.has(pid));
|
|
1784
|
+
if (unverified.length && ![...owned].some((pid) => !keep.has(pid))) return yield* new TestSpawnError({ command, message: `Cannot verify test process ownership for PIDs: ${unverified.join(", ")}; not signalled` });
|
|
1785
|
+
if (unverified.length) yield* Console2.warn(`Warning: unverified process PIDs ${unverified.join(", ")}; not signalled. Cleaning verified descendants first.`);
|
|
1786
|
+
return [...owned].flatMap((pid) => table.has(pid) && !keep.has(pid) ? [table.get(pid)] : []);
|
|
1787
|
+
});
|
|
1788
|
+
const signal = (pending, value) => Effect3.gen(function* () {
|
|
1789
|
+
const current = yield* snapshot;
|
|
1790
|
+
for (const item of pending) {
|
|
1791
|
+
if (current.get(item.pid)?.birth !== item.birth) continue;
|
|
1792
|
+
yield* Effect3.sync(() => {
|
|
1793
|
+
try {
|
|
1794
|
+
if (roots.has(item.pid) && current.get(item.pid)?.pgid === item.pid) kill(-item.pid, value);
|
|
1795
|
+
} catch {
|
|
1796
|
+
}
|
|
1797
|
+
try {
|
|
1798
|
+
kill(item.pid, value);
|
|
1799
|
+
} catch {
|
|
1800
|
+
}
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
const inspectUnowned = Effect3.gen(function* () {
|
|
1805
|
+
if (!scratch) return;
|
|
1806
|
+
const table = lastSnapshot ?? (yield* snapshot);
|
|
1807
|
+
const registered = yield* Effect3.forEach([...liveLedgers], (path) => fs.readFileString(path).pipe(Effect3.catch(() => Effect3.succeed(""))));
|
|
1808
|
+
const known = new Set(registered.join("\n").split("\n").flatMap((line) => {
|
|
1809
|
+
const parsed = Schema5.decodeOption(Schema5.fromJsonString(Record2))(line);
|
|
1810
|
+
return parsed._tag === "Some" && table.get(parsed.value.pid)?.birth === parsed.value.birth ? [parsed.value.pid] : [];
|
|
1811
|
+
}));
|
|
1812
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
1813
|
+
const since = processesSince === void 0 ? -Infinity : Math.floor(processesSince / 1e3) * 1e3;
|
|
1814
|
+
const possible = [...table.values()].filter((item) => !known.has(item.pid) && (processesSince === void 0 || Date.parse(item.birth + " UTC") >= since));
|
|
1815
|
+
for (const item of possible) if (item.argv.includes(scratch)) candidates.add(item.pid);
|
|
1816
|
+
if (process.platform === "linux") yield* Effect3.forEach(possible.map((item) => item.pid), (pid) => fs.readLink(`/proc/${pid}/cwd`).pipe(
|
|
1817
|
+
Effect3.catch(() => Effect3.succeed("")),
|
|
1818
|
+
Effect3.tap((cwd) => Effect3.sync(() => {
|
|
1819
|
+
if (cwd === scratch || cwd.startsWith(scratch + "/")) candidates.add(pid);
|
|
1820
|
+
}))
|
|
1821
|
+
), { concurrency: 8, discard: true });
|
|
1822
|
+
else if (process.platform === "darwin" && possible.length) {
|
|
1823
|
+
const cwdStarted = performance.now();
|
|
1824
|
+
yield* trace("cwd-start", { candidates: possible.length });
|
|
1825
|
+
const cwd = yield* inspectScratchCwd(possible.map((item) => item.pid)).pipe(Effect3.catch(() => Console2.warn("Warning: cannot inspect scratch working directories; argv backstop remains active").pipe(Effect3.as({ stdout: "" }))));
|
|
1826
|
+
yield* trace("cwd-done", { elapsedMs: performance.now() - cwdStarted });
|
|
1827
|
+
let pid = 0;
|
|
1828
|
+
for (const row of cwd.stdout.split("\n")) {
|
|
1829
|
+
if (row.startsWith("p")) pid = Number(row.slice(1));
|
|
1830
|
+
if (row.startsWith("n") && (row.slice(1) === scratch || row.slice(1).startsWith(scratch + "/"))) candidates.add(pid);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
const survivors = [...candidates].filter((pid) => table.has(pid) && !known.has(pid));
|
|
1834
|
+
if (survivors.length) yield* Console2.warn(`Warning: unowned scratch-related process PIDs ${survivors.join(", ")} survived; not signalled because ownership is unproven`);
|
|
1835
|
+
}).pipe(Effect3.catch(() => Console2.warn("Warning: cannot inspect unowned scratch-related survivors; no unverified PID was signalled")));
|
|
1836
|
+
const warnUnowned = Effect3.gen(function* () {
|
|
1837
|
+
if (!scratch) return;
|
|
1838
|
+
const started = yield* Clock.currentTimeMillis;
|
|
1839
|
+
if (!lastSnapshot) return yield* Console2.warn("Warning: scratch backstop unavailable without a process snapshot; no unverified PID was signalled");
|
|
1840
|
+
yield* bounded("scratch backstop", inspectUnowned, 2e3).pipe(Effect3.catch((error3) => Console2.warn(`Warning: ${error3.message}; unowned PIDs were not signalled`)));
|
|
1841
|
+
const elapsed = Math.max(0, (yield* Clock.currentTimeMillis) - started);
|
|
1842
|
+
yield* Effect3.sync(() => onBackstop?.(elapsed));
|
|
1843
|
+
});
|
|
1844
|
+
const semaphore = yield* Semaphore.make(1);
|
|
1845
|
+
let closed;
|
|
1846
|
+
const sweep = (preserved, retained = []) => Effect3.scoped(Effect3.gen(function* () {
|
|
1847
|
+
deadline = performance.now() + 1e4;
|
|
1848
|
+
lastSnapshot = void 0;
|
|
1849
|
+
ledgerRows = [];
|
|
1850
|
+
verified.clear();
|
|
1851
|
+
const keep = new Set(preserved);
|
|
1852
|
+
effectiveKeep = keep;
|
|
1853
|
+
const discovering = createEffectLogic(() => bounded("discovery", discover(keep, retained)).pipe(Effect3.result));
|
|
1854
|
+
const stopping = createEffectLogic(({ input }) => bounded("stop", signal(input, "SIGSTOP"), 3e3).pipe(Effect3.result));
|
|
1855
|
+
const killing = createEffectLogic(({ input }) => bounded("kill", signal(input, "SIGKILL"), 3e3).pipe(Effect3.result));
|
|
1856
|
+
const machine = setupEffect({
|
|
1857
|
+
schemas: { context: types(), events: { CLOSE: Schema5.Struct({}) } },
|
|
1858
|
+
actors: { discovering, stopping, killing }
|
|
1859
|
+
}).createMachine({
|
|
1860
|
+
context: { pending: [], round: 0, failure: void 0 },
|
|
1861
|
+
output: ({ context }) => context,
|
|
1862
|
+
initial: "tracking",
|
|
1863
|
+
states: {
|
|
1864
|
+
tracking: { on: { CLOSE: { target: "discovering" } } },
|
|
1865
|
+
discovering: { invoke: { src: "discovering", onDone: ({ context, event }) => Result.isFailure(event.output) ? { target: "failed", context: { ...context, failure: event.output.failure.message } } : { target: event.output.success.length ? "stopping" : "closed", context: { ...context, pending: event.output.success } } } },
|
|
1866
|
+
stopping: { invoke: { src: "stopping", input: ({ context }) => context.pending, onDone: ({ context, event }) => Result.isFailure(event.output) ? { target: "failed", context: { ...context, failure: event.output.failure.message } } : { target: "killing" } } },
|
|
1867
|
+
killing: { invoke: { src: "killing", input: ({ context }) => context.pending, onDone: ({ context, event }) => Result.isFailure(event.output) ? { target: "failed", context: { ...context, failure: event.output.failure.message } } : { target: "verifying" } } },
|
|
1868
|
+
verifying: { invoke: { src: "discovering", onDone: ({ context, event }) => {
|
|
1869
|
+
if (Result.isFailure(event.output)) return { target: "failed", context: { ...context, failure: event.output.failure.message } };
|
|
1870
|
+
const remaining = event.output.success;
|
|
1871
|
+
if (!remaining.length) return { target: "closed", context: { ...context, pending: [] } };
|
|
1872
|
+
return context.round < 3 ? { target: "stopping", context: { ...context, pending: remaining, round: context.round + 1 } } : { target: "failed", context: { ...context, pending: remaining, failure: `Cannot kill owned test PIDs: ${remaining.map((item) => item.pid).join(", ")}` } };
|
|
1873
|
+
} } },
|
|
1874
|
+
closed: { type: "final" },
|
|
1875
|
+
failed: { type: "final" }
|
|
1876
|
+
}
|
|
1877
|
+
});
|
|
1878
|
+
const actor = yield* createEffectActor(machine);
|
|
1879
|
+
yield* send(actor, { type: "CLOSE" });
|
|
1880
|
+
const joined = yield* bounded("state machine", join(actor), 8e3).pipe(Effect3.result);
|
|
1881
|
+
const result5 = joined._tag === "Success" ? joined.success : { ...actor.getSnapshot().context, failure: joined.failure.message };
|
|
1882
|
+
if (result5.failure) {
|
|
1883
|
+
yield* Effect3.sync(() => {
|
|
1884
|
+
actor.stop();
|
|
1885
|
+
for (const item of verified.values()) {
|
|
1886
|
+
try {
|
|
1887
|
+
kill(item.pid, "SIGKILL");
|
|
1888
|
+
} catch {
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
});
|
|
1892
|
+
const unverified = [...new Set(ledgerRows.filter((item) => !verified.has(item.pid) && !effectiveKeep.has(item.pid)).map((item) => item.pid))];
|
|
1893
|
+
yield* Console2.warn(`Warning: cleanup degraded; SIGKILL attempted for birth-verified PIDs ${[...verified.keys()].join(", ") || "none"}; exit unconfirmed; unverified ledger PIDs ${unverified.join(", ") || "none"} were not signalled`);
|
|
1894
|
+
}
|
|
1895
|
+
yield* warnUnowned;
|
|
1896
|
+
if (result5.failure) yield* Console2.warn(`Warning: ${result5.failure} (tracked PIDs ${(result5.pending.length ? result5.pending.map((item) => item.pid) : [...roots]).join(", ")}); ownership ledger kept at ${ledger}; continuing without reusing the host`);
|
|
1897
|
+
return result5.failure ? "warning" : "clean";
|
|
1898
|
+
})).pipe(Effect3.uninterruptible);
|
|
1899
|
+
const reap = (preserved, retained = []) => semaphore.withPermit(Effect3.suspend(() => closed === void 0 ? sweep(preserved, retained) : Effect3.succeed(closed)));
|
|
1900
|
+
const cleanup = semaphore.withPermit(Effect3.gen(function* () {
|
|
1901
|
+
if (closed === void 0) closed = yield* sweep([]);
|
|
1902
|
+
}));
|
|
1903
|
+
yield* Effect3.addFinalizer(() => Effect3.gen(function* () {
|
|
1904
|
+
yield* cleanup;
|
|
1905
|
+
if (closed === "clean") yield* fs.remove(directory, { recursive: true }).pipe(
|
|
1906
|
+
Effect3.interruptible,
|
|
1907
|
+
Effect3.timeout(2e3),
|
|
1908
|
+
Effect3.catch((error3) => Console2.warn(`Warning: cannot remove process ledger directory: ${error3.message}`))
|
|
1909
|
+
);
|
|
1910
|
+
}).pipe(Effect3.ensuring(Effect3.sync(() => {
|
|
1911
|
+
liveLedgers.delete(ledger);
|
|
1912
|
+
}))));
|
|
1913
|
+
const existing = process.env.NODE_OPTIONS ?? "";
|
|
1914
|
+
return {
|
|
1915
|
+
env: { ...process.env, MUTANT_CAFE_PROCESS_PHASE: void 0, [tokenKey]: token, [ledgerKey]: ledger, [preloadKey]: url, NODE_OPTIONS: `${existing} --import=${url}`.trim() },
|
|
1916
|
+
addRoot: (pid) => {
|
|
1917
|
+
roots.add(pid);
|
|
1918
|
+
},
|
|
1919
|
+
cleanup,
|
|
1920
|
+
reap,
|
|
1921
|
+
trace
|
|
1922
|
+
};
|
|
1923
|
+
});
|
|
1924
|
+
|
|
1925
|
+
// packages/runner/src/Preflight.ts
|
|
1926
|
+
var Issues = Schema6.Array(SelectionIssue);
|
|
1340
1927
|
var probe = String.raw`
|
|
1341
1928
|
import { readFile, readdir } from "node:fs/promises";
|
|
1342
1929
|
import { resolve, relative, dirname, isAbsolute, sep } from "node:path";
|
|
@@ -1478,13 +2065,17 @@ if (otherRunner) {
|
|
|
1478
2065
|
}
|
|
1479
2066
|
console.log('mutant-cafe-preflight:' + JSON.stringify([...new Map(issues.map(issue => [JSON.stringify(issue), issue])).values()]));
|
|
1480
2067
|
`;
|
|
1481
|
-
var preflight =
|
|
2068
|
+
var preflight = Effect4.fn("TestRunner.preflight")(function* (root, tsconfig = "tsconfig.json", timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS, options = {}) {
|
|
1482
2069
|
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
1483
|
-
const
|
|
2070
|
+
const since = options.processesSince ?? (yield* Clock2.currentTimeMillis);
|
|
2071
|
+
const owned = yield* acquireProcessTree(root, options.onBackstop, since);
|
|
2072
|
+
yield* owned.trace("preflight-start", { budgetMs: timeoutMs });
|
|
2073
|
+
const output = yield* spawner.string(ChildProcess.make(process.execPath, ["--input-type=module", "--eval", probe, tsconfig], { cwd: root, env: owned.env, detached: true, killSignal: "SIGKILL", forceKillAfter: "100 millis", stdin: "ignore" })).pipe(Effect4.onInterrupt(() => owned.cleanup));
|
|
2074
|
+
yield* owned.trace("preflight-done");
|
|
1484
2075
|
const encoded = output.split("\n").find((line) => line.startsWith("mutant-cafe-preflight:"))?.slice("mutant-cafe-preflight:".length);
|
|
1485
|
-
const issues = encoded === void 0 ? [{ kind: "warning", reason: "Vitest selection probe returned no evidence" }] : yield*
|
|
2076
|
+
const issues = encoded === void 0 ? [{ kind: "warning", reason: "Vitest selection probe returned no evidence" }] : yield* Schema6.decodeEffect(Schema6.fromJsonString(Issues))(encoded);
|
|
1486
2077
|
return issues;
|
|
1487
|
-
});
|
|
2078
|
+
}, (effect5, _root, _tsconfig = "tsconfig.json", timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS, _options = {}) => effect5.pipe(Effect4.timeout(timeoutMs), Effect4.scoped));
|
|
1488
2079
|
function unreliableFor(baseline, file, testFiles) {
|
|
1489
2080
|
return baseline.unreliable?.filter((issue) => {
|
|
1490
2081
|
switch (issue.kind) {
|
|
@@ -1501,110 +2092,1063 @@ function unreliableFor(baseline, file, testFiles) {
|
|
|
1501
2092
|
}
|
|
1502
2093
|
|
|
1503
2094
|
// packages/runner/src/TestRunner.ts
|
|
1504
|
-
import * as
|
|
2095
|
+
import * as Effect6 from "effect/Effect";
|
|
1505
2096
|
import * as Layer3 from "effect/Layer";
|
|
1506
|
-
import * as
|
|
2097
|
+
import * as FileSystem7 from "effect/FileSystem";
|
|
1507
2098
|
import * as Path3 from "effect/Path";
|
|
1508
2099
|
import * as Stream2 from "effect/Stream";
|
|
1509
|
-
import * as
|
|
2100
|
+
import * as Schema8 from "effect/Schema";
|
|
2101
|
+
import * as Scope3 from "effect/Scope";
|
|
2102
|
+
import { createRequire } from "node:module";
|
|
2103
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
1510
2104
|
import * as ChildProcess2 from "effect/process/ChildProcess";
|
|
1511
2105
|
import * as ChildProcessSpawner3 from "effect/process/ChildProcessSpawner";
|
|
1512
|
-
|
|
2106
|
+
|
|
2107
|
+
// packages/runner/src/WarmRunner.ts
|
|
2108
|
+
import { createEffectActor as createEffectActor2, send as send2, setupEffect as setupEffect2 } from "@xstate/effect";
|
|
2109
|
+
import { spawn } from "node:child_process";
|
|
2110
|
+
import * as Clock3 from "effect/Clock";
|
|
2111
|
+
import * as Effect5 from "effect/Effect";
|
|
2112
|
+
import * as Console3 from "effect/Console";
|
|
2113
|
+
import * as FileSystem5 from "effect/FileSystem";
|
|
2114
|
+
import * as Schema7 from "effect/Schema";
|
|
2115
|
+
import * as Scope from "effect/Scope";
|
|
2116
|
+
import * as Exit from "effect/Exit";
|
|
2117
|
+
|
|
2118
|
+
// packages/runner/src/WarmPolicy.ts
|
|
2119
|
+
var warmPolicySource = String.raw`
|
|
2120
|
+
function warmRefusal(version, ctx, selectionOnly = false) {
|
|
2121
|
+
if (!/^5\./.test(version)) return "unverified Vitest major: " + version + " (verified: 5)";
|
|
2122
|
+
if (!ctx) return null;
|
|
2123
|
+
const writable = (object, key) => {
|
|
2124
|
+
while (object) {
|
|
2125
|
+
const field = Object.getOwnPropertyDescriptor(object, key);
|
|
2126
|
+
if (field) return field.writable === true;
|
|
2127
|
+
object = Object.getPrototypeOf(object);
|
|
2128
|
+
}
|
|
2129
|
+
return false;
|
|
2130
|
+
};
|
|
2131
|
+
for (const key of ["pool", "cancelPromise", "runningPromise", "configOverride", "reporters", "initializeGlobalSetup"])
|
|
2132
|
+
if (!(key in ctx) || !writable(ctx, key)) return "unsupported private field: " + key;
|
|
2133
|
+
if (!Object.isExtensible(ctx) || !Object.isExtensible(ctx.configOverride) || typeof ctx.watcher?.invalidates?.add !== "function" || typeof ctx.vite?.transformRequest !== "function")
|
|
2134
|
+
return "unsupported transform/invalidation boundary";
|
|
2135
|
+
if (!Object.isExtensible(ctx.config) || ctx.projects.some(project => !project.vite?.environments || Object.values(project.vite.environments).some(environment => typeof environment.moduleGraph?.getModulesByFile !== "function")))
|
|
2136
|
+
return "unsupported private module graph";
|
|
2137
|
+
if (selectionOnly) return null;
|
|
2138
|
+
for (const config of [ctx.config, ...ctx.projects.flatMap(project => [project.config, project.vite.config.test ?? {}])]) {
|
|
2139
|
+
if (config.globalSetup && (!Array.isArray(config.globalSetup) || config.globalSetup.length)) return "globalSetup requires cold execution for per-mutant parity";
|
|
2140
|
+
if (config.browser?.enabled || (config.pool !== undefined && !["forks", "threads"].includes(config.pool))) return "unsupported warm pool: " + (config.browser?.enabled ? "browser" : (typeof config.pool === "string" ? config.pool : "custom"));
|
|
2141
|
+
}
|
|
2142
|
+
return null;
|
|
2143
|
+
}
|
|
2144
|
+
`;
|
|
2145
|
+
var workerDeathSource = String.raw`
|
|
2146
|
+
function workerDied(error, seen = new Set()) {
|
|
2147
|
+
if (!error || typeof error !== "object" || seen.has(error)) return false;
|
|
2148
|
+
seen.add(error);
|
|
2149
|
+
const description = String(error.name ?? "") + " " + String(error.message ?? "");
|
|
2150
|
+
const diagnostic = error.name !== "AssertionError";
|
|
2151
|
+
return (diagnostic && (description.includes("Worker exited unexpectedly") || description.includes("[vitest-pool]:")
|
|
2152
|
+
|| (typeof error.code === "string" && error.code.startsWith("ERR_WORKER_"))))
|
|
2153
|
+
|| workerDied(error.cause, seen) || workerDied(error.error, seen) || workerDied(error.result, seen)
|
|
2154
|
+
|| (Array.isArray(error.errors) && error.errors.some(item => workerDied(item, seen)))
|
|
2155
|
+
|| (Array.isArray(error.tasks) && error.tasks.some(item => workerDied(item, seen)));
|
|
2156
|
+
}
|
|
2157
|
+
`;
|
|
2158
|
+
|
|
2159
|
+
// packages/runner/src/VitestHost.ts
|
|
2160
|
+
var vitestLauncherSource = `
|
|
2161
|
+
import { createRequire } from "node:module";
|
|
2162
|
+
import { dirname, resolve } from "node:path";
|
|
2163
|
+
import { pathToFileURL } from "node:url";
|
|
2164
|
+
${processTraceSource}
|
|
2165
|
+
traceProcess("vitest-resolve-start");
|
|
2166
|
+
const require = createRequire(pathToFileURL(process.cwd() + "/package.json"));
|
|
2167
|
+
const pkgFile = require.resolve("vitest/package.json");
|
|
2168
|
+
const pkg = require(pkgFile);
|
|
2169
|
+
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.vitest;
|
|
2170
|
+
if (typeof bin !== "string") throw new Error("Installed Vitest has no CLI bin");
|
|
2171
|
+
const cli = resolve(dirname(pkgFile), bin);
|
|
2172
|
+
process.argv = [process.execPath, cli, ...process.argv.slice(2)];
|
|
2173
|
+
traceProcess("vitest-resolved");
|
|
2174
|
+
await import(pathToFileURL(cli).href);
|
|
2175
|
+
`;
|
|
2176
|
+
var reporterSource = (marker, probe2) => `
|
|
2177
|
+
import { relative, dirname } from "node:path";
|
|
2178
|
+
${processTraceSource}
|
|
2179
|
+
${workerDeathSource}
|
|
2180
|
+
export default class {
|
|
2181
|
+
files = []; collected = false; failed = false; durations = {}; timeouts = {}; workers = 0; concurrency = 0; fileDurations = {}; firstTestStart = 0; verdict = null; crashed = false;
|
|
2182
|
+
constructor(token = ${JSON.stringify(probe2?.token ?? null)}, setupFile = ${JSON.stringify(probe2?.setupFile ?? null)}) { this.token = token; this.setupFile = setupFile; this.loaded = false; this.originals = []; this.timeoutDetails = {}; this.activeModules = new Set(); this.hooks = new Map(); this.allowances = []; this.telemetryWarnings = []; }
|
|
2183
|
+
onInit(ctx) {
|
|
2184
|
+
traceProcess("vitest-start");
|
|
2185
|
+
this.ctx = ctx;
|
|
2186
|
+
if (!this.setupFile) return;
|
|
2187
|
+
for (const vite of new Set(ctx.projects.map(project => project.vite.config))) {
|
|
2188
|
+
const fs = vite.server?.fs;
|
|
2189
|
+
if (fs) { this.allowances.push([fs, fs.allow]); fs.allow = [...fs.allow, dirname(this.setupFile)]; }
|
|
2190
|
+
}
|
|
2191
|
+
for (const config of new Set(ctx.projects.map(project => project.config))) {
|
|
2192
|
+
this.originals.push([config, config.setupFiles]);
|
|
2193
|
+
config.setupFiles = [this.setupFile, ...config.setupFiles];
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
restore() {
|
|
2197
|
+
for (const [config, setupFiles] of this.originals) config.setupFiles = setupFiles;
|
|
2198
|
+
for (const [fs, allow] of this.allowances) fs.allow = allow;
|
|
2199
|
+
this.originals = []; this.allowances = [];
|
|
2200
|
+
}
|
|
2201
|
+
onHookStart(hook) { this.hooks.set(hook.entity.id + hook.name, performance.now()); }
|
|
2202
|
+
onHookEnd(hook) {
|
|
2203
|
+
const module = hook.entity.module ?? hook.entity;
|
|
2204
|
+
const started = this.hooks.get(hook.entity.id + hook.name);
|
|
2205
|
+
if (module.moduleId && started !== undefined) {
|
|
2206
|
+
const file = relative(process.cwd(), module.moduleId);
|
|
2207
|
+
this.durations[file] = Math.max(this.durations[file] ?? 0, performance.now() - started);
|
|
2208
|
+
console.log(${JSON.stringify(marker + "duration:")} + JSON.stringify({ file, duration: this.durations[file], timeout: 0, key: file + "::hook::" + hook.entity.id + hook.name, start: this.firstTestStart }));
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
onUserConsoleLog(log) {
|
|
2212
|
+
if (this.token && log.content.includes(this.token)) { this.loaded = true; process.send?.({ type: "probeLoaded" }); console.log(${JSON.stringify(marker + "probeLoaded")}); }
|
|
2213
|
+
}
|
|
2214
|
+
onTestRunStart(specifications) {
|
|
2215
|
+
traceProcess("test-run-start", { files: specifications.length });
|
|
2216
|
+
this.probeSupported = specifications.every(spec => ["forks", "threads", "vmForks", "vmThreads"].includes(spec.pool) && spec.project.config.environment === "node");
|
|
2217
|
+
console.log(${JSON.stringify(marker + "probeSupported:")} + JSON.stringify(this.probeSupported));
|
|
2218
|
+
const workers = this.ctx.config.maxWorkers;
|
|
2219
|
+
this.workers = Number.isSafeInteger(workers) && workers > 0 ? workers : undefined;
|
|
2220
|
+
if (this.workers !== undefined) console.log(${JSON.stringify(marker + "workers:")} + this.workers);
|
|
2221
|
+
else {
|
|
2222
|
+
const warning = "Internal reporter telemetry error: testWorkers=" + String(workers) + "; resolved worker budget unavailable, omitted";
|
|
2223
|
+
this.telemetryWarnings.push(warning);
|
|
2224
|
+
console.log(${JSON.stringify(marker + "telemetryWarning:")} + JSON.stringify(warning));
|
|
2225
|
+
}
|
|
2226
|
+
this.files = specifications.map(spec => relative(process.cwd(), spec.moduleId));
|
|
2227
|
+
process.send?.({ type: "selected", files: this.files });
|
|
2228
|
+
console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(this.files));
|
|
2229
|
+
}
|
|
2230
|
+
onTestModuleStart(module) {
|
|
2231
|
+
traceProcess("test-module-start");
|
|
2232
|
+
this.activeModules.add(module.moduleId);
|
|
2233
|
+
this.concurrency = Math.max(this.concurrency, this.activeModules.size);
|
|
2234
|
+
console.log(${JSON.stringify(marker + "concurrency:")} + this.concurrency);
|
|
2235
|
+
}
|
|
2236
|
+
onTestModuleCollected() {
|
|
2237
|
+
this.collected = true;
|
|
2238
|
+
process.send?.({ type: "collected" });
|
|
2239
|
+
console.log(${JSON.stringify(marker + "collected")});
|
|
2240
|
+
}
|
|
2241
|
+
onTestModuleEnd(module) {
|
|
2242
|
+
const file = relative(process.cwd(), module.moduleId);
|
|
2243
|
+
this.crashed ||= (module.errors?.() ?? []).some(error => workerDied(error));
|
|
2244
|
+
const timing = module.diagnostic();
|
|
2245
|
+
this.fileDurations[file] = timing.duration + timing.collectDuration + timing.prepareDuration + timing.setupDuration + timing.environmentSetupDuration;
|
|
2246
|
+
console.log(${JSON.stringify(marker + "fileDuration:")} + JSON.stringify({ file, duration: this.fileDurations[file] }));
|
|
2247
|
+
this.activeModules.delete(module.moduleId);
|
|
2248
|
+
}
|
|
2249
|
+
onTestCaseResult(test) {
|
|
2250
|
+
const result = test.result();
|
|
2251
|
+
this.crashed ||= (result.errors ?? []).some(error => workerDied(error));
|
|
2252
|
+
const state = result.state;
|
|
2253
|
+
if (state === "failed") { this.failed = true; process.send?.({ type: "failed" }); console.log(${JSON.stringify(marker + "failed")}); }
|
|
2254
|
+
if (state === "passed") {
|
|
2255
|
+
const start = test.diagnostic()?.startTime ?? 0;
|
|
2256
|
+
if (start > 0) this.firstTestStart = this.firstTestStart ? Math.min(this.firstTestStart, start) : start;
|
|
2257
|
+
const file = relative(process.cwd(), test.module.moduleId);
|
|
2258
|
+
this.durations[file] = Math.max(this.durations[file] ?? 0, test.diagnostic()?.duration ?? 0);
|
|
2259
|
+
this.timeouts[file] = Math.max(this.timeouts[file] ?? 0, test.options.timeout ?? 0);
|
|
2260
|
+
this.timeoutDetails[file + "::" + test.id] = test.options.timeout ?? 0;
|
|
2261
|
+
console.log(${JSON.stringify(marker + "duration:")} + JSON.stringify({ file, duration: this.durations[file], timeout: this.timeouts[file], key: file + "::" + test.id, start: this.firstTestStart }));
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
onTestRunEnd(modules, errors = [], state) {
|
|
2265
|
+
this.verdict = state ?? null;
|
|
2266
|
+
this.crashed ||= errors.some(error => workerDied(error)) || modules.some(module => workerDied(module.task) || (module.errors?.() ?? []).some(error => workerDied(error)));
|
|
2267
|
+
// Vitest's official run verdict also covers cancelled or pending modules.
|
|
2268
|
+
// Parallel bail can omit case-result hooks and module-end results.
|
|
2269
|
+
if ((state != null && state !== "passed") || (!this.ctx?.config.dangerouslyIgnoreUnhandledErrors && errors.length)) { this.failed = true; process.send?.({ type: "failed" }); console.log(${JSON.stringify(marker + "failed")}); }
|
|
2270
|
+
if (!this.files.length) console.log(${JSON.stringify(marker + "empty")});
|
|
2271
|
+
this.restore();
|
|
2272
|
+
}
|
|
2273
|
+
}`;
|
|
2274
|
+
var vitestHostSource = String.raw`
|
|
2275
|
+
import { createRequire } from "node:module";
|
|
2276
|
+
import { pathToFileURL } from "node:url";
|
|
2277
|
+
import { resolve } from "node:path";
|
|
2278
|
+
import { readFileSync } from "node:fs";
|
|
2279
|
+
const require = createRequire(resolve("package.json"));
|
|
2280
|
+
const { default: Reporter } = await import(pathToFileURL(process.argv[2]).href);
|
|
2281
|
+
${warmPolicySource}
|
|
2282
|
+
${workerDeathSource}
|
|
2283
|
+
let ctx;
|
|
2284
|
+
let reporter;
|
|
2285
|
+
const retained = () => {
|
|
2286
|
+
try { return readFileSync(process.env.MUTANT_CAFE_PROCESS_LEDGER, "utf8").split("\n").filter(Boolean).flatMap(line => { try { const item = JSON.parse(line); return item.phase === "setup" ? [{ pid: item.pid, birth: item.birth }] : []; } catch { return []; } }); }
|
|
2287
|
+
catch { return []; }
|
|
2288
|
+
};
|
|
2289
|
+
const setup = async fn => {
|
|
2290
|
+
const previous = process.env.MUTANT_CAFE_PROCESS_PHASE;
|
|
2291
|
+
process.env.MUTANT_CAFE_PROCESS_PHASE = "setup";
|
|
2292
|
+
try { return await fn(); } finally { if (previous === undefined) delete process.env.MUTANT_CAFE_PROCESS_PHASE; else process.env.MUTANT_CAFE_PROCESS_PHASE = previous; }
|
|
2293
|
+
};
|
|
2294
|
+
try {
|
|
2295
|
+
const version = JSON.parse(readFileSync(require.resolve("vitest/package.json"), "utf8")).version;
|
|
2296
|
+
const versionRefusal = warmRefusal(version, null);
|
|
2297
|
+
if (versionRefusal) throw new Error(versionRefusal);
|
|
2298
|
+
const { createVitest } = await import(pathToFileURL(require.resolve("vitest/node")).href);
|
|
2299
|
+
if (typeof createVitest !== "function") throw new Error("createVitest is unavailable");
|
|
2300
|
+
ctx = await setup(() => createVitest({ root: process.cwd(), run: true, watch: false, cache: false, fsModuleCache: false,
|
|
2301
|
+
bail: 1, passWithNoTests: true, reporters: ["default", new Reporter()] }, { plugins: [{ name: "mutant-cafe-health", resolveId(id) { if (id === "virtual:mutant-cafe-health") return "\0mutant-cafe-health"; }, load(id) { if (id === "\0mutant-cafe-health") return "export default 1"; } }] }));
|
|
2302
|
+
if (typeof ctx.runTestSpecifications !== "function" || typeof ctx.invalidateFile !== "function"
|
|
2303
|
+
|| typeof ctx.cancelCurrentRun !== "function" || typeof ctx.getRelevantTestSpecifications !== "function" || typeof ctx.initializeGlobalSetup !== "function") {
|
|
2304
|
+
throw new Error("installed Vitest does not expose the supported warm API");
|
|
2305
|
+
}
|
|
2306
|
+
const refusal = warmRefusal(version, ctx, process.argv[3] === "select");
|
|
2307
|
+
if (refusal) throw new Error(refusal);
|
|
2308
|
+
const isolated = config => config.isolate !== false &&
|
|
2309
|
+
!Object.values(config.poolOptions ?? {}).some(pool => pool?.isolate === false);
|
|
2310
|
+
const script = JSON.parse(readFileSync(resolve("package.json"), "utf8")).scripts?.test ?? "";
|
|
2311
|
+
if (process.argv[3] !== "select" && (/(?:^|\s)--no-isolate(?:\s|$)|--isolate(?:=|\s+)false/.test(script) || !isolated(ctx.config) || !isolated(ctx.vite.config.test ?? {}) ||
|
|
2312
|
+
ctx.projects.some(project => !isolated(project.config) || !isolated(project.vite.config.test ?? {})))) {
|
|
2313
|
+
throw new Error("isolate: false (including poolOptions or --no-isolate) cannot reset module state");
|
|
2314
|
+
}
|
|
2315
|
+
const initialize = ctx.initializeGlobalSetup.bind(ctx);
|
|
2316
|
+
ctx.initializeGlobalSetup = (...args) => setup(async () => {
|
|
2317
|
+
const result = await initialize(...args);
|
|
2318
|
+
process.send({ type: "retained", pids: retained() });
|
|
2319
|
+
return result;
|
|
2320
|
+
});
|
|
2321
|
+
await setup(() => ctx.standalone());
|
|
2322
|
+
process.send({ type: "retained", pids: retained() });
|
|
2323
|
+
process.send({ type: "ready" });
|
|
2324
|
+
} catch (error) {
|
|
2325
|
+
process.send({ type: "fallback", message: String(error) });
|
|
2326
|
+
await ctx?.close();
|
|
2327
|
+
process.exit(0);
|
|
2328
|
+
}
|
|
2329
|
+
// invalidateFile clears Vitest's transform cache. Walk importers explicitly as
|
|
2330
|
+
// well, and queue every path for the pool's module runner invalidation boundary.
|
|
2331
|
+
function invalidate(file) {
|
|
2332
|
+
const paths = new Set([resolve(file)]);
|
|
2333
|
+
for (const project of ctx.projects) {
|
|
2334
|
+
for (const environment of Object.values(project.vite.environments)) {
|
|
2335
|
+
const seen = new Set();
|
|
2336
|
+
const visit = module => {
|
|
2337
|
+
if (seen.has(module)) return;
|
|
2338
|
+
seen.add(module);
|
|
2339
|
+
if (module.file) paths.add(module.file);
|
|
2340
|
+
for (const importer of module.importers) visit(importer);
|
|
2341
|
+
};
|
|
2342
|
+
for (const module of environment.moduleGraph.getModulesByFile(resolve(file)) ?? []) visit(module);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
for (const path of paths) { ctx.invalidateFile(path); ctx.watcher.invalidates.add(path); }
|
|
2346
|
+
}
|
|
2347
|
+
const defaultReporters = ctx.reporters.filter(reporter => !(reporter instanceof Reporter));
|
|
2348
|
+
process.on("message", async request => {
|
|
2349
|
+
try {
|
|
2350
|
+
if (request.type === "close") { await ctx.close(); process.exit(0); }
|
|
2351
|
+
if (request.type === "cancel") { await ctx.cancelCurrentRun("keyboard-input"); return; }
|
|
2352
|
+
if (request.type === "invalidate") { invalidate(request.file); process.send({ type: "invalidated" }); return; }
|
|
2353
|
+
if (request.type === "ping") {
|
|
2354
|
+
if (!ctx.runningPromise) ctx.cancelPromise = undefined;
|
|
2355
|
+
const module = ctx.vite.moduleGraph?.getModuleById("\0mutant-cafe-health");
|
|
2356
|
+
if (module) ctx.vite.moduleGraph.invalidateModule(module);
|
|
2357
|
+
const transformed = await ctx.vite.transformRequest("virtual:mutant-cafe-health");
|
|
2358
|
+
if (!transformed?.code) throw new Error("health transform failed");
|
|
2359
|
+
process.send({ type: "healthy" });
|
|
2360
|
+
return;
|
|
2361
|
+
}
|
|
2362
|
+
if (request.type === "quiesce") {
|
|
2363
|
+
const pool = ctx.pool;
|
|
2364
|
+
ctx.pool = undefined;
|
|
2365
|
+
let closing;
|
|
2366
|
+
try { closing = pool?.close?.(); } catch { /* Disposable pool is already dead. */ }
|
|
2367
|
+
process.send({ type: "quiescing" });
|
|
2368
|
+
try { await closing; } catch { /* Parent verifies and reaps its children. */ }
|
|
2369
|
+
process.send({ type: "quiesced" });
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
if (request.type === "select") {
|
|
2373
|
+
ctx.config.related = [resolve(request.file)];
|
|
2374
|
+
const specs = await ctx.getRelevantTestSpecifications();
|
|
2375
|
+
process.send({ type: "selection", files: specs.map(spec => spec.moduleId) });
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
if (request.type !== "run") return;
|
|
2379
|
+
if (process.argv[3] === "select") {
|
|
2380
|
+
process.send({ type: "protocolError", message: "Selection-only host cannot execute tests" });
|
|
2381
|
+
return;
|
|
2382
|
+
}
|
|
2383
|
+
reporter = new Reporter(request.probe?.token ?? null, request.probe?.setupFile ?? null);
|
|
2384
|
+
reporter.onInit(ctx);
|
|
2385
|
+
ctx.reporters = [...defaultReporters, reporter];
|
|
2386
|
+
ctx.config.related = request.file ? [resolve(request.file)] : undefined;
|
|
2387
|
+
if (request.testTimeout === undefined) { delete ctx.configOverride.testTimeout; delete ctx.configOverride.hookTimeout; }
|
|
2388
|
+
else { ctx.configOverride.testTimeout = request.testTimeout; ctx.configOverride.hookTimeout = request.testTimeout; }
|
|
2389
|
+
const specs = await ctx.getRelevantTestSpecifications();
|
|
2390
|
+
// The shared adapter handles the full-suite fallback and remaining budget.
|
|
2391
|
+
const empty = specs.length === 0;
|
|
2392
|
+
let result;
|
|
2393
|
+
try { result = await ctx.runTestSpecifications(specs, !request.file); }
|
|
2394
|
+
catch (error) {
|
|
2395
|
+
// A thrown run error (for example a mutant breaking global setup) is a
|
|
2396
|
+
// failure, not evidence that the host or a worker died.
|
|
2397
|
+
console.error(error?.stack ?? String(error));
|
|
2398
|
+
reporter.failed = true;
|
|
2399
|
+
reporter.verdict = "failed";
|
|
2400
|
+
result = { unhandledErrors: [error] };
|
|
2401
|
+
}
|
|
2402
|
+
if (!["passed", "failed", "interrupted"].includes(reporter.verdict)) throw new Error("installed Vitest does not expose the supported current-run verdict");
|
|
2403
|
+
// Use the official current-run verdict, not retained module state. In a
|
|
2404
|
+
// parallel bail, child failures can exist while the module stays pending.
|
|
2405
|
+
process.send({ type: "retained", pids: retained() });
|
|
2406
|
+
const failed = reporter.failed || (!ctx.config.dangerouslyIgnoreUnhandledErrors && result.unhandledErrors.length > 0);
|
|
2407
|
+
process.send({ type: "result", status: failed ? "failed" : empty ? "untested" : "passed",
|
|
2408
|
+
testFiles: reporter.files, testsCollected: reporter.collected, testDurations: reporter.durations, testTimeouts: reporter.timeouts, testWorkers: reporter.workers, testConcurrency: reporter.concurrency, testFileDurations: reporter.fileDurations, firstTestStart: reporter.firstTestStart, probeSupported: reporter.probeSupported, probeLoaded: reporter.loaded, testTimeoutDetails: reporter.timeoutDetails,
|
|
2409
|
+
telemetryWarnings: reporter.telemetryWarnings, crashed: reporter.crashed || result.unhandledErrors.some(error => workerDied(error)) });
|
|
2410
|
+
process.exitCode = 0;
|
|
2411
|
+
} catch (error) { reporter?.restore(); process.send({ type: "crash", message: String(error) }); }
|
|
2412
|
+
});
|
|
2413
|
+
`;
|
|
2414
|
+
|
|
2415
|
+
// packages/runner/src/WarmRunner.ts
|
|
2416
|
+
var Message = Schema7.Union([
|
|
2417
|
+
Schema7.Struct({ type: Schema7.Literal("ready") }),
|
|
2418
|
+
Schema7.Struct({ type: Schema7.Literal("retained"), pids: Schema7.Array(Schema7.Struct({ pid: Schema7.Int, birth: Schema7.String })) }),
|
|
2419
|
+
Schema7.Struct({ type: Schema7.Literal("invalidated") }),
|
|
2420
|
+
Schema7.Struct({ type: Schema7.Literal("collected") }),
|
|
2421
|
+
Schema7.Struct({ type: Schema7.Literal("failed") }),
|
|
2422
|
+
Schema7.Struct({ type: Schema7.Literal("selected"), files: Schema7.Array(Schema7.String) }),
|
|
2423
|
+
Schema7.Struct({ type: Schema7.Literal("selection"), files: Schema7.Array(Schema7.String) }),
|
|
2424
|
+
Schema7.Struct({ type: Schema7.Literal("probeLoaded") }),
|
|
2425
|
+
Schema7.Struct({ type: Schema7.Literal("quiescing") }),
|
|
2426
|
+
Schema7.Struct({ type: Schema7.Literal("quiesced") }),
|
|
2427
|
+
Schema7.Struct({ type: Schema7.Literal("healthy") }),
|
|
2428
|
+
Schema7.Struct({ type: Schema7.Literal("fallback"), message: Schema7.String }),
|
|
2429
|
+
Schema7.Struct({ type: Schema7.Literal("crash"), message: Schema7.String }),
|
|
2430
|
+
Schema7.Struct({
|
|
2431
|
+
type: Schema7.Literal("result"),
|
|
2432
|
+
status: Schema7.Literals(["passed", "failed", "untested"]),
|
|
2433
|
+
testFiles: Schema7.Array(Schema7.String),
|
|
2434
|
+
testsCollected: Schema7.Boolean,
|
|
2435
|
+
testDurations: Schema7.Record(Schema7.String, Schema7.Finite),
|
|
2436
|
+
testTimeouts: Schema7.Record(Schema7.String, Schema7.Finite),
|
|
2437
|
+
testWorkers: Schema7.optional(Schema7.Int),
|
|
2438
|
+
testConcurrency: Schema7.optional(Schema7.Int),
|
|
2439
|
+
telemetryWarnings: Schema7.optional(Schema7.Array(Schema7.String)),
|
|
2440
|
+
testFileDurations: Schema7.Record(Schema7.String, Schema7.Finite),
|
|
2441
|
+
firstTestStart: Schema7.Finite,
|
|
2442
|
+
probeSupported: Schema7.Boolean,
|
|
2443
|
+
probeLoaded: Schema7.Boolean,
|
|
2444
|
+
testTimeoutDetails: Schema7.Record(Schema7.String, Schema7.Finite),
|
|
2445
|
+
crashed: Schema7.Boolean
|
|
2446
|
+
})
|
|
2447
|
+
]);
|
|
2448
|
+
var ReporterMessageError = class extends Error {
|
|
2449
|
+
kind = "reporter";
|
|
2450
|
+
};
|
|
2451
|
+
function decodeWarmMessage(value) {
|
|
2452
|
+
try {
|
|
2453
|
+
const raw = Schema7.decodeUnknownSync(Schema7.Record(Schema7.String, Schema7.Unknown))(value);
|
|
2454
|
+
const cleaned = cleanTelemetry(raw, "warm message");
|
|
2455
|
+
if (raw.type === "result") {
|
|
2456
|
+
for (const [key, fallback] of Object.entries({ testDurations: {}, testTimeouts: {}, testFileDurations: {}, testTimeoutDetails: {}, firstTestStart: 0 }))
|
|
2457
|
+
if (cleaned.value[key] === void 0) Reflect.set(cleaned.value, key, fallback);
|
|
2458
|
+
const previous = cleaned.value.telemetryWarnings;
|
|
2459
|
+
Reflect.set(cleaned.value, "telemetryWarnings", [...Array.isArray(previous) ? previous : [], ...cleaned.warnings]);
|
|
2460
|
+
}
|
|
2461
|
+
return Schema7.decodeUnknownSync(Message)(cleaned.value);
|
|
2462
|
+
} catch (error3) {
|
|
2463
|
+
const actual = (() => {
|
|
2464
|
+
try {
|
|
2465
|
+
return JSON.stringify(value)?.slice(0, 4096) ?? String(value);
|
|
2466
|
+
} catch {
|
|
2467
|
+
return "[unserializable frame]";
|
|
2468
|
+
}
|
|
2469
|
+
})();
|
|
2470
|
+
throw new ReporterMessageError(`Internal warm reporter protocol error: ${String(error3)}; received ${actual}`);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
var Host = class {
|
|
2474
|
+
child;
|
|
2475
|
+
exited;
|
|
2476
|
+
tree;
|
|
2477
|
+
scope;
|
|
2478
|
+
output = "";
|
|
2479
|
+
collected = false;
|
|
2480
|
+
failed = false;
|
|
2481
|
+
testFiles = [];
|
|
2482
|
+
runPending;
|
|
2483
|
+
retained = [];
|
|
2484
|
+
pending;
|
|
2485
|
+
startup;
|
|
2486
|
+
quiescing;
|
|
2487
|
+
quiesced;
|
|
2488
|
+
constructor(root, script, reporter, tree, scope, selectionOnly = false, decode = decodeWarmMessage) {
|
|
2489
|
+
this.tree = tree;
|
|
2490
|
+
this.scope = scope;
|
|
2491
|
+
this.child = spawn(process.execPath, [script, reporter, selectionOnly ? "select" : "run"], {
|
|
2492
|
+
cwd: root,
|
|
2493
|
+
env: tree.env,
|
|
2494
|
+
detached: true,
|
|
2495
|
+
stdio: ["ignore", "pipe", "pipe", "ipc"]
|
|
2496
|
+
});
|
|
2497
|
+
if (this.child.pid) tree.addRoot(this.child.pid);
|
|
2498
|
+
this.startup = this.wait();
|
|
2499
|
+
this.child.stdout?.on("data", (chunk) => {
|
|
2500
|
+
this.output += String(chunk);
|
|
2501
|
+
});
|
|
2502
|
+
this.child.stderr?.on("data", (chunk) => {
|
|
2503
|
+
this.output += String(chunk);
|
|
2504
|
+
});
|
|
2505
|
+
this.child.on("message", (value) => {
|
|
2506
|
+
try {
|
|
2507
|
+
const message = decode(value);
|
|
2508
|
+
if (message.type === "retained") {
|
|
2509
|
+
this.retained = message.pids;
|
|
2510
|
+
return;
|
|
2511
|
+
}
|
|
2512
|
+
if (message.type === "quiescing") {
|
|
2513
|
+
this.quiescing?.();
|
|
2514
|
+
return;
|
|
2515
|
+
}
|
|
2516
|
+
if (message.type === "quiesced") {
|
|
2517
|
+
this.quiesced?.();
|
|
2518
|
+
return;
|
|
2519
|
+
}
|
|
2520
|
+
if (message.type === "collected") {
|
|
2521
|
+
this.collected = true;
|
|
2522
|
+
return;
|
|
2523
|
+
}
|
|
2524
|
+
if (message.type === "failed") {
|
|
2525
|
+
this.failed = true;
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
if (message.type === "probeLoaded") return;
|
|
2529
|
+
if (message.type === "selected") {
|
|
2530
|
+
this.testFiles = message.files;
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
const pending = this.pending;
|
|
2534
|
+
this.pending = void 0;
|
|
2535
|
+
pending?.resolve(message);
|
|
2536
|
+
} catch (error3) {
|
|
2537
|
+
this.pending?.reject(error3 instanceof ReporterMessageError ? error3 : new ReporterMessageError(String(error3)));
|
|
2538
|
+
}
|
|
2539
|
+
});
|
|
2540
|
+
this.exited = new Promise((resolve2) => this.child.once("close", () => {
|
|
2541
|
+
this.pending?.reject(new Error(`Vitest host exited: ${this.output.slice(-4e3)}`));
|
|
2542
|
+
this.pending = void 0;
|
|
2543
|
+
resolve2();
|
|
2544
|
+
}));
|
|
2545
|
+
this.child.on("error", (error3) => {
|
|
2546
|
+
this.pending?.reject(error3);
|
|
2547
|
+
this.pending = void 0;
|
|
2548
|
+
});
|
|
2549
|
+
}
|
|
2550
|
+
wait() {
|
|
2551
|
+
return new Promise((resolve2, reject) => {
|
|
2552
|
+
this.pending = { resolve: resolve2, reject };
|
|
2553
|
+
});
|
|
2554
|
+
}
|
|
2555
|
+
quiesce() {
|
|
2556
|
+
const started = new Promise((resolve2) => {
|
|
2557
|
+
this.quiescing = resolve2;
|
|
2558
|
+
});
|
|
2559
|
+
const done = new Promise((resolve2) => {
|
|
2560
|
+
this.quiesced = resolve2;
|
|
2561
|
+
});
|
|
2562
|
+
this.post({ type: "quiesce" });
|
|
2563
|
+
return { started, done };
|
|
2564
|
+
}
|
|
2565
|
+
ready() {
|
|
2566
|
+
return this.startup;
|
|
2567
|
+
}
|
|
2568
|
+
request(message) {
|
|
2569
|
+
const response = this.wait();
|
|
2570
|
+
this.post(message);
|
|
2571
|
+
return response;
|
|
2572
|
+
}
|
|
2573
|
+
post(message) {
|
|
2574
|
+
if (this.child.connected) this.child.send(message, (error3) => {
|
|
2575
|
+
if (error3) this.pending?.reject(error3);
|
|
2576
|
+
});
|
|
2577
|
+
else this.pending?.reject(new Error("Vitest host disconnected"));
|
|
2578
|
+
}
|
|
2579
|
+
close() {
|
|
2580
|
+
return Scope.close(this.scope, Exit.succeed(void 0));
|
|
2581
|
+
}
|
|
2582
|
+
grace() {
|
|
2583
|
+
const self = this;
|
|
2584
|
+
return Effect5.gen(function* () {
|
|
2585
|
+
self.post({ type: "close" });
|
|
2586
|
+
const exited = Effect5.promise(() => self.exited);
|
|
2587
|
+
const result5 = yield* exited.pipe(Effect5.interruptible, Effect5.timeout(500), Effect5.result);
|
|
2588
|
+
if (result5._tag === "Failure") yield* Effect5.sync(() => {
|
|
2589
|
+
self.child.kill("SIGKILL");
|
|
2590
|
+
});
|
|
2591
|
+
});
|
|
2592
|
+
}
|
|
2593
|
+
};
|
|
2594
|
+
var lifecycle = setupEffect2({ schemas: { events: {
|
|
2595
|
+
RUN: Schema7.Struct({}),
|
|
2596
|
+
DONE: Schema7.Struct({}),
|
|
2597
|
+
CANCEL: Schema7.Struct({}),
|
|
2598
|
+
RESTART: Schema7.Struct({}),
|
|
2599
|
+
READY: Schema7.Struct({}),
|
|
2600
|
+
FAIL: Schema7.Struct({}),
|
|
2601
|
+
FALLBACK: Schema7.Struct({})
|
|
2602
|
+
} } }).createMachine({
|
|
2603
|
+
initial: "idle",
|
|
2604
|
+
on: { FAIL: { target: ".failed" }, FALLBACK: { target: ".cold" } },
|
|
2605
|
+
states: {
|
|
2606
|
+
idle: { on: { RUN: { target: "running" }, RESTART: { target: "restarting" } } },
|
|
2607
|
+
running: { on: { DONE: { target: "idle" }, CANCEL: { target: "cancelling" }, RESTART: { target: "restarting" } } },
|
|
2608
|
+
cancelling: { on: { DONE: { target: "idle" }, RESTART: { target: "restarting" } } },
|
|
2609
|
+
restarting: { on: { READY: { target: "idle" } } },
|
|
2610
|
+
failed: { on: { FALLBACK: { target: "cold" } } },
|
|
2611
|
+
cold: { type: "final" }
|
|
2612
|
+
}
|
|
2613
|
+
});
|
|
2614
|
+
var openWarmRunner = Effect5.fn("TestRunner.openWarm")(function* (dir, onFallback, options = {}) {
|
|
2615
|
+
const fs = yield* FileSystem5.FileSystem;
|
|
2616
|
+
const parentScope = yield* Scope.Scope;
|
|
2617
|
+
const temp = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-warm-" });
|
|
2618
|
+
const script = `${temp}/host.mjs`;
|
|
2619
|
+
const reporter = `${temp}/reporter.mjs`;
|
|
2620
|
+
yield* fs.writeFileString(script, vitestHostSource);
|
|
2621
|
+
yield* fs.writeFileString(reporter, reporterSource("mutant-warm:"));
|
|
2622
|
+
const actor = yield* createEffectActor2(lifecycle);
|
|
2623
|
+
let host;
|
|
2624
|
+
const attempt = (fn11) => Effect5.tryPromise({
|
|
2625
|
+
try: fn11,
|
|
2626
|
+
catch: (error3) => new TestSpawnError({ command: ["vitest", "warm"], message: String(error3), ...error3 instanceof ReporterMessageError ? { kind: "reporter" } : {} })
|
|
2627
|
+
}).pipe(Effect5.interruptible);
|
|
2628
|
+
const close2 = () => host === void 0 ? Effect5.void : host.close();
|
|
2629
|
+
const abortHost = (error3) => Effect5.gen(function* () {
|
|
2630
|
+
yield* send2(actor, { type: "FAIL" });
|
|
2631
|
+
yield* close2();
|
|
2632
|
+
return yield* error3;
|
|
2633
|
+
});
|
|
2634
|
+
yield* Effect5.addFinalizer(() => close2().pipe(Effect5.orDie));
|
|
2635
|
+
const start = Effect5.gen(function* () {
|
|
2636
|
+
const scope = yield* Scope.make();
|
|
2637
|
+
yield* Effect5.addFinalizer(() => Scope.close(scope, Exit.succeed(void 0))).pipe(Effect5.provideService(Scope.Scope, parentScope));
|
|
2638
|
+
const tree = yield* acquireProcessTree(dir.path, options.onBackstop, options.processesSince).pipe(
|
|
2639
|
+
Effect5.provideService(Scope.Scope, scope),
|
|
2640
|
+
Effect5.provideService(FileSystem5.FileSystem, fs),
|
|
2641
|
+
Effect5.mapError((error3) => new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) }))
|
|
2642
|
+
);
|
|
2643
|
+
const active = new Host(dir.path, script, reporter, tree, scope, options.selectionOnly === true, options.decodeMessage);
|
|
2644
|
+
host = active;
|
|
2645
|
+
yield* Effect5.addFinalizer(() => active.grace()).pipe(Effect5.provideService(Scope.Scope, scope));
|
|
2646
|
+
const initialized = yield* attempt(() => host.ready()).pipe(
|
|
2647
|
+
Effect5.timeout(3e4),
|
|
2648
|
+
Effect5.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) })),
|
|
2649
|
+
Effect5.result
|
|
2650
|
+
);
|
|
2651
|
+
if (initialized._tag === "Failure") return yield* abortHost(initialized.failure);
|
|
2652
|
+
const ready = initialized.success;
|
|
2653
|
+
if (ready.type !== "ready") {
|
|
2654
|
+
if (!options.quiet) yield* (options.warn ?? Console3.warn)(`Warning: warm Vitest unavailable; using cold mode: ${"message" in ready ? ready.message : ready.type}`);
|
|
2655
|
+
yield* Effect5.sync(() => onFallback("message" in ready ? ready.message : `Unexpected startup frame: ${ready.type}`));
|
|
2656
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
2657
|
+
yield* close2();
|
|
2658
|
+
}
|
|
2659
|
+
});
|
|
2660
|
+
const retire = Effect5.gen(function* () {
|
|
2661
|
+
yield* send2(actor, { type: "RESTART" });
|
|
2662
|
+
yield* close2();
|
|
2663
|
+
});
|
|
2664
|
+
const restart = Effect5.gen(function* () {
|
|
2665
|
+
yield* retire;
|
|
2666
|
+
yield* start;
|
|
2667
|
+
yield* Effect5.sync(() => options.onRestart?.());
|
|
2668
|
+
if (actor.getSnapshot().value !== "cold") yield* send2(actor, { type: "READY" });
|
|
2669
|
+
});
|
|
2670
|
+
yield* start;
|
|
2671
|
+
const isCold = () => actor.getSnapshot().value === "cold";
|
|
2672
|
+
const invalidate = Effect5.fn("Warm.invalidate")(function* (file) {
|
|
2673
|
+
if (isCold() || actor.getSnapshot().value === "failed") return;
|
|
2674
|
+
if (actor.getSnapshot().value === "restarting") {
|
|
2675
|
+
yield* start;
|
|
2676
|
+
yield* Effect5.sync(() => options.onRestart?.());
|
|
2677
|
+
if (!isCold()) yield* send2(actor, { type: "READY" });
|
|
2678
|
+
return;
|
|
2679
|
+
}
|
|
2680
|
+
const result5 = yield* attempt(() => host.request({ type: "invalidate", file })).pipe(Effect5.timeout(1e3), Effect5.result);
|
|
2681
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
2682
|
+
if (result5._tag === "Failure") yield* restart;
|
|
2683
|
+
});
|
|
2684
|
+
const finish = Effect5.fn("Warm.finish")(function* (active, pending) {
|
|
2685
|
+
const pool = active.quiesce();
|
|
2686
|
+
const started = yield* attempt(() => pool.started).pipe(Effect5.timeout(500), Effect5.result);
|
|
2687
|
+
const clean = yield* active.tree.reap(active.child.pid === void 0 ? [] : [active.child.pid], active.retained);
|
|
2688
|
+
if (clean !== "clean" || started._tag === "Failure") return false;
|
|
2689
|
+
yield* attempt(() => pool.done).pipe(Effect5.timeout(100), Effect5.result);
|
|
2690
|
+
const settled = yield* attempt(() => pending).pipe(Effect5.timeout(500), Effect5.result);
|
|
2691
|
+
const health = settled._tag === "Success" ? yield* attempt(() => active.request({ type: "ping" })).pipe(Effect5.timeout(500), Effect5.result) : settled;
|
|
2692
|
+
return clean === "clean" && started._tag === "Success" && health._tag === "Success" && health.success.type === "healthy";
|
|
2693
|
+
});
|
|
2694
|
+
const run2 = Effect5.fn("Warm.run")(function* (file, timeoutMs, testTimeout, probe2) {
|
|
2695
|
+
if (isCold()) return void 0;
|
|
2696
|
+
if (options.selectionOnly) return yield* abortHost(new TestSpawnError({ command: ["vitest", "select"], kind: "reporter", message: "Selection-only host cannot execute tests" }));
|
|
2697
|
+
const command = ["vitest", ...file ? ["related", file, "--run"] : ["run"], "--reporter=default"];
|
|
2698
|
+
for (let crash = 0; crash < 2; crash++) {
|
|
2699
|
+
const active = host;
|
|
2700
|
+
active.output = "";
|
|
2701
|
+
active.collected = false;
|
|
2702
|
+
active.failed = false;
|
|
2703
|
+
active.testFiles = [];
|
|
2704
|
+
const started = yield* Clock3.currentTimeMillis;
|
|
2705
|
+
active.runPending = void 0;
|
|
2706
|
+
const budgetMs = timeoutMs ?? DEFAULT_BASELINE_TIMEOUT_MS;
|
|
2707
|
+
const operation = Effect5.gen(function* () {
|
|
2708
|
+
yield* active.tree.trace("warm-attempt-start", { budgetMs });
|
|
2709
|
+
yield* send2(actor, { type: "RUN" });
|
|
2710
|
+
const pending2 = active.request({ type: "run", file, testTimeout, probe: probe2 });
|
|
2711
|
+
active.runPending = pending2;
|
|
2712
|
+
return yield* attempt(() => pending2);
|
|
2713
|
+
});
|
|
2714
|
+
const result5 = yield* operation.pipe(Effect5.interruptible, Effect5.timeout(budgetMs), Effect5.result);
|
|
2715
|
+
const pending = active.runPending;
|
|
2716
|
+
if (result5._tag === "Success" && result5.success.type === "result" && !result5.success.crashed) {
|
|
2717
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2718
|
+
else yield* retire;
|
|
2719
|
+
return {
|
|
2720
|
+
...result5.success,
|
|
2721
|
+
startupMs: result5.success.firstTestStart > 0 ? Math.max(0, Math.ceil(result5.success.firstTestStart - started)) : 0,
|
|
2722
|
+
...active.child.pid === void 0 ? {} : { hostPid: active.child.pid },
|
|
2723
|
+
command,
|
|
2724
|
+
output: active.output,
|
|
2725
|
+
durationMs: (yield* Clock3.currentTimeMillis) - started
|
|
2726
|
+
};
|
|
2727
|
+
}
|
|
2728
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TimeoutError") {
|
|
2729
|
+
yield* Effect5.sync(() => options.onPoolReset?.());
|
|
2730
|
+
yield* active.tree.trace("warm-deadline", { budgetMs });
|
|
2731
|
+
const failedAtDeadline = active.failed;
|
|
2732
|
+
yield* send2(actor, { type: "CANCEL" });
|
|
2733
|
+
active.post({ type: "cancel" });
|
|
2734
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2735
|
+
else yield* retire;
|
|
2736
|
+
return {
|
|
2737
|
+
status: failedAtDeadline ? "failed" : "timedOut",
|
|
2738
|
+
command,
|
|
2739
|
+
output: active.output,
|
|
2740
|
+
durationMs: (yield* Clock3.currentTimeMillis) - started,
|
|
2741
|
+
...active.child.pid === void 0 ? {} : { hostPid: active.child.pid },
|
|
2742
|
+
testsCollected: active.collected,
|
|
2743
|
+
testFiles: active.testFiles
|
|
2744
|
+
};
|
|
2745
|
+
}
|
|
2746
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
2747
|
+
yield* Effect5.sync(() => options.onPoolReset?.());
|
|
2748
|
+
if (crash === 0) {
|
|
2749
|
+
yield* Console3.warn(`Warning: Vitest pool crashed; restarting once: ${result5._tag === "Failure" ? String(result5.failure) : "message" in result5.success ? result5.success.message : result5.success.type}`);
|
|
2750
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2751
|
+
else yield* restart;
|
|
2752
|
+
} else {
|
|
2753
|
+
yield* send2(actor, { type: "FAIL" });
|
|
2754
|
+
yield* close2();
|
|
2755
|
+
yield* Console3.warn("Warning: Vitest pool crashed twice for one mutant; using cold mode for the rest of this run");
|
|
2756
|
+
yield* Effect5.sync(() => onFallback("Vitest pool crashed twice for one mutant"));
|
|
2757
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
2758
|
+
}
|
|
2759
|
+
if (isCold()) return void 0;
|
|
2760
|
+
}
|
|
2761
|
+
return void 0;
|
|
2762
|
+
}, (effect5) => effect5.pipe(Effect5.onInterrupt(() => Effect5.gen(function* () {
|
|
2763
|
+
yield* send2(actor, { type: "CANCEL" });
|
|
2764
|
+
const active = host;
|
|
2765
|
+
yield* Effect5.sync(() => options.onPoolReset?.());
|
|
2766
|
+
active?.post({ type: "cancel" });
|
|
2767
|
+
if (active?.runPending && (yield* finish(active, active.runPending).pipe(Effect5.orDie))) yield* send2(actor, { type: "DONE" });
|
|
2768
|
+
else {
|
|
2769
|
+
yield* retire.pipe(Effect5.orDie);
|
|
2770
|
+
yield* Effect5.sync(() => onFallback("Interrupted run retired its unhealthy host"));
|
|
2771
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
2772
|
+
}
|
|
2773
|
+
}))));
|
|
2774
|
+
const disable = Effect5.gen(function* () {
|
|
2775
|
+
if (isCold()) return;
|
|
2776
|
+
yield* close2();
|
|
2777
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
2778
|
+
});
|
|
2779
|
+
const select = Effect5.fn("Warm.select")(function* (file) {
|
|
2780
|
+
if (isCold()) return void 0;
|
|
2781
|
+
const result5 = yield* attempt(() => host.request({ type: "select", file })).pipe(Effect5.timeout(3e4), Effect5.result);
|
|
2782
|
+
if (result5._tag === "Success" && result5.success.type === "selection") return result5.success.files;
|
|
2783
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
2784
|
+
yield* restart;
|
|
2785
|
+
return void 0;
|
|
2786
|
+
});
|
|
2787
|
+
return { run: run2, invalidate, disable, select };
|
|
2788
|
+
});
|
|
2789
|
+
|
|
2790
|
+
// packages/runner/src/Mode.ts
|
|
2791
|
+
function startupCost(observed, copies) {
|
|
2792
|
+
return Math.max(0, copies - observed.length) * Math.max(0, ...observed);
|
|
2793
|
+
}
|
|
2794
|
+
function chooseMode(sample) {
|
|
2795
|
+
const fixedSaving = (sample.coldStartupMs ?? 0) - (sample.warmRunStartupMs ?? 0);
|
|
2796
|
+
const savingPerFile = (sample.coldMs - sample.warmMs - fixedSaving) / Math.max(1, sample.testFiles);
|
|
2797
|
+
const savingPerMutant = fixedSaving + savingPerFile;
|
|
2798
|
+
return sample.warmMs * 10 <= sample.coldMs * 9 && savingPerMutant * sample.mutants > sample.warmStartupMs ? "warm" : "cold";
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
// packages/runner/src/TestRunner.ts
|
|
2802
|
+
var baselineTimedOut = (timeoutMs, command) => new BaselineTimedOut({
|
|
2803
|
+
timeoutMs,
|
|
2804
|
+
command,
|
|
2805
|
+
message: `Baseline exceeded ${timeoutMs / 1e3} seconds overall, including selection and startup. Increase --baseline-timeout (seconds), or baselineTimeoutMs in mutants.config.json, for a longer suite.`
|
|
2806
|
+
});
|
|
2807
|
+
var TestRunnerLive = Layer3.effect(TestRunner, Effect6.gen(function* () {
|
|
1513
2808
|
const spawner = yield* ChildProcessSpawner3.ChildProcessSpawner;
|
|
1514
|
-
const fs = yield*
|
|
2809
|
+
const fs = yield* FileSystem7.FileSystem;
|
|
1515
2810
|
const path = yield* Path3.Path;
|
|
1516
|
-
|
|
2811
|
+
let warmDisabled = false;
|
|
2812
|
+
let modeReason;
|
|
2813
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
2814
|
+
const auto = /* @__PURE__ */ new Map();
|
|
2815
|
+
const primers = /* @__PURE__ */ new Map();
|
|
2816
|
+
const backstopTotals = /* @__PURE__ */ new Map();
|
|
2817
|
+
let baselineBudgetMs = DEFAULT_BASELINE_TIMEOUT_MS;
|
|
2818
|
+
const lastCommands = /* @__PURE__ */ new Map();
|
|
2819
|
+
const onBackstop = (dir) => (ms) => {
|
|
2820
|
+
backstopTotals.set(dir, (backstopTotals.get(dir) ?? 0) + ms);
|
|
2821
|
+
};
|
|
2822
|
+
const scopes = /* @__PURE__ */ new Map();
|
|
2823
|
+
const openedAt = /* @__PURE__ */ new Map();
|
|
2824
|
+
const selectors = /* @__PURE__ */ new Map();
|
|
2825
|
+
let automaticMode = "pending";
|
|
2826
|
+
let hostRestarts = 0;
|
|
2827
|
+
let poolResets = 0;
|
|
2828
|
+
let warned = false;
|
|
2829
|
+
const warn6 = (message) => Effect6.suspend(() => {
|
|
2830
|
+
if (warned) return Effect6.void;
|
|
2831
|
+
warned = true;
|
|
2832
|
+
return Console4.warn(message);
|
|
2833
|
+
});
|
|
2834
|
+
const sessionOptions = { onRestart: () => {
|
|
2835
|
+
hostRestarts++;
|
|
2836
|
+
}, onPoolReset: () => {
|
|
2837
|
+
poolResets++;
|
|
2838
|
+
} };
|
|
2839
|
+
const execute2 = Effect6.fn("TestRunner.execute")(function* (dir, args, timeoutMs, testTimeoutMs, forceCold = false, probe2) {
|
|
2840
|
+
const overallMs = timeoutMs ?? baselineBudgetMs;
|
|
2841
|
+
const beforeBackstop = backstopTotals.get(dir.path) ?? 0;
|
|
2842
|
+
const backstopMs = () => Math.max(0, (backstopTotals.get(dir.path) ?? 0) - beforeBackstop);
|
|
2843
|
+
const session = sessions.get(dir.path);
|
|
2844
|
+
if (session !== void 0 && !warmDisabled && !auto.has(dir.path) && !forceCold) {
|
|
2845
|
+
if (timeoutMs === void 0) yield* Console4.error(`Baseline command: vitest run --reporter=default (warm Node API, cwd: ${dir.path})`);
|
|
2846
|
+
const run3 = yield* session.run(args[0] === "related" ? args[1] : void 0, overallMs, testTimeoutMs ?? (timeoutMs === void 0 ? void 0 : Math.max(1, Math.floor(timeoutMs / 2))), probe2);
|
|
2847
|
+
if (run3 !== void 0) return { ...run3, backstopMs: backstopMs(), exitCode: run3.status === "passed" || run3.status === "untested" ? 0 : 1 };
|
|
2848
|
+
}
|
|
1517
2849
|
const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
|
|
1518
|
-
|
|
2850
|
+
Effect6.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) }))
|
|
1519
2851
|
);
|
|
1520
2852
|
const reporter = path.join(reporterDir, "reporter.mjs");
|
|
2853
|
+
const launcher = path.join(reporterDir, "launch.mjs");
|
|
2854
|
+
yield* fs.writeFileString(launcher, vitestLauncherSource).pipe(Effect6.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
1521
2855
|
const marker = `mutant-cafe:${path.basename(reporterDir)}:`;
|
|
1522
|
-
yield* fs.writeFileString(reporter,
|
|
1523
|
-
export default class {
|
|
1524
|
-
files = 0;
|
|
1525
|
-
onTestRunStart(specifications) { this.files = specifications.length; console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(specifications.map(spec => relative(process.cwd(), spec.moduleId)))); }
|
|
1526
|
-
onTestModuleCollected() { console.log(${JSON.stringify(marker + "collected")}); }
|
|
1527
|
-
onTestCaseResult(test) { if (test.result().state === "failed") console.log(${JSON.stringify(marker + "failed")}); }
|
|
1528
|
-
onTestRunEnd() { if (this.files === 0) console.log(${JSON.stringify(marker + "empty")}); }
|
|
1529
|
-
}`).pipe(Effect4.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
2856
|
+
yield* fs.writeFileString(reporter, reporterSource(marker, probe2)).pipe(Effect6.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
1530
2857
|
const command = [
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
"vitest",
|
|
2858
|
+
process.execPath,
|
|
2859
|
+
launcher,
|
|
1534
2860
|
...args,
|
|
1535
2861
|
"--reporter=default",
|
|
1536
2862
|
`--reporter=${reporter}`,
|
|
1537
2863
|
"--bail",
|
|
1538
2864
|
"1",
|
|
1539
|
-
...timeoutMs === void 0 ? [] : ["--testTimeout", String(Math.max(1, Math.floor(timeoutMs / 2)))],
|
|
2865
|
+
...timeoutMs === void 0 ? [] : ["--testTimeout", String(testTimeoutMs ?? Math.max(1, Math.floor(timeoutMs / 2))), "--hookTimeout", String(testTimeoutMs ?? Math.max(1, Math.floor(timeoutMs / 2)))],
|
|
1540
2866
|
"--no-cache",
|
|
1541
2867
|
"--no-fsModuleCache"
|
|
1542
2868
|
];
|
|
1543
|
-
|
|
1544
|
-
const
|
|
2869
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
2870
|
+
const owned = yield* acquireProcessTree(dir.path, onBackstop(dir.path), openedAt.get(dir.path)).pipe(
|
|
2871
|
+
Effect6.provideService(FileSystem7.FileSystem, fs),
|
|
2872
|
+
Effect6.mapError((error3) => new TestSpawnError({ command, message: String(error3) }))
|
|
2873
|
+
);
|
|
1545
2874
|
const chunks = [];
|
|
1546
2875
|
let exitCode = 1;
|
|
1547
|
-
const child =
|
|
2876
|
+
const child = Effect6.scoped(Effect6.gen(function* () {
|
|
2877
|
+
if (timeoutMs === void 0) yield* Console4.error(`Baseline command: ${formatTestCommand(command)} (cwd: ${dir.path})`);
|
|
2878
|
+
lastCommands.set(dir.path, command);
|
|
2879
|
+
yield* owned.trace("cold-spawn-start", { budgetMs: overallMs });
|
|
1548
2880
|
const handle = yield* spawner.spawn(ChildProcess2.make(command[0], command.slice(1), {
|
|
1549
2881
|
cwd: dir.path,
|
|
2882
|
+
env: owned.env,
|
|
1550
2883
|
// Node's scoped spawner kills the detached process group, not just pnpm.
|
|
1551
2884
|
detached: true,
|
|
1552
2885
|
killSignal: "SIGKILL",
|
|
1553
2886
|
forceKillAfter: "100 millis",
|
|
1554
2887
|
stdin: "ignore"
|
|
1555
2888
|
}));
|
|
1556
|
-
|
|
2889
|
+
yield* Effect6.sync(() => owned.addRoot(handle.pid));
|
|
2890
|
+
yield* owned.trace("cold-spawn", { childPid: handle.pid });
|
|
2891
|
+
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect6.sync(() => {
|
|
1557
2892
|
chunks.push(chunk);
|
|
1558
2893
|
})));
|
|
1559
|
-
const [code] = yield*
|
|
2894
|
+
const [code] = yield* Effect6.all([handle.exitCode.pipe(Effect6.tap(() => owned.cleanup)), collect], { concurrency: "unbounded" });
|
|
1560
2895
|
exitCode = code;
|
|
1561
2896
|
return code === 0 ? "passed" : "failed";
|
|
1562
|
-
}));
|
|
1563
|
-
const status = yield*
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
2897
|
+
}).pipe(Effect6.onInterrupt(() => owned.cleanup)));
|
|
2898
|
+
const status = yield* child.pipe(
|
|
2899
|
+
Effect6.timeout(overallMs),
|
|
2900
|
+
Effect6.catchTag("TimeoutError", () => Effect6.sync(() => {
|
|
2901
|
+
exitCode = 124;
|
|
2902
|
+
chunks.push(`
|
|
2903
|
+
Vitest timed out after ${overallMs}ms overall, including startup.
|
|
2904
|
+
`);
|
|
2905
|
+
return "timedOut";
|
|
2906
|
+
}))
|
|
2907
|
+
).pipe(Effect6.mapError((error3) => new TestSpawnError({ command, message: error3.message })));
|
|
2908
|
+
yield* owned.cleanup;
|
|
2909
|
+
const ended = yield* Clock4.currentTimeMillis;
|
|
1568
2910
|
const output = chunks.join("");
|
|
1569
2911
|
const failed = output.includes(marker + "failed");
|
|
1570
2912
|
const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
|
|
1571
|
-
const selected = selection === void 0 ? [] : yield*
|
|
1572
|
-
|
|
2913
|
+
const selected = selection === void 0 ? [] : yield* Schema8.decodeEffect(Schema8.fromJsonString(Schema8.Array(Schema8.String)))(selection).pipe(
|
|
2914
|
+
Effect6.mapError((error3) => new TestSpawnError({ command, kind: "reporter", message: `Internal cold reporter protocol error in selected files: ${String(error3)}` }))
|
|
1573
2915
|
);
|
|
2916
|
+
const telemetryWarnings = [];
|
|
2917
|
+
for (const part of output.split(marker + "telemetryWarning:").slice(1)) {
|
|
2918
|
+
const warning = Schema8.decodeOption(Schema8.fromJsonString(Schema8.String))(part.split("\n")[0]);
|
|
2919
|
+
if (warning._tag === "Some") telemetryWarnings.push(warning.value);
|
|
2920
|
+
}
|
|
2921
|
+
const testDurations = {};
|
|
2922
|
+
const testFileDurations = {};
|
|
2923
|
+
let firstTestStart = 0;
|
|
2924
|
+
const testTimeouts = {};
|
|
2925
|
+
const testTimeoutDetails = {};
|
|
2926
|
+
for (const line of output.split("\n")) {
|
|
2927
|
+
const entry = line.split(marker + "duration:")[1];
|
|
2928
|
+
if (entry === void 0) continue;
|
|
2929
|
+
const decoded = Schema8.decodeOption(Schema8.fromJsonString(Schema8.Struct({ file: Schema8.String, duration: Schema8.Finite, timeout: Schema8.Finite, key: Schema8.String, start: Schema8.Finite })))(entry);
|
|
2930
|
+
if (decoded._tag === "None") {
|
|
2931
|
+
telemetryWarnings.push("Internal reporter telemetry error: invalid cold timing marker; omitted");
|
|
2932
|
+
continue;
|
|
2933
|
+
}
|
|
2934
|
+
const timing = decoded.value;
|
|
2935
|
+
if (timing.start > 0) firstTestStart = firstTestStart ? Math.min(firstTestStart, timing.start) : timing.start;
|
|
2936
|
+
testDurations[timing.file] = Math.max(testDurations[timing.file] ?? 0, timing.duration);
|
|
2937
|
+
testTimeoutDetails[timing.key] = timing.timeout;
|
|
2938
|
+
testTimeouts[timing.file] = Math.max(testTimeouts[timing.file] ?? 0, timing.timeout);
|
|
2939
|
+
}
|
|
2940
|
+
for (const part of output.split(marker + "fileDuration:").slice(1)) {
|
|
2941
|
+
const decoded = Schema8.decodeOption(Schema8.fromJsonString(Schema8.Struct({ file: Schema8.String, duration: Schema8.Finite })))(part.split("\n")[0]);
|
|
2942
|
+
if (decoded._tag === "None") {
|
|
2943
|
+
telemetryWarnings.push("Internal reporter telemetry error: invalid cold file timing marker; omitted");
|
|
2944
|
+
continue;
|
|
2945
|
+
}
|
|
2946
|
+
const timing = decoded.value;
|
|
2947
|
+
testFileDurations[timing.file] = timing.duration;
|
|
2948
|
+
}
|
|
1574
2949
|
const run2 = {
|
|
1575
2950
|
status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
|
|
1576
2951
|
durationMs: ended - started,
|
|
1577
2952
|
command,
|
|
1578
2953
|
output,
|
|
1579
2954
|
testsCollected: output.includes(marker + "collected"),
|
|
1580
|
-
testFiles: selected
|
|
2955
|
+
testFiles: selected,
|
|
2956
|
+
testDurations,
|
|
2957
|
+
testTimeouts,
|
|
2958
|
+
testTimeoutDetails,
|
|
2959
|
+
testFileDurations,
|
|
2960
|
+
startupMs: firstTestStart ? Math.max(0, Math.ceil(firstTestStart - started)) : 0,
|
|
2961
|
+
probeSupported: output.includes(marker + "probeSupported:true"),
|
|
2962
|
+
probeLoaded: output.includes(marker + "probeLoaded"),
|
|
2963
|
+
testWorkers: output.includes(marker + "workers:") ? Number(output.split(marker + "workers:")[1]?.split("\n")[0]) : void 0,
|
|
2964
|
+
testConcurrency: Math.max(0, ...output.split(marker + "concurrency:").slice(1).map((part) => Number(part.split("\n")[0])))
|
|
1581
2965
|
};
|
|
1582
|
-
|
|
1583
|
-
|
|
2966
|
+
const cleaned = cleanTelemetry(run2, "cold run");
|
|
2967
|
+
return { ...cleaned.value, backstopMs: backstopMs(), telemetryWarnings: [...telemetryWarnings, ...cleaned.warnings], exitCode };
|
|
2968
|
+
}, Effect6.scoped);
|
|
1584
2969
|
return TestRunner.of({
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
2970
|
+
stats: Effect6.sync(() => ({ hostRestarts, poolResets })),
|
|
2971
|
+
open: Effect6.fn("TestRunner.open")(function* (dir, cold, warm = false, mutants = 1) {
|
|
2972
|
+
scopes.set(dir.path, yield* Scope3.Scope);
|
|
2973
|
+
openedAt.set(dir.path, yield* Clock4.currentTimeMillis);
|
|
2974
|
+
yield* Effect6.addFinalizer(() => Effect6.sync(() => {
|
|
2975
|
+
sessions.delete(dir.path);
|
|
2976
|
+
selectors.delete(dir.path);
|
|
2977
|
+
auto.delete(dir.path);
|
|
2978
|
+
primers.delete(dir.path);
|
|
2979
|
+
scopes.delete(dir.path);
|
|
2980
|
+
backstopTotals.delete(dir.path);
|
|
2981
|
+
openedAt.delete(dir.path);
|
|
2982
|
+
lastCommands.delete(dir.path);
|
|
2983
|
+
if (scopes.size === 0) {
|
|
2984
|
+
baselineBudgetMs = DEFAULT_BASELINE_TIMEOUT_MS;
|
|
2985
|
+
warmDisabled = false;
|
|
2986
|
+
automaticMode = "pending";
|
|
2987
|
+
hostRestarts = 0;
|
|
2988
|
+
poolResets = 0;
|
|
2989
|
+
warned = false;
|
|
2990
|
+
modeReason = void 0;
|
|
2991
|
+
}
|
|
2992
|
+
}));
|
|
2993
|
+
if (cold) modeReason = "Explicit --cold";
|
|
2994
|
+
if (cold || warmDisabled || !warm && automaticMode === "cold") return;
|
|
2995
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
2996
|
+
const session = yield* openWarmRunner(dir, (reason) => {
|
|
2997
|
+
warmDisabled = true;
|
|
2998
|
+
modeReason = reason;
|
|
2999
|
+
}, { ...sessionOptions, quiet: !warm, warn: warn6, onBackstop: onBackstop(dir.path), processesSince: openedAt.get(dir.path) }).pipe(Effect6.provideService(FileSystem7.FileSystem, fs), Effect6.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) })));
|
|
3000
|
+
sessions.set(dir.path, session);
|
|
3001
|
+
if (warmDisabled || !warm && automaticMode === "cold") {
|
|
3002
|
+
yield* session.disable;
|
|
3003
|
+
return;
|
|
3004
|
+
}
|
|
3005
|
+
if (warm) modeReason = "Explicit --warm; supported configuration";
|
|
3006
|
+
if (!warm && automaticMode === "pending") auto.set(dir.path, { startupMs: (yield* Clock4.currentTimeMillis) - started, mutants });
|
|
3007
|
+
}),
|
|
3008
|
+
invalidate: (dir, file) => sessions.get(dir.path)?.invalidate(file) ?? Effect6.void,
|
|
3009
|
+
selectRelated: Effect6.fn("TestRunner.selectRelated")(function* (dir, file) {
|
|
3010
|
+
const session = sessions.get(dir.path);
|
|
3011
|
+
if (session !== void 0 && !warmDisabled) return yield* session.select(file);
|
|
3012
|
+
let selector = selectors.get(dir.path) ?? selectors.values().next().value;
|
|
3013
|
+
if (!selector) {
|
|
3014
|
+
const scope = scopes.get(dir.path);
|
|
3015
|
+
if (!scope) return void 0;
|
|
3016
|
+
selector = yield* openWarmRunner(dir, () => {
|
|
3017
|
+
}, { quiet: true, selectionOnly: true, onBackstop: onBackstop(dir.path), processesSince: openedAt.get(dir.path) }).pipe(
|
|
3018
|
+
Effect6.provideService(FileSystem7.FileSystem, fs),
|
|
3019
|
+
Effect6.provideService(Scope3.Scope, scope),
|
|
3020
|
+
Effect6.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "select"], message: String(error3) }))
|
|
3021
|
+
);
|
|
3022
|
+
selectors.set(dir.path, selector);
|
|
3023
|
+
}
|
|
3024
|
+
return yield* selector.select(file);
|
|
3025
|
+
}),
|
|
3026
|
+
probeReachability: Effect6.fn("TestRunner.probeReachability")(function* (dir, mutant, timeoutMs) {
|
|
3027
|
+
if (!dir.poison) return { file: mutant.file, status: "unsupported", durationMs: 0, testCommand: [], output: "Scratch adapter cannot poison modules" };
|
|
3028
|
+
const temporary = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-probe-" });
|
|
3029
|
+
const signal = path.join(temporary, "loaded");
|
|
3030
|
+
const control = path.join(temporary, "control");
|
|
3031
|
+
const token = `mutant-cafe-probe:${path.basename(temporary)}`;
|
|
3032
|
+
const setupFile = path.join(temporary, "setup.mjs");
|
|
3033
|
+
const vitest = yield* Effect6.try({
|
|
3034
|
+
try: () => pathToFileURL2(path.join(path.dirname(createRequire(path.join(dir.path, "package.json")).resolve("vitest/package.json")), "dist/index.js")).href,
|
|
3035
|
+
catch: (error3) => new TestSpawnError({ command: ["vitest", "probe"], message: String(error3) })
|
|
3036
|
+
});
|
|
3037
|
+
yield* fs.writeFileString(setupFile, `import { beforeAll, afterAll } from ${JSON.stringify(vitest)};
|
|
3038
|
+
beforeAll(() => globalThis.process.getBuiltinModule("node:fs").writeFileSync(${JSON.stringify(control)}, "ready"));
|
|
3039
|
+
afterAll(() => { if (globalThis[Symbol.for(${JSON.stringify(token)})]) throw new Error(${JSON.stringify(token)}); });`);
|
|
3040
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
3041
|
+
const invalidate = () => sessions.get(dir.path)?.invalidate(mutant.file) ?? Effect6.void;
|
|
3042
|
+
const run2 = yield* Effect6.acquireUseRelease(
|
|
3043
|
+
dir.poison(mutant, signal, token),
|
|
3044
|
+
() => Effect6.gen(function* () {
|
|
3045
|
+
yield* invalidate();
|
|
3046
|
+
return yield* execute2(dir, ["run", "--passWithNoTests"], timeoutMs, void 0, false, { token, setupFile });
|
|
3047
|
+
}),
|
|
3048
|
+
() => dir.revert(mutant).pipe(Effect6.andThen(invalidate), Effect6.orDie)
|
|
3049
|
+
);
|
|
3050
|
+
const supported = yield* fs.exists(control);
|
|
3051
|
+
const loaded = (yield* fs.exists(signal)) || run2.probeLoaded === true;
|
|
3052
|
+
return {
|
|
3053
|
+
file: mutant.file,
|
|
3054
|
+
status: !supported ? "unsupported" : run2.status === "passed" && !loaded ? "unreachable" : "reachable",
|
|
3055
|
+
durationMs: (yield* Clock4.currentTimeMillis) - started,
|
|
3056
|
+
testCommand: run2.command,
|
|
3057
|
+
output: run2.output
|
|
3058
|
+
};
|
|
3059
|
+
}, (effect5) => effect5.pipe(Effect6.scoped, Effect6.mapError((error3) => error3._tag === "ScratchError" || error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "probe"], message: String(error3) })))),
|
|
3060
|
+
baseline: Effect6.fn("TestRunner.baseline")(function* (dir, tsconfig, timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS) {
|
|
3061
|
+
baselineBudgetMs = timeoutMs;
|
|
3062
|
+
lastCommands.delete(dir.path);
|
|
3063
|
+
const unreliable = yield* preflight(dir.path, tsconfig, timeoutMs, { processesSince: openedAt.get(dir.path), onBackstop: onBackstop(dir.path) }).pipe(Effect6.provideService(FileSystem7.FileSystem, fs), Effect6.provideService(ChildProcessSpawner3.ChildProcessSpawner, spawner), Effect6.catch((error3) => Effect6.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error3)}` }])));
|
|
3064
|
+
for (const issue of unreliable) yield* Console4.warn(`Warning (${issue.kind}): ${issue.reason}`);
|
|
1588
3065
|
if (unreliable.some((issue) => issue.kind === "runner")) {
|
|
1589
3066
|
const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
|
|
1590
|
-
yield*
|
|
3067
|
+
yield* Console4.warn(`Baseline command (not executed: unsupported runner): ${command.join(" ")}`);
|
|
1591
3068
|
return { durationMs: 0, testCommand: command, unreliable };
|
|
1592
3069
|
}
|
|
1593
|
-
const run2 = yield*
|
|
3070
|
+
const run2 = yield* execute2(dir, ["run", "--passWithNoTests"], void 0, void 0, auto.has(dir.path));
|
|
3071
|
+
if (run2.status === "timedOut") return yield* baselineTimedOut(timeoutMs, run2.command);
|
|
1594
3072
|
if (run2.status !== "passed" && run2.status !== "untested") {
|
|
1595
|
-
return yield*
|
|
3073
|
+
return yield* Effect6.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output, command: run2.command }));
|
|
3074
|
+
}
|
|
3075
|
+
if (sessions.has(dir.path)) yield* sessions.get(dir.path).invalidate(run2.testFiles?.[0] ?? "package.json");
|
|
3076
|
+
if (auto.has(dir.path)) primers.set(dir.path, run2);
|
|
3077
|
+
return {
|
|
3078
|
+
durationMs: run2.durationMs,
|
|
3079
|
+
testCommand: run2.command,
|
|
3080
|
+
unreliable,
|
|
3081
|
+
hostPid: run2.hostPid,
|
|
3082
|
+
telemetryWarnings: run2.telemetryWarnings,
|
|
3083
|
+
testTimeoutDetails: run2.testTimeoutDetails,
|
|
3084
|
+
testDurations: run2.testDurations,
|
|
3085
|
+
testTimeouts: run2.testTimeouts,
|
|
3086
|
+
testWorkers: run2.testWorkers,
|
|
3087
|
+
testConcurrency: run2.testConcurrency,
|
|
3088
|
+
testFileDurations: run2.testFileDurations,
|
|
3089
|
+
startupMs: run2.startupMs,
|
|
3090
|
+
probeSupported: run2.probeSupported,
|
|
3091
|
+
runnerModeReason: modeReason ?? (auto.has(dir.path) ? "Auto calibration pending" : "Cold execution; no warm session"),
|
|
3092
|
+
runnerMode: sessions.has(dir.path) && !warmDisabled && !auto.has(dir.path) ? "warm" : "cold"
|
|
3093
|
+
};
|
|
3094
|
+
}, (effect5, dir, _tsconfig, timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS) => effect5.pipe(
|
|
3095
|
+
Effect6.timeout(timeoutMs),
|
|
3096
|
+
Effect6.catchTag("TimeoutError", () => Effect6.fail(baselineTimedOut(timeoutMs, lastCommands.get(dir.path) ?? [])))
|
|
3097
|
+
)),
|
|
3098
|
+
calibrate: Effect6.fn("TestRunner.calibrate")(function* (dir, mutants, copies) {
|
|
3099
|
+
const primer = primers.get(dir.path) ?? primers.values().next().value;
|
|
3100
|
+
if (!primer || automaticMode !== "pending" || auto.size === 0 || warmDisabled) return {};
|
|
3101
|
+
const disable = Effect6.gen(function* () {
|
|
3102
|
+
automaticMode = "cold";
|
|
3103
|
+
warmDisabled = true;
|
|
3104
|
+
auto.clear();
|
|
3105
|
+
for (const session of sessions.values()) yield* session.disable;
|
|
3106
|
+
});
|
|
3107
|
+
if (mutants <= (primer.testFiles?.length ?? 0)) {
|
|
3108
|
+
modeReason = `Auto: small selection (${mutants} testable mutants across ${primer.testFiles?.length ?? 0} files)`;
|
|
3109
|
+
yield* disable;
|
|
3110
|
+
yield* Console4.warn(`Vitest auto mode: cold; small selection (${mutants} testable mutants across ${primer.testFiles?.length ?? 0} files), skipping paired calibration`);
|
|
3111
|
+
return { runnerMode: "cold", runnerModeReason: modeReason, testableMutants: mutants };
|
|
1596
3112
|
}
|
|
1597
|
-
|
|
3113
|
+
const startups = [...auto.values()].map((entry) => entry.startupMs);
|
|
3114
|
+
auto.clear();
|
|
3115
|
+
const cold = yield* execute2(dir, ["run", "--passWithNoTests"], void 0, void 0, true);
|
|
3116
|
+
if (cold.status === "timedOut") return yield* baselineTimedOut(baselineBudgetMs, cold.command);
|
|
3117
|
+
if (cold.status !== "passed" && cold.status !== "untested") return yield* new BaselineFailed({ exitCode: cold.exitCode, output: cold.output, command: cold.command });
|
|
3118
|
+
const warm = yield* execute2(dir, ["run", "--passWithNoTests"]);
|
|
3119
|
+
if (warm.status === "timedOut") return yield* baselineTimedOut(baselineBudgetMs, warm.command);
|
|
3120
|
+
if (warm.status !== "passed" && warm.status !== "untested") return yield* new BaselineFailed({ exitCode: warm.exitCode, output: warm.output, command: warm.command });
|
|
3121
|
+
const calibration2 = {
|
|
3122
|
+
coldMs: cold.durationMs,
|
|
3123
|
+
warmMs: warm.durationMs,
|
|
3124
|
+
warmStartupMs: startupCost(startups, copies),
|
|
3125
|
+
overheadMs: warm.durationMs + cold.durationMs,
|
|
3126
|
+
coldStartupMs: cold.startupMs ?? 0,
|
|
3127
|
+
warmRunStartupMs: warm.startupMs ?? 0,
|
|
3128
|
+
testFiles: cold.testFiles?.length ?? 0,
|
|
3129
|
+
mutants
|
|
3130
|
+
};
|
|
3131
|
+
const sameSelection = JSON.stringify([...warm.testFiles ?? []].sort()) === JSON.stringify([...cold.testFiles ?? []].sort());
|
|
3132
|
+
const choice = !warmDisabled && warm.status === cold.status && sameSelection ? chooseMode(calibration2) : "cold";
|
|
3133
|
+
modeReason = warmDisabled ? modeReason ?? "Warm execution failed during calibration" : !sameSelection || warm.status !== cold.status ? "Auto: cold/warm selection or status mismatch" : `Auto: paired measurements favor ${choice}`;
|
|
3134
|
+
automaticMode = choice;
|
|
3135
|
+
auto.clear();
|
|
3136
|
+
yield* Console4.warn(`Vitest auto mode: ${choice}; paired cold ${cold.durationMs} ms, warm ${warm.durationMs} ms; ${mutants} testable mutants, ${copies} copies, startup ${calibration2.warmStartupMs} ms`);
|
|
3137
|
+
if (choice === "cold") yield* disable;
|
|
3138
|
+
else if (sessions.has(dir.path)) yield* sessions.get(dir.path).invalidate(warm.testFiles?.[0] ?? "package.json");
|
|
3139
|
+
const run2 = choice === "cold" ? cold : warm;
|
|
3140
|
+
return { runnerMode: choice, runnerModeReason: modeReason, calibration: calibration2, testableMutants: mutants, hostPid: run2.hostPid };
|
|
1598
3141
|
}),
|
|
1599
|
-
runRelated:
|
|
1600
|
-
const related = yield*
|
|
3142
|
+
runRelated: Effect6.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs, testTimeoutMs) {
|
|
3143
|
+
const related = yield* execute2(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs, testTimeoutMs);
|
|
1601
3144
|
if (related.status !== "untested") return related;
|
|
1602
3145
|
const remaining = Math.max(1, timeoutMs - related.durationMs);
|
|
1603
|
-
const full = yield*
|
|
3146
|
+
const full = yield* execute2(dir, ["run", "--passWithNoTests"], remaining, testTimeoutMs);
|
|
1604
3147
|
return {
|
|
1605
3148
|
...full,
|
|
1606
3149
|
status: full.status === "passed" ? "untested" : full.status,
|
|
1607
3150
|
durationMs: related.durationMs + full.durationMs,
|
|
3151
|
+
backstopMs: (related.backstopMs ?? 0) + (full.backstopMs ?? 0),
|
|
1608
3152
|
output: related.output + "\nFull-suite fallback:\n" + full.output
|
|
1609
3153
|
};
|
|
1610
3154
|
})
|
|
@@ -1612,14 +3156,14 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
|
|
|
1612
3156
|
}));
|
|
1613
3157
|
|
|
1614
3158
|
// packages/runner/src/Run.ts
|
|
1615
|
-
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
1616
|
-
import { types } from "xstate";
|
|
1617
|
-
import * as
|
|
3159
|
+
import { createEffectActor as createEffectActor3, createEffectLogic as createEffectLogic2, join as join2, send as send3, setupEffect as setupEffect3 } from "@xstate/effect";
|
|
3160
|
+
import { types as types2 } from "xstate";
|
|
3161
|
+
import * as Effect7 from "effect/Effect";
|
|
1618
3162
|
import * as Pool from "effect/Pool";
|
|
1619
3163
|
import * as Path5 from "effect/Path";
|
|
1620
|
-
import * as
|
|
1621
|
-
import * as
|
|
1622
|
-
import * as
|
|
3164
|
+
import * as Result2 from "effect/Result";
|
|
3165
|
+
import * as Schema9 from "effect/Schema";
|
|
3166
|
+
import * as Scope5 from "effect/Scope";
|
|
1623
3167
|
import * as Stream3 from "effect/Stream";
|
|
1624
3168
|
var ScratchPool = class {
|
|
1625
3169
|
value;
|
|
@@ -1627,15 +3171,15 @@ var ScratchPool = class {
|
|
|
1627
3171
|
this.value = value;
|
|
1628
3172
|
}
|
|
1629
3173
|
};
|
|
1630
|
-
var runMutants =
|
|
3174
|
+
var runMutants = Effect7.fn("Runner.runMutants")(function* (config, mutants) {
|
|
1631
3175
|
const scratch = yield* Scratch;
|
|
1632
3176
|
const tests = yield* TestRunner;
|
|
1633
3177
|
const source = yield* MutantSource;
|
|
1634
3178
|
const reporter = yield* Reporter;
|
|
1635
|
-
const scope = yield*
|
|
3179
|
+
const scope = yield* Scope5.Scope;
|
|
1636
3180
|
const path = yield* Path5.Path;
|
|
1637
3181
|
const jobs = Math.max(1, Math.floor(config.jobs));
|
|
1638
|
-
const report = (state2) => ({
|
|
3182
|
+
const report = (state2) => sanitizeReportTelemetry({
|
|
1639
3183
|
schemaVersion: 2,
|
|
1640
3184
|
tool: "mutant.cafe",
|
|
1641
3185
|
root: config.root,
|
|
@@ -1643,92 +3187,205 @@ var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
1643
3187
|
timeoutMs: state2.timeoutMs,
|
|
1644
3188
|
results: state2.results,
|
|
1645
3189
|
notMutated: state2.notMutated,
|
|
1646
|
-
|
|
3190
|
+
reachabilityProbes: state2.probes,
|
|
3191
|
+
hostRestarts: state2.hostRestarts,
|
|
3192
|
+
poolResets: state2.poolResets,
|
|
3193
|
+
...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineTimedOut" ? `BaselineTimedOut: ${state2.failure.message}` : state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${formatTestCommand(state2.failure.command)}
|
|
1647
3194
|
${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
1648
|
-
});
|
|
1649
|
-
const capture = (effect5) =>
|
|
1650
|
-
const copying =
|
|
1651
|
-
const
|
|
1652
|
-
|
|
3195
|
+
}).report;
|
|
3196
|
+
const capture = (effect5) => Effect7.result(effect5);
|
|
3197
|
+
const copying = createEffectLogic2(({ input }) => capture(Effect7.gen(function* () {
|
|
3198
|
+
const acquire = Effect7.gen(function* () {
|
|
3199
|
+
const dir = yield* scratch.acquire(config.root);
|
|
3200
|
+
if (tests.open) yield* tests.open(dir, config.cold ?? false, config.warm ?? false, input);
|
|
3201
|
+
return dir;
|
|
3202
|
+
}).pipe(Effect7.mapError((error3) => error3._tag === "ScratchError" ? error3 : new ScratchError({ operation: "warm runner", path: config.root, message: String(error3) })));
|
|
3203
|
+
const pool = yield* Pool.make({ acquire, size: jobs }).pipe(
|
|
3204
|
+
Effect7.provideService(Scope5.Scope, scope)
|
|
1653
3205
|
);
|
|
1654
|
-
yield*
|
|
3206
|
+
yield* Effect7.scoped(Pool.get(pool));
|
|
1655
3207
|
return new ScratchPool(pool);
|
|
1656
3208
|
})));
|
|
1657
|
-
const baselining =
|
|
1658
|
-
if (input === void 0) return yield*
|
|
1659
|
-
const baseline = yield*
|
|
3209
|
+
const baselining = createEffectLogic2(({ input }) => capture(Effect7.gen(function* () {
|
|
3210
|
+
if (input === void 0) return yield* Effect7.die("Missing scratch pool");
|
|
3211
|
+
const baseline = yield* Effect7.scoped(Effect7.gen(function* () {
|
|
1660
3212
|
const dir = yield* Pool.get(input.value);
|
|
1661
|
-
return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig);
|
|
3213
|
+
return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig, config.baselineTimeoutMs);
|
|
1662
3214
|
}));
|
|
1663
3215
|
return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
|
|
1664
3216
|
})));
|
|
1665
|
-
const generating =
|
|
1666
|
-
const testing =
|
|
3217
|
+
const generating = createEffectLogic2(() => capture(Stream3.runCollect(mutants ?? source.generate(config))));
|
|
3218
|
+
const testing = createEffectLogic2(({ input }) => capture(Effect7.gen(function* () {
|
|
1667
3219
|
const dirs = input.state.pool?.value;
|
|
1668
|
-
if (dirs === void 0) return yield*
|
|
3220
|
+
if (dirs === void 0) return yield* Effect7.die("Missing scratch pool");
|
|
3221
|
+
let baseline = input.state.baseline;
|
|
3222
|
+
const viabilityById = /* @__PURE__ */ new Map();
|
|
3223
|
+
const preReported = /* @__PURE__ */ new Set();
|
|
3224
|
+
if (!config.cold && !config.warm && tests.calibrate) yield* Effect7.forEach(input.state.pending, (mutant) => Effect7.gen(function* () {
|
|
3225
|
+
const viability = yield* source.checkViable(mutant);
|
|
3226
|
+
viabilityById.set(mutant.id, viability);
|
|
3227
|
+
if (viability.analysisFailed) {
|
|
3228
|
+
preReported.add(mutant.id);
|
|
3229
|
+
yield* input.skip(viability.analysisFailed);
|
|
3230
|
+
} else if (!viability.viable) {
|
|
3231
|
+
preReported.add(mutant.id);
|
|
3232
|
+
const result5 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
3233
|
+
yield* input.record(result5);
|
|
3234
|
+
yield* reporter.progress(result5);
|
|
3235
|
+
}
|
|
3236
|
+
}), { concurrency: jobs, discard: true });
|
|
3237
|
+
const unreachable = /* @__PURE__ */ new Map();
|
|
3238
|
+
const selectRelated = tests.selectRelated;
|
|
3239
|
+
const probeReachability = tests.probeReachability;
|
|
3240
|
+
if (input.state.baseline.probeSupported && selectRelated && probeReachability) {
|
|
3241
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3242
|
+
const builtTests = input.state.baseline.unreliable?.flatMap((issue) => issue.kind === "built" ? issue.testFiles : []) ?? [];
|
|
3243
|
+
for (const mutant of input.state.pending) {
|
|
3244
|
+
if (viabilityById.has(mutant.id) && !viabilityById.get(mutant.id)?.viable) continue;
|
|
3245
|
+
const file = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
3246
|
+
if (seen.has(file)) continue;
|
|
3247
|
+
seen.add(file);
|
|
3248
|
+
if (unreliableFor(input.state.baseline, file, builtTests).length) continue;
|
|
3249
|
+
const probe2 = yield* Effect7.scoped(Effect7.gen(function* () {
|
|
3250
|
+
const dir = yield* Pool.get(dirs);
|
|
3251
|
+
if (!dir.poison) return void 0;
|
|
3252
|
+
const files = yield* selectRelated(dir, file);
|
|
3253
|
+
if (files === void 0 || files.length) return void 0;
|
|
3254
|
+
return yield* probeReachability(dir, { ...mutant, file }, input.state.timeoutMs);
|
|
3255
|
+
}));
|
|
3256
|
+
if (probe2) {
|
|
3257
|
+
yield* input.probe(probe2);
|
|
3258
|
+
if (probe2.status === "unreachable") unreachable.set(file, probe2);
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
const calibrate = tests.calibrate;
|
|
3263
|
+
if (calibrate) {
|
|
3264
|
+
const testable = input.state.pending.filter((mutant) => {
|
|
3265
|
+
const file = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
3266
|
+
return viabilityById.get(mutant.id)?.viable && !unreachable.has(file) && !unreliableFor(baseline, file).length;
|
|
3267
|
+
}).length;
|
|
3268
|
+
const selected = yield* Effect7.scoped(Effect7.gen(function* () {
|
|
3269
|
+
const dir = yield* Pool.get(dirs);
|
|
3270
|
+
return yield* calibrate(dir, testable, config.jobs);
|
|
3271
|
+
}));
|
|
3272
|
+
baseline = { ...baseline, ...selected };
|
|
3273
|
+
yield* input.updateBaseline(baseline);
|
|
3274
|
+
}
|
|
1669
3275
|
const neverBudgets = /* @__PURE__ */ new Map();
|
|
3276
|
+
const neverLimits = /* @__PURE__ */ new Map();
|
|
3277
|
+
const neverBases = /* @__PURE__ */ new Map();
|
|
3278
|
+
const neverAllowances = /* @__PURE__ */ new Map();
|
|
1670
3279
|
for (const mutant of input.state.pending) {
|
|
3280
|
+
if (viabilityById.has(mutant.id) && !viabilityById.get(mutant.id)?.viable) continue;
|
|
3281
|
+
if (unreachable.has(path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file)) continue;
|
|
1671
3282
|
if (mutant.genre !== "EffectNever" || neverBudgets.has(mutant.file) || unreliableFor(input.state.baseline, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file).length > 0) continue;
|
|
1672
|
-
|
|
3283
|
+
let probeTimeout = Math.max(1, Math.floor(input.state.timeoutMs / 2));
|
|
3284
|
+
const originalTimeouts = new Set(Object.values(baseline.testTimeoutDetails ?? {}));
|
|
3285
|
+
while (originalTimeouts.has(probeTimeout)) probeTimeout++;
|
|
3286
|
+
const measured = yield* Effect7.scoped(Effect7.gen(function* () {
|
|
1673
3287
|
const dir = yield* Pool.get(dirs);
|
|
1674
|
-
return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs);
|
|
3288
|
+
return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs, probeTimeout);
|
|
1675
3289
|
}));
|
|
1676
|
-
if (measured.status === "
|
|
3290
|
+
if (measured.status === "timedOut") return yield* new BaselineTimedOut({
|
|
3291
|
+
timeoutMs: input.state.timeoutMs,
|
|
3292
|
+
command: measured.command,
|
|
3293
|
+
message: `Clean related probe exceeded ${input.state.timeoutMs / 1e3} seconds. Increase --timeout for a longer probe.`
|
|
3294
|
+
});
|
|
3295
|
+
if (measured.status === "failed") {
|
|
1677
3296
|
return yield* new BaselineFailed({ exitCode: 1, output: measured.output, command: measured.command });
|
|
1678
3297
|
}
|
|
1679
|
-
|
|
3298
|
+
const files = measured.testFiles ?? Object.keys(measured.testDurations ?? baseline.testDurations ?? {});
|
|
3299
|
+
const slowest = Math.max(0, ...files.map((file) => baseline.testDurations?.[file] ?? measured.testDurations?.[file] ?? 0));
|
|
3300
|
+
const relatedDuration = baseline.testFileDurations === void 0 ? baseline.durationMs : files.reduce((sum, file) => sum + (baseline.testFileDurations?.[file] ?? 0), 0);
|
|
3301
|
+
neverAllowances.set(mutant.file, Math.ceil(relatedDuration) + (baseline.startupMs ?? 0));
|
|
3302
|
+
neverBases.set(mutant.file, slowest);
|
|
3303
|
+
neverBudgets.set(mutant.file, Math.max(2e3, config.neverTimeoutMs, Math.ceil(slowest * config.timeoutMultiplier)));
|
|
3304
|
+
const explicit = Object.entries(baseline.testTimeoutDetails ?? {}).filter(([key, value]) => value > 0 && measured.testTimeoutDetails?.[key] === value).map(([, value]) => value);
|
|
3305
|
+
neverLimits.set(mutant.file, Math.max(0, ...explicit));
|
|
1680
3306
|
}
|
|
1681
3307
|
yield* Stream3.fromIterable(input.state.pending).pipe(
|
|
1682
|
-
Stream3.mapEffect((mutant) =>
|
|
1683
|
-
|
|
3308
|
+
Stream3.mapEffect((mutant) => Effect7.scoped(Effect7.gen(function* () {
|
|
3309
|
+
if (preReported.has(mutant.id)) return;
|
|
3310
|
+
const viability = viabilityById.get(mutant.id) ?? (yield* source.checkViable(mutant));
|
|
1684
3311
|
if (viability.analysisFailed) {
|
|
1685
3312
|
yield* input.skip(viability.analysisFailed);
|
|
1686
3313
|
return;
|
|
1687
3314
|
}
|
|
1688
3315
|
if (!viability.viable) {
|
|
1689
|
-
const
|
|
1690
|
-
yield* input.record(
|
|
1691
|
-
yield* reporter.progress(
|
|
3316
|
+
const result6 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
3317
|
+
yield* input.record(result6);
|
|
3318
|
+
yield* reporter.progress(result6);
|
|
1692
3319
|
return;
|
|
1693
3320
|
}
|
|
1694
3321
|
const localFile = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
1695
3322
|
const unreliable = unreliableFor(input.state.baseline, localFile);
|
|
1696
3323
|
if (unreliable.length) {
|
|
1697
|
-
const
|
|
1698
|
-
yield* input.record(
|
|
1699
|
-
yield* reporter.progress(
|
|
3324
|
+
const result6 = { mutant, outcome: "unreliable", durationMs: 0, testCommand: input.state.baseline.testCommand, diagnostics: unreliable.map((issue) => issue.reason) };
|
|
3325
|
+
yield* input.record(result6);
|
|
3326
|
+
yield* reporter.progress(result6);
|
|
3327
|
+
return;
|
|
3328
|
+
}
|
|
3329
|
+
const cached = unreachable.get(localFile);
|
|
3330
|
+
if (cached) {
|
|
3331
|
+
const result6 = {
|
|
3332
|
+
mutant,
|
|
3333
|
+
outcome: "untested",
|
|
3334
|
+
durationMs: 0,
|
|
3335
|
+
testCommand: [],
|
|
3336
|
+
diagnostics: ["The full-suite module-load probe passed without loading this file"]
|
|
3337
|
+
};
|
|
3338
|
+
yield* input.record(result6);
|
|
3339
|
+
yield* reporter.progress(result6);
|
|
1700
3340
|
return;
|
|
1701
3341
|
}
|
|
1702
3342
|
const dir = yield* Pool.get(dirs);
|
|
1703
|
-
const
|
|
3343
|
+
const testTimeoutMs = mutant.genre === "EffectNever" ? neverBudgets.get(mutant.file) : void 0;
|
|
3344
|
+
const timeoutMs = testTimeoutMs === void 0 ? input.state.timeoutMs : Math.max(testTimeoutMs, neverLimits.get(mutant.file) ?? 0) + (neverAllowances.get(mutant.file) ?? 0);
|
|
3345
|
+
const run2 = yield* Effect7.acquireUseRelease(
|
|
1704
3346
|
dir.apply(mutant),
|
|
1705
|
-
() =>
|
|
1706
|
-
|
|
1707
|
-
|
|
3347
|
+
() => Effect7.gen(function* () {
|
|
3348
|
+
if (tests.invalidate) yield* tests.invalidate(dir, localFile);
|
|
3349
|
+
return yield* tests.runRelated(dir, localFile, timeoutMs, testTimeoutMs);
|
|
3350
|
+
}),
|
|
3351
|
+
// Restore and re-invalidate even on interruption before leasing again.
|
|
3352
|
+
() => Effect7.gen(function* () {
|
|
3353
|
+
yield* dir.revert(mutant);
|
|
3354
|
+
if (tests.invalidate) yield* tests.invalidate(dir, localFile);
|
|
3355
|
+
}).pipe(Effect7.orDie)
|
|
1708
3356
|
);
|
|
1709
3357
|
const selectedIssues = unreliableFor(input.state.baseline, localFile, run2.testFiles);
|
|
1710
|
-
const
|
|
3358
|
+
const result5 = {
|
|
1711
3359
|
mutant,
|
|
1712
3360
|
// A kill before collection proves nothing about whether tests noticed.
|
|
1713
3361
|
outcome: selectedIssues.length ? "unreliable" : run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
|
|
1714
3362
|
durationMs: run2.durationMs,
|
|
3363
|
+
timeoutMs: testTimeoutMs ?? timeoutMs,
|
|
3364
|
+
outerTimeoutMs: timeoutMs,
|
|
3365
|
+
...testTimeoutMs === void 0 ? {} : { hangBudgetBaseMs: neverBases.get(mutant.file) },
|
|
3366
|
+
backstopMs: run2.backstopMs,
|
|
3367
|
+
telemetryWarnings: run2.telemetryWarnings,
|
|
3368
|
+
testWorkers: run2.testWorkers,
|
|
3369
|
+
testConcurrency: run2.testConcurrency,
|
|
1715
3370
|
testCommand: run2.command,
|
|
1716
3371
|
diagnostics: selectedIssues.map((issue) => issue.reason),
|
|
1717
3372
|
...run2.output === "" ? {} : { output: run2.output }
|
|
1718
3373
|
};
|
|
1719
|
-
yield* input.record(
|
|
1720
|
-
yield* reporter.progress(
|
|
3374
|
+
yield* input.record(result5);
|
|
3375
|
+
yield* reporter.progress(result5);
|
|
1721
3376
|
})), { concurrency: jobs }),
|
|
1722
3377
|
Stream3.runDrain
|
|
1723
3378
|
);
|
|
1724
3379
|
})));
|
|
1725
|
-
const reporting =
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
3380
|
+
const reporting = createEffectLogic2(({ input }) => capture(Effect7.gen(function* () {
|
|
3381
|
+
const stats = yield* tests.stats ?? Effect7.succeed({ hostRestarts: 0, poolResets: 0 });
|
|
3382
|
+
if (!input.reported) yield* reporter.write({ ...report(input), ...stats });
|
|
3383
|
+
return stats;
|
|
3384
|
+
})));
|
|
3385
|
+
const machine = setupEffect3({
|
|
1729
3386
|
schemas: {
|
|
1730
|
-
context:
|
|
1731
|
-
events: { CANCEL:
|
|
3387
|
+
context: types2(),
|
|
3388
|
+
events: { CANCEL: Schema9.Struct({}), RESULT: Schema9.Struct({ result: MutantResult }), SKIP: Schema9.Struct({ entry: NotMutated }), PROBE: Schema9.Struct({ entry: ReachabilityProbe }), BASELINE: Schema9.Struct({ entry: Baseline }) }
|
|
1732
3389
|
},
|
|
1733
3390
|
actors: { copying, baselining, generating, testing, reporting }
|
|
1734
3391
|
}).createMachine({
|
|
@@ -1740,39 +3397,46 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1740
3397
|
pending: [],
|
|
1741
3398
|
results: [],
|
|
1742
3399
|
reported: false,
|
|
1743
|
-
notMutated: []
|
|
3400
|
+
notMutated: [],
|
|
3401
|
+
probes: [],
|
|
3402
|
+
hostRestarts: 0,
|
|
3403
|
+
poolResets: 0
|
|
1744
3404
|
},
|
|
1745
3405
|
output: ({ context }) => context,
|
|
1746
3406
|
initial: "generating",
|
|
1747
3407
|
on: {
|
|
1748
3408
|
CANCEL: { target: ".interrupted" },
|
|
3409
|
+
BASELINE: ({ context, event }) => ({ context: { ...context, baseline: event.entry } }),
|
|
3410
|
+
PROBE: ({ context, event }) => ({ context: { ...context, probes: [...context.probes, event.entry] } }),
|
|
1749
3411
|
SKIP: ({ context, event }) => ({ context: { ...context, notMutated: [...new Map([...context.notMutated, event.entry].map((entry) => [JSON.stringify(entry), entry])).values()] } }),
|
|
1750
3412
|
RESULT: ({ context, event }) => ({ context: { ...context, results: [...context.results, event.result] } })
|
|
1751
3413
|
},
|
|
1752
3414
|
states: {
|
|
1753
|
-
copying: { invoke: { src: "copying", onDone: ({ context, event }) =>
|
|
3415
|
+
copying: { invoke: { src: "copying", input: ({ context }) => context.pending.length, onDone: ({ context, event }) => Result2.isSuccess(event.output) ? { target: "baseline", context: { ...context, pool: event.output.success } } : { target: "failed", context: { ...context, failure: event.output.failure } } } },
|
|
1754
3416
|
baseline: { invoke: {
|
|
1755
3417
|
src: "baselining",
|
|
1756
3418
|
input: ({ context }) => context.pool,
|
|
1757
|
-
onDone: ({ context, event }) =>
|
|
3419
|
+
onDone: ({ context, event }) => Result2.isSuccess(event.output) ? { target: "testing", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
|
|
1758
3420
|
...context,
|
|
1759
3421
|
failure: event.output.failure,
|
|
1760
|
-
baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
3422
|
+
baseline: event.output.failure._tag === "BaselineFailed" || event.output.failure._tag === "BaselineTimedOut" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
1761
3423
|
} }
|
|
1762
3424
|
} },
|
|
1763
|
-
generating: { invoke: { src: "generating", onDone: ({ context, event }) =>
|
|
3425
|
+
generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result2.isSuccess(event.output) ? { target: event.output.success.length ? "copying" : "reporting", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
|
|
1764
3426
|
testing: { invoke: {
|
|
1765
3427
|
src: "testing",
|
|
1766
3428
|
input: ({ context, self }) => ({
|
|
1767
3429
|
state: context,
|
|
1768
3430
|
// Queue completion before progress can trigger CANCEL. The parent's
|
|
1769
3431
|
// FIFO mailbox commits this result before handling that cancellation.
|
|
1770
|
-
record: (
|
|
1771
|
-
skip: (entry) =>
|
|
3432
|
+
record: (result5) => send3(self, { type: "RESULT", result: result5 }),
|
|
3433
|
+
skip: (entry) => send3(self, { type: "SKIP", entry }),
|
|
3434
|
+
probe: (entry) => send3(self, { type: "PROBE", entry }),
|
|
3435
|
+
updateBaseline: (entry) => send3(self, { type: "BASELINE", entry })
|
|
1772
3436
|
}),
|
|
1773
3437
|
onDone: ({ context, event }) => ({ target: "reporting", context: {
|
|
1774
3438
|
...context,
|
|
1775
|
-
failure:
|
|
3439
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1776
3440
|
} })
|
|
1777
3441
|
} },
|
|
1778
3442
|
reporting: { invoke: {
|
|
@@ -1780,8 +3444,9 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1780
3444
|
input: ({ context }) => context,
|
|
1781
3445
|
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
1782
3446
|
...context,
|
|
1783
|
-
|
|
1784
|
-
|
|
3447
|
+
...Result2.isSuccess(event.output) ? event.output.success : {},
|
|
3448
|
+
reported: Result2.isSuccess(event.output),
|
|
3449
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1785
3450
|
} })
|
|
1786
3451
|
} },
|
|
1787
3452
|
interrupted: { invoke: {
|
|
@@ -1789,57 +3454,58 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1789
3454
|
input: ({ context }) => context,
|
|
1790
3455
|
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
1791
3456
|
...context,
|
|
1792
|
-
|
|
1793
|
-
|
|
3457
|
+
...Result2.isSuccess(event.output) ? event.output.success : {},
|
|
3458
|
+
reported: Result2.isSuccess(event.output),
|
|
3459
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1794
3460
|
} })
|
|
1795
3461
|
} },
|
|
1796
3462
|
failed: { type: "final" },
|
|
1797
3463
|
done: { type: "final" }
|
|
1798
3464
|
}
|
|
1799
3465
|
});
|
|
1800
|
-
const state = yield*
|
|
1801
|
-
const actor = yield*
|
|
1802
|
-
return yield*
|
|
1803
|
-
yield*
|
|
1804
|
-
yield*
|
|
3466
|
+
const state = yield* Effect7.scoped(Effect7.gen(function* () {
|
|
3467
|
+
const actor = yield* createEffectActor3(machine);
|
|
3468
|
+
return yield* join2(actor).pipe(Effect7.orDie, Effect7.onInterrupt(() => Effect7.gen(function* () {
|
|
3469
|
+
yield* send3(actor, { type: "CANCEL" });
|
|
3470
|
+
yield* join2(actor).pipe(Effect7.orDie);
|
|
1805
3471
|
})));
|
|
1806
3472
|
}));
|
|
1807
3473
|
if (state.failure !== void 0) return yield* state.failure;
|
|
1808
3474
|
return report(state);
|
|
1809
|
-
},
|
|
3475
|
+
}, Effect7.scoped);
|
|
1810
3476
|
|
|
1811
3477
|
// packages/cli/src/bin.ts
|
|
1812
|
-
import * as
|
|
3478
|
+
import * as Effect12 from "effect/Effect";
|
|
1813
3479
|
import * as Layer5 from "effect/Layer";
|
|
1814
3480
|
import * as Stream7 from "effect/Stream";
|
|
1815
3481
|
|
|
1816
3482
|
// packages/cli/src/Command.ts
|
|
1817
|
-
import * as
|
|
1818
|
-
import * as
|
|
1819
|
-
import * as
|
|
3483
|
+
import * as Console6 from "effect/Console";
|
|
3484
|
+
import * as Effect11 from "effect/Effect";
|
|
3485
|
+
import * as FileSystem15 from "effect/FileSystem";
|
|
1820
3486
|
import * as Option from "effect/Option";
|
|
1821
3487
|
import * as Path13 from "effect/Path";
|
|
1822
3488
|
import * as Ref from "effect/Ref";
|
|
1823
|
-
import * as
|
|
3489
|
+
import * as Schema13 from "effect/Schema";
|
|
1824
3490
|
import * as Stream6 from "effect/Stream";
|
|
1825
3491
|
import * as Command from "effect/cli/Command";
|
|
1826
3492
|
import * as Flag from "effect/cli/Flag";
|
|
1827
3493
|
|
|
1828
3494
|
// packages/cli/src/Diff.ts
|
|
1829
|
-
import * as
|
|
1830
|
-
import * as
|
|
3495
|
+
import * as Effect8 from "effect/Effect";
|
|
3496
|
+
import * as FileSystem9 from "effect/FileSystem";
|
|
1831
3497
|
import * as Path7 from "effect/Path";
|
|
1832
|
-
import * as
|
|
3498
|
+
import * as Schema10 from "effect/Schema";
|
|
1833
3499
|
import * as Stream4 from "effect/Stream";
|
|
1834
3500
|
import * as ChildProcess3 from "effect/process/ChildProcess";
|
|
1835
|
-
var DiffMismatch = class extends
|
|
1836
|
-
path:
|
|
1837
|
-
message:
|
|
3501
|
+
var DiffMismatch = class extends Schema10.TaggedError()("DiffMismatch", {
|
|
3502
|
+
path: Schema10.String,
|
|
3503
|
+
message: Schema10.String
|
|
1838
3504
|
}) {
|
|
1839
3505
|
};
|
|
1840
|
-
var parseDiff = (text, path) =>
|
|
3506
|
+
var parseDiff = (text, path) => Effect8.try({
|
|
1841
3507
|
try: () => {
|
|
1842
|
-
const
|
|
3508
|
+
const fail4 = (message) => {
|
|
1843
3509
|
throw new DiffParseError({ path, message });
|
|
1844
3510
|
};
|
|
1845
3511
|
if (text === "") return [];
|
|
@@ -1851,12 +3517,12 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1851
3517
|
while (i < input.length) {
|
|
1852
3518
|
const line = input[i++];
|
|
1853
3519
|
if (line.startsWith("diff --git ") || /^(index |new file mode |deleted file mode |old mode |new mode |similarity index |rename from |rename to )/.test(line)) continue;
|
|
1854
|
-
if (!line.startsWith("--- "))
|
|
3520
|
+
if (!line.startsWith("--- ")) fail4("Expected a unified diff file header");
|
|
1855
3521
|
const next = input[i++];
|
|
1856
|
-
if (!next?.startsWith("+++ "))
|
|
3522
|
+
if (!next?.startsWith("+++ ")) fail4("Missing new-side file header");
|
|
1857
3523
|
const raw = next.slice(4).split(" ")[0];
|
|
1858
3524
|
const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
|
|
1859
|
-
if (typeof decoded !== "string")
|
|
3525
|
+
if (typeof decoded !== "string") fail4("Invalid file path");
|
|
1860
3526
|
const file = String(decoded).replace(/^b\//, "");
|
|
1861
3527
|
const lines2 = [];
|
|
1862
3528
|
let hunks = 0;
|
|
@@ -1864,22 +3530,22 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1864
3530
|
let previousOldEnd = 0;
|
|
1865
3531
|
while (input[i]?.startsWith("@@")) {
|
|
1866
3532
|
const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
|
|
1867
|
-
if (!match2)
|
|
3533
|
+
if (!match2) fail4("Invalid hunk header");
|
|
1868
3534
|
let oldRemaining = Number(match2[2] ?? 1);
|
|
1869
3535
|
let newRemaining = Number(match2[4] ?? 1);
|
|
1870
3536
|
let newLine = Number(match2[3]);
|
|
1871
3537
|
const oldStart = Number(match2[1]);
|
|
1872
3538
|
const oldCount = oldRemaining;
|
|
1873
|
-
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger))
|
|
1874
|
-
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0)
|
|
1875
|
-
if (newLine < previousEnd || oldStart < previousOldEnd)
|
|
3539
|
+
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail4("Hunk range is not a safe integer");
|
|
3540
|
+
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail4("Nonempty hunk cannot start at zero");
|
|
3541
|
+
if (newLine < previousEnd || oldStart < previousOldEnd) fail4("Overlapping or unordered hunks");
|
|
1876
3542
|
let previousPrefix = "";
|
|
1877
3543
|
const markNoNewline = () => {
|
|
1878
3544
|
if (previousPrefix === "+" || previousPrefix === " ") {
|
|
1879
3545
|
const last = lines2.at(-1);
|
|
1880
|
-
if (last === void 0 || last.noNewline)
|
|
3546
|
+
if (last === void 0 || last.noNewline) fail4("Unexpected no-newline marker");
|
|
1881
3547
|
lines2[lines2.length - 1] = { ...last, noNewline: true };
|
|
1882
|
-
} else if (previousPrefix !== "-")
|
|
3548
|
+
} else if (previousPrefix !== "-") fail4("Unexpected no-newline marker");
|
|
1883
3549
|
previousPrefix = "";
|
|
1884
3550
|
};
|
|
1885
3551
|
hunks++;
|
|
@@ -1889,15 +3555,15 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1889
3555
|
markNoNewline();
|
|
1890
3556
|
continue;
|
|
1891
3557
|
}
|
|
1892
|
-
if (body === void 0)
|
|
3558
|
+
if (body === void 0) fail4("Truncated hunk");
|
|
1893
3559
|
const prefix = body[0];
|
|
1894
3560
|
if (prefix === " " || prefix === "-") oldRemaining--;
|
|
1895
3561
|
if (prefix === " " || prefix === "+") {
|
|
1896
3562
|
newRemaining--;
|
|
1897
3563
|
lines2.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
|
|
1898
|
-
} else if (prefix !== "-")
|
|
3564
|
+
} else if (prefix !== "-") fail4("Invalid hunk line");
|
|
1899
3565
|
previousPrefix = prefix;
|
|
1900
|
-
if (oldRemaining < 0 || newRemaining < 0)
|
|
3566
|
+
if (oldRemaining < 0 || newRemaining < 0) fail4("Hunk count does not match its body");
|
|
1901
3567
|
}
|
|
1902
3568
|
if (input[i] === "\") {
|
|
1903
3569
|
markNoNewline();
|
|
@@ -1906,28 +3572,28 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1906
3572
|
previousEnd = newLine;
|
|
1907
3573
|
previousOldEnd = oldStart + oldCount;
|
|
1908
3574
|
}
|
|
1909
|
-
if (hunks === 0)
|
|
3575
|
+
if (hunks === 0) fail4("File has no hunks");
|
|
1910
3576
|
sawFile = true;
|
|
1911
3577
|
if (file !== "/dev/null") patches.push({ file, lines: lines2 });
|
|
1912
3578
|
}
|
|
1913
|
-
if (!sawFile)
|
|
3579
|
+
if (!sawFile) fail4("No unified diff found");
|
|
1914
3580
|
return patches;
|
|
1915
3581
|
},
|
|
1916
|
-
catch: (error3) =>
|
|
3582
|
+
catch: (error3) => Schema10.is(DiffParseError)(error3) ? error3 : new DiffParseError({ path, message: String(error3) })
|
|
1917
3583
|
});
|
|
1918
|
-
var selectDiffScope =
|
|
1919
|
-
const fs = yield*
|
|
3584
|
+
var selectDiffScope = Effect8.fn("selectDiffScope")(function* (options) {
|
|
3585
|
+
const fs = yield* FileSystem9.FileSystem;
|
|
1920
3586
|
const path = yield* Path7.Path;
|
|
1921
3587
|
const diffPath = path.resolve(options.root, options.diffPath);
|
|
1922
|
-
const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(
|
|
3588
|
+
const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(Effect8.mapError((error3) => new DiffParseError({ path: diffPath, message: String(error3) }))));
|
|
1923
3589
|
const patches = yield* parseDiff(text, diffPath);
|
|
1924
|
-
const gitRoot = yield*
|
|
3590
|
+
const gitRoot = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
1925
3591
|
const handle = yield* ChildProcess3.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
|
|
1926
|
-
const [output, code] = yield*
|
|
3592
|
+
const [output, code] = yield* Effect8.all([Stream4.mkString(Stream4.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
|
|
1927
3593
|
if (Number(code) !== 0 || !output.trim()) return options.root;
|
|
1928
3594
|
const physicalRoot = yield* fs.realPath(options.root);
|
|
1929
3595
|
return path.resolve(options.root, path.relative(physicalRoot, output.trim()));
|
|
1930
|
-
})).pipe(
|
|
3596
|
+
})).pipe(Effect8.catch(() => Effect8.succeed(options.root)));
|
|
1931
3597
|
const changed = /* @__PURE__ */ new Map();
|
|
1932
3598
|
for (const patch of patches) {
|
|
1933
3599
|
const repositoryPath = path.resolve(gitRoot, patch.file);
|
|
@@ -1939,7 +3605,7 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
|
1939
3605
|
return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
|
|
1940
3606
|
}
|
|
1941
3607
|
if (!(yield* fs.exists(candidate))) continue;
|
|
1942
|
-
const current = yield* fs.readFileString(candidate).pipe(
|
|
3608
|
+
const current = yield* fs.readFileString(candidate).pipe(Effect8.mapError((error3) => new DiffMismatch({ path: patch.file, message: String(error3) })));
|
|
1943
3609
|
const lines2 = current.split("\n");
|
|
1944
3610
|
const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
|
|
1945
3611
|
if (patch.lines.every((line) => {
|
|
@@ -1966,11 +3632,13 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
|
1966
3632
|
});
|
|
1967
3633
|
|
|
1968
3634
|
// packages/cli/src/ExitCode.ts
|
|
1969
|
-
var reportExitCode = (report) => report.results.some((
|
|
3635
|
+
var reportExitCode = (report) => report.results.some((result5) => result5.outcome === "missed") ? 2 : report.results.some((result5) => result5.outcome === "unreliable") ? 7 : report.results.some((result5) => result5.outcome === "untested") ? 2 : report.results.some((result5) => result5.outcome === "timeout") || report.failure?.startsWith("BaselineTimedOut:") ? 3 : 0;
|
|
1970
3636
|
var errorExitCode = (error3) => {
|
|
1971
3637
|
switch (error3._tag) {
|
|
1972
3638
|
case "BaselineFailed":
|
|
1973
3639
|
return 4;
|
|
3640
|
+
case "BaselineTimedOut":
|
|
3641
|
+
return 3;
|
|
1974
3642
|
case "DiffMismatch":
|
|
1975
3643
|
return 5;
|
|
1976
3644
|
case "DiffParseError":
|
|
@@ -1988,14 +3656,14 @@ var errorExitCode = (error3) => {
|
|
|
1988
3656
|
};
|
|
1989
3657
|
|
|
1990
3658
|
// packages/cli/src/Reporter.ts
|
|
1991
|
-
import * as
|
|
1992
|
-
import * as
|
|
1993
|
-
import * as
|
|
1994
|
-
import * as
|
|
3659
|
+
import * as Clock5 from "effect/Clock";
|
|
3660
|
+
import * as Console5 from "effect/Console";
|
|
3661
|
+
import * as Effect9 from "effect/Effect";
|
|
3662
|
+
import * as FileSystem11 from "effect/FileSystem";
|
|
1995
3663
|
import * as Layer4 from "effect/Layer";
|
|
1996
3664
|
import * as Path9 from "effect/Path";
|
|
1997
|
-
import * as
|
|
1998
|
-
import * as
|
|
3665
|
+
import * as Schema11 from "effect/Schema";
|
|
3666
|
+
import * as Semaphore2 from "effect/Semaphore";
|
|
1999
3667
|
|
|
2000
3668
|
// packages/cli/src/UnifiedDiff.ts
|
|
2001
3669
|
var shortestEdits = (before, after) => {
|
|
@@ -2013,7 +3681,7 @@ var shortestEdits = (before, after) => {
|
|
|
2013
3681
|
}
|
|
2014
3682
|
frontier.set(diagonal, x);
|
|
2015
3683
|
if (x < before.length || y < after.length) continue;
|
|
2016
|
-
const
|
|
3684
|
+
const result5 = [];
|
|
2017
3685
|
x = before.length;
|
|
2018
3686
|
y = after.length;
|
|
2019
3687
|
for (let depth = trace.length - 1; depth >= 0; depth--) {
|
|
@@ -2024,14 +3692,14 @@ var shortestEdits = (before, after) => {
|
|
|
2024
3692
|
const previousX = previous.get(previousK) ?? 0;
|
|
2025
3693
|
const previousY = previousX - previousK;
|
|
2026
3694
|
while (x > previousX && y > previousY) {
|
|
2027
|
-
|
|
3695
|
+
result5.push({ sign: " ", text: before[--x] });
|
|
2028
3696
|
y--;
|
|
2029
3697
|
}
|
|
2030
3698
|
if (depth === 0) break;
|
|
2031
|
-
if (x === previousX)
|
|
2032
|
-
else
|
|
3699
|
+
if (x === previousX) result5.push({ sign: "+", text: after[--y] });
|
|
3700
|
+
else result5.push({ sign: "-", text: before[--x] });
|
|
2033
3701
|
}
|
|
2034
|
-
return
|
|
3702
|
+
return result5.reverse();
|
|
2035
3703
|
}
|
|
2036
3704
|
}
|
|
2037
3705
|
return [];
|
|
@@ -2053,10 +3721,10 @@ var edits = (before, after) => {
|
|
|
2053
3721
|
};
|
|
2054
3722
|
var lines = (text) => {
|
|
2055
3723
|
if (!text) return [];
|
|
2056
|
-
const
|
|
2057
|
-
if (text.endsWith("\n"))
|
|
2058
|
-
else
|
|
2059
|
-
return
|
|
3724
|
+
const result5 = text.split("\n");
|
|
3725
|
+
if (text.endsWith("\n")) result5.pop();
|
|
3726
|
+
else result5[result5.length - 1] += "\n\";
|
|
3727
|
+
return result5;
|
|
2060
3728
|
};
|
|
2061
3729
|
var unifiedDiff = (original, modified, file) => {
|
|
2062
3730
|
if (original === modified) return "";
|
|
@@ -2087,11 +3755,17 @@ var unifiedDiff = (original, modified, file) => {
|
|
|
2087
3755
|
|
|
2088
3756
|
// packages/cli/src/Summary.ts
|
|
2089
3757
|
var outcomeNames = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
2090
|
-
var
|
|
3758
|
+
var backstopCosts = (report) => {
|
|
3759
|
+
const samples = report.results.flatMap((result5) => result5.backstopMs !== void 0 && Number.isFinite(result5.backstopMs) ? [result5.backstopMs] : []).sort((a, b) => a - b);
|
|
3760
|
+
if (!samples.length) return "";
|
|
3761
|
+
const percentile = (p) => samples[Math.max(0, Math.ceil(samples.length * p) - 1)].toFixed(1);
|
|
3762
|
+
return `; backstop per mutant p50 ${percentile(0.5)} ms, p90 ${percentile(0.9)} ms (${samples.length} measured)`;
|
|
3763
|
+
};
|
|
3764
|
+
var countsLine = (report, notMutated) => `${report.selected ?? report.results.length} selected, ${report.run ?? report.results.length} run, ${report.budgetSkipped ?? 0} budget-skipped; ` + outcomeNames.map((outcome) => `${report.results.filter((result5) => result5.outcome === outcome).length} ${outcome}`).join(", ") + `; ${notMutated} not mutated` + (report.hostRestarts === void 0 ? "" : `; ${report.hostRestarts} host restarts, ${report.poolResets ?? 0} pool resets`) + backstopCosts(report);
|
|
2091
3765
|
var cell = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\\", "\\\\").replaceAll("|", "\\|").replaceAll("`", "`").replace(/[\r\n]+/g, " ");
|
|
2092
3766
|
var markdownSummary = (options) => {
|
|
2093
3767
|
const { report, path } = options;
|
|
2094
|
-
const rows = report.results.filter((
|
|
3768
|
+
const rows = report.results.filter((result5) => result5.outcome === "missed" || result5.outcome === "timeout" || result5.outcome === "untested" || result5.outcome === "unreliable");
|
|
2095
3769
|
const exit = report.failure?.startsWith("BaselineFailed") ? 4 : reportExitCode(report);
|
|
2096
3770
|
return [
|
|
2097
3771
|
options.marker,
|
|
@@ -2114,27 +3788,28 @@ var shortType = (text) => {
|
|
|
2114
3788
|
return line.length > 80 ? line.slice(0, 79) + "\u2026" : line;
|
|
2115
3789
|
};
|
|
2116
3790
|
var outcomes = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
2117
|
-
var jsonReport =
|
|
2118
|
-
var logText = (
|
|
2119
|
-
..."output" in
|
|
2120
|
-
...
|
|
3791
|
+
var jsonReport = Schema11.encodeEffect(Schema11.fromJsonString(RunReport));
|
|
3792
|
+
var logText = (result5) => [
|
|
3793
|
+
..."output" in result5 && typeof result5.output === "string" ? [result5.output] : [],
|
|
3794
|
+
...result5.diagnostics
|
|
2121
3795
|
].join("\n");
|
|
2122
|
-
var makeReporter =
|
|
2123
|
-
const fs = yield*
|
|
3796
|
+
var makeReporter = Effect9.fn("makeReporter")(function* (options) {
|
|
3797
|
+
const fs = yield* FileSystem11.FileSystem;
|
|
2124
3798
|
const path = yield* Path9.Path;
|
|
2125
3799
|
const dir = path.resolve(options.root, options.outDir);
|
|
2126
|
-
const started = yield*
|
|
2127
|
-
const semaphore = yield*
|
|
3800
|
+
const started = yield* Clock5.currentTimeMillis;
|
|
3801
|
+
const semaphore = yield* Semaphore2.make(1);
|
|
2128
3802
|
const results = [];
|
|
2129
3803
|
let pendingError;
|
|
2130
3804
|
let summarized = false;
|
|
3805
|
+
const telemetryWarned = /* @__PURE__ */ new Set();
|
|
2131
3806
|
const writeError = (error3) => new ReportWriteError({ path: dir, message: String(error3) });
|
|
2132
3807
|
const ids = /* @__PURE__ */ new Set();
|
|
2133
3808
|
for (const mutant of options.mutants) {
|
|
2134
3809
|
if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
|
|
2135
3810
|
ids.add(mutant.id);
|
|
2136
3811
|
}
|
|
2137
|
-
yield*
|
|
3812
|
+
yield* Effect9.gen(function* () {
|
|
2138
3813
|
const relative2 = path.relative(dir, path.resolve(options.root));
|
|
2139
3814
|
if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
|
|
2140
3815
|
return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
|
|
@@ -2149,87 +3824,92 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
|
|
|
2149
3824
|
}
|
|
2150
3825
|
yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
|
|
2151
3826
|
yield* fs.makeDirectory(path.join(dir, "logs"), { recursive: true });
|
|
2152
|
-
}).pipe(
|
|
2153
|
-
const encodedMutants = yield*
|
|
2154
|
-
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(
|
|
3827
|
+
}).pipe(Effect9.mapError(writeError));
|
|
3828
|
+
const encodedMutants = yield* Schema11.encodeEffect(Schema11.fromJsonString(Schema11.Array(Mutant)))(options.mutants).pipe(Effect9.mapError(writeError));
|
|
3829
|
+
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect9.mapError(writeError));
|
|
2155
3830
|
yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
|
|
2156
|
-
`).join("")).pipe(
|
|
2157
|
-
yield*
|
|
3831
|
+
`).join("")).pipe(Effect9.mapError(writeError));
|
|
3832
|
+
yield* Effect9.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect9.mapError(writeError));
|
|
2158
3833
|
for (const mutant of options.mutants) {
|
|
2159
|
-
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(
|
|
2160
|
-
yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(original, original.slice(0, mutant.replacement.startOffset) + mutant.replacement.text + original.slice(mutant.replacement.endOffset), path.relative(options.root, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))).pipe(
|
|
3834
|
+
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect9.mapError(writeError));
|
|
3835
|
+
yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(original, original.slice(0, mutant.replacement.startOffset) + mutant.replacement.text + original.slice(mutant.replacement.endOffset), path.relative(options.root, path.resolve(options.root, mutant.file)).replaceAll("\\", "/"))).pipe(Effect9.mapError(writeError));
|
|
2161
3836
|
}
|
|
2162
|
-
const writeLists = (items) =>
|
|
2163
|
-
const lines2 = items.filter((
|
|
3837
|
+
const writeLists = (items) => Effect9.forEach(outcomes, (outcome) => {
|
|
3838
|
+
const lines2 = items.filter((result5) => result5.outcome === outcome).map((result5) => mutantLine(result5.mutant, options.root, path));
|
|
2164
3839
|
return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines2.length === 0 ? "" : lines2.join("\n") + "\n");
|
|
2165
3840
|
}, { discard: true });
|
|
2166
3841
|
const service = Reporter.of({
|
|
2167
|
-
progress: (
|
|
2168
|
-
results.push(
|
|
2169
|
-
if (!options.markdown?.stdout) yield*
|
|
2170
|
-
yield*
|
|
2171
|
-
if (!ids.has(
|
|
3842
|
+
progress: (result5) => semaphore.withPermit(Effect9.gen(function* () {
|
|
3843
|
+
results.push(result5);
|
|
3844
|
+
if (!options.markdown?.stdout) yield* Console5.log(`${result5.outcome} ${mutantLine(result5.mutant, options.root, path)} (${result5.durationMs}ms)`);
|
|
3845
|
+
yield* Effect9.gen(function* () {
|
|
3846
|
+
if (!ids.has(result5.mutant.id)) return yield* writeError("Progress result does not belong to this report");
|
|
2172
3847
|
yield* writeLists(results);
|
|
2173
|
-
yield* fs.writeFileString(path.join(dir, "logs", `${
|
|
2174
|
-
}).pipe(
|
|
3848
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result5.mutant.id}.log`), logText(result5));
|
|
3849
|
+
}).pipe(Effect9.catch((error3) => Effect9.gen(function* () {
|
|
2175
3850
|
if (pendingError === void 0) {
|
|
2176
3851
|
pendingError = writeError(error3);
|
|
2177
|
-
yield*
|
|
3852
|
+
yield* Console5.warn(`Report write failed: ${pendingError.message}`);
|
|
2178
3853
|
}
|
|
2179
3854
|
})));
|
|
2180
3855
|
})),
|
|
2181
|
-
write: (report) => semaphore.withPermit(
|
|
3856
|
+
write: (report) => semaphore.withPermit(Effect9.gen(function* () {
|
|
2182
3857
|
if (pendingError !== void 0) return yield* pendingError;
|
|
2183
3858
|
const notMutated = [...new Map([...options.notMutated ?? [], ...report.notMutated ?? []].map((item) => [JSON.stringify(item), item])).values()];
|
|
2184
3859
|
yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), notMutated.map((item) => `${path.relative(options.root, item.file)}:${item.span?.start.line ?? "?"}:${item.span?.start.column ?? "?"}: ${item.functionName}: ${item.reason}
|
|
2185
|
-
`).join("")).pipe(
|
|
3860
|
+
`).join("")).pipe(Effect9.mapError(writeError));
|
|
3861
|
+
const telemetry = sanitizeReportTelemetry(report);
|
|
2186
3862
|
const counted = {
|
|
2187
|
-
...report,
|
|
3863
|
+
...telemetry.report,
|
|
2188
3864
|
notMutated,
|
|
2189
3865
|
selected: options.selected ?? options.mutants.length,
|
|
2190
3866
|
run: report.results.length,
|
|
2191
3867
|
budgetSkipped: options.budgetSkipped ?? 0
|
|
2192
3868
|
};
|
|
2193
|
-
const encoded = yield* jsonReport(counted).pipe(
|
|
2194
|
-
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(
|
|
2195
|
-
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(
|
|
2196
|
-
yield* writeLists(report.results).pipe(
|
|
2197
|
-
for (const
|
|
2198
|
-
if (!ids.has(
|
|
2199
|
-
yield* fs.writeFileString(path.join(dir, "logs", `${
|
|
3869
|
+
const encoded = yield* jsonReport(counted).pipe(Effect9.mapError(writeError));
|
|
3870
|
+
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect9.mapError(writeError));
|
|
3871
|
+
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect9.mapError(writeError));
|
|
3872
|
+
yield* writeLists(report.results).pipe(Effect9.mapError(writeError));
|
|
3873
|
+
for (const result5 of report.results) {
|
|
3874
|
+
if (!ids.has(result5.mutant.id)) return yield* writeError("Final result does not belong to this report");
|
|
3875
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result5.mutant.id}.log`), logText(result5)).pipe(Effect9.mapError(writeError));
|
|
3876
|
+
}
|
|
3877
|
+
for (const warning of telemetry.warnings) if (!telemetryWarned.has(warning)) {
|
|
3878
|
+
telemetryWarned.add(warning);
|
|
3879
|
+
yield* Console5.warn(warning);
|
|
2200
3880
|
}
|
|
2201
3881
|
if (options.markdown !== void 0) {
|
|
2202
3882
|
const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: notMutated.length });
|
|
2203
3883
|
for (const file of new Set(options.markdown.files)) {
|
|
2204
|
-
yield* fs.writeFileString(file, markdown).pipe(
|
|
3884
|
+
yield* fs.writeFileString(file, markdown).pipe(Effect9.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) })));
|
|
2205
3885
|
}
|
|
2206
|
-
if (!summarized && options.markdown.stdout) yield*
|
|
3886
|
+
if (!summarized && options.markdown.stdout) yield* Console5.log(markdown);
|
|
2207
3887
|
}
|
|
2208
3888
|
if (summarized) return;
|
|
2209
3889
|
summarized = true;
|
|
2210
|
-
if (report.results.some((
|
|
2211
|
-
const elapsed = (yield*
|
|
2212
|
-
if (!options.markdown?.stdout) yield*
|
|
2213
|
-
if (options.markdown === void 0 && report.failure !== void 0) yield*
|
|
3890
|
+
if (report.results.some((result5) => result5.outcome === "unreliable")) yield* Console5.warn("Unreliable: the configured Vitest run cannot see all tests. See unreliable.txt and per-mutant diagnostics; these are not missed mutants.");
|
|
3891
|
+
const elapsed = (yield* Clock5.currentTimeMillis) - started;
|
|
3892
|
+
if (!options.markdown?.stdout) yield* Console5.log(countsLine(counted, notMutated.length) + `; ${(elapsed / 1e3).toFixed(2)}s`);
|
|
3893
|
+
if (options.markdown === void 0 && report.failure !== void 0) yield* Console5.warn(report.failure);
|
|
2214
3894
|
}))
|
|
2215
3895
|
});
|
|
2216
3896
|
return service;
|
|
2217
3897
|
});
|
|
2218
3898
|
|
|
2219
3899
|
// packages/cli/src/Git.ts
|
|
2220
|
-
import * as
|
|
2221
|
-
import * as
|
|
3900
|
+
import * as Effect10 from "effect/Effect";
|
|
3901
|
+
import * as FileSystem13 from "effect/FileSystem";
|
|
2222
3902
|
import * as Path11 from "effect/Path";
|
|
2223
|
-
import * as
|
|
3903
|
+
import * as Schema12 from "effect/Schema";
|
|
2224
3904
|
import * as Stream5 from "effect/Stream";
|
|
2225
3905
|
import * as ChildProcess4 from "effect/process/ChildProcess";
|
|
2226
|
-
var UsageError = class extends
|
|
3906
|
+
var UsageError = class extends Schema12.TaggedError()("UsageError", { message: Schema12.String }) {
|
|
2227
3907
|
};
|
|
2228
|
-
var git =
|
|
3908
|
+
var git = Effect10.fn("git")(function* (root, args) {
|
|
2229
3909
|
const command = `git ${args.join(" ")}`;
|
|
2230
|
-
return yield*
|
|
3910
|
+
return yield* Effect10.scoped(Effect10.gen(function* () {
|
|
2231
3911
|
const handle = yield* ChildProcess4.make("git", args, { cwd: root });
|
|
2232
|
-
const [stdout, stderr, code] = yield*
|
|
3912
|
+
const [stdout, stderr, code] = yield* Effect10.all([
|
|
2233
3913
|
Stream5.mkString(Stream5.decodeText(handle.stdout)),
|
|
2234
3914
|
Stream5.mkString(Stream5.decodeText(handle.stderr)),
|
|
2235
3915
|
handle.exitCode
|
|
@@ -2237,13 +3917,13 @@ var git = Effect8.fn("git")(function* (root, args) {
|
|
|
2237
3917
|
if (Number(code) !== 0) return yield* new UsageError({ message: `${command}:
|
|
2238
3918
|
${stderr}` });
|
|
2239
3919
|
return stdout;
|
|
2240
|
-
})).pipe(
|
|
3920
|
+
})).pipe(Effect10.mapError((error3) => error3._tag === "UsageError" ? error3 : new UsageError({ message: `${command}: ${String(error3)}` })));
|
|
2241
3921
|
});
|
|
2242
|
-
var repositoryRoot =
|
|
3922
|
+
var repositoryRoot = Effect10.fn("repositoryRoot")(function* (root) {
|
|
2243
3923
|
const path = yield* Path11.Path;
|
|
2244
|
-
const fs = yield*
|
|
3924
|
+
const fs = yield* FileSystem13.FileSystem;
|
|
2245
3925
|
const top = (yield* git(root, ["rev-parse", "--show-toplevel"])).trim();
|
|
2246
|
-
const physical = yield* fs.realPath(root).pipe(
|
|
3926
|
+
const physical = yield* fs.realPath(root).pipe(Effect10.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
2247
3927
|
return path.resolve(root, path.relative(physical, top));
|
|
2248
3928
|
});
|
|
2249
3929
|
|
|
@@ -2260,17 +3940,21 @@ var flags = {
|
|
|
2260
3940
|
include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
|
|
2261
3941
|
exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
|
|
2262
3942
|
exportedOnly: Flag.Boolean("exported-only").pipe(Flag.withDefault(false), Flag.withDescription("Only exported binding paths, returned curried functions and Layer service methods; exclude local helpers")),
|
|
3943
|
+
warm: Flag.Boolean("warm").pipe(Flag.withDefault(false), Flag.withDescription("Force a persistent Vitest instance instead of automatic selection")),
|
|
3944
|
+
cold: Flag.Boolean("cold").pipe(Flag.withDefault(false), Flag.withDescription("Start a fresh Vitest process for each test execution")),
|
|
2263
3945
|
jobs: Flag.Int("jobs").pipe(Flag.optional, Flag.withDescription("Concurrent scratch/test workers; default 1")),
|
|
2264
|
-
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds")),
|
|
3946
|
+
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds, including startup")),
|
|
3947
|
+
baselineTimeout: Flag.Finite("baseline-timeout").pipe(Flag.optional, Flag.withDescription("Overall baseline deadline in seconds, including selection and startup; default 1800 (30 minutes)")),
|
|
2265
3948
|
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional, Flag.withDescription("Baseline duration multiplier; default 5")),
|
|
2266
3949
|
minimumTimeout: Flag.Finite("minimum-test-timeout").pipe(Flag.optional, Flag.withDescription("Minimum test timeout in seconds")),
|
|
2267
3950
|
output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
|
|
2268
3951
|
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
|
|
2269
3952
|
};
|
|
2270
|
-
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) =>
|
|
2271
|
-
const fs = yield*
|
|
3953
|
+
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect11.gen(function* () {
|
|
3954
|
+
const fs = yield* FileSystem15.FileSystem;
|
|
2272
3955
|
const path = yield* Path13.Path;
|
|
2273
3956
|
const root = path.resolve(options.root);
|
|
3957
|
+
if (input.cold && input.warm) return yield* new UsageError({ message: "--warm and --cold are mutually exclusive" });
|
|
2274
3958
|
const range = Option.getOrUndefined(input.inDiffRange);
|
|
2275
3959
|
const inDiff = Option.getOrUndefined(input.inDiff);
|
|
2276
3960
|
const maxMutants = Option.getOrUndefined(input.maxMutants);
|
|
@@ -2282,15 +3966,15 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2282
3966
|
if (maxMutants !== void 0 && (!Number.isSafeInteger(maxMutants) || maxMutants < 0)) return yield* new UsageError({ message: "--max-mutants must be a nonnegative safe integer" });
|
|
2283
3967
|
if (!["text", "json", "github"].includes(input.format) || input.format === "json" && !input.list) return yield* new UsageError({ message: "--format expects text, github, or json with --list" });
|
|
2284
3968
|
if (/[\r\n]/.test(input.summaryMarker)) return yield* new UsageError({ message: "--summary-marker must be one line" });
|
|
2285
|
-
const gitRoot = range !== void 0 ? yield* repositoryRoot(root) : yield* repositoryRoot(root).pipe(
|
|
3969
|
+
const gitRoot = range !== void 0 ? yield* repositoryRoot(root) : yield* repositoryRoot(root).pipe(Effect11.catch(() => Effect11.succeed(root)));
|
|
2286
3970
|
const diffText = range === void 0 ? void 0 : yield* git(gitRoot, ["diff", "--no-ext-diff", "--no-color", range, "--"]);
|
|
2287
3971
|
const configPath = path.join(root, "mutants.config.json");
|
|
2288
3972
|
const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
|
|
2289
|
-
|
|
2290
|
-
|
|
3973
|
+
Effect11.flatMap(Schema13.decodeEffect(Schema13.fromJsonString(ConfigFile))),
|
|
3974
|
+
Effect11.mapError((error3) => new UsageError({ message: `Invalid mutants.config.json: ${String(error3)}` }))
|
|
2291
3975
|
) : {};
|
|
2292
3976
|
const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
|
|
2293
|
-
const config = yield*
|
|
3977
|
+
const config = yield* Schema13.decodeEffect(RunConfig)({
|
|
2294
3978
|
root,
|
|
2295
3979
|
tsconfig: input.tsconfig,
|
|
2296
3980
|
exportedOnly: input.exportedOnly,
|
|
@@ -2298,19 +3982,22 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2298
3982
|
exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
|
|
2299
3983
|
functionFilter: fileConfig.functionFilter ?? [],
|
|
2300
3984
|
...inDiff === void 0 ? {} : { inDiff },
|
|
3985
|
+
cold: input.cold,
|
|
3986
|
+
warm: input.warm,
|
|
2301
3987
|
jobs: Option.getOrElse(input.jobs, () => fileConfig.jobs ?? 1),
|
|
2302
3988
|
...Option.isSome(timeoutMs) ? { timeoutMs: timeoutMs.value } : {},
|
|
3989
|
+
baselineTimeoutMs: Option.match(input.baselineTimeout, { onNone: () => fileConfig.baselineTimeoutMs ?? DEFAULT_BASELINE_TIMEOUT_MS, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
2303
3990
|
timeoutMultiplier: Option.getOrElse(input.timeoutMultiplier, () => fileConfig.timeoutMultiplier ?? 5),
|
|
2304
3991
|
minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
2305
3992
|
neverTimeoutMs: 1e3,
|
|
2306
3993
|
outDir: input.output
|
|
2307
|
-
}).pipe(
|
|
2308
|
-
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
|
|
3994
|
+
}).pipe(Effect11.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
3995
|
+
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0 || config.baselineTimeoutMs !== void 0 && config.baselineTimeoutMs <= 0) {
|
|
2309
3996
|
return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
|
|
2310
3997
|
}
|
|
2311
3998
|
const source = yield* MutantSource;
|
|
2312
3999
|
const generated = yield* Stream6.runCollect(source.generate(config)).pipe(
|
|
2313
|
-
|
|
4000
|
+
Effect11.mapError((error3) => error3.reason === "selection" ? new UsageError({ message: error3.diagnostics.join("\n") }) : error3)
|
|
2314
4001
|
);
|
|
2315
4002
|
const skipped2 = yield* source.notMutated(config);
|
|
2316
4003
|
const selected = inDiff === void 0 && diffText === void 0 ? { mutants: generated, notMutated: skipped2 } : yield* selectDiffScope({ root, diffPath: inDiff ?? `git diff ${range}`, ...diffText === void 0 ? {} : { diffText }, mutants: generated, notMutated: skipped2 });
|
|
@@ -2322,7 +4009,7 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2322
4009
|
const counts = { selected: ordered.length, run: 0, budgetSkipped: ordered.length - mutants.length };
|
|
2323
4010
|
if (mutants.length === 0) {
|
|
2324
4011
|
const cause = ordered.length > 0 ? "budget" : range !== void 0 ? "range" : inDiff !== void 0 || diffText !== void 0 ? "diff" : config.functionFilter.length || config.exportedOnly ? "filter" : "file selection";
|
|
2325
|
-
yield*
|
|
4012
|
+
yield* Console6.error(`0 mutants selected (${counts.selected} before budget); cause: ${cause}. Baseline skipped.`);
|
|
2326
4013
|
}
|
|
2327
4014
|
const markdown = input.format === "github" || summaryMd !== void 0 ? {
|
|
2328
4015
|
gitRoot,
|
|
@@ -2343,33 +4030,33 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2343
4030
|
report: { schemaVersion: 2, tool: "mutant.cafe", root, baseline: { durationMs: 0, testCommand: [] }, timeoutMs: 0, results: [], ...counts }
|
|
2344
4031
|
});
|
|
2345
4032
|
for (const file of new Set(markdown.files)) yield* fs.writeFileString(file, text).pipe(
|
|
2346
|
-
|
|
4033
|
+
Effect11.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) }))
|
|
2347
4034
|
);
|
|
2348
4035
|
if (markdown.stdout) {
|
|
2349
|
-
yield*
|
|
4036
|
+
yield* Console6.log(text);
|
|
2350
4037
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2351
4038
|
return;
|
|
2352
4039
|
}
|
|
2353
4040
|
}
|
|
2354
4041
|
if (input.list && input.format === "json") {
|
|
2355
|
-
yield*
|
|
4042
|
+
yield* Console6.log(yield* Schema13.encodeEffect(Schema13.fromJsonString(MutantList))({ schemaVersion: 2, tool: "mutant.cafe", mutants, notMutated, counts }));
|
|
2356
4043
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2357
4044
|
return;
|
|
2358
4045
|
}
|
|
2359
4046
|
if (input.list) {
|
|
2360
|
-
for (const mutant of mutants) yield*
|
|
4047
|
+
for (const mutant of mutants) yield* Console6.log(mutantLine(mutant, config.root, path));
|
|
2361
4048
|
const perFile = /* @__PURE__ */ new Map();
|
|
2362
4049
|
for (const mutant of mutants) {
|
|
2363
4050
|
const file = path.relative(root, path.resolve(root, mutant.file));
|
|
2364
4051
|
perFile.set(file, (perFile.get(file) ?? 0) + 1);
|
|
2365
4052
|
}
|
|
2366
|
-
for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield*
|
|
2367
|
-
yield*
|
|
4053
|
+
for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield* Console6.log(`${file}: ${count} mutants`);
|
|
4054
|
+
yield* Console6.log(`${mutants.length} mutants total; ${notMutated.length} not mutated; ${counts.selected} selected, 0 run, ${counts.budgetSkipped} budget-skipped`);
|
|
2368
4055
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2369
4056
|
return;
|
|
2370
4057
|
}
|
|
2371
4058
|
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated, selected: counts.selected, budgetSkipped: counts.budgetSkipped, ...markdown === void 0 ? {} : { markdown } });
|
|
2372
|
-
const report = yield* (mutants.length === 0 ?
|
|
4059
|
+
const report = yield* (mutants.length === 0 ? Effect11.succeed({
|
|
2373
4060
|
schemaVersion: 2,
|
|
2374
4061
|
tool: "mutant.cafe",
|
|
2375
4062
|
root,
|
|
@@ -2377,8 +4064,8 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2377
4064
|
timeoutMs: 0,
|
|
2378
4065
|
results: []
|
|
2379
4066
|
}) : options.run(config, mutants)).pipe(
|
|
2380
|
-
|
|
2381
|
-
|
|
4067
|
+
Effect11.provideService(Reporter, reporter),
|
|
4068
|
+
Effect11.catchTag("BaselineFailed", (error3) => Effect11.gen(function* () {
|
|
2382
4069
|
const failed = {
|
|
2383
4070
|
schemaVersion: 2,
|
|
2384
4071
|
tool: "mutant.cafe",
|
|
@@ -2386,31 +4073,45 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2386
4073
|
baseline: { durationMs: 0, testCommand: error3.command },
|
|
2387
4074
|
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
2388
4075
|
results: [],
|
|
2389
|
-
failure: `BaselineFailed: ${error3.command
|
|
4076
|
+
failure: `BaselineFailed: ${formatTestCommand(error3.command)}
|
|
2390
4077
|
${error3.output.slice(-8e3)}`
|
|
2391
4078
|
};
|
|
2392
4079
|
yield* reporter.write(failed);
|
|
2393
4080
|
if (!input.advisory) return yield* error3;
|
|
2394
|
-
if (markdown === void 0) yield*
|
|
4081
|
+
if (markdown === void 0) yield* Console6.log("Advisory: baseline failed; would exit 4 without --advisory.");
|
|
2395
4082
|
return failed;
|
|
4083
|
+
})),
|
|
4084
|
+
Effect11.catchTag("BaselineTimedOut", (error3) => Effect11.gen(function* () {
|
|
4085
|
+
const timedOut = {
|
|
4086
|
+
schemaVersion: 2,
|
|
4087
|
+
tool: "mutant.cafe",
|
|
4088
|
+
root,
|
|
4089
|
+
baseline: { durationMs: 0, testCommand: error3.command },
|
|
4090
|
+
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
4091
|
+
results: [],
|
|
4092
|
+
failure: `BaselineTimedOut: ${error3.message}`
|
|
4093
|
+
};
|
|
4094
|
+
yield* reporter.write(timedOut);
|
|
4095
|
+
if (!input.advisory) return yield* error3;
|
|
4096
|
+
return timedOut;
|
|
2396
4097
|
}))
|
|
2397
4098
|
);
|
|
2398
|
-
if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield*
|
|
4099
|
+
if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield* Console6.log(`Advisory: would exit ${reportExitCode(report)} without --advisory.`);
|
|
2399
4100
|
yield* reporter.write(report);
|
|
2400
4101
|
if (options.onExit !== void 0) yield* options.onExit(input.advisory ? 0 : reportExitCode(report));
|
|
2401
4102
|
}));
|
|
2402
|
-
var runCli =
|
|
4103
|
+
var runCli = Effect11.fn("runCli")(function* (options) {
|
|
2403
4104
|
const code = yield* Ref.make(0);
|
|
2404
4105
|
const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
|
|
2405
|
-
yield* Command.runWith(command, { version: "0.1.
|
|
2406
|
-
|
|
2407
|
-
yield*
|
|
2408
|
-
${error3.diagnostics.join("\n")}` : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${error3.command
|
|
4106
|
+
yield* Command.runWith(command, { version: "0.1.6" })(options.args).pipe(
|
|
4107
|
+
Effect11.catch((error3) => Effect11.gen(function* () {
|
|
4108
|
+
yield* Console6.error(error3._tag === "ProgramLoadError" ? `${error3.tsconfig}:
|
|
4109
|
+
${error3.diagnostics.join("\n")}` : error3._tag === "BaselineTimedOut" ? error3.message : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${formatTestCommand(error3.command)}
|
|
2409
4110
|
${error3.output.slice(-8e3)}` : String(error3));
|
|
2410
4111
|
yield* Ref.set(code, errorExitCode(error3));
|
|
2411
4112
|
})),
|
|
2412
|
-
|
|
2413
|
-
yield*
|
|
4113
|
+
Effect11.catchDefect((defect) => Effect11.gen(function* () {
|
|
4114
|
+
yield* Console6.error(`Internal error: ${String(defect)}`);
|
|
2414
4115
|
yield* Ref.set(code, 70);
|
|
2415
4116
|
}))
|
|
2416
4117
|
);
|
|
@@ -2422,11 +4123,11 @@ var run = (config, mutants) => runMutants(config, Stream7.fromIterable(mutants))
|
|
|
2422
4123
|
var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
|
|
2423
4124
|
Layer5.provideMerge(NodeServices.layer)
|
|
2424
4125
|
);
|
|
2425
|
-
var main =
|
|
4126
|
+
var main = Effect12.gen(function* () {
|
|
2426
4127
|
const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
|
|
2427
|
-
yield*
|
|
4128
|
+
yield* Effect12.sync(() => {
|
|
2428
4129
|
process.exitCode = code;
|
|
2429
4130
|
});
|
|
2430
|
-
}).pipe(
|
|
4131
|
+
}).pipe(Effect12.provide(live));
|
|
2431
4132
|
NodeRuntime.runMain(main);
|
|
2432
4133
|
//# sourceMappingURL=bin.js.map
|