mutant-cafe 0.1.5 → 0.1.7
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 +25 -4
- package/dist/bin.js +2391 -436
- 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.Literals(["reporter", "vitest-version"])),
|
|
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,44 +216,117 @@ var TestRunner = class extends Context.Service()("mutant.cafe/TestRunner") {
|
|
|
172
216
|
var Reporter = class extends Context.Service()("mutant.cafe/Reporter") {
|
|
173
217
|
};
|
|
174
218
|
|
|
175
|
-
// packages/
|
|
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
|
+
|
|
268
|
+
// packages/core/src/Selection.ts
|
|
176
269
|
import * as Effect from "effect/Effect";
|
|
270
|
+
import * as Path from "effect/Path";
|
|
271
|
+
var excludeLinkedCandidates = Effect.fn("Selection.excludeLinkedCandidates")(function* (root, candidates, linkedRoots) {
|
|
272
|
+
const path = yield* Path.Path;
|
|
273
|
+
const mutants = [];
|
|
274
|
+
const skipped2 = [];
|
|
275
|
+
for (const mutant of candidates) {
|
|
276
|
+
const file = path.isAbsolute(mutant.file) ? path.relative(root, mutant.file) : mutant.file;
|
|
277
|
+
const linked = linkedRoots.some((link) => {
|
|
278
|
+
const relative2 = path.relative(link, file);
|
|
279
|
+
return relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2);
|
|
280
|
+
});
|
|
281
|
+
if (linked) skipped2.push({
|
|
282
|
+
file: path.resolve(root, file),
|
|
283
|
+
functionName: mutant.functionName,
|
|
284
|
+
span: mutant.span,
|
|
285
|
+
reason: "Source is in a linked ignored tree; original files are not mutation targets"
|
|
286
|
+
});
|
|
287
|
+
else mutants.push(mutant);
|
|
288
|
+
}
|
|
289
|
+
return { mutants, notMutated: [...new Map(skipped2.map((entry) => [JSON.stringify(entry), entry])).values()] };
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
// packages/engine/src/index.ts
|
|
293
|
+
import * as Effect2 from "effect/Effect";
|
|
177
294
|
import * as Layer from "effect/Layer";
|
|
178
295
|
import * as Stream from "effect/Stream";
|
|
179
296
|
import * as Schema4 from "effect/Schema";
|
|
180
297
|
|
|
181
298
|
// packages/engine/src/Generate.ts
|
|
182
299
|
import { createHash } from "node:crypto";
|
|
183
|
-
function* generateFunction(
|
|
184
|
-
const issue =
|
|
300
|
+
function* generateFunction(fn12) {
|
|
301
|
+
const issue = fn12.generationIssue?.();
|
|
185
302
|
if (issue) return issue;
|
|
186
|
-
const api =
|
|
303
|
+
const api = fn12.api;
|
|
187
304
|
const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
|
|
188
|
-
const pinned = `((): ${
|
|
189
|
-
const text =
|
|
190
|
-
return makeMutant(
|
|
305
|
+
const pinned = `((): ${fn12.returnType} => (${expression}))()`;
|
|
306
|
+
const text = fn12.block ? `{ return ${fn12.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
|
|
307
|
+
return makeMutant(fn12, genre, text, value.synthetic, description);
|
|
191
308
|
};
|
|
192
|
-
const shape =
|
|
309
|
+
const shape = fn12.shape;
|
|
193
310
|
const fits = (value) => new TextEncoder().encode(value.text).byteLength <= 2048;
|
|
194
311
|
const values = "values" in shape ? shape.values.filter(fits) : [];
|
|
195
312
|
switch (shape.kind) {
|
|
196
313
|
case "Effect": {
|
|
197
|
-
const
|
|
198
|
-
if (
|
|
314
|
+
const succeed7 = api("Effect", "succeed");
|
|
315
|
+
if (succeed7) {
|
|
199
316
|
for (const value of values) {
|
|
200
|
-
if (!
|
|
317
|
+
if (!fn12.equivalentValues.includes(value.text) && !(fn12.generator && value.text === fn12.literal)) yield candidate("EffectSucceed", `${succeed7}(${value.text})`, value);
|
|
201
318
|
}
|
|
202
319
|
}
|
|
203
|
-
const
|
|
320
|
+
const fail4 = api("Effect", "fail");
|
|
204
321
|
const catchTag3 = api("Effect", "catchTag");
|
|
205
322
|
for (const error3 of shape.errors) {
|
|
206
|
-
if (
|
|
323
|
+
if (fail4 && fits(error3)) yield candidate("EffectFail", `${fail4}(${error3.text})`, error3, `${fail4}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
|
|
207
324
|
const recoveries = values.length ? shape.enumerateRecoveries ? values : values.slice(0, 1) : [void 0];
|
|
208
|
-
const
|
|
209
|
-
const original =
|
|
325
|
+
const gen11 = api("Effect", "gen");
|
|
326
|
+
const original = fn12.generator ? gen11 && `((): ${fn12.returnType} => ${gen11}(function* () ${fn12.original}))()` : fn12.block ? `((): ${fn12.returnType} => ${fn12.original})()` : `((): ${fn12.returnType} => (${fn12.original}))()`;
|
|
210
327
|
for (const value of recoveries) {
|
|
211
328
|
const die3 = api("Effect", "die");
|
|
212
|
-
const recovery = value &&
|
|
329
|
+
const recovery = value && succeed7 ? `${succeed7}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
|
|
213
330
|
if (catchTag3 && recovery && original) {
|
|
214
331
|
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
332
|
}
|
|
@@ -230,52 +347,52 @@ function* generateFunction(fn9) {
|
|
|
230
347
|
}
|
|
231
348
|
case "Stream": {
|
|
232
349
|
const empty = api("Stream", "empty");
|
|
233
|
-
const
|
|
234
|
-
const
|
|
350
|
+
const make12 = api("Stream", "make");
|
|
351
|
+
const fail4 = api("Stream", "fail");
|
|
235
352
|
if (empty) yield candidate("StreamEmpty", empty);
|
|
236
|
-
if (
|
|
237
|
-
if (
|
|
238
|
-
for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${
|
|
353
|
+
if (make12) for (const value of values) yield candidate("StreamOne", `${make12}(${value.text})`, value);
|
|
354
|
+
if (fail4) {
|
|
355
|
+
for (const error3 of shape.errors) if (fits(error3)) yield candidate("StreamFail", `${fail4}(${error3.text})`, error3);
|
|
239
356
|
}
|
|
240
357
|
break;
|
|
241
358
|
}
|
|
242
359
|
case "Layer": {
|
|
243
360
|
const layer2 = api("Layer", "effectContext");
|
|
244
|
-
const
|
|
361
|
+
const fail4 = api("Effect", "fail");
|
|
245
362
|
const die2 = api("Effect", "die");
|
|
246
363
|
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}(${
|
|
364
|
+
if (layer2 && fail4) {
|
|
365
|
+
for (const error3 of shape.errors) if (fits(error3)) yield candidate("LayerFail", `${layer2}(${fail4}(${error3.text}))`, error3);
|
|
249
366
|
}
|
|
250
367
|
break;
|
|
251
368
|
}
|
|
252
369
|
case "Void":
|
|
253
|
-
yield makeMutant(
|
|
370
|
+
if (!fn12.equivalentValues.includes("{}")) yield makeMutant(fn12, "FnValue", "{}", false, "an empty body");
|
|
254
371
|
break;
|
|
255
372
|
default: {
|
|
256
373
|
const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
|
|
257
374
|
for (const value of values) {
|
|
258
|
-
if (value.text ===
|
|
375
|
+
if (value.text === fn12.literal || fn12.equivalentValues.includes(value.text)) continue;
|
|
259
376
|
yield candidate(genre, value.text, value);
|
|
260
377
|
}
|
|
261
378
|
}
|
|
262
379
|
}
|
|
263
380
|
}
|
|
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([
|
|
381
|
+
function makeMutant(fn12, genre, text, synthetic, description) {
|
|
382
|
+
const additions = fn12.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
|
|
383
|
+
const prefix = fn12.sourcePrefix ?? "";
|
|
384
|
+
const insertion = fn12.importInsertionOffset ?? 0;
|
|
385
|
+
const replacement = additions.length && fn12.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn12.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn12.startOffset, endOffset: fn12.endOffset, text };
|
|
386
|
+
const id = createHash("sha256").update(JSON.stringify([fn12.identityFile ?? fn12.file, fn12.name, fn12.identityOrdinal ?? 0, fn12.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
|
|
270
387
|
return {
|
|
271
388
|
id,
|
|
272
|
-
file:
|
|
273
|
-
functionName:
|
|
274
|
-
returnType:
|
|
275
|
-
displayReturnType:
|
|
389
|
+
file: fn12.file,
|
|
390
|
+
functionName: fn12.name,
|
|
391
|
+
returnType: fn12.returnType,
|
|
392
|
+
displayReturnType: fn12.displayReturnType,
|
|
276
393
|
genre,
|
|
277
|
-
description: `replace ${
|
|
278
|
-
span:
|
|
394
|
+
description: `replace ${fn12.name} -> ${fn12.returnType} with ${description}`,
|
|
395
|
+
span: fn12.span,
|
|
279
396
|
replacement,
|
|
280
397
|
synthetic
|
|
281
398
|
};
|
|
@@ -302,6 +419,8 @@ var ProgramSession = class {
|
|
|
302
419
|
if (config.error) throw new ProgramLoadError({ tsconfig: configPath, diagnostics: diagnosticsText([config.error]) });
|
|
303
420
|
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, resolve(configPath, ".."));
|
|
304
421
|
if (parsed.errors.length) throw new ProgramLoadError({ tsconfig: configPath, diagnostics: diagnosticsText(parsed.errors) });
|
|
422
|
+
parsed.options.incremental = false;
|
|
423
|
+
delete parsed.options.tsBuildInfoFile;
|
|
305
424
|
this.host = ts.createCompilerHost(parsed.options, true);
|
|
306
425
|
const read = this.host.getSourceFile;
|
|
307
426
|
this.host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => {
|
|
@@ -397,7 +516,7 @@ function makeTypeScriptOracle() {
|
|
|
397
516
|
const b = source.getLineAndCharacterOfPosition(end);
|
|
398
517
|
const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
|
|
399
518
|
const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
|
|
400
|
-
const originals = equivalentSuccessValues(body,
|
|
519
|
+
const originals = generator ? equivalentLiteralValues(body) : equivalentSuccessValues(body, checker);
|
|
401
520
|
if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
|
|
402
521
|
notMutated.push({ file, functionName: name, span: nodeSpan(node), reason: "generic: naked or context-only type-parameter return" });
|
|
403
522
|
} else found.push({
|
|
@@ -410,7 +529,7 @@ function makeTypeScriptOracle() {
|
|
|
410
529
|
returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
|
|
411
530
|
displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
|
|
412
531
|
skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
|
|
413
|
-
equivalentValues: shape.kind === "
|
|
532
|
+
equivalentValues: shape.kind === "Void" && ts.isBlock(body) && body.statements.length === 0 ? ["{}"] : "values" in shape ? shape.values.filter((value) => isEquivalentSuccess(value.text, shape.kind === "Effect" ? originals : equivalentLiteralValues(body))).map((value) => value.text) : [],
|
|
414
533
|
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
415
534
|
startOffset: start,
|
|
416
535
|
endOffset: end,
|
|
@@ -483,10 +602,10 @@ function makeTypeScriptOracle() {
|
|
|
483
602
|
const found = [];
|
|
484
603
|
visit(source);
|
|
485
604
|
const occurrences = /* @__PURE__ */ new Map();
|
|
486
|
-
for (const
|
|
487
|
-
const ordinal = occurrences.get(
|
|
488
|
-
occurrences.set(
|
|
489
|
-
functions.push({ ...
|
|
605
|
+
for (const fn12 of found) {
|
|
606
|
+
const ordinal = occurrences.get(fn12.name) ?? 0;
|
|
607
|
+
occurrences.set(fn12.name, ordinal + 1);
|
|
608
|
+
functions.push({ ...fn12, identityOrdinal: ordinal });
|
|
490
609
|
}
|
|
491
610
|
}
|
|
492
611
|
const unmatched = config.include.filter((glob) => !matched.has(glob));
|
|
@@ -670,9 +789,9 @@ function functionName(node, checker) {
|
|
|
670
789
|
}
|
|
671
790
|
function wrappedEffect(node, checker) {
|
|
672
791
|
if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
|
|
673
|
-
const
|
|
674
|
-
if (family(
|
|
675
|
-
const signature =
|
|
792
|
+
const result5 = checker.getTypeAtLocation(node.parent);
|
|
793
|
+
if (family(result5, checker)?.kind === "Effect") return result5;
|
|
794
|
+
const signature = result5.getCallSignatures()[0];
|
|
676
795
|
if (!signature) return void 0;
|
|
677
796
|
const returned = checker.getReturnTypeOfSignature(signature);
|
|
678
797
|
return family(returned, checker)?.kind === "Effect" ? returned : void 0;
|
|
@@ -711,11 +830,25 @@ function generatorContract(node, checker) {
|
|
|
711
830
|
};
|
|
712
831
|
}
|
|
713
832
|
function literalOfBody(body, checker) {
|
|
714
|
-
const
|
|
715
|
-
const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
|
|
833
|
+
const expression = returnedExpression(body);
|
|
716
834
|
if (!expression) return void 0;
|
|
717
|
-
|
|
718
|
-
|
|
835
|
+
if (ts.isStringLiteral(expression)) return JSON.stringify(expression.text);
|
|
836
|
+
if (ts.isNumericLiteral(expression)) return String(Number(expression.text));
|
|
837
|
+
if (expression.kind === ts.SyntaxKind.TrueKeyword) return "true";
|
|
838
|
+
if (expression.kind === ts.SyntaxKind.FalseKeyword) return "false";
|
|
839
|
+
if (expression.kind === ts.SyntaxKind.NullKeyword) return "null";
|
|
840
|
+
if (ts.isIdentifier(expression)) {
|
|
841
|
+
let symbol = checker.getSymbolAtLocation(expression);
|
|
842
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
|
|
843
|
+
const constant = symbol?.declarations?.some((declaration) => ts.isEnumMember(declaration) || ts.isVariableDeclaration(declaration) && ts.isVariableDeclarationList(declaration.parent) && !!(declaration.parent.flags & ts.NodeFlags.Const));
|
|
844
|
+
if (constant) {
|
|
845
|
+
const type = checker.getTypeAtLocation(expression);
|
|
846
|
+
if (type.isStringLiteral()) return JSON.stringify(type.value);
|
|
847
|
+
if (type.isNumberLiteral()) return String(type.value);
|
|
848
|
+
if (type.flags & ts.TypeFlags.BooleanLiteral) return checker.typeToString(type);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return void 0;
|
|
719
852
|
}
|
|
720
853
|
function generatorBody(node, checker) {
|
|
721
854
|
if (!node.body) return void 0;
|
|
@@ -919,10 +1052,13 @@ function returnTypeText(type, checker, node) {
|
|
|
919
1052
|
return print(type);
|
|
920
1053
|
}
|
|
921
1054
|
function literalData(node) {
|
|
922
|
-
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return literalData(node.expression);
|
|
1055
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isTypeAssertionExpression(node) || ts.isNonNullExpression(node)) return literalData(node.expression);
|
|
923
1056
|
if (ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return [node.kind, node.text];
|
|
924
1057
|
if (ts.isIdentifier(node) && node.text === "undefined") return ["undefined"];
|
|
925
|
-
if (ts.isPrefixUnaryExpression(node))
|
|
1058
|
+
if (ts.isPrefixUnaryExpression(node)) {
|
|
1059
|
+
const operand = literalData(node.operand);
|
|
1060
|
+
return operand === void 0 ? void 0 : [node.operator, operand];
|
|
1061
|
+
}
|
|
926
1062
|
if (ts.isArrayLiteralExpression(node)) {
|
|
927
1063
|
const items = node.elements.map(literalData);
|
|
928
1064
|
return items.every((item) => item !== void 0) ? ["array", items] : void 0;
|
|
@@ -940,17 +1076,54 @@ function literalData(node) {
|
|
|
940
1076
|
}
|
|
941
1077
|
return void 0;
|
|
942
1078
|
}
|
|
943
|
-
function
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1079
|
+
function unwrapped(node) {
|
|
1080
|
+
while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isTypeAssertionExpression(node) || ts.isNonNullExpression(node)) node = node.expression;
|
|
1081
|
+
return node;
|
|
1082
|
+
}
|
|
1083
|
+
function returnedExpression(body) {
|
|
1084
|
+
if (!ts.isBlock(body)) return unwrapped(body);
|
|
1085
|
+
const statement = body.statements.length === 1 ? body.statements[0] : void 0;
|
|
1086
|
+
return statement && ts.isReturnStatement(statement) && statement.expression ? unwrapped(statement.expression) : void 0;
|
|
1087
|
+
}
|
|
1088
|
+
function equivalentLiteralValues(body) {
|
|
1089
|
+
const expression = returnedExpression(body);
|
|
1090
|
+
const value = expression && literalData(expression);
|
|
1091
|
+
return value === void 0 ? [] : [JSON.stringify(value)];
|
|
1092
|
+
}
|
|
1093
|
+
function equivalentSuccessValues(body, checker) {
|
|
1094
|
+
const expression = returnedExpression(body);
|
|
1095
|
+
if (!expression) return [];
|
|
1096
|
+
const namespace = (node, seen = /* @__PURE__ */ new Set()) => {
|
|
1097
|
+
node = unwrapped(node);
|
|
1098
|
+
if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node)) return false;
|
|
1099
|
+
if (ts.isPropertyAccessExpression(node) && !namespace(node.expression, seen)) return false;
|
|
1100
|
+
let symbol = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(node) ? node.name : node);
|
|
1101
|
+
if (!symbol || seen.has(symbol)) return false;
|
|
1102
|
+
seen.add(symbol);
|
|
1103
|
+
if (symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
|
|
1104
|
+
return symbol.declarations?.some((declaration) => {
|
|
1105
|
+
if (ts.isSourceFile(declaration)) return /\/node_modules\/effect\/(?:.*\/)?(?:Effect|index)\.(?:d\.)?ts$/.test(declaration.fileName);
|
|
1106
|
+
return ts.isVariableDeclaration(declaration) && !!declaration.initializer && ts.isVariableDeclarationList(declaration.parent) && !!(declaration.parent.flags & ts.NodeFlags.Const) && namespace(declaration.initializer, seen);
|
|
1107
|
+
}) ?? false;
|
|
1108
|
+
};
|
|
1109
|
+
const member = (node, seen = /* @__PURE__ */ new Set()) => {
|
|
1110
|
+
node = unwrapped(node);
|
|
1111
|
+
if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node)) return void 0;
|
|
1112
|
+
if (ts.isPropertyAccessExpression(node) && !namespace(node.expression)) return void 0;
|
|
1113
|
+
let symbol = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(node) ? node.name : node);
|
|
1114
|
+
if (!symbol || seen.has(symbol)) return void 0;
|
|
1115
|
+
seen.add(symbol);
|
|
1116
|
+
if (symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
|
|
1117
|
+
for (const declaration of symbol.declarations ?? []) {
|
|
1118
|
+
if (/\/node_modules\/effect\/(?:.*\/)?Effect\.(?:d\.)?ts$/.test(declaration.getSourceFile().fileName)) return symbol.name === "void_" ? "void" : symbol.name;
|
|
1119
|
+
if (ts.isVariableDeclaration(declaration) && declaration.initializer && ts.isVariableDeclarationList(declaration.parent) && declaration.parent.flags & ts.NodeFlags.Const) return member(declaration.initializer, seen);
|
|
949
1120
|
}
|
|
950
|
-
|
|
1121
|
+
return void 0;
|
|
951
1122
|
};
|
|
952
|
-
|
|
953
|
-
return
|
|
1123
|
+
if (member(expression) === "void") return [JSON.stringify(["undefined"])];
|
|
1124
|
+
if (!ts.isCallExpression(expression) || expression.arguments.length !== 1 || member(expression.expression) !== "succeed") return [];
|
|
1125
|
+
const value = literalData(expression.arguments[0]);
|
|
1126
|
+
return value === void 0 ? [] : [JSON.stringify(value)];
|
|
954
1127
|
}
|
|
955
1128
|
function isEquivalentSuccess(text, values) {
|
|
956
1129
|
const source = ts.createSourceFile("literal.ts", `(${text})`, ts.ScriptTarget.Latest, true);
|
|
@@ -981,11 +1154,11 @@ function smallFinite(type) {
|
|
|
981
1154
|
const members = type.isUnion() ? type.types : [type];
|
|
982
1155
|
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
1156
|
}
|
|
984
|
-
function boundCandidates(candidates,
|
|
1157
|
+
function boundCandidates(candidates, types3, node) {
|
|
985
1158
|
const unique = [...new Map(candidates.map((value) => [valueKey(value.text), value])).values()];
|
|
986
|
-
const members =
|
|
987
|
-
const
|
|
988
|
-
if (
|
|
1159
|
+
const members = types3.flatMap((type) => type.isUnion() ? type.types : [type]);
|
|
1160
|
+
const finite2 = members.length <= 8 && members.every((member) => member.isLiteral() || !!(member.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
|
|
1161
|
+
if (finite2 || unique.length <= 6) return { values: unique, omitted: 0 };
|
|
989
1162
|
const absence = unique.find((value) => value.text === "undefined");
|
|
990
1163
|
const defined = unique.filter((value) => value !== absence);
|
|
991
1164
|
const preferred = ["null", '""', "0", "false", "[]", "({ })"].flatMap((text) => {
|
|
@@ -1014,14 +1187,14 @@ function objectDiscriminants(node) {
|
|
|
1014
1187
|
}
|
|
1015
1188
|
function returnedDiscriminants(node) {
|
|
1016
1189
|
if (!isFunction(node) || !node.body) return /* @__PURE__ */ new Set();
|
|
1017
|
-
const
|
|
1190
|
+
const result5 = new Set(objectDiscriminants(node.body));
|
|
1018
1191
|
const visit = (child) => {
|
|
1019
1192
|
if (isFunction(child)) return;
|
|
1020
|
-
if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression))
|
|
1193
|
+
if (ts.isReturnStatement(child) && child.expression) for (const key of objectDiscriminants(child.expression)) result5.add(key);
|
|
1021
1194
|
ts.forEachChild(child, visit);
|
|
1022
1195
|
};
|
|
1023
1196
|
visit(node.body);
|
|
1024
|
-
return
|
|
1197
|
+
return result5;
|
|
1025
1198
|
}
|
|
1026
1199
|
function shapeNotices(shape, type, checker, node) {
|
|
1027
1200
|
const notices = [...shape.synthesisIssues ?? []];
|
|
@@ -1140,18 +1313,18 @@ function synthesizeValues(type, checker, location, ancestors, depth, issues) {
|
|
|
1140
1313
|
// packages/engine/src/index.ts
|
|
1141
1314
|
var MutantSourceLive = Layer.effect(
|
|
1142
1315
|
MutantSource,
|
|
1143
|
-
|
|
1316
|
+
Effect2.sync(() => makeMutantSource(makeTypeScriptOracle()))
|
|
1144
1317
|
);
|
|
1145
1318
|
function makeMutantSource(oracle) {
|
|
1146
|
-
const discover = (config) =>
|
|
1319
|
+
const discover = (config) => Effect2.try({
|
|
1147
1320
|
try: () => {
|
|
1148
1321
|
const discovered = oracle.discover(config);
|
|
1149
1322
|
const notMutated = [...discovered.notMutated];
|
|
1150
1323
|
const mutants = [];
|
|
1151
1324
|
const failed = /* @__PURE__ */ new Set();
|
|
1152
|
-
const generatedFunctions = discovered.functions.map((
|
|
1325
|
+
const generatedFunctions = discovered.functions.map((fn12) => {
|
|
1153
1326
|
try {
|
|
1154
|
-
const iterator = generateFunction(
|
|
1327
|
+
const iterator = generateFunction(fn12);
|
|
1155
1328
|
const generated = [];
|
|
1156
1329
|
let step = iterator.next();
|
|
1157
1330
|
while (!step.done) {
|
|
@@ -1159,32 +1332,32 @@ function makeMutantSource(oracle) {
|
|
|
1159
1332
|
step = iterator.next();
|
|
1160
1333
|
}
|
|
1161
1334
|
if (step.value) {
|
|
1162
|
-
failed.add(
|
|
1163
|
-
notMutated.push({ file:
|
|
1164
|
-
return { fn:
|
|
1335
|
+
failed.add(fn12);
|
|
1336
|
+
notMutated.push({ file: fn12.file, functionName: fn12.name, span: fn12.span, reason: step.value });
|
|
1337
|
+
return { fn: fn12, generated: [] };
|
|
1165
1338
|
}
|
|
1166
|
-
return { fn:
|
|
1339
|
+
return { fn: fn12, generated };
|
|
1167
1340
|
} catch (error3) {
|
|
1168
|
-
failed.add(
|
|
1341
|
+
failed.add(fn12);
|
|
1169
1342
|
notMutated.push({
|
|
1170
|
-
file:
|
|
1171
|
-
functionName:
|
|
1172
|
-
span:
|
|
1343
|
+
file: fn12.file,
|
|
1344
|
+
functionName: fn12.name,
|
|
1345
|
+
span: fn12.span,
|
|
1173
1346
|
reason: `analysis failed: ${error3 instanceof Error ? error3.message : String(error3)}`
|
|
1174
1347
|
});
|
|
1175
|
-
return { fn:
|
|
1348
|
+
return { fn: fn12, generated: [] };
|
|
1176
1349
|
}
|
|
1177
1350
|
});
|
|
1178
|
-
for (const { fn:
|
|
1179
|
-
if (failed.has(
|
|
1351
|
+
for (const { fn: fn12, generated } of generatedFunctions) {
|
|
1352
|
+
if (failed.has(fn12)) continue;
|
|
1180
1353
|
{
|
|
1181
|
-
const reasons = [...
|
|
1182
|
-
if (!generated.length && !reasons.length) reasons.push(
|
|
1183
|
-
const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file ===
|
|
1354
|
+
const reasons = [...fn12.notices ?? []];
|
|
1355
|
+
if (!generated.length && !reasons.length) reasons.push(fn12.skipReason ?? `return not synthesizable (type ${fn12.displayReturnType})`);
|
|
1356
|
+
const innerMutated = !generated.length && generatedFunctions.some(({ fn: inner, generated: generated2 }) => inner.file === fn12.file && inner.startOffset > fn12.startOffset && inner.endOffset < fn12.endOffset && generated2.length > 0);
|
|
1184
1357
|
if (innerMutated && !generated.length) {
|
|
1185
1358
|
for (let i = 0; i < reasons.length; i++) if (reasons[i].startsWith("return not synthesizable")) reasons[i] += "; inner functions mutated";
|
|
1186
1359
|
}
|
|
1187
|
-
if (reasons.length) notMutated.push({ file:
|
|
1360
|
+
if (reasons.length) notMutated.push({ file: fn12.file, functionName: fn12.name, span: fn12.span, reason: [...new Set(reasons)].join("; ") });
|
|
1188
1361
|
}
|
|
1189
1362
|
mutants.push(...generated);
|
|
1190
1363
|
}
|
|
@@ -1196,9 +1369,9 @@ function makeMutantSource(oracle) {
|
|
|
1196
1369
|
}
|
|
1197
1370
|
});
|
|
1198
1371
|
return {
|
|
1199
|
-
notMutated: (config) => discover(config).pipe(
|
|
1200
|
-
generate: (config) => Stream.unwrap(discover(config).pipe(
|
|
1201
|
-
checkViable: (mutant) =>
|
|
1372
|
+
notMutated: (config) => discover(config).pipe(Effect2.map((result5) => result5.notMutated)),
|
|
1373
|
+
generate: (config) => Stream.unwrap(discover(config).pipe(Effect2.map((result5) => Stream.fromIterable(result5.mutants)))),
|
|
1374
|
+
checkViable: (mutant) => Effect2.sync(() => {
|
|
1202
1375
|
try {
|
|
1203
1376
|
return oracle.checkViable(mutant);
|
|
1204
1377
|
} catch (error3) {
|
|
@@ -1214,40 +1387,256 @@ function makeMutantSource(oracle) {
|
|
|
1214
1387
|
}
|
|
1215
1388
|
|
|
1216
1389
|
// packages/runner/src/Scratch.ts
|
|
1217
|
-
import * as
|
|
1390
|
+
import * as Effect3 from "effect/Effect";
|
|
1391
|
+
import * as Console from "effect/Console";
|
|
1218
1392
|
import * as FileSystem from "effect/FileSystem";
|
|
1219
1393
|
import * as Layer2 from "effect/Layer";
|
|
1220
|
-
import * as
|
|
1221
|
-
|
|
1394
|
+
import * as Path3 from "effect/Path";
|
|
1395
|
+
import * as ChildProcess from "effect/process/ChildProcess";
|
|
1396
|
+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
1397
|
+
import * as Stream2 from "effect/Stream";
|
|
1398
|
+
import * as Schema5 from "effect/Schema";
|
|
1399
|
+
|
|
1400
|
+
// packages/runner/src/Poison.ts
|
|
1401
|
+
function prologueEnd(source) {
|
|
1402
|
+
let position = source.charCodeAt(0) === 65279 ? 1 : 0;
|
|
1403
|
+
if (source.startsWith("#!", position)) {
|
|
1404
|
+
const newline = source.indexOf("\n", position);
|
|
1405
|
+
position = newline < 0 ? source.length : newline + 1;
|
|
1406
|
+
}
|
|
1407
|
+
const trivia = (from) => {
|
|
1408
|
+
let at = from;
|
|
1409
|
+
while (at < source.length) {
|
|
1410
|
+
if (/\s/.test(source[at])) {
|
|
1411
|
+
at++;
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
if (source.startsWith("//", at)) {
|
|
1415
|
+
const end = source.indexOf("\n", at);
|
|
1416
|
+
at = end < 0 ? source.length : end + 1;
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
if (source.startsWith("/*", at)) {
|
|
1420
|
+
const end = source.indexOf("*/", at + 2);
|
|
1421
|
+
at = end < 0 ? source.length : end + 2;
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
break;
|
|
1425
|
+
}
|
|
1426
|
+
return at;
|
|
1427
|
+
};
|
|
1428
|
+
while (position < source.length) {
|
|
1429
|
+
const start = trivia(position);
|
|
1430
|
+
const quote = source[start];
|
|
1431
|
+
if (quote !== '"' && quote !== "'") break;
|
|
1432
|
+
let end = start + 1;
|
|
1433
|
+
while (end < source.length && source[end] !== quote) end += source[end] === "\\" ? 2 : 1;
|
|
1434
|
+
if (end >= source.length) break;
|
|
1435
|
+
end++;
|
|
1436
|
+
const next = trivia(end);
|
|
1437
|
+
if (source[next] === ";") {
|
|
1438
|
+
position = next + 1;
|
|
1439
|
+
continue;
|
|
1440
|
+
}
|
|
1441
|
+
const continuation = /^(?:[([.`+*/%<>=!?:&,|^~\-]|in\b|instanceof\b)/.test(source.slice(next));
|
|
1442
|
+
if (next === source.length || !continuation && /[\r\n]/.test(source.slice(end, next))) {
|
|
1443
|
+
position = next;
|
|
1444
|
+
continue;
|
|
1445
|
+
}
|
|
1446
|
+
break;
|
|
1447
|
+
}
|
|
1448
|
+
return position;
|
|
1449
|
+
}
|
|
1450
|
+
function poisonInsertion(source, signal, token) {
|
|
1451
|
+
return { offset: prologueEnd(source), text: `
|
|
1452
|
+
try { globalThis.process.getBuiltinModule("node:fs").writeFileSync(${JSON.stringify(signal)}, ${JSON.stringify(token)}); }
|
|
1453
|
+
catch { console.error(${JSON.stringify(token)}); }
|
|
1454
|
+
try { globalThis[globalThis.Symbol.for(${JSON.stringify(token)})] = true; } catch {}
|
|
1455
|
+
throw new Error(${JSON.stringify(token)});
|
|
1456
|
+
` };
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
// packages/runner/src/Scratch.ts
|
|
1460
|
+
var ScratchLive = Layer2.effect(Scratch, Effect3.gen(function* () {
|
|
1222
1461
|
const fs = yield* FileSystem.FileSystem;
|
|
1223
|
-
const path = yield*
|
|
1462
|
+
const path = yield* Path3.Path;
|
|
1463
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
1224
1464
|
const failure = (operation, location, error3) => new ScratchError({ operation, path: location, message: error3.message });
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1465
|
+
const skipVanished = (from, to) => (effect5) => effect5.pipe(Effect3.catch((error3) => {
|
|
1466
|
+
if (error3._tag !== "PlatformError" || error3.reason._tag !== "NotFound") return Effect3.fail(error3);
|
|
1467
|
+
return Effect3.gen(function* () {
|
|
1468
|
+
const entry = yield* fs.lstat(from).pipe(Effect3.result);
|
|
1469
|
+
if (entry._tag === "Success") {
|
|
1470
|
+
if (entry.success.type !== "SymbolicLink") return yield* Effect3.fail(error3);
|
|
1471
|
+
const target = yield* fs.stat(from).pipe(Effect3.result);
|
|
1472
|
+
if (target._tag === "Success") return yield* Effect3.fail(error3);
|
|
1473
|
+
if (target.failure.reason._tag !== "NotFound") return yield* Effect3.fail(target.failure);
|
|
1474
|
+
yield* Console.warn(`Warning: scratch copy skipped a dangling symlink: ${from}`);
|
|
1475
|
+
} else if (entry.failure.reason._tag !== "NotFound") return yield* Effect3.fail(entry.failure);
|
|
1476
|
+
yield* fs.remove(to, { recursive: true, force: true });
|
|
1477
|
+
yield* Effect3.logDebug("Scratch copy skipped a vanished source", { source: from });
|
|
1478
|
+
});
|
|
1479
|
+
}));
|
|
1480
|
+
const discover = Effect3.fn("Scratch.discover")(function* (root) {
|
|
1481
|
+
let source = path.resolve(root);
|
|
1482
|
+
let copyRoot = source;
|
|
1483
|
+
let ancestor = source;
|
|
1484
|
+
while (true) {
|
|
1485
|
+
if ((yield* fs.exists(path.join(ancestor, "pnpm-workspace.yaml"))) || (yield* fs.exists(path.join(ancestor, ".git")))) {
|
|
1486
|
+
copyRoot = ancestor;
|
|
1487
|
+
break;
|
|
1488
|
+
}
|
|
1489
|
+
const parent = path.dirname(ancestor);
|
|
1490
|
+
if (parent === ancestor) break;
|
|
1491
|
+
ancestor = parent;
|
|
1492
|
+
}
|
|
1493
|
+
const git2 = (args, cwd = source) => Effect3.scoped(Effect3.gen(function* () {
|
|
1494
|
+
const env = { ...process.env };
|
|
1495
|
+
for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]) delete env[key];
|
|
1496
|
+
const child = yield* spawner.spawn(ChildProcess.make("git", ["-C", cwd, ...args], { stdin: "ignore", env, extendEnv: false }));
|
|
1497
|
+
const [code, output] = yield* Effect3.all([child.exitCode, child.stdout.pipe(Stream2.decodeText(), Stream2.mkString), child.stderr.pipe(Stream2.runDrain)], { concurrency: "unbounded" });
|
|
1498
|
+
return { code, output };
|
|
1499
|
+
}));
|
|
1500
|
+
let gitAncestor = source;
|
|
1501
|
+
let inRepository = false;
|
|
1502
|
+
while (true) {
|
|
1503
|
+
if (yield* fs.exists(path.join(gitAncestor, ".git"))) {
|
|
1504
|
+
inRepository = true;
|
|
1505
|
+
break;
|
|
1506
|
+
}
|
|
1507
|
+
const parent = path.dirname(gitAncestor);
|
|
1508
|
+
if (parent === gitAncestor) break;
|
|
1509
|
+
gitAncestor = parent;
|
|
1510
|
+
}
|
|
1511
|
+
let selected;
|
|
1512
|
+
let directories;
|
|
1513
|
+
const linked = /* @__PURE__ */ new Set();
|
|
1514
|
+
const unreadable = /* @__PURE__ */ new Set();
|
|
1515
|
+
const ignoredRoots = /* @__PURE__ */ new Set();
|
|
1516
|
+
const pruneUnreadable = (location) => Effect3.gen(function* () {
|
|
1517
|
+
unreadable.add(location);
|
|
1518
|
+
yield* Console.warn(`Warning: scratch copy skipped an unreadable ignored tree: ${location}`);
|
|
1519
|
+
});
|
|
1520
|
+
const originalSource = source;
|
|
1521
|
+
const originalCopyRoot = copyRoot;
|
|
1522
|
+
if (inRepository) yield* Effect3.gen(function* () {
|
|
1523
|
+
const repository = yield* git2(["rev-parse", "--show-toplevel"]);
|
|
1524
|
+
if (repository.code !== 0) return yield* new ScratchError({ operation: "git rev-parse", path: source, message: `Git exited ${repository.code}` });
|
|
1525
|
+
source = yield* fs.realPath(source);
|
|
1526
|
+
copyRoot = path.resolve(repository.output.trim());
|
|
1527
|
+
const files = yield* git2(["ls-files", "--cached", "--others", "--exclude-standard", "--full-name", "-z"], copyRoot).pipe(Effect3.mapError((error3) => failure("git", source, error3)));
|
|
1528
|
+
if (files.code !== 0) return yield* Effect3.fail(new ScratchError({ operation: "git ls-files", path: source, message: `Git exited ${files.code}` }));
|
|
1529
|
+
selected = new Set(files.output.split("\0").filter(Boolean).map((file) => path.resolve(copyRoot, file)));
|
|
1530
|
+
const ignored = yield* git2(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], copyRoot);
|
|
1531
|
+
if (ignored.code !== 0) return yield* new ScratchError({ operation: "git ls-files", path: source, message: `Git exited ${ignored.code}` });
|
|
1532
|
+
const independent = (dir) => Effect3.gen(function* () {
|
|
1533
|
+
if ((yield* fs.exists(path.join(dir, ".git"))) || (yield* fs.exists(path.join(dir, "node_modules")))) return true;
|
|
1534
|
+
for (const name of yield* fs.readDirectory(dir)) {
|
|
1535
|
+
const child = path.join(dir, name);
|
|
1536
|
+
const info = yield* fs.lstat(child).pipe(Effect3.result);
|
|
1537
|
+
if (info._tag === "Failure") {
|
|
1538
|
+
if (info.failure.reason._tag === "PermissionDenied") {
|
|
1539
|
+
yield* pruneUnreadable(child);
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
return yield* info.failure;
|
|
1543
|
+
}
|
|
1544
|
+
if (info.success.type === "Directory" && (yield* independent(child))) return true;
|
|
1545
|
+
}
|
|
1546
|
+
return false;
|
|
1547
|
+
}).pipe(Effect3.catch((error3) => error3.reason._tag === "PermissionDenied" ? pruneUnreadable(dir).pipe(Effect3.as(false)) : Effect3.fail(error3)));
|
|
1548
|
+
for (const file of ignored.output.split("\0").filter(Boolean)) {
|
|
1549
|
+
const target = path.resolve(copyRoot, file);
|
|
1550
|
+
if (path.relative(copyRoot, target).split(path.sep).some((part) => ["node_modules", ".git", "mutants.out", ".agent_sources", ".agent-sources", ".brain", ".pi", ".rift"].includes(part))) continue;
|
|
1551
|
+
ignoredRoots.add(target);
|
|
1552
|
+
const info = yield* fs.lstat(target).pipe(Effect3.result);
|
|
1553
|
+
if (info._tag === "Failure") {
|
|
1554
|
+
if (info.failure.reason._tag === "NotFound") continue;
|
|
1555
|
+
if (info.failure.reason._tag === "PermissionDenied") {
|
|
1556
|
+
yield* pruneUnreadable(target);
|
|
1557
|
+
continue;
|
|
1558
|
+
}
|
|
1559
|
+
return yield* info.failure;
|
|
1560
|
+
}
|
|
1561
|
+
if (info.success.type !== "Directory") {
|
|
1562
|
+
selected.add(target);
|
|
1563
|
+
continue;
|
|
1564
|
+
}
|
|
1565
|
+
if (yield* independent(target)) linked.add(target);
|
|
1566
|
+
else selected.add(target);
|
|
1567
|
+
}
|
|
1568
|
+
const PackageEntries = Schema5.fromJsonString(Schema5.Struct({
|
|
1569
|
+
exports: Schema5.optional(Schema5.Unknown),
|
|
1570
|
+
imports: Schema5.optional(Schema5.Unknown),
|
|
1571
|
+
main: Schema5.optional(Schema5.String),
|
|
1572
|
+
module: Schema5.optional(Schema5.String),
|
|
1573
|
+
types: Schema5.optional(Schema5.String)
|
|
1574
|
+
}));
|
|
1575
|
+
const targets = (entry) => typeof entry === "string" ? [entry] : Array.isArray(entry) ? entry.flatMap(targets) : entry !== null && typeof entry === "object" ? Object.values(entry).flatMap(targets) : [];
|
|
1576
|
+
for (const file of [...selected]) {
|
|
1577
|
+
if (path.basename(file) !== "package.json" || !(yield* fs.exists(file))) continue;
|
|
1578
|
+
const decoded = yield* Schema5.decodeEffect(PackageEntries)(yield* fs.readFileString(file)).pipe(Effect3.result);
|
|
1579
|
+
if (decoded._tag === "Failure") {
|
|
1580
|
+
yield* Console.warn(`Warning: cannot inspect package entry points for scratch copying: ${file}`);
|
|
1581
|
+
continue;
|
|
1582
|
+
}
|
|
1583
|
+
const pkg = decoded.success;
|
|
1584
|
+
const root2 = path.dirname(file);
|
|
1585
|
+
const entries = [...targets(pkg.exports), ...targets(pkg.imports)].filter((entry) => entry.startsWith("./"));
|
|
1586
|
+
entries.push(...[pkg.main, pkg.module, pkg.types].filter((entry) => entry !== void 0));
|
|
1587
|
+
for (const entry of entries) {
|
|
1588
|
+
const relative2 = path.relative(root2, path.resolve(root2, entry));
|
|
1589
|
+
if (!relative2 || relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) continue;
|
|
1590
|
+
const first = relative2.split(path.sep)[0];
|
|
1591
|
+
if (!["node_modules", ".git"].includes(first)) selected.add(path.join(root2, first));
|
|
1234
1592
|
}
|
|
1235
|
-
const parent = path.dirname(ancestor);
|
|
1236
|
-
if (parent === ancestor) break;
|
|
1237
|
-
ancestor = parent;
|
|
1238
1593
|
}
|
|
1239
|
-
|
|
1594
|
+
directories = /* @__PURE__ */ new Set([copyRoot]);
|
|
1595
|
+
for (const file of [...selected, ...linked]) {
|
|
1596
|
+
let parent = path.dirname(file);
|
|
1597
|
+
while (parent !== copyRoot && parent !== path.dirname(parent)) {
|
|
1598
|
+
directories.add(parent);
|
|
1599
|
+
parent = path.dirname(parent);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
}).pipe(Effect3.catch((error3) => Effect3.gen(function* () {
|
|
1603
|
+
yield* Console.warn(`Warning: Git scratch discovery failed; using recursive copy: ${error3.message}`);
|
|
1604
|
+
source = originalSource;
|
|
1605
|
+
copyRoot = originalCopyRoot;
|
|
1606
|
+
selected = void 0;
|
|
1607
|
+
directories = void 0;
|
|
1608
|
+
linked.clear();
|
|
1609
|
+
unreadable.clear();
|
|
1610
|
+
ignoredRoots.clear();
|
|
1611
|
+
})));
|
|
1612
|
+
const linkedRoots = () => [...linked].filter((root2) => !selected?.has(root2) && !unreadable.has(root2)).map((root2) => path.relative(source, root2)).filter((root2) => root2 !== ".." && !root2.startsWith(`..${path.sep}`) && !path.isAbsolute(root2));
|
|
1613
|
+
return { source, copyRoot, selected, directories, linked, unreadable, ignoredRoots, pruneUnreadable, linkedRoots };
|
|
1614
|
+
}, (effect5, root) => effect5.pipe(Effect3.mapError((error3) => failure("discover", root, error3))));
|
|
1615
|
+
return Scratch.of({
|
|
1616
|
+
inspect: Effect3.fn("Scratch.inspect")(function* (root) {
|
|
1617
|
+
return (yield* discover(root)).linkedRoots();
|
|
1618
|
+
}),
|
|
1619
|
+
acquire: Effect3.fn("Scratch.acquire")(function* (root) {
|
|
1620
|
+
const plan = yield* discover(root);
|
|
1621
|
+
const { source, copyRoot, selected, directories, linked, unreadable, ignoredRoots, pruneUnreadable } = plan;
|
|
1622
|
+
const skipUnreadable = (from, to, enabled) => (effect5) => effect5.pipe(Effect3.catch((error3) => enabled && error3._tag === "PlatformError" && error3.reason._tag === "PermissionDenied" && error3.reason.pathOrDescriptor === from && ["access", "realPath", "stat", "lstat", "readDirectory"].includes(error3.reason.method) ? pruneUnreadable(from).pipe(Effect3.andThen(fs.remove(to, { recursive: true, force: true }))) : Effect3.fail(error3)));
|
|
1623
|
+
const temp = yield* Effect3.acquireRelease(
|
|
1240
1624
|
fs.makeTempDirectory({ prefix: "mutant-cafe-" }).pipe(
|
|
1241
|
-
|
|
1625
|
+
Effect3.mapError((error3) => failure("create", source, error3))
|
|
1242
1626
|
),
|
|
1243
|
-
(dir2) => fs.remove(dir2, { recursive: true }).pipe(
|
|
1627
|
+
(dir2) => fs.remove(dir2, { recursive: true, force: true }).pipe(Effect3.interruptible, Effect3.timeout(3e4), Effect3.catch((error3) => Console.warn(`Warning: scratch removal did not complete within its cleanup budget: ${error3.message}`, { path: dir2 })))
|
|
1244
1628
|
);
|
|
1245
|
-
const copy = (from, to, ancestors) =>
|
|
1629
|
+
const copy = (from, to, ancestors, filter = true, ignored = false) => Effect3.gen(function* () {
|
|
1630
|
+
if (unreadable.has(from)) return;
|
|
1631
|
+
if (linked.has(from) && !selected?.has(from)) {
|
|
1632
|
+
yield* fs.symlink(from, to);
|
|
1633
|
+
return;
|
|
1634
|
+
}
|
|
1246
1635
|
const real = yield* fs.realPath(from);
|
|
1247
1636
|
const info = yield* fs.stat(from);
|
|
1248
1637
|
if (info.type === "Directory") {
|
|
1249
1638
|
if (ancestors.includes(real)) {
|
|
1250
|
-
return yield*
|
|
1639
|
+
return yield* Effect3.fail(new ScratchError({ operation: "copy", path: from, message: "Cyclic directory symlink" }));
|
|
1251
1640
|
}
|
|
1252
1641
|
yield* fs.makeDirectory(to, { recursive: true });
|
|
1253
1642
|
const entries = yield* fs.readDirectory(from);
|
|
@@ -1255,88 +1644,518 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
1255
1644
|
if ([".git", "mutants.out", ".agent_sources", ".agent-sources", ".brain", ".pi", ".rift"].includes(entry)) continue;
|
|
1256
1645
|
const src = path.join(from, entry);
|
|
1257
1646
|
const dest = path.join(to, entry);
|
|
1647
|
+
const filterChildren = filter && !selected?.has(from);
|
|
1648
|
+
if (filterChildren && selected && directories && !selected.has(src) && !directories.has(src) && !linked.has(src) && entry !== "node_modules") continue;
|
|
1258
1649
|
if (entry === "node_modules") {
|
|
1259
|
-
const linkDependencies = (from2, to2) =>
|
|
1650
|
+
const linkDependencies = (from2, to2, ignored2) => Effect3.gen(function* () {
|
|
1260
1651
|
yield* fs.makeDirectory(to2, { recursive: true });
|
|
1261
1652
|
for (const name of yield* fs.readDirectory(from2)) {
|
|
1262
1653
|
if ([".vite", ".vite-temp", ".vitest", ".cache"].includes(name)) continue;
|
|
1263
1654
|
const dependency = path.join(from2, name);
|
|
1264
1655
|
const destination = path.join(to2, name);
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1656
|
+
yield* Effect3.gen(function* () {
|
|
1657
|
+
if (name.startsWith("@")) {
|
|
1658
|
+
yield* linkDependencies(dependency, destination, ignored2);
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
const realDependency = yield* fs.realPath(dependency);
|
|
1662
|
+
const rel = path.relative(copyRoot, realDependency);
|
|
1663
|
+
const inside = rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) && !rel.split(path.sep).includes("node_modules") && (!selected || selected.has(realDependency) || directories?.has(realDependency));
|
|
1664
|
+
yield* fs.symlink(inside ? path.join(temp, rel) : realDependency, destination);
|
|
1665
|
+
}).pipe(skipVanished(dependency, destination), skipUnreadable(dependency, destination, ignored2));
|
|
1273
1666
|
}
|
|
1274
1667
|
});
|
|
1275
|
-
yield* linkDependencies(src, dest);
|
|
1668
|
+
yield* linkDependencies(src, dest, ignored || ignoredRoots.has(from)).pipe(skipVanished(src, dest), skipUnreadable(src, dest, ignored || ignoredRoots.has(from)));
|
|
1276
1669
|
} else {
|
|
1277
|
-
yield* copy(src, dest, [...ancestors, real]);
|
|
1670
|
+
yield* copy(src, dest, [...ancestors, real], filterChildren, ignored || ignoredRoots.has(from));
|
|
1278
1671
|
}
|
|
1279
1672
|
}
|
|
1280
1673
|
} else if (info.type === "File") {
|
|
1674
|
+
if (ignored || ignoredRoots.has(from)) yield* fs.access(from, { readable: true });
|
|
1281
1675
|
yield* fs.copyFile(from, to);
|
|
1282
1676
|
}
|
|
1283
|
-
}).pipe(
|
|
1677
|
+
}).pipe(skipVanished(from, to), skipUnreadable(from, to, ignored || ignoredRoots.has(from)), Effect3.mapError((error3) => failure("copy", from, error3)));
|
|
1284
1678
|
yield* copy(copyRoot, temp, []);
|
|
1285
1679
|
const packageRoot = yield* fs.realPath(path.join(temp, path.relative(copyRoot, source))).pipe(
|
|
1286
|
-
|
|
1680
|
+
Effect3.mapError((error3) => failure("resolve", source, error3))
|
|
1287
1681
|
);
|
|
1682
|
+
const packageRelative = path.relative(yield* fs.realPath(temp), packageRoot);
|
|
1683
|
+
if (packageRelative === ".." || packageRelative.startsWith(`..${path.sep}`) || path.isAbsolute(packageRelative)) {
|
|
1684
|
+
return yield* new ScratchError({ operation: "resolve", path: source, message: "Requested package is inside a linked ignored tree; refusing to mutate the original checkout. Choose an editable source package outside that tree." });
|
|
1685
|
+
}
|
|
1288
1686
|
const originals = /* @__PURE__ */ new Map();
|
|
1289
|
-
const target = (mutant) =>
|
|
1687
|
+
const target = (mutant) => Effect3.gen(function* () {
|
|
1290
1688
|
const relative2 = path.isAbsolute(mutant.file) ? path.relative(source, mutant.file) : mutant.file;
|
|
1291
1689
|
const location = path.resolve(packageRoot, relative2);
|
|
1292
1690
|
const rel = path.relative(packageRoot, location);
|
|
1293
1691
|
if (rel === "" || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel) || rel.split(path.sep).includes("node_modules")) {
|
|
1294
|
-
return yield*
|
|
1692
|
+
return yield* Effect3.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file must be inside the copied source tree" }));
|
|
1295
1693
|
}
|
|
1296
|
-
const real = yield* fs.realPath(location).pipe(
|
|
1694
|
+
const real = yield* fs.realPath(location).pipe(Effect3.mapError((error3) => failure("resolve", location, error3)));
|
|
1297
1695
|
const realRelative = path.relative(packageRoot, real);
|
|
1298
1696
|
if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
1299
|
-
return yield*
|
|
1697
|
+
return yield* Effect3.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file resolves outside the scratch package" }));
|
|
1300
1698
|
}
|
|
1301
1699
|
return location;
|
|
1302
1700
|
});
|
|
1303
1701
|
const dir = {
|
|
1304
1702
|
path: packageRoot,
|
|
1305
|
-
|
|
1703
|
+
linkedRoots: plan.linkedRoots(),
|
|
1704
|
+
apply: Effect3.fn("Scratch.apply")(function* (mutant) {
|
|
1306
1705
|
const location = yield* target(mutant);
|
|
1307
1706
|
const bytes = yield* fs.readFile(location);
|
|
1308
1707
|
originals.set(location, bytes);
|
|
1309
1708
|
const original = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
|
|
1310
1709
|
const { startOffset, endOffset, text } = mutant.replacement;
|
|
1311
1710
|
if (startOffset < 0 || endOffset < startOffset || endOffset > original.length) {
|
|
1312
|
-
return yield*
|
|
1711
|
+
return yield* Effect3.fail(new ScratchError({ operation: "apply", path: location, message: "Replacement offsets are outside the file" }));
|
|
1313
1712
|
}
|
|
1314
1713
|
yield* fs.writeFileString(location, original.slice(0, startOffset) + text + original.slice(endOffset));
|
|
1315
|
-
}, (effect5, mutant) => effect5.pipe(
|
|
1316
|
-
|
|
1714
|
+
}, (effect5, mutant) => effect5.pipe(Effect3.mapError((error3) => failure("apply", mutant.file, error3)))),
|
|
1715
|
+
poison: Effect3.fn("Scratch.poison")(function* (mutant, signal, token) {
|
|
1716
|
+
const location = yield* target(mutant);
|
|
1717
|
+
const bytes = yield* fs.readFile(location).pipe(Effect3.mapError((error3) => failure("probe", location, error3)));
|
|
1718
|
+
const original = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
|
|
1719
|
+
const insertion = poisonInsertion(original, signal, token);
|
|
1720
|
+
yield* dir.apply({ ...mutant, replacement: { startOffset: insertion.offset, endOffset: insertion.offset, text: insertion.text } });
|
|
1721
|
+
}),
|
|
1722
|
+
revert: Effect3.fn("Scratch.revert")(function* (mutant) {
|
|
1317
1723
|
const location = yield* target(mutant);
|
|
1318
1724
|
const bytes = originals.get(location);
|
|
1319
1725
|
if (bytes !== void 0) {
|
|
1320
1726
|
yield* fs.writeFile(location, bytes);
|
|
1321
1727
|
originals.delete(location);
|
|
1322
1728
|
}
|
|
1323
|
-
}, (effect5, mutant) => effect5.pipe(
|
|
1729
|
+
}, (effect5, mutant) => effect5.pipe(Effect3.mapError((error3) => failure("revert", mutant.file, error3))))
|
|
1324
1730
|
};
|
|
1325
1731
|
return dir;
|
|
1326
|
-
}, (effect5, root) => effect5.pipe(
|
|
1732
|
+
}, (effect5, root) => effect5.pipe(Effect3.mapError((error3) => error3._tag === "ScratchError" ? error3 : failure("acquire", root, error3))))
|
|
1327
1733
|
});
|
|
1328
1734
|
}));
|
|
1329
1735
|
|
|
1330
1736
|
// packages/runner/src/TestRunner.ts
|
|
1737
|
+
import * as Clock4 from "effect/Clock";
|
|
1738
|
+
import * as Console4 from "effect/Console";
|
|
1739
|
+
|
|
1740
|
+
// packages/runner/src/Preflight.ts
|
|
1741
|
+
import * as Effect5 from "effect/Effect";
|
|
1742
|
+
import * as Clock2 from "effect/Clock";
|
|
1743
|
+
import * as Schema7 from "effect/Schema";
|
|
1744
|
+
import * as ChildProcess2 from "effect/process/ChildProcess";
|
|
1745
|
+
import * as ChildProcessSpawner3 from "effect/process/ChildProcessSpawner";
|
|
1746
|
+
|
|
1747
|
+
// packages/runner/src/ProcessTree.ts
|
|
1748
|
+
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
1749
|
+
import { types } from "xstate";
|
|
1750
|
+
|
|
1751
|
+
// packages/runner/src/ProcessTrace.ts
|
|
1752
|
+
var processTraceSource = String.raw`
|
|
1753
|
+
import { appendFileSync as appendProcessTrace } from "node:fs";
|
|
1754
|
+
const traceProcess = (stage, details = {}) => {
|
|
1755
|
+
const destination = process.env.MUTANT_CAFE_PROCESS_TRACE;
|
|
1756
|
+
if (destination) try {
|
|
1757
|
+
appendProcessTrace(destination, JSON.stringify({ at: Date.now(), pid: process.pid, ppid: process.ppid, stage, ...details }) + "\n");
|
|
1758
|
+
} catch { /* Diagnostics cannot determine a verdict or prevent cleanup. */ }
|
|
1759
|
+
};
|
|
1760
|
+
`;
|
|
1761
|
+
|
|
1762
|
+
// packages/runner/src/ProcessTree.ts
|
|
1763
|
+
import * as Console2 from "effect/Console";
|
|
1331
1764
|
import * as Clock from "effect/Clock";
|
|
1332
|
-
import * as
|
|
1765
|
+
import * as Context2 from "effect/Context";
|
|
1766
|
+
import * as Effect4 from "effect/Effect";
|
|
1767
|
+
import * as FileSystem3 from "effect/FileSystem";
|
|
1768
|
+
import * as Result from "effect/Result";
|
|
1769
|
+
import * as Schema6 from "effect/Schema";
|
|
1770
|
+
import * as Semaphore from "effect/Semaphore";
|
|
1771
|
+
import { execFile } from "node:child_process";
|
|
1772
|
+
import { promisify } from "node:util";
|
|
1773
|
+
import { randomUUID } from "node:crypto";
|
|
1774
|
+
import { pathToFileURL } from "node:url";
|
|
1775
|
+
var execute = promisify(execFile);
|
|
1776
|
+
var liveLedgers = /* @__PURE__ */ new Set();
|
|
1777
|
+
var ProcessInspector = Context2.Reference("mutant.cafe/ProcessInspector", { defaultValue: () => ({ inspect: (args) => Effect4.tryPromise({
|
|
1778
|
+
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" } }),
|
|
1779
|
+
catch: () => new TestSpawnError({ command: ["ps"], message: "Cannot inspect owned test processes" })
|
|
1780
|
+
}) }) });
|
|
1781
|
+
var PartialCwd = Schema6.Struct({ code: Schema6.Literal(1), stdout: Schema6.String, signal: Schema6.optional(Schema6.Null), killed: Schema6.optional(Schema6.Literal(false)) });
|
|
1782
|
+
var inspectScratchCwd = (pids, probe2 = {
|
|
1783
|
+
live: (pid) => {
|
|
1784
|
+
if (pid <= 0) return false;
|
|
1785
|
+
try {
|
|
1786
|
+
process.kill(pid, 0);
|
|
1787
|
+
return true;
|
|
1788
|
+
} catch {
|
|
1789
|
+
return false;
|
|
1790
|
+
}
|
|
1791
|
+
},
|
|
1792
|
+
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" } })
|
|
1793
|
+
}) => Effect4.tryPromise({
|
|
1794
|
+
// @effect-diagnostics-next-line asyncFunction:off -- Native execFile adapter preserves partial stdout while Effect supplies cancellation.
|
|
1795
|
+
try: async (signal) => {
|
|
1796
|
+
const live2 = pids.filter(probe2.live);
|
|
1797
|
+
if (!live2.length) return { stdout: "" };
|
|
1798
|
+
try {
|
|
1799
|
+
return await probe2.read(live2, signal);
|
|
1800
|
+
} catch (error3) {
|
|
1801
|
+
const partial = Schema6.decodeUnknownOption(PartialCwd)(error3);
|
|
1802
|
+
if (partial._tag === "Some") return { stdout: partial.value.stdout };
|
|
1803
|
+
throw error3;
|
|
1804
|
+
}
|
|
1805
|
+
},
|
|
1806
|
+
catch: () => new TestSpawnError({ command: ["lsof"], message: "Cannot inspect scratch working directories" })
|
|
1807
|
+
});
|
|
1808
|
+
var tokenKey = "MUTANT_CAFE_PROCESS_TOKEN";
|
|
1809
|
+
var ledgerKey = "MUTANT_CAFE_PROCESS_LEDGER";
|
|
1810
|
+
var preloadKey = "MUTANT_CAFE_PROCESS_PRELOAD";
|
|
1811
|
+
var preloadSource = `import cp from "node:child_process";
|
|
1812
|
+
${processTraceSource}
|
|
1813
|
+
import { appendFileSync } from "node:fs";
|
|
1814
|
+
import { syncBuiltinESMExports } from "node:module";
|
|
1815
|
+
const nativeExec = Symbol.for("mutant.cafe.nativeExecFile");
|
|
1816
|
+
const inspect = cp[nativeExec] ?? (cp[nativeExec] = cp.execFile);
|
|
1817
|
+
const ledger = process.env.${ledgerKey};
|
|
1818
|
+
const token = process.env.${tokenKey};
|
|
1819
|
+
const preload = process.env.${preloadKey};
|
|
1820
|
+
traceProcess("preload-start");
|
|
1821
|
+
// Async native inspection plus an independent timer: execFileSync's timeout
|
|
1822
|
+
// still waits for a kernel-blocked helper to exit, freezing the Node thread.
|
|
1823
|
+
const record = pid => new Promise(resolve => {
|
|
1824
|
+
if (!pid || !ledger) return resolve();
|
|
1825
|
+
const began = performance.now();
|
|
1826
|
+
const phase = process.env.MUTANT_CAFE_PROCESS_PHASE;
|
|
1827
|
+
let settled = false; let child;
|
|
1828
|
+
const done = (stage, started = "") => {
|
|
1829
|
+
if (settled) return;
|
|
1830
|
+
settled = true; clearTimeout(timer);
|
|
1831
|
+
if (started) try { appendFileSync(ledger, JSON.stringify({ pid, birth: started, phase }) + "\\n"); } catch {}
|
|
1832
|
+
traceProcess(stage, { targetPid: pid, elapsedMs: performance.now() - began });
|
|
1833
|
+
resolve();
|
|
1834
|
+
};
|
|
1835
|
+
const timer = setTimeout(() => {
|
|
1836
|
+
done("ps-record-timeout");
|
|
1837
|
+
try { child?.kill("SIGKILL"); } catch {}
|
|
1838
|
+
child?.stdout?.destroy(); child?.stderr?.destroy(); child?.unref();
|
|
1839
|
+
}, 1000);
|
|
1840
|
+
traceProcess("ps-record-start", { targetPid: pid });
|
|
1841
|
+
try {
|
|
1842
|
+
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()));
|
|
1843
|
+
} catch { done("ps-record-failed"); }
|
|
1844
|
+
});
|
|
1845
|
+
if (ledger && token && preload) {
|
|
1846
|
+
// Await only our own birth before user code can busy-loop. Child-spawn records
|
|
1847
|
+
// are asynchronous; implicit Node children also record themselves here.
|
|
1848
|
+
await record(process.pid);
|
|
1849
|
+
traceProcess("preload-ready");
|
|
1850
|
+
const environment = node => {
|
|
1851
|
+
const env = { ...process.env };
|
|
1852
|
+
const ownImport = "--import=" + preload;
|
|
1853
|
+
const original = (env.NODE_OPTIONS || "").replaceAll(ownImport, "").trim();
|
|
1854
|
+
if (node && env.${ledgerKey} === ledger && env.${tokenKey} === token) env.NODE_OPTIONS = (original + " " + ownImport).trim();
|
|
1855
|
+
else if (original) env.NODE_OPTIONS = original;
|
|
1856
|
+
else delete env.NODE_OPTIONS;
|
|
1857
|
+
return env;
|
|
1858
|
+
};
|
|
1859
|
+
const options = (value, node) => value?.env !== undefined ? value : ({ ...value, env: environment(node) });
|
|
1860
|
+
for (const name of ["spawn", "fork", "execFile", "exec"]) {
|
|
1861
|
+
const original = cp[name];
|
|
1862
|
+
const wrapped = function (...args) {
|
|
1863
|
+
const index = name === "exec" ? 1 : Array.isArray(args[1]) || (args[1] === undefined && args.length > 2) ? 2 : 1;
|
|
1864
|
+
const value = typeof args[index] === "object" && args[index] !== null ? args[index] : undefined;
|
|
1865
|
+
const node = name === "fork" ? (value?.execPath || process.execPath) === process.execPath : args[0] === process.execPath;
|
|
1866
|
+
if (typeof args[index] === "function") args.splice(index, 0, options(undefined, node));
|
|
1867
|
+
else args[index] = options(value, node);
|
|
1868
|
+
traceProcess("spawn-start", { method: name, node });
|
|
1869
|
+
const child = original.apply(this, args);
|
|
1870
|
+
traceProcess("spawn-return", { method: name, childPid: child.pid, node });
|
|
1871
|
+
child.once("spawn", () => traceProcess("spawn", { method: name, childPid: child.pid, node }));
|
|
1872
|
+
// Exact birth inspection cannot block spawn: a minimal-env child can be
|
|
1873
|
+
// orphaned before this async callback if its parent exits immediately.
|
|
1874
|
+
// Without a birth row, surviving PPID edge or label, it stays warning-only
|
|
1875
|
+
// (cwd/argv backstop). A PID plus approximate spawn time is not reuse proof.
|
|
1876
|
+
void record(child.pid);
|
|
1877
|
+
return child;
|
|
1878
|
+
};
|
|
1879
|
+
const custom = Symbol.for("nodejs.util.promisify.custom");
|
|
1880
|
+
const descriptors = Object.getOwnPropertyDescriptors(original);
|
|
1881
|
+
delete descriptors[custom];
|
|
1882
|
+
Object.defineProperties(wrapped, descriptors);
|
|
1883
|
+
if (name === "exec" || name === "execFile") Object.defineProperty(wrapped, custom, { value: (...args) => {
|
|
1884
|
+
let child;
|
|
1885
|
+
const promise = new Promise((resolve, reject) => {
|
|
1886
|
+
child = wrapped(...args, (error, stdout, stderr) => {
|
|
1887
|
+
if (error) { error.stdout = stdout; error.stderr = stderr; reject(error); }
|
|
1888
|
+
else resolve({ stdout, stderr });
|
|
1889
|
+
});
|
|
1890
|
+
});
|
|
1891
|
+
promise.child = child;
|
|
1892
|
+
return promise;
|
|
1893
|
+
} });
|
|
1894
|
+
cp[name] = wrapped;
|
|
1895
|
+
}
|
|
1896
|
+
syncBuiltinESMExports();
|
|
1897
|
+
}
|
|
1898
|
+
`;
|
|
1899
|
+
var Record2 = Schema6.Struct({ pid: Schema6.Int, birth: Schema6.String });
|
|
1900
|
+
var acquireProcessTree = Effect4.fn("ProcessTree.acquire")(function* (scratch, onBackstop, processesSince) {
|
|
1901
|
+
const fs = yield* FileSystem3.FileSystem;
|
|
1902
|
+
const directory = yield* fs.makeTempDirectory({ prefix: "mutant-processes-" });
|
|
1903
|
+
const ledger = `${directory}/pids.jsonl`;
|
|
1904
|
+
const script = `${directory}/register.mjs`;
|
|
1905
|
+
const token = yield* Effect4.sync(randomUUID);
|
|
1906
|
+
const url = pathToFileURL(script).href;
|
|
1907
|
+
yield* fs.writeFileString(ledger, "");
|
|
1908
|
+
yield* fs.writeFileString(script, preloadSource);
|
|
1909
|
+
liveLedgers.add(ledger);
|
|
1910
|
+
const trace = (stage, details = {}) => {
|
|
1911
|
+
const destination = process.env.MUTANT_CAFE_PROCESS_TRACE;
|
|
1912
|
+
return destination ? Clock.currentTimeMillis.pipe(Effect4.flatMap((at) => fs.writeFileString(destination, JSON.stringify({ at, pid: process.pid, ppid: process.ppid, stage, ...details }) + "\n", { flag: "a" })), Effect4.timeout(100), Effect4.catch(() => Effect4.void)) : Effect4.void;
|
|
1913
|
+
};
|
|
1914
|
+
const roots = /* @__PURE__ */ new Set();
|
|
1915
|
+
const command = ["vitest", "process-cleanup"];
|
|
1916
|
+
const inspector = yield* ProcessInspector;
|
|
1917
|
+
let deadline = Infinity;
|
|
1918
|
+
let lastSnapshot;
|
|
1919
|
+
let ledgerRows = [];
|
|
1920
|
+
const verified = /* @__PURE__ */ new Map();
|
|
1921
|
+
let effectiveKeep = /* @__PURE__ */ new Set();
|
|
1922
|
+
const kill = inspector.signal ?? ((pid, signal2) => {
|
|
1923
|
+
process.kill(pid, signal2);
|
|
1924
|
+
});
|
|
1925
|
+
const bounded = (phase, effect5, limit = 7e3) => Effect4.suspend(() => {
|
|
1926
|
+
const remaining = Math.min(limit, deadline - performance.now());
|
|
1927
|
+
if (remaining <= 0) return Effect4.fail(new TestSpawnError({ command, message: `Cleanup deadline exceeded during ${phase}` }));
|
|
1928
|
+
return effect5.pipe(Effect4.interruptible, Effect4.timeout(remaining), Effect4.mapError(() => new TestSpawnError({ command, message: `Cleanup ${phase} failed or exceeded its ${Math.ceil(remaining)} ms budget` })));
|
|
1929
|
+
});
|
|
1930
|
+
const inspect = (args) => bounded("ps inspection", Effect4.gen(function* () {
|
|
1931
|
+
const began = performance.now();
|
|
1932
|
+
yield* trace("inspect-start", { operation: args[0] ?? "ps" });
|
|
1933
|
+
const result5 = yield* inspector.inspect(args);
|
|
1934
|
+
yield* trace("inspect-done", { elapsedMs: performance.now() - began });
|
|
1935
|
+
return result5;
|
|
1936
|
+
}), 2e3);
|
|
1937
|
+
const snapshot = Effect4.gen(function* () {
|
|
1938
|
+
const result5 = yield* inspect(["-A", "-ww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,args="]);
|
|
1939
|
+
const found = /* @__PURE__ */ new Map();
|
|
1940
|
+
for (const line of result5.stdout.split("\n")) {
|
|
1941
|
+
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);
|
|
1942
|
+
if (!match2) continue;
|
|
1943
|
+
const pid = Number(match2[1]);
|
|
1944
|
+
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] ?? "" });
|
|
1945
|
+
}
|
|
1946
|
+
for (const [pid, item] of verified) if (found.get(pid)?.birth !== item.birth) verified.delete(pid);
|
|
1947
|
+
lastSnapshot = found;
|
|
1948
|
+
return found;
|
|
1949
|
+
});
|
|
1950
|
+
const discover = (preserved, retained) => Effect4.gen(function* () {
|
|
1951
|
+
const registered = yield* fs.readFileString(ledger).pipe(Effect4.mapError(() => new TestSpawnError({ command, message: "Cannot read the test process ownership ledger" })));
|
|
1952
|
+
ledgerRows = registered.split("\n").flatMap((line) => {
|
|
1953
|
+
const parsed = Schema6.decodeOption(Schema6.fromJsonString(Record2))(line);
|
|
1954
|
+
return parsed._tag === "Some" ? [parsed.value] : [];
|
|
1955
|
+
});
|
|
1956
|
+
const table = yield* snapshot;
|
|
1957
|
+
const keep = new Set(preserved);
|
|
1958
|
+
const subtrees = new Set(retained.filter((item) => table.get(item.pid)?.birth === item.birth).map((item) => item.pid));
|
|
1959
|
+
let keepAdded;
|
|
1960
|
+
do {
|
|
1961
|
+
keepAdded = false;
|
|
1962
|
+
for (const item of table.values()) if (subtrees.has(item.ppid) && !subtrees.has(item.pid)) {
|
|
1963
|
+
subtrees.add(item.pid);
|
|
1964
|
+
keepAdded = true;
|
|
1965
|
+
}
|
|
1966
|
+
} while (keepAdded);
|
|
1967
|
+
for (const pid of subtrees) keep.add(pid);
|
|
1968
|
+
effectiveKeep = keep;
|
|
1969
|
+
const owned = /* @__PURE__ */ new Set();
|
|
1970
|
+
const claim = (pid) => {
|
|
1971
|
+
owned.add(pid);
|
|
1972
|
+
const item = table.get(pid);
|
|
1973
|
+
if (item && !keep.has(pid)) verified.set(pid, item);
|
|
1974
|
+
};
|
|
1975
|
+
const closeDescendants = () => {
|
|
1976
|
+
let added;
|
|
1977
|
+
do {
|
|
1978
|
+
added = false;
|
|
1979
|
+
for (const item of table.values()) if (owned.has(item.ppid) && !owned.has(item.pid)) {
|
|
1980
|
+
claim(item.pid);
|
|
1981
|
+
added = true;
|
|
1982
|
+
}
|
|
1983
|
+
} while (added);
|
|
1984
|
+
};
|
|
1985
|
+
const uncertain = /* @__PURE__ */ new Set();
|
|
1986
|
+
for (const item of ledgerRows) if (table.get(item.pid)?.birth === item.birth) claim(item.pid);
|
|
1987
|
+
closeDescendants();
|
|
1988
|
+
if (process.platform === "linux") {
|
|
1989
|
+
yield* Effect4.forEach([...table.keys()], (pid) => fs.readFileString(`/proc/${pid}/environ`).pipe(
|
|
1990
|
+
Effect4.catch(() => Effect4.succeed("")),
|
|
1991
|
+
Effect4.tap((environment) => Effect4.sync(() => {
|
|
1992
|
+
if (!owned.has(pid) && environment.split("\0").includes(`${tokenKey}=${token}`)) {
|
|
1993
|
+
claim(pid);
|
|
1994
|
+
closeDescendants();
|
|
1995
|
+
}
|
|
1996
|
+
}))
|
|
1997
|
+
), { concurrency: 8, discard: true });
|
|
1998
|
+
} else {
|
|
1999
|
+
const labelled = yield* inspect(["axeww", "-o", "pid=,lstart=,command="]);
|
|
2000
|
+
const label = new RegExp("(?:^|\\s)" + tokenKey + "=" + token + "(?:\\s|$)");
|
|
2001
|
+
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)];
|
|
2002
|
+
for (const [index, row] of rows.entries()) {
|
|
2003
|
+
const pid = Number(row[1]);
|
|
2004
|
+
const record = labelled.stdout.slice(row.index, rows[index + 1]?.index);
|
|
2005
|
+
if (owned.has(pid) || table.get(pid)?.birth !== row[2]?.trim() || !label.test(record)) continue;
|
|
2006
|
+
const argv = yield* inspect(["ww", "-p", String(pid), "-o", "command="]).pipe(Effect4.result);
|
|
2007
|
+
const environment = yield* inspect(["eww", "-p", String(pid), "-o", "command="]).pipe(Effect4.result);
|
|
2008
|
+
const after = yield* inspect(["ww", "-p", String(pid), "-o", "command="]).pipe(Effect4.result);
|
|
2009
|
+
if (Result.isFailure(argv) || Result.isFailure(environment) || Result.isFailure(after)) continue;
|
|
2010
|
+
const prefix = argv.success.stdout.trimEnd();
|
|
2011
|
+
if (prefix && prefix === after.success.stdout.trimEnd() && environment.success.stdout.startsWith(prefix + " ") && label.test(environment.success.stdout.slice(prefix.length))) uncertain.add(pid);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
closeDescendants();
|
|
2015
|
+
const unverified = [...uncertain].filter((pid) => !owned.has(pid));
|
|
2016
|
+
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` });
|
|
2017
|
+
if (unverified.length) yield* Console2.warn(`Warning: unverified process PIDs ${unverified.join(", ")}; not signalled. Cleaning verified descendants first.`);
|
|
2018
|
+
return [...owned].flatMap((pid) => table.has(pid) && !keep.has(pid) ? [table.get(pid)] : []);
|
|
2019
|
+
});
|
|
2020
|
+
const signal = (pending, value) => Effect4.gen(function* () {
|
|
2021
|
+
const current = yield* snapshot;
|
|
2022
|
+
for (const item of pending) {
|
|
2023
|
+
if (current.get(item.pid)?.birth !== item.birth) continue;
|
|
2024
|
+
yield* Effect4.sync(() => {
|
|
2025
|
+
try {
|
|
2026
|
+
if (roots.has(item.pid) && current.get(item.pid)?.pgid === item.pid) kill(-item.pid, value);
|
|
2027
|
+
} catch {
|
|
2028
|
+
}
|
|
2029
|
+
try {
|
|
2030
|
+
kill(item.pid, value);
|
|
2031
|
+
} catch {
|
|
2032
|
+
}
|
|
2033
|
+
});
|
|
2034
|
+
}
|
|
2035
|
+
});
|
|
2036
|
+
const inspectUnowned = Effect4.gen(function* () {
|
|
2037
|
+
if (!scratch) return;
|
|
2038
|
+
const table = lastSnapshot ?? (yield* snapshot);
|
|
2039
|
+
const registered = yield* Effect4.forEach([...liveLedgers], (path) => fs.readFileString(path).pipe(Effect4.catch(() => Effect4.succeed(""))));
|
|
2040
|
+
const known = new Set(registered.join("\n").split("\n").flatMap((line) => {
|
|
2041
|
+
const parsed = Schema6.decodeOption(Schema6.fromJsonString(Record2))(line);
|
|
2042
|
+
return parsed._tag === "Some" && table.get(parsed.value.pid)?.birth === parsed.value.birth ? [parsed.value.pid] : [];
|
|
2043
|
+
}));
|
|
2044
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
2045
|
+
const since = processesSince === void 0 ? -Infinity : Math.floor(processesSince / 1e3) * 1e3;
|
|
2046
|
+
const possible = [...table.values()].filter((item) => !known.has(item.pid) && (processesSince === void 0 || Date.parse(item.birth + " UTC") >= since));
|
|
2047
|
+
for (const item of possible) if (item.argv.includes(scratch)) candidates.add(item.pid);
|
|
2048
|
+
if (process.platform === "linux") yield* Effect4.forEach(possible.map((item) => item.pid), (pid) => fs.readLink(`/proc/${pid}/cwd`).pipe(
|
|
2049
|
+
Effect4.catch(() => Effect4.succeed("")),
|
|
2050
|
+
Effect4.tap((cwd) => Effect4.sync(() => {
|
|
2051
|
+
if (cwd === scratch || cwd.startsWith(scratch + "/")) candidates.add(pid);
|
|
2052
|
+
}))
|
|
2053
|
+
), { concurrency: 8, discard: true });
|
|
2054
|
+
else if (process.platform === "darwin" && possible.length) {
|
|
2055
|
+
const cwdStarted = performance.now();
|
|
2056
|
+
yield* trace("cwd-start", { candidates: possible.length });
|
|
2057
|
+
const cwd = yield* inspectScratchCwd(possible.map((item) => item.pid)).pipe(Effect4.catch(() => Console2.warn("Warning: cannot inspect scratch working directories; argv backstop remains active").pipe(Effect4.as({ stdout: "" }))));
|
|
2058
|
+
yield* trace("cwd-done", { elapsedMs: performance.now() - cwdStarted });
|
|
2059
|
+
let pid = 0;
|
|
2060
|
+
for (const row of cwd.stdout.split("\n")) {
|
|
2061
|
+
if (row.startsWith("p")) pid = Number(row.slice(1));
|
|
2062
|
+
if (row.startsWith("n") && (row.slice(1) === scratch || row.slice(1).startsWith(scratch + "/"))) candidates.add(pid);
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
const survivors = [...candidates].filter((pid) => table.has(pid) && !known.has(pid));
|
|
2066
|
+
if (survivors.length) yield* Console2.warn(`Warning: unowned scratch-related process PIDs ${survivors.join(", ")} survived; not signalled because ownership is unproven`);
|
|
2067
|
+
}).pipe(Effect4.catch(() => Console2.warn("Warning: cannot inspect unowned scratch-related survivors; no unverified PID was signalled")));
|
|
2068
|
+
const warnUnowned = Effect4.gen(function* () {
|
|
2069
|
+
if (!scratch) return;
|
|
2070
|
+
const started = yield* Clock.currentTimeMillis;
|
|
2071
|
+
if (!lastSnapshot) return yield* Console2.warn("Warning: scratch backstop unavailable without a process snapshot; no unverified PID was signalled");
|
|
2072
|
+
yield* bounded("scratch backstop", inspectUnowned, 2e3).pipe(Effect4.catch((error3) => Console2.warn(`Warning: ${error3.message}; unowned PIDs were not signalled`)));
|
|
2073
|
+
const elapsed = Math.max(0, (yield* Clock.currentTimeMillis) - started);
|
|
2074
|
+
yield* Effect4.sync(() => onBackstop?.(elapsed));
|
|
2075
|
+
});
|
|
2076
|
+
const semaphore = yield* Semaphore.make(1);
|
|
2077
|
+
let closed;
|
|
2078
|
+
const sweep = (preserved, retained = []) => Effect4.scoped(Effect4.gen(function* () {
|
|
2079
|
+
deadline = performance.now() + 1e4;
|
|
2080
|
+
lastSnapshot = void 0;
|
|
2081
|
+
ledgerRows = [];
|
|
2082
|
+
verified.clear();
|
|
2083
|
+
const keep = new Set(preserved);
|
|
2084
|
+
effectiveKeep = keep;
|
|
2085
|
+
const discovering = createEffectLogic(() => bounded("discovery", discover(keep, retained)).pipe(Effect4.result));
|
|
2086
|
+
const stopping = createEffectLogic(({ input }) => bounded("stop", signal(input, "SIGSTOP"), 3e3).pipe(Effect4.result));
|
|
2087
|
+
const killing = createEffectLogic(({ input }) => bounded("kill", signal(input, "SIGKILL"), 3e3).pipe(Effect4.result));
|
|
2088
|
+
const machine = setupEffect({
|
|
2089
|
+
schemas: { context: types(), events: { CLOSE: Schema6.Struct({}) } },
|
|
2090
|
+
actors: { discovering, stopping, killing }
|
|
2091
|
+
}).createMachine({
|
|
2092
|
+
context: { pending: [], round: 0, failure: void 0 },
|
|
2093
|
+
output: ({ context }) => context,
|
|
2094
|
+
initial: "tracking",
|
|
2095
|
+
states: {
|
|
2096
|
+
tracking: { on: { CLOSE: { target: "discovering" } } },
|
|
2097
|
+
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 } } } },
|
|
2098
|
+
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" } } },
|
|
2099
|
+
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" } } },
|
|
2100
|
+
verifying: { invoke: { src: "discovering", onDone: ({ context, event }) => {
|
|
2101
|
+
if (Result.isFailure(event.output)) return { target: "failed", context: { ...context, failure: event.output.failure.message } };
|
|
2102
|
+
const remaining = event.output.success;
|
|
2103
|
+
if (!remaining.length) return { target: "closed", context: { ...context, pending: [] } };
|
|
2104
|
+
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(", ")}` } };
|
|
2105
|
+
} } },
|
|
2106
|
+
closed: { type: "final" },
|
|
2107
|
+
failed: { type: "final" }
|
|
2108
|
+
}
|
|
2109
|
+
});
|
|
2110
|
+
const actor = yield* createEffectActor(machine);
|
|
2111
|
+
yield* send(actor, { type: "CLOSE" });
|
|
2112
|
+
const joined = yield* bounded("state machine", join(actor), 8e3).pipe(Effect4.result);
|
|
2113
|
+
const result5 = joined._tag === "Success" ? joined.success : { ...actor.getSnapshot().context, failure: joined.failure.message };
|
|
2114
|
+
if (result5.failure) {
|
|
2115
|
+
yield* Effect4.sync(() => {
|
|
2116
|
+
actor.stop();
|
|
2117
|
+
for (const item of verified.values()) {
|
|
2118
|
+
try {
|
|
2119
|
+
kill(item.pid, "SIGKILL");
|
|
2120
|
+
} catch {
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
});
|
|
2124
|
+
const unverified = [...new Set(ledgerRows.filter((item) => !verified.has(item.pid) && !effectiveKeep.has(item.pid)).map((item) => item.pid))];
|
|
2125
|
+
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`);
|
|
2126
|
+
}
|
|
2127
|
+
yield* warnUnowned;
|
|
2128
|
+
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`);
|
|
2129
|
+
return result5.failure ? "warning" : "clean";
|
|
2130
|
+
})).pipe(Effect4.uninterruptible);
|
|
2131
|
+
const reap = (preserved, retained = []) => semaphore.withPermit(Effect4.suspend(() => closed === void 0 ? sweep(preserved, retained) : Effect4.succeed(closed)));
|
|
2132
|
+
const cleanup = semaphore.withPermit(Effect4.gen(function* () {
|
|
2133
|
+
if (closed === void 0) closed = yield* sweep([]);
|
|
2134
|
+
}));
|
|
2135
|
+
yield* Effect4.addFinalizer(() => Effect4.gen(function* () {
|
|
2136
|
+
yield* cleanup;
|
|
2137
|
+
if (closed === "clean") yield* fs.remove(directory, { recursive: true }).pipe(
|
|
2138
|
+
Effect4.interruptible,
|
|
2139
|
+
Effect4.timeout(2e3),
|
|
2140
|
+
Effect4.catch((error3) => Console2.warn(`Warning: cannot remove process ledger directory: ${error3.message}`))
|
|
2141
|
+
);
|
|
2142
|
+
}).pipe(Effect4.ensuring(Effect4.sync(() => {
|
|
2143
|
+
liveLedgers.delete(ledger);
|
|
2144
|
+
}))));
|
|
2145
|
+
const existing = process.env.NODE_OPTIONS ?? "";
|
|
2146
|
+
return {
|
|
2147
|
+
env: { ...process.env, MUTANT_CAFE_PROCESS_PHASE: void 0, [tokenKey]: token, [ledgerKey]: ledger, [preloadKey]: url, NODE_OPTIONS: `${existing} --import=${url}`.trim() },
|
|
2148
|
+
addRoot: (pid) => {
|
|
2149
|
+
roots.add(pid);
|
|
2150
|
+
},
|
|
2151
|
+
cleanup,
|
|
2152
|
+
reap,
|
|
2153
|
+
trace
|
|
2154
|
+
};
|
|
2155
|
+
});
|
|
1333
2156
|
|
|
1334
2157
|
// packages/runner/src/Preflight.ts
|
|
1335
|
-
|
|
1336
|
-
import * as Schema5 from "effect/Schema";
|
|
1337
|
-
import * as ChildProcess from "effect/process/ChildProcess";
|
|
1338
|
-
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
1339
|
-
var Issues = Schema5.Array(SelectionIssue);
|
|
2158
|
+
var Issues = Schema7.Array(SelectionIssue);
|
|
1340
2159
|
var probe = String.raw`
|
|
1341
2160
|
import { readFile, readdir } from "node:fs/promises";
|
|
1342
2161
|
import { resolve, relative, dirname, isAbsolute, sep } from "node:path";
|
|
@@ -1353,6 +2172,14 @@ if (otherRunner) {
|
|
|
1353
2172
|
issues.push({ kind: "runner", reason: 'package.json scripts.test = ' + JSON.stringify(script) + '; mutant.cafe only runs Vitest' });
|
|
1354
2173
|
} else {
|
|
1355
2174
|
if (!vitestScript) issues.push({ kind: "warning", reason: 'package.json scripts.test = ' + JSON.stringify(script) + (delegated ? '; delegated test runner: Vitest selection is unverified' : '; unknown test wrapper: Vitest selection is unverified') });
|
|
2175
|
+
// Resolve from the adopter's package, not mutant.cafe's bundled dependencies.
|
|
2176
|
+
const require = createRequire(resolve(root, "package.json"));
|
|
2177
|
+
let version;
|
|
2178
|
+
try { version = JSON.parse(await readFile(require.resolve("vitest/package.json"), "utf8")).version; } catch {}
|
|
2179
|
+
if (typeof version === "string" && /^\d+\./.test(version) && Number(version.split(".")[0]) < 5) {
|
|
2180
|
+
console.log("mutant-cafe-vitest-version:" + JSON.stringify(version));
|
|
2181
|
+
process.exit(0);
|
|
2182
|
+
}
|
|
1356
2183
|
let ctx;
|
|
1357
2184
|
try {
|
|
1358
2185
|
const { createVitest } = await import("vitest/node");
|
|
@@ -1478,13 +2305,22 @@ if (otherRunner) {
|
|
|
1478
2305
|
}
|
|
1479
2306
|
console.log('mutant-cafe-preflight:' + JSON.stringify([...new Map(issues.map(issue => [JSON.stringify(issue), issue])).values()]));
|
|
1480
2307
|
`;
|
|
1481
|
-
var preflight =
|
|
1482
|
-
const spawner = yield*
|
|
1483
|
-
const
|
|
2308
|
+
var preflight = Effect5.fn("TestRunner.preflight")(function* (root, tsconfig = "tsconfig.json", timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS, options = {}) {
|
|
2309
|
+
const spawner = yield* ChildProcessSpawner3.ChildProcessSpawner;
|
|
2310
|
+
const since = options.processesSince ?? (yield* Clock2.currentTimeMillis);
|
|
2311
|
+
const owned = yield* acquireProcessTree(root, options.onBackstop, since);
|
|
2312
|
+
yield* owned.trace("preflight-start", { budgetMs: timeoutMs });
|
|
2313
|
+
const output = yield* spawner.string(ChildProcess2.make(process.execPath, ["--input-type=module", "--eval", probe, tsconfig], { cwd: root, env: owned.env, detached: true, killSignal: "SIGKILL", forceKillAfter: "100 millis", stdin: "ignore" })).pipe(Effect5.onInterrupt(() => owned.cleanup));
|
|
2314
|
+
yield* owned.trace("preflight-done");
|
|
2315
|
+
const version = output.split("\n").find((line) => line.startsWith("mutant-cafe-vitest-version:"))?.slice("mutant-cafe-vitest-version:".length);
|
|
2316
|
+
if (version !== void 0) {
|
|
2317
|
+
const found = yield* Schema7.decodeEffect(Schema7.fromJsonString(Schema7.String))(version);
|
|
2318
|
+
return yield* new TestSpawnError({ kind: "vitest-version", command: ["vitest"], message: `mutant.cafe needs vitest >= 5.0, found ${found}` });
|
|
2319
|
+
}
|
|
1484
2320
|
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*
|
|
2321
|
+
const issues = encoded === void 0 ? [{ kind: "warning", reason: "Vitest selection probe returned no evidence" }] : yield* Schema7.decodeEffect(Schema7.fromJsonString(Issues))(encoded);
|
|
1486
2322
|
return issues;
|
|
1487
|
-
});
|
|
2323
|
+
}, (effect5, _root, _tsconfig = "tsconfig.json", timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS, _options = {}) => effect5.pipe(Effect5.timeout(timeoutMs), Effect5.scoped));
|
|
1488
2324
|
function unreliableFor(baseline, file, testFiles) {
|
|
1489
2325
|
return baseline.unreliable?.filter((issue) => {
|
|
1490
2326
|
switch (issue.kind) {
|
|
@@ -1501,110 +2337,1061 @@ function unreliableFor(baseline, file, testFiles) {
|
|
|
1501
2337
|
}
|
|
1502
2338
|
|
|
1503
2339
|
// packages/runner/src/TestRunner.ts
|
|
1504
|
-
import * as
|
|
2340
|
+
import * as Effect7 from "effect/Effect";
|
|
1505
2341
|
import * as Layer3 from "effect/Layer";
|
|
1506
|
-
import * as
|
|
1507
|
-
import * as
|
|
1508
|
-
import * as
|
|
1509
|
-
import * as
|
|
1510
|
-
import * as
|
|
1511
|
-
import
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
2342
|
+
import * as FileSystem7 from "effect/FileSystem";
|
|
2343
|
+
import * as Path5 from "effect/Path";
|
|
2344
|
+
import * as Stream3 from "effect/Stream";
|
|
2345
|
+
import * as Schema9 from "effect/Schema";
|
|
2346
|
+
import * as Scope3 from "effect/Scope";
|
|
2347
|
+
import { createRequire } from "node:module";
|
|
2348
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
2349
|
+
import * as ChildProcess3 from "effect/process/ChildProcess";
|
|
2350
|
+
import * as ChildProcessSpawner5 from "effect/process/ChildProcessSpawner";
|
|
2351
|
+
|
|
2352
|
+
// packages/runner/src/WarmRunner.ts
|
|
2353
|
+
import { createEffectActor as createEffectActor2, send as send2, setupEffect as setupEffect2 } from "@xstate/effect";
|
|
2354
|
+
import { spawn } from "node:child_process";
|
|
2355
|
+
import * as Clock3 from "effect/Clock";
|
|
2356
|
+
import * as Effect6 from "effect/Effect";
|
|
2357
|
+
import * as Console3 from "effect/Console";
|
|
2358
|
+
import * as FileSystem5 from "effect/FileSystem";
|
|
2359
|
+
import * as Schema8 from "effect/Schema";
|
|
2360
|
+
import * as Scope from "effect/Scope";
|
|
2361
|
+
import * as Exit from "effect/Exit";
|
|
2362
|
+
|
|
2363
|
+
// packages/runner/src/WarmPolicy.ts
|
|
2364
|
+
var warmPolicySource = String.raw`
|
|
2365
|
+
function warmRefusal(version, ctx, selectionOnly = false) {
|
|
2366
|
+
if (!/^5\./.test(version)) return "unverified Vitest major: " + version + " (verified: 5)";
|
|
2367
|
+
if (!ctx) return null;
|
|
2368
|
+
const writable = (object, key) => {
|
|
2369
|
+
while (object) {
|
|
2370
|
+
const field = Object.getOwnPropertyDescriptor(object, key);
|
|
2371
|
+
if (field) return field.writable === true;
|
|
2372
|
+
object = Object.getPrototypeOf(object);
|
|
2373
|
+
}
|
|
2374
|
+
return false;
|
|
2375
|
+
};
|
|
2376
|
+
for (const key of ["pool", "cancelPromise", "runningPromise", "configOverride", "reporters", "initializeGlobalSetup"])
|
|
2377
|
+
if (!(key in ctx) || !writable(ctx, key)) return "unsupported private field: " + key;
|
|
2378
|
+
if (!Object.isExtensible(ctx) || !Object.isExtensible(ctx.configOverride) || typeof ctx.watcher?.invalidates?.add !== "function" || typeof ctx.vite?.transformRequest !== "function")
|
|
2379
|
+
return "unsupported transform/invalidation boundary";
|
|
2380
|
+
if (!Object.isExtensible(ctx.config) || ctx.projects.some(project => !project.vite?.environments || Object.values(project.vite.environments).some(environment => typeof environment.moduleGraph?.getModulesByFile !== "function")))
|
|
2381
|
+
return "unsupported private module graph";
|
|
2382
|
+
if (selectionOnly) return null;
|
|
2383
|
+
for (const config of [ctx.config, ...ctx.projects.flatMap(project => [project.config, project.vite.config.test ?? {}])]) {
|
|
2384
|
+
if (config.globalSetup && (!Array.isArray(config.globalSetup) || config.globalSetup.length)) return "globalSetup requires cold execution for per-mutant parity";
|
|
2385
|
+
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"));
|
|
2386
|
+
}
|
|
2387
|
+
return null;
|
|
2388
|
+
}
|
|
2389
|
+
`;
|
|
2390
|
+
var workerDeathSource = String.raw`
|
|
2391
|
+
function workerDied(error, seen = new Set()) {
|
|
2392
|
+
if (!error || typeof error !== "object" || seen.has(error)) return false;
|
|
2393
|
+
seen.add(error);
|
|
2394
|
+
const description = String(error.name ?? "") + " " + String(error.message ?? "");
|
|
2395
|
+
const diagnostic = error.name !== "AssertionError";
|
|
2396
|
+
return (diagnostic && (description.includes("Worker exited unexpectedly") || description.includes("[vitest-pool]:")
|
|
2397
|
+
|| (typeof error.code === "string" && error.code.startsWith("ERR_WORKER_"))))
|
|
2398
|
+
|| workerDied(error.cause, seen) || workerDied(error.error, seen) || workerDied(error.result, seen)
|
|
2399
|
+
|| (Array.isArray(error.errors) && error.errors.some(item => workerDied(item, seen)))
|
|
2400
|
+
|| (Array.isArray(error.tasks) && error.tasks.some(item => workerDied(item, seen)));
|
|
2401
|
+
}
|
|
2402
|
+
`;
|
|
2403
|
+
|
|
2404
|
+
// packages/runner/src/VitestHost.ts
|
|
2405
|
+
var vitestLauncherSource = `
|
|
2406
|
+
import { createRequire } from "node:module";
|
|
2407
|
+
import { dirname, resolve } from "node:path";
|
|
2408
|
+
import { pathToFileURL } from "node:url";
|
|
2409
|
+
${processTraceSource}
|
|
2410
|
+
traceProcess("vitest-resolve-start");
|
|
2411
|
+
const require = createRequire(pathToFileURL(process.cwd() + "/package.json"));
|
|
2412
|
+
const pkgFile = require.resolve("vitest/package.json");
|
|
2413
|
+
const pkg = require(pkgFile);
|
|
2414
|
+
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.vitest;
|
|
2415
|
+
if (typeof bin !== "string") throw new Error("Installed Vitest has no CLI bin");
|
|
2416
|
+
const cli = resolve(dirname(pkgFile), bin);
|
|
2417
|
+
process.argv = [process.execPath, cli, ...process.argv.slice(2)];
|
|
2418
|
+
traceProcess("vitest-resolved");
|
|
2419
|
+
await import(pathToFileURL(cli).href);
|
|
2420
|
+
`;
|
|
2421
|
+
var reporterSource = (marker, probe2) => `
|
|
2422
|
+
import { relative, dirname } from "node:path";
|
|
2423
|
+
${processTraceSource}
|
|
2424
|
+
${workerDeathSource}
|
|
2425
|
+
export default class {
|
|
2426
|
+
files = []; collected = false; failed = false; durations = {}; timeouts = {}; workers = 0; concurrency = 0; fileDurations = {}; firstTestStart = 0; verdict = null; crashed = false;
|
|
2427
|
+
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 = []; }
|
|
2428
|
+
onInit(ctx) {
|
|
2429
|
+
traceProcess("vitest-start");
|
|
2430
|
+
this.ctx = ctx;
|
|
2431
|
+
if (!this.setupFile) return;
|
|
2432
|
+
for (const vite of new Set(ctx.projects.map(project => project.vite.config))) {
|
|
2433
|
+
const fs = vite.server?.fs;
|
|
2434
|
+
if (fs) { this.allowances.push([fs, fs.allow]); fs.allow = [...fs.allow, dirname(this.setupFile)]; }
|
|
2435
|
+
}
|
|
2436
|
+
for (const config of new Set(ctx.projects.map(project => project.config))) {
|
|
2437
|
+
this.originals.push([config, config.setupFiles]);
|
|
2438
|
+
config.setupFiles = [this.setupFile, ...config.setupFiles];
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
restore() {
|
|
2442
|
+
for (const [config, setupFiles] of this.originals) config.setupFiles = setupFiles;
|
|
2443
|
+
for (const [fs, allow] of this.allowances) fs.allow = allow;
|
|
2444
|
+
this.originals = []; this.allowances = [];
|
|
2445
|
+
}
|
|
2446
|
+
onHookStart(hook) { this.hooks.set(hook.entity.id + hook.name, performance.now()); }
|
|
2447
|
+
onHookEnd(hook) {
|
|
2448
|
+
const module = hook.entity.module ?? hook.entity;
|
|
2449
|
+
const started = this.hooks.get(hook.entity.id + hook.name);
|
|
2450
|
+
if (module.moduleId && started !== undefined) {
|
|
2451
|
+
const file = relative(process.cwd(), module.moduleId);
|
|
2452
|
+
this.durations[file] = Math.max(this.durations[file] ?? 0, performance.now() - started);
|
|
2453
|
+
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 }));
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
onUserConsoleLog(log) {
|
|
2457
|
+
if (this.token && log.content.includes(this.token)) { this.loaded = true; process.send?.({ type: "probeLoaded" }); console.log(${JSON.stringify(marker + "probeLoaded")}); }
|
|
2458
|
+
}
|
|
2459
|
+
onTestRunStart(specifications) {
|
|
2460
|
+
traceProcess("test-run-start", { files: specifications.length });
|
|
2461
|
+
this.probeSupported = specifications.every(spec => ["forks", "threads", "vmForks", "vmThreads"].includes(spec.pool) && spec.project.config.environment === "node");
|
|
2462
|
+
console.log(${JSON.stringify(marker + "probeSupported:")} + JSON.stringify(this.probeSupported));
|
|
2463
|
+
const workers = this.ctx.config.maxWorkers;
|
|
2464
|
+
this.workers = Number.isSafeInteger(workers) && workers > 0 ? workers : undefined;
|
|
2465
|
+
if (this.workers !== undefined) console.log(${JSON.stringify(marker + "workers:")} + this.workers);
|
|
2466
|
+
else {
|
|
2467
|
+
const warning = "Internal reporter telemetry error: testWorkers=" + String(workers) + "; resolved worker budget unavailable, omitted";
|
|
2468
|
+
this.telemetryWarnings.push(warning);
|
|
2469
|
+
console.log(${JSON.stringify(marker + "telemetryWarning:")} + JSON.stringify(warning));
|
|
2470
|
+
}
|
|
2471
|
+
this.files = specifications.map(spec => relative(process.cwd(), spec.moduleId));
|
|
2472
|
+
process.send?.({ type: "selected", files: this.files });
|
|
2473
|
+
console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(this.files));
|
|
2474
|
+
}
|
|
2475
|
+
onTestModuleStart(module) {
|
|
2476
|
+
traceProcess("test-module-start");
|
|
2477
|
+
this.activeModules.add(module.moduleId);
|
|
2478
|
+
this.concurrency = Math.max(this.concurrency, this.activeModules.size);
|
|
2479
|
+
console.log(${JSON.stringify(marker + "concurrency:")} + this.concurrency);
|
|
2480
|
+
}
|
|
2481
|
+
onTestModuleCollected() {
|
|
2482
|
+
this.collected = true;
|
|
2483
|
+
process.send?.({ type: "collected" });
|
|
2484
|
+
console.log(${JSON.stringify(marker + "collected")});
|
|
2485
|
+
}
|
|
2486
|
+
onTestModuleEnd(module) {
|
|
2487
|
+
const file = relative(process.cwd(), module.moduleId);
|
|
2488
|
+
this.crashed ||= (module.errors?.() ?? []).some(error => workerDied(error));
|
|
2489
|
+
const timing = module.diagnostic();
|
|
2490
|
+
this.fileDurations[file] = timing.duration + timing.collectDuration + timing.prepareDuration + timing.setupDuration + timing.environmentSetupDuration;
|
|
2491
|
+
console.log(${JSON.stringify(marker + "fileDuration:")} + JSON.stringify({ file, duration: this.fileDurations[file] }));
|
|
2492
|
+
this.activeModules.delete(module.moduleId);
|
|
2493
|
+
}
|
|
2494
|
+
onTestCaseResult(test) {
|
|
2495
|
+
const result = test.result();
|
|
2496
|
+
this.crashed ||= (result.errors ?? []).some(error => workerDied(error));
|
|
2497
|
+
const state = result.state;
|
|
2498
|
+
if (state === "failed") { this.failed = true; process.send?.({ type: "failed" }); console.log(${JSON.stringify(marker + "failed")}); }
|
|
2499
|
+
if (state === "passed") {
|
|
2500
|
+
const start = test.diagnostic()?.startTime ?? 0;
|
|
2501
|
+
if (start > 0) this.firstTestStart = this.firstTestStart ? Math.min(this.firstTestStart, start) : start;
|
|
2502
|
+
const file = relative(process.cwd(), test.module.moduleId);
|
|
2503
|
+
this.durations[file] = Math.max(this.durations[file] ?? 0, test.diagnostic()?.duration ?? 0);
|
|
2504
|
+
this.timeouts[file] = Math.max(this.timeouts[file] ?? 0, test.options.timeout ?? 0);
|
|
2505
|
+
this.timeoutDetails[file + "::" + test.id] = test.options.timeout ?? 0;
|
|
2506
|
+
console.log(${JSON.stringify(marker + "duration:")} + JSON.stringify({ file, duration: this.durations[file], timeout: this.timeouts[file], key: file + "::" + test.id, start: this.firstTestStart }));
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
onTestRunEnd(modules, errors = [], state) {
|
|
2510
|
+
this.verdict = state ?? null;
|
|
2511
|
+
this.crashed ||= errors.some(error => workerDied(error)) || modules.some(module => workerDied(module.task) || (module.errors?.() ?? []).some(error => workerDied(error)));
|
|
2512
|
+
// Vitest's official run verdict also covers cancelled or pending modules.
|
|
2513
|
+
// Parallel bail can omit case-result hooks and module-end results.
|
|
2514
|
+
if ((state != null && state !== "passed") || (!this.ctx?.config.dangerouslyIgnoreUnhandledErrors && errors.length)) { this.failed = true; process.send?.({ type: "failed" }); console.log(${JSON.stringify(marker + "failed")}); }
|
|
2515
|
+
if (!this.files.length) console.log(${JSON.stringify(marker + "empty")});
|
|
2516
|
+
this.restore();
|
|
2517
|
+
}
|
|
2518
|
+
}`;
|
|
2519
|
+
var vitestHostSource = String.raw`
|
|
2520
|
+
import { createRequire } from "node:module";
|
|
2521
|
+
import { pathToFileURL } from "node:url";
|
|
2522
|
+
import { resolve } from "node:path";
|
|
2523
|
+
import { readFileSync } from "node:fs";
|
|
2524
|
+
const require = createRequire(resolve("package.json"));
|
|
2525
|
+
const { default: Reporter } = await import(pathToFileURL(process.argv[2]).href);
|
|
2526
|
+
${warmPolicySource}
|
|
2527
|
+
${workerDeathSource}
|
|
2528
|
+
let ctx;
|
|
2529
|
+
let reporter;
|
|
2530
|
+
const retained = () => {
|
|
2531
|
+
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 []; } }); }
|
|
2532
|
+
catch { return []; }
|
|
2533
|
+
};
|
|
2534
|
+
const setup = async fn => {
|
|
2535
|
+
const previous = process.env.MUTANT_CAFE_PROCESS_PHASE;
|
|
2536
|
+
process.env.MUTANT_CAFE_PROCESS_PHASE = "setup";
|
|
2537
|
+
try { return await fn(); } finally { if (previous === undefined) delete process.env.MUTANT_CAFE_PROCESS_PHASE; else process.env.MUTANT_CAFE_PROCESS_PHASE = previous; }
|
|
2538
|
+
};
|
|
2539
|
+
try {
|
|
2540
|
+
const version = JSON.parse(readFileSync(require.resolve("vitest/package.json"), "utf8")).version;
|
|
2541
|
+
const versionRefusal = warmRefusal(version, null);
|
|
2542
|
+
if (versionRefusal) throw new Error(versionRefusal);
|
|
2543
|
+
const { createVitest } = await import(pathToFileURL(require.resolve("vitest/node")).href);
|
|
2544
|
+
if (typeof createVitest !== "function") throw new Error("createVitest is unavailable");
|
|
2545
|
+
ctx = await setup(() => createVitest({ root: process.cwd(), run: true, watch: false, cache: false, fsModuleCache: false,
|
|
2546
|
+
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"; } }] }));
|
|
2547
|
+
if (typeof ctx.runTestSpecifications !== "function" || typeof ctx.invalidateFile !== "function"
|
|
2548
|
+
|| typeof ctx.cancelCurrentRun !== "function" || typeof ctx.getRelevantTestSpecifications !== "function" || typeof ctx.initializeGlobalSetup !== "function") {
|
|
2549
|
+
throw new Error("installed Vitest does not expose the supported warm API");
|
|
2550
|
+
}
|
|
2551
|
+
const refusal = warmRefusal(version, ctx, process.argv[3] === "select");
|
|
2552
|
+
if (refusal) throw new Error(refusal);
|
|
2553
|
+
const isolated = config => config.isolate !== false &&
|
|
2554
|
+
!Object.values(config.poolOptions ?? {}).some(pool => pool?.isolate === false);
|
|
2555
|
+
const script = JSON.parse(readFileSync(resolve("package.json"), "utf8")).scripts?.test ?? "";
|
|
2556
|
+
if (process.argv[3] !== "select" && (/(?:^|\s)--no-isolate(?:\s|$)|--isolate(?:=|\s+)false/.test(script) || !isolated(ctx.config) || !isolated(ctx.vite.config.test ?? {}) ||
|
|
2557
|
+
ctx.projects.some(project => !isolated(project.config) || !isolated(project.vite.config.test ?? {})))) {
|
|
2558
|
+
throw new Error("isolate: false (including poolOptions or --no-isolate) cannot reset module state");
|
|
2559
|
+
}
|
|
2560
|
+
const initialize = ctx.initializeGlobalSetup.bind(ctx);
|
|
2561
|
+
ctx.initializeGlobalSetup = (...args) => setup(async () => {
|
|
2562
|
+
const result = await initialize(...args);
|
|
2563
|
+
process.send({ type: "retained", pids: retained() });
|
|
2564
|
+
return result;
|
|
2565
|
+
});
|
|
2566
|
+
await setup(() => ctx.standalone());
|
|
2567
|
+
process.send({ type: "retained", pids: retained() });
|
|
2568
|
+
process.send({ type: "ready" });
|
|
2569
|
+
} catch (error) {
|
|
2570
|
+
process.send({ type: "fallback", message: String(error) });
|
|
2571
|
+
await ctx?.close();
|
|
2572
|
+
process.exit(0);
|
|
2573
|
+
}
|
|
2574
|
+
// invalidateFile clears Vitest's transform cache. Walk importers explicitly as
|
|
2575
|
+
// well, and queue every path for the pool's module runner invalidation boundary.
|
|
2576
|
+
function invalidate(file) {
|
|
2577
|
+
const paths = new Set([resolve(file)]);
|
|
2578
|
+
for (const project of ctx.projects) {
|
|
2579
|
+
for (const environment of Object.values(project.vite.environments)) {
|
|
2580
|
+
const seen = new Set();
|
|
2581
|
+
const visit = module => {
|
|
2582
|
+
if (seen.has(module)) return;
|
|
2583
|
+
seen.add(module);
|
|
2584
|
+
if (module.file) paths.add(module.file);
|
|
2585
|
+
for (const importer of module.importers) visit(importer);
|
|
2586
|
+
};
|
|
2587
|
+
for (const module of environment.moduleGraph.getModulesByFile(resolve(file)) ?? []) visit(module);
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
for (const path of paths) { ctx.invalidateFile(path); ctx.watcher.invalidates.add(path); }
|
|
2591
|
+
}
|
|
2592
|
+
const defaultReporters = ctx.reporters.filter(reporter => !(reporter instanceof Reporter));
|
|
2593
|
+
process.on("message", async request => {
|
|
2594
|
+
try {
|
|
2595
|
+
if (request.type === "close") { await ctx.close(); process.exit(0); }
|
|
2596
|
+
if (request.type === "cancel") { await ctx.cancelCurrentRun("keyboard-input"); return; }
|
|
2597
|
+
if (request.type === "invalidate") { invalidate(request.file); process.send({ type: "invalidated" }); return; }
|
|
2598
|
+
if (request.type === "ping") {
|
|
2599
|
+
if (!ctx.runningPromise) ctx.cancelPromise = undefined;
|
|
2600
|
+
const module = ctx.vite.moduleGraph?.getModuleById("\0mutant-cafe-health");
|
|
2601
|
+
if (module) ctx.vite.moduleGraph.invalidateModule(module);
|
|
2602
|
+
const transformed = await ctx.vite.transformRequest("virtual:mutant-cafe-health");
|
|
2603
|
+
if (!transformed?.code) throw new Error("health transform failed");
|
|
2604
|
+
process.send({ type: "healthy" });
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
if (request.type === "quiesce") {
|
|
2608
|
+
const pool = ctx.pool;
|
|
2609
|
+
ctx.pool = undefined;
|
|
2610
|
+
let closing;
|
|
2611
|
+
try { closing = pool?.close?.(); } catch { /* Disposable pool is already dead. */ }
|
|
2612
|
+
process.send({ type: "quiescing" });
|
|
2613
|
+
try { await closing; } catch { /* Parent verifies and reaps its children. */ }
|
|
2614
|
+
process.send({ type: "quiesced" });
|
|
2615
|
+
return;
|
|
2616
|
+
}
|
|
2617
|
+
if (request.type === "select") {
|
|
2618
|
+
ctx.config.related = [resolve(request.file)];
|
|
2619
|
+
const specs = await ctx.getRelevantTestSpecifications();
|
|
2620
|
+
process.send({ type: "selection", files: specs.map(spec => spec.moduleId) });
|
|
2621
|
+
return;
|
|
2622
|
+
}
|
|
2623
|
+
if (request.type !== "run") return;
|
|
2624
|
+
if (process.argv[3] === "select") {
|
|
2625
|
+
process.send({ type: "protocolError", message: "Selection-only host cannot execute tests" });
|
|
2626
|
+
return;
|
|
2627
|
+
}
|
|
2628
|
+
reporter = new Reporter(request.probe?.token ?? null, request.probe?.setupFile ?? null);
|
|
2629
|
+
reporter.onInit(ctx);
|
|
2630
|
+
ctx.reporters = [...defaultReporters, reporter];
|
|
2631
|
+
ctx.config.related = request.file ? [resolve(request.file)] : undefined;
|
|
2632
|
+
if (request.testTimeout === undefined) { delete ctx.configOverride.testTimeout; delete ctx.configOverride.hookTimeout; }
|
|
2633
|
+
else { ctx.configOverride.testTimeout = request.testTimeout; ctx.configOverride.hookTimeout = request.testTimeout; }
|
|
2634
|
+
const specs = await ctx.getRelevantTestSpecifications();
|
|
2635
|
+
// The shared adapter handles the full-suite fallback and remaining budget.
|
|
2636
|
+
const empty = specs.length === 0;
|
|
2637
|
+
let result;
|
|
2638
|
+
try { result = await ctx.runTestSpecifications(specs, !request.file); }
|
|
2639
|
+
catch (error) {
|
|
2640
|
+
// A thrown run error (for example a mutant breaking global setup) is a
|
|
2641
|
+
// failure, not evidence that the host or a worker died.
|
|
2642
|
+
console.error(error?.stack ?? String(error));
|
|
2643
|
+
reporter.failed = true;
|
|
2644
|
+
reporter.verdict = "failed";
|
|
2645
|
+
result = { unhandledErrors: [error] };
|
|
2646
|
+
}
|
|
2647
|
+
if (!["passed", "failed", "interrupted"].includes(reporter.verdict)) throw new Error("installed Vitest does not expose the supported current-run verdict");
|
|
2648
|
+
// Use the official current-run verdict, not retained module state. In a
|
|
2649
|
+
// parallel bail, child failures can exist while the module stays pending.
|
|
2650
|
+
process.send({ type: "retained", pids: retained() });
|
|
2651
|
+
const failed = reporter.failed || (!ctx.config.dangerouslyIgnoreUnhandledErrors && result.unhandledErrors.length > 0);
|
|
2652
|
+
process.send({ type: "result", status: failed ? "failed" : empty ? "untested" : "passed",
|
|
2653
|
+
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,
|
|
2654
|
+
telemetryWarnings: reporter.telemetryWarnings, crashed: reporter.crashed || result.unhandledErrors.some(error => workerDied(error)) });
|
|
2655
|
+
process.exitCode = 0;
|
|
2656
|
+
} catch (error) { reporter?.restore(); process.send({ type: "crash", message: String(error) }); }
|
|
2657
|
+
});
|
|
2658
|
+
`;
|
|
2659
|
+
|
|
2660
|
+
// packages/runner/src/WarmRunner.ts
|
|
2661
|
+
var Message = Schema8.Union([
|
|
2662
|
+
Schema8.Struct({ type: Schema8.Literal("ready") }),
|
|
2663
|
+
Schema8.Struct({ type: Schema8.Literal("retained"), pids: Schema8.Array(Schema8.Struct({ pid: Schema8.Int, birth: Schema8.String })) }),
|
|
2664
|
+
Schema8.Struct({ type: Schema8.Literal("invalidated") }),
|
|
2665
|
+
Schema8.Struct({ type: Schema8.Literal("collected") }),
|
|
2666
|
+
Schema8.Struct({ type: Schema8.Literal("failed") }),
|
|
2667
|
+
Schema8.Struct({ type: Schema8.Literal("selected"), files: Schema8.Array(Schema8.String) }),
|
|
2668
|
+
Schema8.Struct({ type: Schema8.Literal("selection"), files: Schema8.Array(Schema8.String) }),
|
|
2669
|
+
Schema8.Struct({ type: Schema8.Literal("probeLoaded") }),
|
|
2670
|
+
Schema8.Struct({ type: Schema8.Literal("quiescing") }),
|
|
2671
|
+
Schema8.Struct({ type: Schema8.Literal("quiesced") }),
|
|
2672
|
+
Schema8.Struct({ type: Schema8.Literal("healthy") }),
|
|
2673
|
+
Schema8.Struct({ type: Schema8.Literal("fallback"), message: Schema8.String }),
|
|
2674
|
+
Schema8.Struct({ type: Schema8.Literal("crash"), message: Schema8.String }),
|
|
2675
|
+
Schema8.Struct({
|
|
2676
|
+
type: Schema8.Literal("result"),
|
|
2677
|
+
status: Schema8.Literals(["passed", "failed", "untested"]),
|
|
2678
|
+
testFiles: Schema8.Array(Schema8.String),
|
|
2679
|
+
testsCollected: Schema8.Boolean,
|
|
2680
|
+
testDurations: Schema8.Record(Schema8.String, Schema8.Finite),
|
|
2681
|
+
testTimeouts: Schema8.Record(Schema8.String, Schema8.Finite),
|
|
2682
|
+
testWorkers: Schema8.optional(Schema8.Int),
|
|
2683
|
+
testConcurrency: Schema8.optional(Schema8.Int),
|
|
2684
|
+
telemetryWarnings: Schema8.optional(Schema8.Array(Schema8.String)),
|
|
2685
|
+
testFileDurations: Schema8.Record(Schema8.String, Schema8.Finite),
|
|
2686
|
+
firstTestStart: Schema8.Finite,
|
|
2687
|
+
probeSupported: Schema8.Boolean,
|
|
2688
|
+
probeLoaded: Schema8.Boolean,
|
|
2689
|
+
testTimeoutDetails: Schema8.Record(Schema8.String, Schema8.Finite),
|
|
2690
|
+
crashed: Schema8.Boolean
|
|
2691
|
+
})
|
|
2692
|
+
]);
|
|
2693
|
+
var ReporterMessageError = class extends Error {
|
|
2694
|
+
kind = "reporter";
|
|
2695
|
+
};
|
|
2696
|
+
function decodeWarmMessage(value) {
|
|
2697
|
+
try {
|
|
2698
|
+
const raw = Schema8.decodeUnknownSync(Schema8.Record(Schema8.String, Schema8.Unknown))(value);
|
|
2699
|
+
const cleaned = cleanTelemetry(raw, "warm message");
|
|
2700
|
+
if (raw.type === "result") {
|
|
2701
|
+
for (const [key, fallback] of Object.entries({ testDurations: {}, testTimeouts: {}, testFileDurations: {}, testTimeoutDetails: {}, firstTestStart: 0 }))
|
|
2702
|
+
if (cleaned.value[key] === void 0) Reflect.set(cleaned.value, key, fallback);
|
|
2703
|
+
const previous = cleaned.value.telemetryWarnings;
|
|
2704
|
+
Reflect.set(cleaned.value, "telemetryWarnings", [...Array.isArray(previous) ? previous : [], ...cleaned.warnings]);
|
|
2705
|
+
}
|
|
2706
|
+
return Schema8.decodeUnknownSync(Message)(cleaned.value);
|
|
2707
|
+
} catch (error3) {
|
|
2708
|
+
const actual = (() => {
|
|
2709
|
+
try {
|
|
2710
|
+
return JSON.stringify(value)?.slice(0, 4096) ?? String(value);
|
|
2711
|
+
} catch {
|
|
2712
|
+
return "[unserializable frame]";
|
|
2713
|
+
}
|
|
2714
|
+
})();
|
|
2715
|
+
throw new ReporterMessageError(`Internal warm reporter protocol error: ${String(error3)}; received ${actual}`);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
var Host = class {
|
|
2719
|
+
child;
|
|
2720
|
+
exited;
|
|
2721
|
+
tree;
|
|
2722
|
+
scope;
|
|
2723
|
+
output = "";
|
|
2724
|
+
collected = false;
|
|
2725
|
+
failed = false;
|
|
2726
|
+
testFiles = [];
|
|
2727
|
+
runPending;
|
|
2728
|
+
retained = [];
|
|
2729
|
+
pending;
|
|
2730
|
+
startup;
|
|
2731
|
+
quiescing;
|
|
2732
|
+
quiesced;
|
|
2733
|
+
constructor(root, script, reporter, tree, scope, selectionOnly = false, decode = decodeWarmMessage) {
|
|
2734
|
+
this.tree = tree;
|
|
2735
|
+
this.scope = scope;
|
|
2736
|
+
this.child = spawn(process.execPath, [script, reporter, selectionOnly ? "select" : "run"], {
|
|
2737
|
+
cwd: root,
|
|
2738
|
+
env: tree.env,
|
|
2739
|
+
detached: true,
|
|
2740
|
+
stdio: ["ignore", "pipe", "pipe", "ipc"]
|
|
2741
|
+
});
|
|
2742
|
+
if (this.child.pid) tree.addRoot(this.child.pid);
|
|
2743
|
+
this.startup = this.wait();
|
|
2744
|
+
this.child.stdout?.on("data", (chunk) => {
|
|
2745
|
+
this.output += String(chunk);
|
|
2746
|
+
});
|
|
2747
|
+
this.child.stderr?.on("data", (chunk) => {
|
|
2748
|
+
this.output += String(chunk);
|
|
2749
|
+
});
|
|
2750
|
+
this.child.on("message", (value) => {
|
|
2751
|
+
try {
|
|
2752
|
+
const message = decode(value);
|
|
2753
|
+
if (message.type === "retained") {
|
|
2754
|
+
this.retained = message.pids;
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
if (message.type === "quiescing") {
|
|
2758
|
+
this.quiescing?.();
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
if (message.type === "quiesced") {
|
|
2762
|
+
this.quiesced?.();
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
if (message.type === "collected") {
|
|
2766
|
+
this.collected = true;
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
if (message.type === "failed") {
|
|
2770
|
+
this.failed = true;
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
if (message.type === "probeLoaded") return;
|
|
2774
|
+
if (message.type === "selected") {
|
|
2775
|
+
this.testFiles = message.files;
|
|
2776
|
+
return;
|
|
2777
|
+
}
|
|
2778
|
+
const pending = this.pending;
|
|
2779
|
+
this.pending = void 0;
|
|
2780
|
+
pending?.resolve(message);
|
|
2781
|
+
} catch (error3) {
|
|
2782
|
+
this.pending?.reject(error3 instanceof ReporterMessageError ? error3 : new ReporterMessageError(String(error3)));
|
|
2783
|
+
}
|
|
2784
|
+
});
|
|
2785
|
+
this.exited = new Promise((resolve2) => this.child.once("close", () => {
|
|
2786
|
+
this.pending?.reject(new Error(`Vitest host exited: ${this.output.slice(-4e3)}`));
|
|
2787
|
+
this.pending = void 0;
|
|
2788
|
+
resolve2();
|
|
2789
|
+
}));
|
|
2790
|
+
this.child.on("error", (error3) => {
|
|
2791
|
+
this.pending?.reject(error3);
|
|
2792
|
+
this.pending = void 0;
|
|
2793
|
+
});
|
|
2794
|
+
}
|
|
2795
|
+
wait() {
|
|
2796
|
+
return new Promise((resolve2, reject) => {
|
|
2797
|
+
this.pending = { resolve: resolve2, reject };
|
|
2798
|
+
});
|
|
2799
|
+
}
|
|
2800
|
+
quiesce() {
|
|
2801
|
+
const started = new Promise((resolve2) => {
|
|
2802
|
+
this.quiescing = resolve2;
|
|
2803
|
+
});
|
|
2804
|
+
const done = new Promise((resolve2) => {
|
|
2805
|
+
this.quiesced = resolve2;
|
|
2806
|
+
});
|
|
2807
|
+
this.post({ type: "quiesce" });
|
|
2808
|
+
return { started, done };
|
|
2809
|
+
}
|
|
2810
|
+
ready() {
|
|
2811
|
+
return this.startup;
|
|
2812
|
+
}
|
|
2813
|
+
request(message) {
|
|
2814
|
+
const response = this.wait();
|
|
2815
|
+
this.post(message);
|
|
2816
|
+
return response;
|
|
2817
|
+
}
|
|
2818
|
+
post(message) {
|
|
2819
|
+
if (this.child.connected) this.child.send(message, (error3) => {
|
|
2820
|
+
if (error3) this.pending?.reject(error3);
|
|
2821
|
+
});
|
|
2822
|
+
else this.pending?.reject(new Error("Vitest host disconnected"));
|
|
2823
|
+
}
|
|
2824
|
+
close() {
|
|
2825
|
+
return Scope.close(this.scope, Exit.succeed(void 0));
|
|
2826
|
+
}
|
|
2827
|
+
grace() {
|
|
2828
|
+
const self = this;
|
|
2829
|
+
return Effect6.gen(function* () {
|
|
2830
|
+
self.post({ type: "close" });
|
|
2831
|
+
const exited = Effect6.promise(() => self.exited);
|
|
2832
|
+
const result5 = yield* exited.pipe(Effect6.interruptible, Effect6.timeout(500), Effect6.result);
|
|
2833
|
+
if (result5._tag === "Failure") yield* Effect6.sync(() => {
|
|
2834
|
+
self.child.kill("SIGKILL");
|
|
2835
|
+
});
|
|
2836
|
+
});
|
|
2837
|
+
}
|
|
2838
|
+
};
|
|
2839
|
+
var lifecycle = setupEffect2({ schemas: { events: {
|
|
2840
|
+
RUN: Schema8.Struct({}),
|
|
2841
|
+
DONE: Schema8.Struct({}),
|
|
2842
|
+
CANCEL: Schema8.Struct({}),
|
|
2843
|
+
RESTART: Schema8.Struct({}),
|
|
2844
|
+
READY: Schema8.Struct({}),
|
|
2845
|
+
FAIL: Schema8.Struct({}),
|
|
2846
|
+
FALLBACK: Schema8.Struct({})
|
|
2847
|
+
} } }).createMachine({
|
|
2848
|
+
initial: "idle",
|
|
2849
|
+
on: { FAIL: { target: ".failed" }, FALLBACK: { target: ".cold" } },
|
|
2850
|
+
states: {
|
|
2851
|
+
idle: { on: { RUN: { target: "running" }, RESTART: { target: "restarting" } } },
|
|
2852
|
+
running: { on: { DONE: { target: "idle" }, CANCEL: { target: "cancelling" }, RESTART: { target: "restarting" } } },
|
|
2853
|
+
cancelling: { on: { DONE: { target: "idle" }, RESTART: { target: "restarting" } } },
|
|
2854
|
+
restarting: { on: { READY: { target: "idle" } } },
|
|
2855
|
+
failed: { on: { FALLBACK: { target: "cold" } } },
|
|
2856
|
+
cold: { type: "final" }
|
|
2857
|
+
}
|
|
2858
|
+
});
|
|
2859
|
+
var openWarmRunner = Effect6.fn("TestRunner.openWarm")(function* (dir, onFallback, options = {}) {
|
|
2860
|
+
const fs = yield* FileSystem5.FileSystem;
|
|
2861
|
+
const parentScope = yield* Scope.Scope;
|
|
2862
|
+
const temp = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-warm-" });
|
|
2863
|
+
const script = `${temp}/host.mjs`;
|
|
2864
|
+
const reporter = `${temp}/reporter.mjs`;
|
|
2865
|
+
yield* fs.writeFileString(script, vitestHostSource);
|
|
2866
|
+
yield* fs.writeFileString(reporter, reporterSource("mutant-warm:"));
|
|
2867
|
+
const actor = yield* createEffectActor2(lifecycle);
|
|
2868
|
+
let host;
|
|
2869
|
+
const attempt = (fn12) => Effect6.tryPromise({
|
|
2870
|
+
try: fn12,
|
|
2871
|
+
catch: (error3) => new TestSpawnError({ command: ["vitest", "warm"], message: String(error3), ...error3 instanceof ReporterMessageError ? { kind: "reporter" } : {} })
|
|
2872
|
+
}).pipe(Effect6.interruptible);
|
|
2873
|
+
const close2 = () => host === void 0 ? Effect6.void : host.close();
|
|
2874
|
+
const abortHost = (error3) => Effect6.gen(function* () {
|
|
2875
|
+
yield* send2(actor, { type: "FAIL" });
|
|
2876
|
+
yield* close2();
|
|
2877
|
+
return yield* error3;
|
|
2878
|
+
});
|
|
2879
|
+
yield* Effect6.addFinalizer(() => close2().pipe(Effect6.orDie));
|
|
2880
|
+
const start = Effect6.gen(function* () {
|
|
2881
|
+
const scope = yield* Scope.make();
|
|
2882
|
+
yield* Effect6.addFinalizer(() => Scope.close(scope, Exit.succeed(void 0))).pipe(Effect6.provideService(Scope.Scope, parentScope));
|
|
2883
|
+
const tree = yield* acquireProcessTree(dir.path, options.onBackstop, options.processesSince).pipe(
|
|
2884
|
+
Effect6.provideService(Scope.Scope, scope),
|
|
2885
|
+
Effect6.provideService(FileSystem5.FileSystem, fs),
|
|
2886
|
+
Effect6.mapError((error3) => new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) }))
|
|
2887
|
+
);
|
|
2888
|
+
const active = new Host(dir.path, script, reporter, tree, scope, options.selectionOnly === true, options.decodeMessage);
|
|
2889
|
+
host = active;
|
|
2890
|
+
yield* Effect6.addFinalizer(() => active.grace()).pipe(Effect6.provideService(Scope.Scope, scope));
|
|
2891
|
+
const initialized = yield* attempt(() => host.ready()).pipe(
|
|
2892
|
+
Effect6.timeout(3e4),
|
|
2893
|
+
Effect6.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) })),
|
|
2894
|
+
Effect6.result
|
|
2895
|
+
);
|
|
2896
|
+
if (initialized._tag === "Failure") return yield* abortHost(initialized.failure);
|
|
2897
|
+
const ready = initialized.success;
|
|
2898
|
+
if (ready.type !== "ready") {
|
|
2899
|
+
if (!options.quiet) yield* (options.warn ?? Console3.warn)(`Warning: warm Vitest unavailable; using cold mode: ${"message" in ready ? ready.message : ready.type}`);
|
|
2900
|
+
yield* Effect6.sync(() => onFallback("message" in ready ? ready.message : `Unexpected startup frame: ${ready.type}`));
|
|
2901
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
2902
|
+
yield* close2();
|
|
2903
|
+
}
|
|
2904
|
+
});
|
|
2905
|
+
const retire = Effect6.gen(function* () {
|
|
2906
|
+
yield* send2(actor, { type: "RESTART" });
|
|
2907
|
+
yield* close2();
|
|
2908
|
+
});
|
|
2909
|
+
const restart = Effect6.gen(function* () {
|
|
2910
|
+
yield* retire;
|
|
2911
|
+
yield* start;
|
|
2912
|
+
yield* Effect6.sync(() => options.onRestart?.());
|
|
2913
|
+
if (actor.getSnapshot().value !== "cold") yield* send2(actor, { type: "READY" });
|
|
2914
|
+
});
|
|
2915
|
+
yield* start;
|
|
2916
|
+
const isCold = () => actor.getSnapshot().value === "cold";
|
|
2917
|
+
const invalidate = Effect6.fn("Warm.invalidate")(function* (file) {
|
|
2918
|
+
if (isCold() || actor.getSnapshot().value === "failed") return;
|
|
2919
|
+
if (actor.getSnapshot().value === "restarting") {
|
|
2920
|
+
yield* start;
|
|
2921
|
+
yield* Effect6.sync(() => options.onRestart?.());
|
|
2922
|
+
if (!isCold()) yield* send2(actor, { type: "READY" });
|
|
2923
|
+
return;
|
|
2924
|
+
}
|
|
2925
|
+
const result5 = yield* attempt(() => host.request({ type: "invalidate", file })).pipe(Effect6.timeout(1e3), Effect6.result);
|
|
2926
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
2927
|
+
if (result5._tag === "Failure") yield* restart;
|
|
2928
|
+
});
|
|
2929
|
+
const finish = Effect6.fn("Warm.finish")(function* (active, pending) {
|
|
2930
|
+
const pool = active.quiesce();
|
|
2931
|
+
const started = yield* attempt(() => pool.started).pipe(Effect6.timeout(500), Effect6.result);
|
|
2932
|
+
const clean = yield* active.tree.reap(active.child.pid === void 0 ? [] : [active.child.pid], active.retained);
|
|
2933
|
+
if (clean !== "clean" || started._tag === "Failure") return false;
|
|
2934
|
+
yield* attempt(() => pool.done).pipe(Effect6.timeout(100), Effect6.result);
|
|
2935
|
+
const settled = yield* attempt(() => pending).pipe(Effect6.timeout(500), Effect6.result);
|
|
2936
|
+
const health = settled._tag === "Success" ? yield* attempt(() => active.request({ type: "ping" })).pipe(Effect6.timeout(500), Effect6.result) : settled;
|
|
2937
|
+
return clean === "clean" && started._tag === "Success" && health._tag === "Success" && health.success.type === "healthy";
|
|
2938
|
+
});
|
|
2939
|
+
const run2 = Effect6.fn("Warm.run")(function* (file, timeoutMs, testTimeout, probe2) {
|
|
2940
|
+
if (isCold()) return void 0;
|
|
2941
|
+
if (options.selectionOnly) return yield* abortHost(new TestSpawnError({ command: ["vitest", "select"], kind: "reporter", message: "Selection-only host cannot execute tests" }));
|
|
2942
|
+
const command = ["vitest", ...file ? ["related", file, "--run"] : ["run"], "--reporter=default"];
|
|
2943
|
+
for (let crash = 0; crash < 2; crash++) {
|
|
2944
|
+
const active = host;
|
|
2945
|
+
active.output = "";
|
|
2946
|
+
active.collected = false;
|
|
2947
|
+
active.failed = false;
|
|
2948
|
+
active.testFiles = [];
|
|
2949
|
+
const started = yield* Clock3.currentTimeMillis;
|
|
2950
|
+
active.runPending = void 0;
|
|
2951
|
+
const budgetMs = timeoutMs ?? DEFAULT_BASELINE_TIMEOUT_MS;
|
|
2952
|
+
const operation = Effect6.gen(function* () {
|
|
2953
|
+
yield* active.tree.trace("warm-attempt-start", { budgetMs });
|
|
2954
|
+
yield* send2(actor, { type: "RUN" });
|
|
2955
|
+
const pending2 = active.request({ type: "run", file, testTimeout, probe: probe2 });
|
|
2956
|
+
active.runPending = pending2;
|
|
2957
|
+
return yield* attempt(() => pending2);
|
|
2958
|
+
});
|
|
2959
|
+
const result5 = yield* operation.pipe(Effect6.interruptible, Effect6.timeout(budgetMs), Effect6.result);
|
|
2960
|
+
const pending = active.runPending;
|
|
2961
|
+
if (result5._tag === "Success" && result5.success.type === "result" && !result5.success.crashed) {
|
|
2962
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2963
|
+
else yield* retire;
|
|
2964
|
+
return {
|
|
2965
|
+
...result5.success,
|
|
2966
|
+
startupMs: result5.success.firstTestStart > 0 ? Math.max(0, Math.ceil(result5.success.firstTestStart - started)) : 0,
|
|
2967
|
+
...active.child.pid === void 0 ? {} : { hostPid: active.child.pid },
|
|
2968
|
+
command,
|
|
2969
|
+
output: active.output,
|
|
2970
|
+
durationMs: (yield* Clock3.currentTimeMillis) - started
|
|
2971
|
+
};
|
|
2972
|
+
}
|
|
2973
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TimeoutError") {
|
|
2974
|
+
yield* Effect6.sync(() => options.onPoolReset?.());
|
|
2975
|
+
yield* active.tree.trace("warm-deadline", { budgetMs });
|
|
2976
|
+
const failedAtDeadline = active.failed;
|
|
2977
|
+
yield* send2(actor, { type: "CANCEL" });
|
|
2978
|
+
active.post({ type: "cancel" });
|
|
2979
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2980
|
+
else yield* retire;
|
|
2981
|
+
return {
|
|
2982
|
+
status: failedAtDeadline ? "failed" : "timedOut",
|
|
2983
|
+
command,
|
|
2984
|
+
output: active.output,
|
|
2985
|
+
durationMs: (yield* Clock3.currentTimeMillis) - started,
|
|
2986
|
+
...active.child.pid === void 0 ? {} : { hostPid: active.child.pid },
|
|
2987
|
+
testsCollected: active.collected,
|
|
2988
|
+
testFiles: active.testFiles
|
|
2989
|
+
};
|
|
2990
|
+
}
|
|
2991
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
2992
|
+
yield* Effect6.sync(() => options.onPoolReset?.());
|
|
2993
|
+
if (crash === 0) {
|
|
2994
|
+
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}`);
|
|
2995
|
+
if (pending && (yield* finish(active, pending))) yield* send2(actor, { type: "DONE" });
|
|
2996
|
+
else yield* restart;
|
|
2997
|
+
} else {
|
|
2998
|
+
yield* send2(actor, { type: "FAIL" });
|
|
2999
|
+
yield* close2();
|
|
3000
|
+
yield* Console3.warn("Warning: Vitest pool crashed twice for one mutant; using cold mode for the rest of this run");
|
|
3001
|
+
yield* Effect6.sync(() => onFallback("Vitest pool crashed twice for one mutant"));
|
|
3002
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
3003
|
+
}
|
|
3004
|
+
if (isCold()) return void 0;
|
|
3005
|
+
}
|
|
3006
|
+
return void 0;
|
|
3007
|
+
}, (effect5) => effect5.pipe(Effect6.onInterrupt(() => Effect6.gen(function* () {
|
|
3008
|
+
yield* send2(actor, { type: "CANCEL" });
|
|
3009
|
+
const active = host;
|
|
3010
|
+
yield* Effect6.sync(() => options.onPoolReset?.());
|
|
3011
|
+
active?.post({ type: "cancel" });
|
|
3012
|
+
if (active?.runPending && (yield* finish(active, active.runPending).pipe(Effect6.orDie))) yield* send2(actor, { type: "DONE" });
|
|
3013
|
+
else {
|
|
3014
|
+
yield* retire.pipe(Effect6.orDie);
|
|
3015
|
+
yield* Effect6.sync(() => onFallback("Interrupted run retired its unhealthy host"));
|
|
3016
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
3017
|
+
}
|
|
3018
|
+
}))));
|
|
3019
|
+
const disable = Effect6.gen(function* () {
|
|
3020
|
+
if (isCold()) return;
|
|
3021
|
+
yield* close2();
|
|
3022
|
+
yield* send2(actor, { type: "FALLBACK" });
|
|
3023
|
+
});
|
|
3024
|
+
const select = Effect6.fn("Warm.select")(function* (file) {
|
|
3025
|
+
if (isCold()) return void 0;
|
|
3026
|
+
const result5 = yield* attempt(() => host.request({ type: "select", file })).pipe(Effect6.timeout(3e4), Effect6.result);
|
|
3027
|
+
if (result5._tag === "Success" && result5.success.type === "selection") return result5.success.files;
|
|
3028
|
+
if (result5._tag === "Failure" && result5.failure._tag === "TestSpawnError" && result5.failure.kind === "reporter") return yield* abortHost(result5.failure);
|
|
3029
|
+
yield* restart;
|
|
3030
|
+
return void 0;
|
|
3031
|
+
});
|
|
3032
|
+
return { run: run2, invalidate, disable, select };
|
|
3033
|
+
});
|
|
3034
|
+
|
|
3035
|
+
// packages/runner/src/Mode.ts
|
|
3036
|
+
function startupCost(observed, copies) {
|
|
3037
|
+
return Math.max(0, copies - observed.length) * Math.max(0, ...observed);
|
|
3038
|
+
}
|
|
3039
|
+
function chooseMode(sample) {
|
|
3040
|
+
const fixedSaving = (sample.coldStartupMs ?? 0) - (sample.warmRunStartupMs ?? 0);
|
|
3041
|
+
const savingPerFile = (sample.coldMs - sample.warmMs - fixedSaving) / Math.max(1, sample.testFiles);
|
|
3042
|
+
const savingPerMutant = fixedSaving + savingPerFile;
|
|
3043
|
+
return sample.warmMs * 10 <= sample.coldMs * 9 && savingPerMutant * sample.mutants > sample.warmStartupMs ? "warm" : "cold";
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
// packages/runner/src/TestRunner.ts
|
|
3047
|
+
var baselineTimedOut = (timeoutMs, command) => new BaselineTimedOut({
|
|
3048
|
+
timeoutMs,
|
|
3049
|
+
command,
|
|
3050
|
+
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.`
|
|
3051
|
+
});
|
|
3052
|
+
var TestRunnerLive = Layer3.effect(TestRunner, Effect7.gen(function* () {
|
|
3053
|
+
const spawner = yield* ChildProcessSpawner5.ChildProcessSpawner;
|
|
3054
|
+
const fs = yield* FileSystem7.FileSystem;
|
|
3055
|
+
const path = yield* Path5.Path;
|
|
3056
|
+
let warmDisabled = false;
|
|
3057
|
+
let modeReason;
|
|
3058
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
3059
|
+
const auto = /* @__PURE__ */ new Map();
|
|
3060
|
+
const primers = /* @__PURE__ */ new Map();
|
|
3061
|
+
const backstopTotals = /* @__PURE__ */ new Map();
|
|
3062
|
+
let baselineBudgetMs = DEFAULT_BASELINE_TIMEOUT_MS;
|
|
3063
|
+
const lastCommands = /* @__PURE__ */ new Map();
|
|
3064
|
+
const onBackstop = (dir) => (ms) => {
|
|
3065
|
+
backstopTotals.set(dir, (backstopTotals.get(dir) ?? 0) + ms);
|
|
3066
|
+
};
|
|
3067
|
+
const scopes = /* @__PURE__ */ new Map();
|
|
3068
|
+
const openedAt = /* @__PURE__ */ new Map();
|
|
3069
|
+
const selectors = /* @__PURE__ */ new Map();
|
|
3070
|
+
let automaticMode = "pending";
|
|
3071
|
+
let hostRestarts = 0;
|
|
3072
|
+
let poolResets = 0;
|
|
3073
|
+
let warned = false;
|
|
3074
|
+
const warn7 = (message) => Effect7.suspend(() => {
|
|
3075
|
+
if (warned) return Effect7.void;
|
|
3076
|
+
warned = true;
|
|
3077
|
+
return Console4.warn(message);
|
|
3078
|
+
});
|
|
3079
|
+
const sessionOptions = { onRestart: () => {
|
|
3080
|
+
hostRestarts++;
|
|
3081
|
+
}, onPoolReset: () => {
|
|
3082
|
+
poolResets++;
|
|
3083
|
+
} };
|
|
3084
|
+
const execute2 = Effect7.fn("TestRunner.execute")(function* (dir, args, timeoutMs, testTimeoutMs, forceCold = false, probe2) {
|
|
3085
|
+
const overallMs = timeoutMs ?? baselineBudgetMs;
|
|
3086
|
+
const beforeBackstop = backstopTotals.get(dir.path) ?? 0;
|
|
3087
|
+
const backstopMs = () => Math.max(0, (backstopTotals.get(dir.path) ?? 0) - beforeBackstop);
|
|
3088
|
+
const session = sessions.get(dir.path);
|
|
3089
|
+
if (session !== void 0 && !warmDisabled && !auto.has(dir.path) && !forceCold) {
|
|
3090
|
+
if (timeoutMs === void 0) yield* Console4.error(`Baseline command: vitest run --reporter=default (warm Node API, cwd: ${dir.path})`);
|
|
3091
|
+
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);
|
|
3092
|
+
if (run3 !== void 0) return { ...run3, backstopMs: backstopMs(), exitCode: run3.status === "passed" || run3.status === "untested" ? 0 : 1 };
|
|
3093
|
+
}
|
|
1517
3094
|
const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
|
|
1518
|
-
|
|
3095
|
+
Effect7.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) }))
|
|
1519
3096
|
);
|
|
1520
3097
|
const reporter = path.join(reporterDir, "reporter.mjs");
|
|
3098
|
+
const launcher = path.join(reporterDir, "launch.mjs");
|
|
3099
|
+
yield* fs.writeFileString(launcher, vitestLauncherSource).pipe(Effect7.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
1521
3100
|
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) })));
|
|
3101
|
+
yield* fs.writeFileString(reporter, reporterSource(marker, probe2)).pipe(Effect7.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
1530
3102
|
const command = [
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
"vitest",
|
|
3103
|
+
process.execPath,
|
|
3104
|
+
launcher,
|
|
1534
3105
|
...args,
|
|
1535
3106
|
"--reporter=default",
|
|
1536
3107
|
`--reporter=${reporter}`,
|
|
1537
3108
|
"--bail",
|
|
1538
3109
|
"1",
|
|
1539
|
-
...timeoutMs === void 0 ? [] : ["--testTimeout", String(Math.max(1, Math.floor(timeoutMs / 2)))],
|
|
3110
|
+
...timeoutMs === void 0 ? [] : ["--testTimeout", String(testTimeoutMs ?? Math.max(1, Math.floor(timeoutMs / 2))), "--hookTimeout", String(testTimeoutMs ?? Math.max(1, Math.floor(timeoutMs / 2)))],
|
|
1540
3111
|
"--no-cache",
|
|
1541
3112
|
"--no-fsModuleCache"
|
|
1542
3113
|
];
|
|
1543
|
-
|
|
1544
|
-
const
|
|
3114
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
3115
|
+
const owned = yield* acquireProcessTree(dir.path, onBackstop(dir.path), openedAt.get(dir.path)).pipe(
|
|
3116
|
+
Effect7.provideService(FileSystem7.FileSystem, fs),
|
|
3117
|
+
Effect7.mapError((error3) => new TestSpawnError({ command, message: String(error3) }))
|
|
3118
|
+
);
|
|
1545
3119
|
const chunks = [];
|
|
1546
3120
|
let exitCode = 1;
|
|
1547
|
-
const child =
|
|
1548
|
-
|
|
3121
|
+
const child = Effect7.scoped(Effect7.gen(function* () {
|
|
3122
|
+
if (timeoutMs === void 0) yield* Console4.error(`Baseline command: ${formatTestCommand(command)} (cwd: ${dir.path})`);
|
|
3123
|
+
lastCommands.set(dir.path, command);
|
|
3124
|
+
yield* owned.trace("cold-spawn-start", { budgetMs: overallMs });
|
|
3125
|
+
const handle = yield* spawner.spawn(ChildProcess3.make(command[0], command.slice(1), {
|
|
1549
3126
|
cwd: dir.path,
|
|
3127
|
+
env: owned.env,
|
|
1550
3128
|
// Node's scoped spawner kills the detached process group, not just pnpm.
|
|
1551
3129
|
detached: true,
|
|
1552
3130
|
killSignal: "SIGKILL",
|
|
1553
3131
|
forceKillAfter: "100 millis",
|
|
1554
3132
|
stdin: "ignore"
|
|
1555
3133
|
}));
|
|
1556
|
-
|
|
3134
|
+
yield* Effect7.sync(() => owned.addRoot(handle.pid));
|
|
3135
|
+
yield* owned.trace("cold-spawn", { childPid: handle.pid });
|
|
3136
|
+
const collect = handle.all.pipe(Stream3.decodeText(), Stream3.runForEach((chunk) => Effect7.sync(() => {
|
|
1557
3137
|
chunks.push(chunk);
|
|
1558
3138
|
})));
|
|
1559
|
-
const [code] = yield*
|
|
3139
|
+
const [code] = yield* Effect7.all([handle.exitCode.pipe(Effect7.tap(() => owned.cleanup)), collect], { concurrency: "unbounded" });
|
|
1560
3140
|
exitCode = code;
|
|
1561
3141
|
return code === 0 ? "passed" : "failed";
|
|
1562
|
-
}));
|
|
1563
|
-
const status = yield*
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
3142
|
+
}).pipe(Effect7.onInterrupt(() => owned.cleanup)));
|
|
3143
|
+
const status = yield* child.pipe(
|
|
3144
|
+
Effect7.timeout(overallMs),
|
|
3145
|
+
Effect7.catchTag("TimeoutError", () => Effect7.sync(() => {
|
|
3146
|
+
exitCode = 124;
|
|
3147
|
+
chunks.push(`
|
|
3148
|
+
Vitest timed out after ${overallMs}ms overall, including startup.
|
|
3149
|
+
`);
|
|
3150
|
+
return "timedOut";
|
|
3151
|
+
}))
|
|
3152
|
+
).pipe(Effect7.mapError((error3) => new TestSpawnError({ command, message: error3.message })));
|
|
3153
|
+
yield* owned.cleanup;
|
|
3154
|
+
const ended = yield* Clock4.currentTimeMillis;
|
|
1568
3155
|
const output = chunks.join("");
|
|
1569
3156
|
const failed = output.includes(marker + "failed");
|
|
1570
3157
|
const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
|
|
1571
|
-
const selected = selection === void 0 ? [] : yield*
|
|
1572
|
-
|
|
3158
|
+
const selected = selection === void 0 ? [] : yield* Schema9.decodeEffect(Schema9.fromJsonString(Schema9.Array(Schema9.String)))(selection).pipe(
|
|
3159
|
+
Effect7.mapError((error3) => new TestSpawnError({ command, kind: "reporter", message: `Internal cold reporter protocol error in selected files: ${String(error3)}` }))
|
|
1573
3160
|
);
|
|
3161
|
+
const telemetryWarnings = [];
|
|
3162
|
+
for (const part of output.split(marker + "telemetryWarning:").slice(1)) {
|
|
3163
|
+
const warning = Schema9.decodeOption(Schema9.fromJsonString(Schema9.String))(part.split("\n")[0]);
|
|
3164
|
+
if (warning._tag === "Some") telemetryWarnings.push(warning.value);
|
|
3165
|
+
}
|
|
3166
|
+
const testDurations = {};
|
|
3167
|
+
const testFileDurations = {};
|
|
3168
|
+
let firstTestStart = 0;
|
|
3169
|
+
const testTimeouts = {};
|
|
3170
|
+
const testTimeoutDetails = {};
|
|
3171
|
+
for (const line of output.split("\n")) {
|
|
3172
|
+
const entry = line.split(marker + "duration:")[1];
|
|
3173
|
+
if (entry === void 0) continue;
|
|
3174
|
+
const decoded = Schema9.decodeOption(Schema9.fromJsonString(Schema9.Struct({ file: Schema9.String, duration: Schema9.Finite, timeout: Schema9.Finite, key: Schema9.String, start: Schema9.Finite })))(entry);
|
|
3175
|
+
if (decoded._tag === "None") {
|
|
3176
|
+
telemetryWarnings.push("Internal reporter telemetry error: invalid cold timing marker; omitted");
|
|
3177
|
+
continue;
|
|
3178
|
+
}
|
|
3179
|
+
const timing = decoded.value;
|
|
3180
|
+
if (timing.start > 0) firstTestStart = firstTestStart ? Math.min(firstTestStart, timing.start) : timing.start;
|
|
3181
|
+
testDurations[timing.file] = Math.max(testDurations[timing.file] ?? 0, timing.duration);
|
|
3182
|
+
testTimeoutDetails[timing.key] = timing.timeout;
|
|
3183
|
+
testTimeouts[timing.file] = Math.max(testTimeouts[timing.file] ?? 0, timing.timeout);
|
|
3184
|
+
}
|
|
3185
|
+
for (const part of output.split(marker + "fileDuration:").slice(1)) {
|
|
3186
|
+
const decoded = Schema9.decodeOption(Schema9.fromJsonString(Schema9.Struct({ file: Schema9.String, duration: Schema9.Finite })))(part.split("\n")[0]);
|
|
3187
|
+
if (decoded._tag === "None") {
|
|
3188
|
+
telemetryWarnings.push("Internal reporter telemetry error: invalid cold file timing marker; omitted");
|
|
3189
|
+
continue;
|
|
3190
|
+
}
|
|
3191
|
+
const timing = decoded.value;
|
|
3192
|
+
testFileDurations[timing.file] = timing.duration;
|
|
3193
|
+
}
|
|
1574
3194
|
const run2 = {
|
|
1575
3195
|
status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
|
|
1576
3196
|
durationMs: ended - started,
|
|
1577
3197
|
command,
|
|
1578
3198
|
output,
|
|
1579
3199
|
testsCollected: output.includes(marker + "collected"),
|
|
1580
|
-
testFiles: selected
|
|
3200
|
+
testFiles: selected,
|
|
3201
|
+
testDurations,
|
|
3202
|
+
testTimeouts,
|
|
3203
|
+
testTimeoutDetails,
|
|
3204
|
+
testFileDurations,
|
|
3205
|
+
startupMs: firstTestStart ? Math.max(0, Math.ceil(firstTestStart - started)) : 0,
|
|
3206
|
+
probeSupported: output.includes(marker + "probeSupported:true"),
|
|
3207
|
+
probeLoaded: output.includes(marker + "probeLoaded"),
|
|
3208
|
+
testWorkers: output.includes(marker + "workers:") ? Number(output.split(marker + "workers:")[1]?.split("\n")[0]) : void 0,
|
|
3209
|
+
testConcurrency: Math.max(0, ...output.split(marker + "concurrency:").slice(1).map((part) => Number(part.split("\n")[0])))
|
|
1581
3210
|
};
|
|
1582
|
-
|
|
1583
|
-
|
|
3211
|
+
const cleaned = cleanTelemetry(run2, "cold run");
|
|
3212
|
+
return { ...cleaned.value, backstopMs: backstopMs(), telemetryWarnings: [...telemetryWarnings, ...cleaned.warnings], exitCode };
|
|
3213
|
+
}, Effect7.scoped);
|
|
1584
3214
|
return TestRunner.of({
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
3215
|
+
stats: Effect7.sync(() => ({ hostRestarts, poolResets })),
|
|
3216
|
+
open: Effect7.fn("TestRunner.open")(function* (dir, cold, warm = false, mutants = 1) {
|
|
3217
|
+
scopes.set(dir.path, yield* Scope3.Scope);
|
|
3218
|
+
openedAt.set(dir.path, yield* Clock4.currentTimeMillis);
|
|
3219
|
+
yield* Effect7.addFinalizer(() => Effect7.sync(() => {
|
|
3220
|
+
sessions.delete(dir.path);
|
|
3221
|
+
selectors.delete(dir.path);
|
|
3222
|
+
auto.delete(dir.path);
|
|
3223
|
+
primers.delete(dir.path);
|
|
3224
|
+
scopes.delete(dir.path);
|
|
3225
|
+
backstopTotals.delete(dir.path);
|
|
3226
|
+
openedAt.delete(dir.path);
|
|
3227
|
+
lastCommands.delete(dir.path);
|
|
3228
|
+
if (scopes.size === 0) {
|
|
3229
|
+
baselineBudgetMs = DEFAULT_BASELINE_TIMEOUT_MS;
|
|
3230
|
+
warmDisabled = false;
|
|
3231
|
+
automaticMode = "pending";
|
|
3232
|
+
hostRestarts = 0;
|
|
3233
|
+
poolResets = 0;
|
|
3234
|
+
warned = false;
|
|
3235
|
+
modeReason = void 0;
|
|
3236
|
+
}
|
|
3237
|
+
}));
|
|
3238
|
+
if (cold) modeReason = "Explicit --cold";
|
|
3239
|
+
if (cold || warmDisabled || !warm && automaticMode === "cold") return;
|
|
3240
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
3241
|
+
const session = yield* openWarmRunner(dir, (reason) => {
|
|
3242
|
+
warmDisabled = true;
|
|
3243
|
+
modeReason = reason;
|
|
3244
|
+
}, { ...sessionOptions, quiet: !warm, warn: warn7, onBackstop: onBackstop(dir.path), processesSince: openedAt.get(dir.path) }).pipe(Effect7.provideService(FileSystem7.FileSystem, fs), Effect7.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "warm"], message: String(error3) })));
|
|
3245
|
+
sessions.set(dir.path, session);
|
|
3246
|
+
if (warmDisabled || !warm && automaticMode === "cold") {
|
|
3247
|
+
yield* session.disable;
|
|
3248
|
+
return;
|
|
3249
|
+
}
|
|
3250
|
+
if (warm) modeReason = "Explicit --warm; supported configuration";
|
|
3251
|
+
if (!warm && automaticMode === "pending") auto.set(dir.path, { startupMs: (yield* Clock4.currentTimeMillis) - started, mutants });
|
|
3252
|
+
}),
|
|
3253
|
+
invalidate: (dir, file) => sessions.get(dir.path)?.invalidate(file) ?? Effect7.void,
|
|
3254
|
+
selectRelated: Effect7.fn("TestRunner.selectRelated")(function* (dir, file) {
|
|
3255
|
+
const session = sessions.get(dir.path);
|
|
3256
|
+
if (session !== void 0 && !warmDisabled) return yield* session.select(file);
|
|
3257
|
+
let selector = selectors.get(dir.path) ?? selectors.values().next().value;
|
|
3258
|
+
if (!selector) {
|
|
3259
|
+
const scope = scopes.get(dir.path);
|
|
3260
|
+
if (!scope) return void 0;
|
|
3261
|
+
selector = yield* openWarmRunner(dir, () => {
|
|
3262
|
+
}, { quiet: true, selectionOnly: true, onBackstop: onBackstop(dir.path), processesSince: openedAt.get(dir.path) }).pipe(
|
|
3263
|
+
Effect7.provideService(FileSystem7.FileSystem, fs),
|
|
3264
|
+
Effect7.provideService(Scope3.Scope, scope),
|
|
3265
|
+
Effect7.mapError((error3) => error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "select"], message: String(error3) }))
|
|
3266
|
+
);
|
|
3267
|
+
selectors.set(dir.path, selector);
|
|
3268
|
+
}
|
|
3269
|
+
return yield* selector.select(file);
|
|
3270
|
+
}),
|
|
3271
|
+
probeReachability: Effect7.fn("TestRunner.probeReachability")(function* (dir, mutant, timeoutMs) {
|
|
3272
|
+
if (!dir.poison) return { file: mutant.file, status: "unsupported", durationMs: 0, testCommand: [], output: "Scratch adapter cannot poison modules" };
|
|
3273
|
+
const temporary = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-probe-" });
|
|
3274
|
+
const signal = path.join(temporary, "loaded");
|
|
3275
|
+
const control = path.join(temporary, "control");
|
|
3276
|
+
const token = `mutant-cafe-probe:${path.basename(temporary)}`;
|
|
3277
|
+
const setupFile = path.join(temporary, "setup.mjs");
|
|
3278
|
+
const vitest = yield* Effect7.try({
|
|
3279
|
+
try: () => pathToFileURL2(path.join(path.dirname(createRequire(path.join(dir.path, "package.json")).resolve("vitest/package.json")), "dist/index.js")).href,
|
|
3280
|
+
catch: (error3) => new TestSpawnError({ command: ["vitest", "probe"], message: String(error3) })
|
|
3281
|
+
});
|
|
3282
|
+
yield* fs.writeFileString(setupFile, `import { beforeAll, afterAll } from ${JSON.stringify(vitest)};
|
|
3283
|
+
beforeAll(() => globalThis.process.getBuiltinModule("node:fs").writeFileSync(${JSON.stringify(control)}, "ready"));
|
|
3284
|
+
afterAll(() => { if (globalThis[Symbol.for(${JSON.stringify(token)})]) throw new Error(${JSON.stringify(token)}); });`);
|
|
3285
|
+
const started = yield* Clock4.currentTimeMillis;
|
|
3286
|
+
const invalidate = () => sessions.get(dir.path)?.invalidate(mutant.file) ?? Effect7.void;
|
|
3287
|
+
const run2 = yield* Effect7.acquireUseRelease(
|
|
3288
|
+
dir.poison(mutant, signal, token),
|
|
3289
|
+
() => Effect7.gen(function* () {
|
|
3290
|
+
yield* invalidate();
|
|
3291
|
+
return yield* execute2(dir, ["run", "--passWithNoTests"], timeoutMs, void 0, false, { token, setupFile });
|
|
3292
|
+
}),
|
|
3293
|
+
() => dir.revert(mutant).pipe(Effect7.andThen(invalidate), Effect7.orDie)
|
|
3294
|
+
);
|
|
3295
|
+
const supported = yield* fs.exists(control);
|
|
3296
|
+
const loaded = (yield* fs.exists(signal)) || run2.probeLoaded === true;
|
|
3297
|
+
return {
|
|
3298
|
+
file: mutant.file,
|
|
3299
|
+
status: !supported ? "unsupported" : run2.status === "passed" && !loaded ? "unreachable" : "reachable",
|
|
3300
|
+
durationMs: (yield* Clock4.currentTimeMillis) - started,
|
|
3301
|
+
testCommand: run2.command,
|
|
3302
|
+
output: run2.output
|
|
3303
|
+
};
|
|
3304
|
+
}, (effect5) => effect5.pipe(Effect7.scoped, Effect7.mapError((error3) => error3._tag === "ScratchError" || error3._tag === "TestSpawnError" ? error3 : new TestSpawnError({ command: ["vitest", "probe"], message: String(error3) })))),
|
|
3305
|
+
baseline: Effect7.fn("TestRunner.baseline")(function* (dir, tsconfig, timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS) {
|
|
3306
|
+
baselineBudgetMs = timeoutMs;
|
|
3307
|
+
lastCommands.delete(dir.path);
|
|
3308
|
+
const unreliable = yield* preflight(dir.path, tsconfig, timeoutMs, { processesSince: openedAt.get(dir.path), onBackstop: onBackstop(dir.path) }).pipe(Effect7.provideService(FileSystem7.FileSystem, fs), Effect7.provideService(ChildProcessSpawner5.ChildProcessSpawner, spawner), Effect7.catch((error3) => error3._tag === "TestSpawnError" && error3.kind === "vitest-version" ? Effect7.fail(error3) : Effect7.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error3)}` }])));
|
|
3309
|
+
for (const issue of unreliable) yield* Console4.warn(`Warning (${issue.kind}): ${issue.reason}`);
|
|
1588
3310
|
if (unreliable.some((issue) => issue.kind === "runner")) {
|
|
1589
3311
|
const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
|
|
1590
|
-
yield*
|
|
1591
|
-
return { durationMs: 0, testCommand: command, unreliable };
|
|
3312
|
+
yield* Console4.warn(`Baseline command (not executed: unsupported runner): ${command.join(" ")}`);
|
|
3313
|
+
return { durationMs: 0, testCommand: command, unreliable, runnerMode: "cold", runnerModeReason: "Unsupported test runner" };
|
|
1592
3314
|
}
|
|
1593
|
-
const run2 = yield*
|
|
3315
|
+
const run2 = yield* execute2(dir, ["run", "--passWithNoTests"], void 0, void 0, auto.has(dir.path));
|
|
3316
|
+
if (run2.status === "timedOut") return yield* baselineTimedOut(timeoutMs, run2.command);
|
|
1594
3317
|
if (run2.status !== "passed" && run2.status !== "untested") {
|
|
1595
|
-
return yield*
|
|
3318
|
+
return yield* Effect7.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output, command: run2.command }));
|
|
1596
3319
|
}
|
|
1597
|
-
|
|
3320
|
+
if (sessions.has(dir.path)) yield* sessions.get(dir.path).invalidate(run2.testFiles?.[0] ?? "package.json");
|
|
3321
|
+
if (auto.has(dir.path)) primers.set(dir.path, run2);
|
|
3322
|
+
return {
|
|
3323
|
+
durationMs: run2.durationMs,
|
|
3324
|
+
testCommand: run2.command,
|
|
3325
|
+
unreliable,
|
|
3326
|
+
hostPid: run2.hostPid,
|
|
3327
|
+
telemetryWarnings: run2.telemetryWarnings,
|
|
3328
|
+
testTimeoutDetails: run2.testTimeoutDetails,
|
|
3329
|
+
testDurations: run2.testDurations,
|
|
3330
|
+
testTimeouts: run2.testTimeouts,
|
|
3331
|
+
testWorkers: run2.testWorkers,
|
|
3332
|
+
testConcurrency: run2.testConcurrency,
|
|
3333
|
+
testFileDurations: run2.testFileDurations,
|
|
3334
|
+
startupMs: run2.startupMs,
|
|
3335
|
+
probeSupported: run2.probeSupported,
|
|
3336
|
+
runnerModeReason: modeReason ?? (auto.has(dir.path) ? "Auto calibration pending" : "Cold execution; no warm session"),
|
|
3337
|
+
runnerMode: sessions.has(dir.path) && !warmDisabled && !auto.has(dir.path) ? "warm" : "cold"
|
|
3338
|
+
};
|
|
3339
|
+
}, (effect5, dir, _tsconfig, timeoutMs = DEFAULT_BASELINE_TIMEOUT_MS) => effect5.pipe(
|
|
3340
|
+
Effect7.timeout(timeoutMs),
|
|
3341
|
+
Effect7.catchTag("TimeoutError", () => Effect7.fail(baselineTimedOut(timeoutMs, lastCommands.get(dir.path) ?? [])))
|
|
3342
|
+
)),
|
|
3343
|
+
calibrate: Effect7.fn("TestRunner.calibrate")(function* (dir, mutants, copies) {
|
|
3344
|
+
const primer = primers.get(dir.path) ?? primers.values().next().value;
|
|
3345
|
+
if (!primer || automaticMode !== "pending" || auto.size === 0 || warmDisabled) return {};
|
|
3346
|
+
const disable = Effect7.gen(function* () {
|
|
3347
|
+
automaticMode = "cold";
|
|
3348
|
+
warmDisabled = true;
|
|
3349
|
+
auto.clear();
|
|
3350
|
+
for (const session of sessions.values()) yield* session.disable;
|
|
3351
|
+
});
|
|
3352
|
+
if (mutants <= (primer.testFiles?.length ?? 0)) {
|
|
3353
|
+
modeReason = `Auto: small selection (${mutants} testable mutants across ${primer.testFiles?.length ?? 0} files)`;
|
|
3354
|
+
yield* disable;
|
|
3355
|
+
return { runnerMode: "cold", runnerModeReason: modeReason, testableMutants: mutants };
|
|
3356
|
+
}
|
|
3357
|
+
const startups = [...auto.values()].map((entry) => entry.startupMs);
|
|
3358
|
+
auto.clear();
|
|
3359
|
+
const cold = yield* execute2(dir, ["run", "--passWithNoTests"], void 0, void 0, true);
|
|
3360
|
+
if (cold.status === "timedOut") return yield* baselineTimedOut(baselineBudgetMs, cold.command);
|
|
3361
|
+
if (cold.status !== "passed" && cold.status !== "untested") return yield* new BaselineFailed({ exitCode: cold.exitCode, output: cold.output, command: cold.command });
|
|
3362
|
+
const warm = yield* execute2(dir, ["run", "--passWithNoTests"]);
|
|
3363
|
+
if (warm.status === "timedOut") return yield* baselineTimedOut(baselineBudgetMs, warm.command);
|
|
3364
|
+
if (warm.status !== "passed" && warm.status !== "untested") return yield* new BaselineFailed({ exitCode: warm.exitCode, output: warm.output, command: warm.command });
|
|
3365
|
+
const calibration2 = {
|
|
3366
|
+
coldMs: cold.durationMs,
|
|
3367
|
+
warmMs: warm.durationMs,
|
|
3368
|
+
warmStartupMs: startupCost(startups, copies),
|
|
3369
|
+
overheadMs: warm.durationMs + cold.durationMs,
|
|
3370
|
+
coldStartupMs: cold.startupMs ?? 0,
|
|
3371
|
+
warmRunStartupMs: warm.startupMs ?? 0,
|
|
3372
|
+
testFiles: cold.testFiles?.length ?? 0,
|
|
3373
|
+
mutants
|
|
3374
|
+
};
|
|
3375
|
+
const sameSelection = JSON.stringify([...warm.testFiles ?? []].sort()) === JSON.stringify([...cold.testFiles ?? []].sort());
|
|
3376
|
+
const choice = !warmDisabled && warm.status === cold.status && sameSelection ? chooseMode(calibration2) : "cold";
|
|
3377
|
+
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}`;
|
|
3378
|
+
automaticMode = choice;
|
|
3379
|
+
auto.clear();
|
|
3380
|
+
if (choice === "cold") yield* disable;
|
|
3381
|
+
else if (sessions.has(dir.path)) yield* sessions.get(dir.path).invalidate(warm.testFiles?.[0] ?? "package.json");
|
|
3382
|
+
const run2 = choice === "cold" ? cold : warm;
|
|
3383
|
+
return { runnerMode: choice, runnerModeReason: modeReason, calibration: calibration2, testableMutants: mutants, hostPid: run2.hostPid };
|
|
1598
3384
|
}),
|
|
1599
|
-
runRelated:
|
|
1600
|
-
const related = yield*
|
|
3385
|
+
runRelated: Effect7.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs, testTimeoutMs) {
|
|
3386
|
+
const related = yield* execute2(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs, testTimeoutMs);
|
|
1601
3387
|
if (related.status !== "untested") return related;
|
|
1602
3388
|
const remaining = Math.max(1, timeoutMs - related.durationMs);
|
|
1603
|
-
const full = yield*
|
|
3389
|
+
const full = yield* execute2(dir, ["run", "--passWithNoTests"], remaining, testTimeoutMs);
|
|
1604
3390
|
return {
|
|
1605
3391
|
...full,
|
|
1606
3392
|
status: full.status === "passed" ? "untested" : full.status,
|
|
1607
3393
|
durationMs: related.durationMs + full.durationMs,
|
|
3394
|
+
backstopMs: (related.backstopMs ?? 0) + (full.backstopMs ?? 0),
|
|
1608
3395
|
output: related.output + "\nFull-suite fallback:\n" + full.output
|
|
1609
3396
|
};
|
|
1610
3397
|
})
|
|
@@ -1612,30 +3399,31 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
|
|
|
1612
3399
|
}));
|
|
1613
3400
|
|
|
1614
3401
|
// packages/runner/src/Run.ts
|
|
1615
|
-
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
1616
|
-
import { types } from "xstate";
|
|
1617
|
-
import * as
|
|
3402
|
+
import { createEffectActor as createEffectActor3, createEffectLogic as createEffectLogic2, join as join2, send as send3, setupEffect as setupEffect3 } from "@xstate/effect";
|
|
3403
|
+
import { types as types2 } from "xstate";
|
|
3404
|
+
import * as Effect8 from "effect/Effect";
|
|
3405
|
+
import * as Console5 from "effect/Console";
|
|
1618
3406
|
import * as Pool from "effect/Pool";
|
|
1619
|
-
import * as
|
|
1620
|
-
import * as
|
|
1621
|
-
import * as
|
|
1622
|
-
import * as
|
|
1623
|
-
import * as
|
|
3407
|
+
import * as Path7 from "effect/Path";
|
|
3408
|
+
import * as Result2 from "effect/Result";
|
|
3409
|
+
import * as Schema10 from "effect/Schema";
|
|
3410
|
+
import * as Scope5 from "effect/Scope";
|
|
3411
|
+
import * as Stream4 from "effect/Stream";
|
|
1624
3412
|
var ScratchPool = class {
|
|
1625
3413
|
value;
|
|
1626
3414
|
constructor(value) {
|
|
1627
3415
|
this.value = value;
|
|
1628
3416
|
}
|
|
1629
3417
|
};
|
|
1630
|
-
var runMutants =
|
|
3418
|
+
var runMutants = Effect8.fn("Runner.runMutants")(function* (config, mutants) {
|
|
1631
3419
|
const scratch = yield* Scratch;
|
|
1632
3420
|
const tests = yield* TestRunner;
|
|
1633
3421
|
const source = yield* MutantSource;
|
|
1634
3422
|
const reporter = yield* Reporter;
|
|
1635
|
-
const scope = yield*
|
|
1636
|
-
const path = yield*
|
|
3423
|
+
const scope = yield* Scope5.Scope;
|
|
3424
|
+
const path = yield* Path7.Path;
|
|
1637
3425
|
const jobs = Math.max(1, Math.floor(config.jobs));
|
|
1638
|
-
const report = (state2) => ({
|
|
3426
|
+
const report = (state2) => sanitizeReportTelemetry({
|
|
1639
3427
|
schemaVersion: 2,
|
|
1640
3428
|
tool: "mutant.cafe",
|
|
1641
3429
|
root: config.root,
|
|
@@ -1643,92 +3431,210 @@ var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
1643
3431
|
timeoutMs: state2.timeoutMs,
|
|
1644
3432
|
results: state2.results,
|
|
1645
3433
|
notMutated: state2.notMutated,
|
|
1646
|
-
|
|
3434
|
+
reachabilityProbes: state2.probes,
|
|
3435
|
+
hostRestarts: state2.hostRestarts,
|
|
3436
|
+
poolResets: state2.poolResets,
|
|
3437
|
+
...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
3438
|
${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
1648
|
-
});
|
|
1649
|
-
const capture = (effect5) =>
|
|
1650
|
-
const copying =
|
|
1651
|
-
const
|
|
1652
|
-
|
|
3439
|
+
}).report;
|
|
3440
|
+
const capture = (effect5) => Effect8.result(effect5);
|
|
3441
|
+
const copying = createEffectLogic2(({ input }) => capture(Effect8.gen(function* () {
|
|
3442
|
+
const acquire = Effect8.gen(function* () {
|
|
3443
|
+
const dir = yield* scratch.acquire(config.root);
|
|
3444
|
+
if (tests.open) yield* tests.open(dir, config.cold ?? false, config.warm ?? false, input);
|
|
3445
|
+
return dir;
|
|
3446
|
+
}).pipe(Effect8.mapError((error3) => error3._tag === "ScratchError" ? error3 : new ScratchError({ operation: "warm runner", path: config.root, message: String(error3) })));
|
|
3447
|
+
const pool = yield* Pool.make({ acquire, size: jobs }).pipe(
|
|
3448
|
+
Effect8.provideService(Scope5.Scope, scope)
|
|
1653
3449
|
);
|
|
1654
|
-
yield*
|
|
3450
|
+
yield* Effect8.scoped(Pool.get(pool));
|
|
1655
3451
|
return new ScratchPool(pool);
|
|
1656
3452
|
})));
|
|
1657
|
-
const baselining =
|
|
1658
|
-
if (input === void 0) return yield*
|
|
1659
|
-
const baseline = yield*
|
|
3453
|
+
const baselining = createEffectLogic2(({ input }) => capture(Effect8.gen(function* () {
|
|
3454
|
+
if (input === void 0) return yield* Effect8.die("Missing scratch pool");
|
|
3455
|
+
const baseline = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
1660
3456
|
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);
|
|
3457
|
+
return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig, config.baselineTimeoutMs);
|
|
1662
3458
|
}));
|
|
1663
3459
|
return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
|
|
1664
3460
|
})));
|
|
1665
|
-
const generating =
|
|
1666
|
-
const testing =
|
|
3461
|
+
const generating = createEffectLogic2(() => capture(Stream4.runCollect(mutants ?? source.generate(config))));
|
|
3462
|
+
const testing = createEffectLogic2(({ input }) => capture(Effect8.gen(function* () {
|
|
1667
3463
|
const dirs = input.state.pool?.value;
|
|
1668
|
-
if (dirs === void 0) return yield*
|
|
3464
|
+
if (dirs === void 0) return yield* Effect8.die("Missing scratch pool");
|
|
3465
|
+
const linkedRoots = yield* Effect8.scoped(Pool.get(dirs).pipe(Effect8.map((dir) => dir.linkedRoots ?? [])));
|
|
3466
|
+
const eligible = yield* excludeLinkedCandidates(config.root, input.state.pending, linkedRoots);
|
|
3467
|
+
for (const entry of eligible.notMutated) yield* input.skip(entry);
|
|
3468
|
+
const pending = eligible.mutants;
|
|
3469
|
+
let baseline = input.state.baseline;
|
|
3470
|
+
const viabilityById = /* @__PURE__ */ new Map();
|
|
3471
|
+
const preReported = /* @__PURE__ */ new Set();
|
|
3472
|
+
if (!config.cold && !config.warm && tests.calibrate) yield* Effect8.forEach(pending, (mutant) => Effect8.gen(function* () {
|
|
3473
|
+
const viability = yield* source.checkViable(mutant);
|
|
3474
|
+
viabilityById.set(mutant.id, viability);
|
|
3475
|
+
if (viability.analysisFailed) {
|
|
3476
|
+
preReported.add(mutant.id);
|
|
3477
|
+
yield* input.skip(viability.analysisFailed);
|
|
3478
|
+
} else if (!viability.viable) {
|
|
3479
|
+
preReported.add(mutant.id);
|
|
3480
|
+
const result5 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
3481
|
+
yield* input.record(result5);
|
|
3482
|
+
yield* reporter.progress(result5);
|
|
3483
|
+
}
|
|
3484
|
+
}), { concurrency: jobs, discard: true });
|
|
3485
|
+
const unreachable = /* @__PURE__ */ new Map();
|
|
3486
|
+
const selectRelated = tests.selectRelated;
|
|
3487
|
+
const probeReachability = tests.probeReachability;
|
|
3488
|
+
if (input.state.baseline.probeSupported && selectRelated && probeReachability) {
|
|
3489
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3490
|
+
const builtTests = input.state.baseline.unreliable?.flatMap((issue) => issue.kind === "built" ? issue.testFiles : []) ?? [];
|
|
3491
|
+
for (const mutant of pending) {
|
|
3492
|
+
if (viabilityById.has(mutant.id) && !viabilityById.get(mutant.id)?.viable) continue;
|
|
3493
|
+
const file = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
3494
|
+
if (seen.has(file)) continue;
|
|
3495
|
+
seen.add(file);
|
|
3496
|
+
if (unreliableFor(input.state.baseline, file, builtTests).length) continue;
|
|
3497
|
+
const probe2 = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
3498
|
+
const dir = yield* Pool.get(dirs);
|
|
3499
|
+
if (!dir.poison) return void 0;
|
|
3500
|
+
const files = yield* selectRelated(dir, file);
|
|
3501
|
+
if (files === void 0 || files.length) return void 0;
|
|
3502
|
+
return yield* probeReachability(dir, { ...mutant, file }, input.state.timeoutMs);
|
|
3503
|
+
}));
|
|
3504
|
+
if (probe2) {
|
|
3505
|
+
yield* input.probe(probe2);
|
|
3506
|
+
if (probe2.status === "unreachable") unreachable.set(file, probe2);
|
|
3507
|
+
}
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
const calibrate = tests.calibrate;
|
|
3511
|
+
if (calibrate) {
|
|
3512
|
+
const testable = pending.filter((mutant) => {
|
|
3513
|
+
const file = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
3514
|
+
return viabilityById.get(mutant.id)?.viable && !unreachable.has(file) && !unreliableFor(baseline, file).length;
|
|
3515
|
+
}).length;
|
|
3516
|
+
const selected = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
3517
|
+
const dir = yield* Pool.get(dirs);
|
|
3518
|
+
return yield* calibrate(dir, testable, config.jobs);
|
|
3519
|
+
}));
|
|
3520
|
+
baseline = { ...baseline, ...selected };
|
|
3521
|
+
yield* input.updateBaseline(baseline);
|
|
3522
|
+
}
|
|
3523
|
+
if (!config.cold && !config.warm) yield* Console5.warn(`Vitest auto mode: ${baseline.runnerMode ?? "cold"}; ${baseline.runnerModeReason ?? "Cold execution; no warm session"}`);
|
|
1669
3524
|
const neverBudgets = /* @__PURE__ */ new Map();
|
|
1670
|
-
|
|
3525
|
+
const neverLimits = /* @__PURE__ */ new Map();
|
|
3526
|
+
const neverBases = /* @__PURE__ */ new Map();
|
|
3527
|
+
const neverAllowances = /* @__PURE__ */ new Map();
|
|
3528
|
+
for (const mutant of pending) {
|
|
3529
|
+
if (viabilityById.has(mutant.id) && !viabilityById.get(mutant.id)?.viable) continue;
|
|
3530
|
+
if (unreachable.has(path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file)) continue;
|
|
1671
3531
|
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
|
-
|
|
3532
|
+
let probeTimeout = Math.max(1, Math.floor(input.state.timeoutMs / 2));
|
|
3533
|
+
const originalTimeouts = new Set(Object.values(baseline.testTimeoutDetails ?? {}));
|
|
3534
|
+
while (originalTimeouts.has(probeTimeout)) probeTimeout++;
|
|
3535
|
+
const measured = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
1673
3536
|
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);
|
|
3537
|
+
return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs, probeTimeout);
|
|
1675
3538
|
}));
|
|
1676
|
-
if (measured.status === "
|
|
3539
|
+
if (measured.status === "timedOut") return yield* new BaselineTimedOut({
|
|
3540
|
+
timeoutMs: input.state.timeoutMs,
|
|
3541
|
+
command: measured.command,
|
|
3542
|
+
message: `Clean related probe exceeded ${input.state.timeoutMs / 1e3} seconds. Increase --timeout for a longer probe.`
|
|
3543
|
+
});
|
|
3544
|
+
if (measured.status === "failed") {
|
|
1677
3545
|
return yield* new BaselineFailed({ exitCode: 1, output: measured.output, command: measured.command });
|
|
1678
3546
|
}
|
|
1679
|
-
|
|
3547
|
+
const files = measured.testFiles ?? Object.keys(measured.testDurations ?? baseline.testDurations ?? {});
|
|
3548
|
+
const slowest = Math.max(0, ...files.map((file) => baseline.testDurations?.[file] ?? measured.testDurations?.[file] ?? 0));
|
|
3549
|
+
const relatedDuration = baseline.testFileDurations === void 0 ? baseline.durationMs : files.reduce((sum, file) => sum + (baseline.testFileDurations?.[file] ?? 0), 0);
|
|
3550
|
+
neverAllowances.set(mutant.file, Math.ceil(relatedDuration) + (baseline.startupMs ?? 0));
|
|
3551
|
+
neverBases.set(mutant.file, slowest);
|
|
3552
|
+
neverBudgets.set(mutant.file, Math.max(2e3, config.neverTimeoutMs, Math.ceil(slowest * config.timeoutMultiplier)));
|
|
3553
|
+
const explicit = Object.entries(baseline.testTimeoutDetails ?? {}).filter(([key, value]) => value > 0 && measured.testTimeoutDetails?.[key] === value).map(([, value]) => value);
|
|
3554
|
+
neverLimits.set(mutant.file, Math.max(0, ...explicit));
|
|
1680
3555
|
}
|
|
1681
|
-
yield*
|
|
1682
|
-
|
|
1683
|
-
|
|
3556
|
+
yield* Stream4.fromIterable(pending).pipe(
|
|
3557
|
+
Stream4.mapEffect((mutant) => Effect8.scoped(Effect8.gen(function* () {
|
|
3558
|
+
if (preReported.has(mutant.id)) return;
|
|
3559
|
+
const viability = viabilityById.get(mutant.id) ?? (yield* source.checkViable(mutant));
|
|
1684
3560
|
if (viability.analysisFailed) {
|
|
1685
3561
|
yield* input.skip(viability.analysisFailed);
|
|
1686
3562
|
return;
|
|
1687
3563
|
}
|
|
1688
3564
|
if (!viability.viable) {
|
|
1689
|
-
const
|
|
1690
|
-
yield* input.record(
|
|
1691
|
-
yield* reporter.progress(
|
|
3565
|
+
const result6 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
3566
|
+
yield* input.record(result6);
|
|
3567
|
+
yield* reporter.progress(result6);
|
|
1692
3568
|
return;
|
|
1693
3569
|
}
|
|
1694
3570
|
const localFile = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
1695
3571
|
const unreliable = unreliableFor(input.state.baseline, localFile);
|
|
1696
3572
|
if (unreliable.length) {
|
|
1697
|
-
const
|
|
1698
|
-
yield* input.record(
|
|
1699
|
-
yield* reporter.progress(
|
|
3573
|
+
const result6 = { mutant, outcome: "unreliable", durationMs: 0, testCommand: input.state.baseline.testCommand, diagnostics: unreliable.map((issue) => issue.reason) };
|
|
3574
|
+
yield* input.record(result6);
|
|
3575
|
+
yield* reporter.progress(result6);
|
|
3576
|
+
return;
|
|
3577
|
+
}
|
|
3578
|
+
const cached = unreachable.get(localFile);
|
|
3579
|
+
if (cached) {
|
|
3580
|
+
const result6 = {
|
|
3581
|
+
mutant,
|
|
3582
|
+
outcome: "untested",
|
|
3583
|
+
durationMs: 0,
|
|
3584
|
+
testCommand: [],
|
|
3585
|
+
diagnostics: ["The full-suite module-load probe passed without loading this file"]
|
|
3586
|
+
};
|
|
3587
|
+
yield* input.record(result6);
|
|
3588
|
+
yield* reporter.progress(result6);
|
|
1700
3589
|
return;
|
|
1701
3590
|
}
|
|
1702
3591
|
const dir = yield* Pool.get(dirs);
|
|
1703
|
-
const
|
|
3592
|
+
const testTimeoutMs = mutant.genre === "EffectNever" ? neverBudgets.get(mutant.file) : void 0;
|
|
3593
|
+
const timeoutMs = testTimeoutMs === void 0 ? input.state.timeoutMs : Math.max(testTimeoutMs, neverLimits.get(mutant.file) ?? 0) + (neverAllowances.get(mutant.file) ?? 0);
|
|
3594
|
+
const run2 = yield* Effect8.acquireUseRelease(
|
|
1704
3595
|
dir.apply(mutant),
|
|
1705
|
-
() =>
|
|
1706
|
-
|
|
1707
|
-
|
|
3596
|
+
() => Effect8.gen(function* () {
|
|
3597
|
+
if (tests.invalidate) yield* tests.invalidate(dir, localFile);
|
|
3598
|
+
return yield* tests.runRelated(dir, localFile, timeoutMs, testTimeoutMs);
|
|
3599
|
+
}),
|
|
3600
|
+
// Restore and re-invalidate even on interruption before leasing again.
|
|
3601
|
+
() => Effect8.gen(function* () {
|
|
3602
|
+
yield* dir.revert(mutant);
|
|
3603
|
+
if (tests.invalidate) yield* tests.invalidate(dir, localFile);
|
|
3604
|
+
}).pipe(Effect8.orDie)
|
|
1708
3605
|
);
|
|
1709
3606
|
const selectedIssues = unreliableFor(input.state.baseline, localFile, run2.testFiles);
|
|
1710
|
-
const
|
|
3607
|
+
const result5 = {
|
|
1711
3608
|
mutant,
|
|
1712
3609
|
// A kill before collection proves nothing about whether tests noticed.
|
|
1713
3610
|
outcome: selectedIssues.length ? "unreliable" : run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
|
|
1714
3611
|
durationMs: run2.durationMs,
|
|
3612
|
+
timeoutMs: testTimeoutMs ?? timeoutMs,
|
|
3613
|
+
outerTimeoutMs: timeoutMs,
|
|
3614
|
+
...testTimeoutMs === void 0 ? {} : { hangBudgetBaseMs: neverBases.get(mutant.file) },
|
|
3615
|
+
backstopMs: run2.backstopMs,
|
|
3616
|
+
telemetryWarnings: run2.telemetryWarnings,
|
|
3617
|
+
testWorkers: run2.testWorkers,
|
|
3618
|
+
testConcurrency: run2.testConcurrency,
|
|
1715
3619
|
testCommand: run2.command,
|
|
1716
3620
|
diagnostics: selectedIssues.map((issue) => issue.reason),
|
|
1717
3621
|
...run2.output === "" ? {} : { output: run2.output }
|
|
1718
3622
|
};
|
|
1719
|
-
yield* input.record(
|
|
1720
|
-
yield* reporter.progress(
|
|
3623
|
+
yield* input.record(result5);
|
|
3624
|
+
yield* reporter.progress(result5);
|
|
1721
3625
|
})), { concurrency: jobs }),
|
|
1722
|
-
|
|
3626
|
+
Stream4.runDrain
|
|
1723
3627
|
);
|
|
1724
3628
|
})));
|
|
1725
|
-
const reporting =
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
3629
|
+
const reporting = createEffectLogic2(({ input }) => capture(Effect8.gen(function* () {
|
|
3630
|
+
const stats = yield* tests.stats ?? Effect8.succeed({ hostRestarts: 0, poolResets: 0 });
|
|
3631
|
+
if (!input.reported) yield* reporter.write({ ...report(input), ...stats });
|
|
3632
|
+
return stats;
|
|
3633
|
+
})));
|
|
3634
|
+
const machine = setupEffect3({
|
|
1729
3635
|
schemas: {
|
|
1730
|
-
context:
|
|
1731
|
-
events: { CANCEL:
|
|
3636
|
+
context: types2(),
|
|
3637
|
+
events: { CANCEL: Schema10.Struct({}), RESULT: Schema10.Struct({ result: MutantResult }), SKIP: Schema10.Struct({ entry: NotMutated }), PROBE: Schema10.Struct({ entry: ReachabilityProbe }), BASELINE: Schema10.Struct({ entry: Baseline }) }
|
|
1732
3638
|
},
|
|
1733
3639
|
actors: { copying, baselining, generating, testing, reporting }
|
|
1734
3640
|
}).createMachine({
|
|
@@ -1740,39 +3646,46 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1740
3646
|
pending: [],
|
|
1741
3647
|
results: [],
|
|
1742
3648
|
reported: false,
|
|
1743
|
-
notMutated: []
|
|
3649
|
+
notMutated: [],
|
|
3650
|
+
probes: [],
|
|
3651
|
+
hostRestarts: 0,
|
|
3652
|
+
poolResets: 0
|
|
1744
3653
|
},
|
|
1745
3654
|
output: ({ context }) => context,
|
|
1746
3655
|
initial: "generating",
|
|
1747
3656
|
on: {
|
|
1748
3657
|
CANCEL: { target: ".interrupted" },
|
|
3658
|
+
BASELINE: ({ context, event }) => ({ context: { ...context, baseline: event.entry } }),
|
|
3659
|
+
PROBE: ({ context, event }) => ({ context: { ...context, probes: [...context.probes, event.entry] } }),
|
|
1749
3660
|
SKIP: ({ context, event }) => ({ context: { ...context, notMutated: [...new Map([...context.notMutated, event.entry].map((entry) => [JSON.stringify(entry), entry])).values()] } }),
|
|
1750
3661
|
RESULT: ({ context, event }) => ({ context: { ...context, results: [...context.results, event.result] } })
|
|
1751
3662
|
},
|
|
1752
3663
|
states: {
|
|
1753
|
-
copying: { invoke: { src: "copying", onDone: ({ context, event }) =>
|
|
3664
|
+
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
3665
|
baseline: { invoke: {
|
|
1755
3666
|
src: "baselining",
|
|
1756
3667
|
input: ({ context }) => context.pool,
|
|
1757
|
-
onDone: ({ context, event }) =>
|
|
3668
|
+
onDone: ({ context, event }) => Result2.isSuccess(event.output) ? { target: "testing", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
|
|
1758
3669
|
...context,
|
|
1759
3670
|
failure: event.output.failure,
|
|
1760
|
-
baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
3671
|
+
baseline: event.output.failure._tag === "BaselineFailed" || event.output.failure._tag === "BaselineTimedOut" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
1761
3672
|
} }
|
|
1762
3673
|
} },
|
|
1763
|
-
generating: { invoke: { src: "generating", onDone: ({ context, event }) =>
|
|
3674
|
+
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
3675
|
testing: { invoke: {
|
|
1765
3676
|
src: "testing",
|
|
1766
3677
|
input: ({ context, self }) => ({
|
|
1767
3678
|
state: context,
|
|
1768
3679
|
// Queue completion before progress can trigger CANCEL. The parent's
|
|
1769
3680
|
// FIFO mailbox commits this result before handling that cancellation.
|
|
1770
|
-
record: (
|
|
1771
|
-
skip: (entry) =>
|
|
3681
|
+
record: (result5) => send3(self, { type: "RESULT", result: result5 }),
|
|
3682
|
+
skip: (entry) => send3(self, { type: "SKIP", entry }),
|
|
3683
|
+
probe: (entry) => send3(self, { type: "PROBE", entry }),
|
|
3684
|
+
updateBaseline: (entry) => send3(self, { type: "BASELINE", entry })
|
|
1772
3685
|
}),
|
|
1773
3686
|
onDone: ({ context, event }) => ({ target: "reporting", context: {
|
|
1774
3687
|
...context,
|
|
1775
|
-
failure:
|
|
3688
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1776
3689
|
} })
|
|
1777
3690
|
} },
|
|
1778
3691
|
reporting: { invoke: {
|
|
@@ -1780,8 +3693,9 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1780
3693
|
input: ({ context }) => context,
|
|
1781
3694
|
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
1782
3695
|
...context,
|
|
1783
|
-
|
|
1784
|
-
|
|
3696
|
+
...Result2.isSuccess(event.output) ? event.output.success : {},
|
|
3697
|
+
reported: Result2.isSuccess(event.output),
|
|
3698
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1785
3699
|
} })
|
|
1786
3700
|
} },
|
|
1787
3701
|
interrupted: { invoke: {
|
|
@@ -1789,57 +3703,58 @@ ${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
|
1789
3703
|
input: ({ context }) => context,
|
|
1790
3704
|
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
1791
3705
|
...context,
|
|
1792
|
-
|
|
1793
|
-
|
|
3706
|
+
...Result2.isSuccess(event.output) ? event.output.success : {},
|
|
3707
|
+
reported: Result2.isSuccess(event.output),
|
|
3708
|
+
failure: Result2.isFailure(event.output) ? event.output.failure : context.failure
|
|
1794
3709
|
} })
|
|
1795
3710
|
} },
|
|
1796
3711
|
failed: { type: "final" },
|
|
1797
3712
|
done: { type: "final" }
|
|
1798
3713
|
}
|
|
1799
3714
|
});
|
|
1800
|
-
const state = yield*
|
|
1801
|
-
const actor = yield*
|
|
1802
|
-
return yield*
|
|
1803
|
-
yield*
|
|
1804
|
-
yield*
|
|
3715
|
+
const state = yield* Effect8.scoped(Effect8.gen(function* () {
|
|
3716
|
+
const actor = yield* createEffectActor3(machine);
|
|
3717
|
+
return yield* join2(actor).pipe(Effect8.orDie, Effect8.onInterrupt(() => Effect8.gen(function* () {
|
|
3718
|
+
yield* send3(actor, { type: "CANCEL" });
|
|
3719
|
+
yield* join2(actor).pipe(Effect8.orDie);
|
|
1805
3720
|
})));
|
|
1806
3721
|
}));
|
|
1807
3722
|
if (state.failure !== void 0) return yield* state.failure;
|
|
1808
3723
|
return report(state);
|
|
1809
|
-
},
|
|
3724
|
+
}, Effect8.scoped);
|
|
1810
3725
|
|
|
1811
3726
|
// packages/cli/src/bin.ts
|
|
1812
|
-
import * as
|
|
3727
|
+
import * as Effect13 from "effect/Effect";
|
|
1813
3728
|
import * as Layer5 from "effect/Layer";
|
|
1814
|
-
import * as
|
|
3729
|
+
import * as Stream8 from "effect/Stream";
|
|
1815
3730
|
|
|
1816
3731
|
// packages/cli/src/Command.ts
|
|
1817
|
-
import * as
|
|
1818
|
-
import * as
|
|
1819
|
-
import * as
|
|
3732
|
+
import * as Console7 from "effect/Console";
|
|
3733
|
+
import * as Effect12 from "effect/Effect";
|
|
3734
|
+
import * as FileSystem15 from "effect/FileSystem";
|
|
1820
3735
|
import * as Option from "effect/Option";
|
|
1821
|
-
import * as
|
|
3736
|
+
import * as Path15 from "effect/Path";
|
|
1822
3737
|
import * as Ref from "effect/Ref";
|
|
1823
|
-
import * as
|
|
1824
|
-
import * as
|
|
3738
|
+
import * as Schema14 from "effect/Schema";
|
|
3739
|
+
import * as Stream7 from "effect/Stream";
|
|
1825
3740
|
import * as Command from "effect/cli/Command";
|
|
1826
3741
|
import * as Flag from "effect/cli/Flag";
|
|
1827
3742
|
|
|
1828
3743
|
// packages/cli/src/Diff.ts
|
|
1829
|
-
import * as
|
|
1830
|
-
import * as
|
|
1831
|
-
import * as
|
|
1832
|
-
import * as
|
|
1833
|
-
import * as
|
|
1834
|
-
import * as
|
|
1835
|
-
var DiffMismatch = class extends
|
|
1836
|
-
path:
|
|
1837
|
-
message:
|
|
3744
|
+
import * as Effect9 from "effect/Effect";
|
|
3745
|
+
import * as FileSystem9 from "effect/FileSystem";
|
|
3746
|
+
import * as Path9 from "effect/Path";
|
|
3747
|
+
import * as Schema11 from "effect/Schema";
|
|
3748
|
+
import * as Stream5 from "effect/Stream";
|
|
3749
|
+
import * as ChildProcess4 from "effect/process/ChildProcess";
|
|
3750
|
+
var DiffMismatch = class extends Schema11.TaggedError()("DiffMismatch", {
|
|
3751
|
+
path: Schema11.String,
|
|
3752
|
+
message: Schema11.String
|
|
1838
3753
|
}) {
|
|
1839
3754
|
};
|
|
1840
|
-
var parseDiff = (text, path) =>
|
|
3755
|
+
var parseDiff = (text, path) => Effect9.try({
|
|
1841
3756
|
try: () => {
|
|
1842
|
-
const
|
|
3757
|
+
const fail4 = (message) => {
|
|
1843
3758
|
throw new DiffParseError({ path, message });
|
|
1844
3759
|
};
|
|
1845
3760
|
if (text === "") return [];
|
|
@@ -1851,12 +3766,12 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1851
3766
|
while (i < input.length) {
|
|
1852
3767
|
const line = input[i++];
|
|
1853
3768
|
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("--- "))
|
|
3769
|
+
if (!line.startsWith("--- ")) fail4("Expected a unified diff file header");
|
|
1855
3770
|
const next = input[i++];
|
|
1856
|
-
if (!next?.startsWith("+++ "))
|
|
3771
|
+
if (!next?.startsWith("+++ ")) fail4("Missing new-side file header");
|
|
1857
3772
|
const raw = next.slice(4).split(" ")[0];
|
|
1858
3773
|
const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
|
|
1859
|
-
if (typeof decoded !== "string")
|
|
3774
|
+
if (typeof decoded !== "string") fail4("Invalid file path");
|
|
1860
3775
|
const file = String(decoded).replace(/^b\//, "");
|
|
1861
3776
|
const lines2 = [];
|
|
1862
3777
|
let hunks = 0;
|
|
@@ -1864,22 +3779,22 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1864
3779
|
let previousOldEnd = 0;
|
|
1865
3780
|
while (input[i]?.startsWith("@@")) {
|
|
1866
3781
|
const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
|
|
1867
|
-
if (!match2)
|
|
3782
|
+
if (!match2) fail4("Invalid hunk header");
|
|
1868
3783
|
let oldRemaining = Number(match2[2] ?? 1);
|
|
1869
3784
|
let newRemaining = Number(match2[4] ?? 1);
|
|
1870
3785
|
let newLine = Number(match2[3]);
|
|
1871
3786
|
const oldStart = Number(match2[1]);
|
|
1872
3787
|
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)
|
|
3788
|
+
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail4("Hunk range is not a safe integer");
|
|
3789
|
+
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail4("Nonempty hunk cannot start at zero");
|
|
3790
|
+
if (newLine < previousEnd || oldStart < previousOldEnd) fail4("Overlapping or unordered hunks");
|
|
1876
3791
|
let previousPrefix = "";
|
|
1877
3792
|
const markNoNewline = () => {
|
|
1878
3793
|
if (previousPrefix === "+" || previousPrefix === " ") {
|
|
1879
3794
|
const last = lines2.at(-1);
|
|
1880
|
-
if (last === void 0 || last.noNewline)
|
|
3795
|
+
if (last === void 0 || last.noNewline) fail4("Unexpected no-newline marker");
|
|
1881
3796
|
lines2[lines2.length - 1] = { ...last, noNewline: true };
|
|
1882
|
-
} else if (previousPrefix !== "-")
|
|
3797
|
+
} else if (previousPrefix !== "-") fail4("Unexpected no-newline marker");
|
|
1883
3798
|
previousPrefix = "";
|
|
1884
3799
|
};
|
|
1885
3800
|
hunks++;
|
|
@@ -1889,15 +3804,15 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1889
3804
|
markNoNewline();
|
|
1890
3805
|
continue;
|
|
1891
3806
|
}
|
|
1892
|
-
if (body === void 0)
|
|
3807
|
+
if (body === void 0) fail4("Truncated hunk");
|
|
1893
3808
|
const prefix = body[0];
|
|
1894
3809
|
if (prefix === " " || prefix === "-") oldRemaining--;
|
|
1895
3810
|
if (prefix === " " || prefix === "+") {
|
|
1896
3811
|
newRemaining--;
|
|
1897
3812
|
lines2.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
|
|
1898
|
-
} else if (prefix !== "-")
|
|
3813
|
+
} else if (prefix !== "-") fail4("Invalid hunk line");
|
|
1899
3814
|
previousPrefix = prefix;
|
|
1900
|
-
if (oldRemaining < 0 || newRemaining < 0)
|
|
3815
|
+
if (oldRemaining < 0 || newRemaining < 0) fail4("Hunk count does not match its body");
|
|
1901
3816
|
}
|
|
1902
3817
|
if (input[i] === "\") {
|
|
1903
3818
|
markNoNewline();
|
|
@@ -1906,28 +3821,28 @@ var parseDiff = (text, path) => Effect6.try({
|
|
|
1906
3821
|
previousEnd = newLine;
|
|
1907
3822
|
previousOldEnd = oldStart + oldCount;
|
|
1908
3823
|
}
|
|
1909
|
-
if (hunks === 0)
|
|
3824
|
+
if (hunks === 0) fail4("File has no hunks");
|
|
1910
3825
|
sawFile = true;
|
|
1911
3826
|
if (file !== "/dev/null") patches.push({ file, lines: lines2 });
|
|
1912
3827
|
}
|
|
1913
|
-
if (!sawFile)
|
|
3828
|
+
if (!sawFile) fail4("No unified diff found");
|
|
1914
3829
|
return patches;
|
|
1915
3830
|
},
|
|
1916
|
-
catch: (error3) =>
|
|
3831
|
+
catch: (error3) => Schema11.is(DiffParseError)(error3) ? error3 : new DiffParseError({ path, message: String(error3) })
|
|
1917
3832
|
});
|
|
1918
|
-
var selectDiffScope =
|
|
1919
|
-
const fs = yield*
|
|
1920
|
-
const path = yield*
|
|
3833
|
+
var selectDiffScope = Effect9.fn("selectDiffScope")(function* (options) {
|
|
3834
|
+
const fs = yield* FileSystem9.FileSystem;
|
|
3835
|
+
const path = yield* Path9.Path;
|
|
1921
3836
|
const diffPath = path.resolve(options.root, options.diffPath);
|
|
1922
|
-
const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(
|
|
3837
|
+
const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(Effect9.mapError((error3) => new DiffParseError({ path: diffPath, message: String(error3) }))));
|
|
1923
3838
|
const patches = yield* parseDiff(text, diffPath);
|
|
1924
|
-
const gitRoot = yield*
|
|
1925
|
-
const handle = yield*
|
|
1926
|
-
const [output, code] = yield*
|
|
3839
|
+
const gitRoot = yield* Effect9.scoped(Effect9.gen(function* () {
|
|
3840
|
+
const handle = yield* ChildProcess4.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
|
|
3841
|
+
const [output, code] = yield* Effect9.all([Stream5.mkString(Stream5.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
|
|
1927
3842
|
if (Number(code) !== 0 || !output.trim()) return options.root;
|
|
1928
3843
|
const physicalRoot = yield* fs.realPath(options.root);
|
|
1929
3844
|
return path.resolve(options.root, path.relative(physicalRoot, output.trim()));
|
|
1930
|
-
})).pipe(
|
|
3845
|
+
})).pipe(Effect9.catch(() => Effect9.succeed(options.root)));
|
|
1931
3846
|
const changed = /* @__PURE__ */ new Map();
|
|
1932
3847
|
for (const patch of patches) {
|
|
1933
3848
|
const repositoryPath = path.resolve(gitRoot, patch.file);
|
|
@@ -1939,7 +3854,7 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
|
1939
3854
|
return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
|
|
1940
3855
|
}
|
|
1941
3856
|
if (!(yield* fs.exists(candidate))) continue;
|
|
1942
|
-
const current = yield* fs.readFileString(candidate).pipe(
|
|
3857
|
+
const current = yield* fs.readFileString(candidate).pipe(Effect9.mapError((error3) => new DiffMismatch({ path: patch.file, message: String(error3) })));
|
|
1943
3858
|
const lines2 = current.split("\n");
|
|
1944
3859
|
const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
|
|
1945
3860
|
if (patch.lines.every((line) => {
|
|
@@ -1966,11 +3881,15 @@ var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
|
1966
3881
|
});
|
|
1967
3882
|
|
|
1968
3883
|
// packages/cli/src/ExitCode.ts
|
|
1969
|
-
var reportExitCode = (report) => report.results.some((
|
|
3884
|
+
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
3885
|
var errorExitCode = (error3) => {
|
|
1971
3886
|
switch (error3._tag) {
|
|
1972
3887
|
case "BaselineFailed":
|
|
1973
3888
|
return 4;
|
|
3889
|
+
case "BaselineTimedOut":
|
|
3890
|
+
return 3;
|
|
3891
|
+
case "TestSpawnError":
|
|
3892
|
+
return error3.kind === "vitest-version" ? 8 : 70;
|
|
1974
3893
|
case "DiffMismatch":
|
|
1975
3894
|
return 5;
|
|
1976
3895
|
case "DiffParseError":
|
|
@@ -1988,14 +3907,14 @@ var errorExitCode = (error3) => {
|
|
|
1988
3907
|
};
|
|
1989
3908
|
|
|
1990
3909
|
// packages/cli/src/Reporter.ts
|
|
1991
|
-
import * as
|
|
1992
|
-
import * as
|
|
1993
|
-
import * as
|
|
1994
|
-
import * as
|
|
3910
|
+
import * as Clock5 from "effect/Clock";
|
|
3911
|
+
import * as Console6 from "effect/Console";
|
|
3912
|
+
import * as Effect10 from "effect/Effect";
|
|
3913
|
+
import * as FileSystem11 from "effect/FileSystem";
|
|
1995
3914
|
import * as Layer4 from "effect/Layer";
|
|
1996
|
-
import * as
|
|
1997
|
-
import * as
|
|
1998
|
-
import * as
|
|
3915
|
+
import * as Path11 from "effect/Path";
|
|
3916
|
+
import * as Schema12 from "effect/Schema";
|
|
3917
|
+
import * as Semaphore2 from "effect/Semaphore";
|
|
1999
3918
|
|
|
2000
3919
|
// packages/cli/src/UnifiedDiff.ts
|
|
2001
3920
|
var shortestEdits = (before, after) => {
|
|
@@ -2013,7 +3932,7 @@ var shortestEdits = (before, after) => {
|
|
|
2013
3932
|
}
|
|
2014
3933
|
frontier.set(diagonal, x);
|
|
2015
3934
|
if (x < before.length || y < after.length) continue;
|
|
2016
|
-
const
|
|
3935
|
+
const result5 = [];
|
|
2017
3936
|
x = before.length;
|
|
2018
3937
|
y = after.length;
|
|
2019
3938
|
for (let depth = trace.length - 1; depth >= 0; depth--) {
|
|
@@ -2024,14 +3943,14 @@ var shortestEdits = (before, after) => {
|
|
|
2024
3943
|
const previousX = previous.get(previousK) ?? 0;
|
|
2025
3944
|
const previousY = previousX - previousK;
|
|
2026
3945
|
while (x > previousX && y > previousY) {
|
|
2027
|
-
|
|
3946
|
+
result5.push({ sign: " ", text: before[--x] });
|
|
2028
3947
|
y--;
|
|
2029
3948
|
}
|
|
2030
3949
|
if (depth === 0) break;
|
|
2031
|
-
if (x === previousX)
|
|
2032
|
-
else
|
|
3950
|
+
if (x === previousX) result5.push({ sign: "+", text: after[--y] });
|
|
3951
|
+
else result5.push({ sign: "-", text: before[--x] });
|
|
2033
3952
|
}
|
|
2034
|
-
return
|
|
3953
|
+
return result5.reverse();
|
|
2035
3954
|
}
|
|
2036
3955
|
}
|
|
2037
3956
|
return [];
|
|
@@ -2053,10 +3972,10 @@ var edits = (before, after) => {
|
|
|
2053
3972
|
};
|
|
2054
3973
|
var lines = (text) => {
|
|
2055
3974
|
if (!text) return [];
|
|
2056
|
-
const
|
|
2057
|
-
if (text.endsWith("\n"))
|
|
2058
|
-
else
|
|
2059
|
-
return
|
|
3975
|
+
const result5 = text.split("\n");
|
|
3976
|
+
if (text.endsWith("\n")) result5.pop();
|
|
3977
|
+
else result5[result5.length - 1] += "\n\";
|
|
3978
|
+
return result5;
|
|
2060
3979
|
};
|
|
2061
3980
|
var unifiedDiff = (original, modified, file) => {
|
|
2062
3981
|
if (original === modified) return "";
|
|
@@ -2087,11 +4006,17 @@ var unifiedDiff = (original, modified, file) => {
|
|
|
2087
4006
|
|
|
2088
4007
|
// packages/cli/src/Summary.ts
|
|
2089
4008
|
var outcomeNames = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
2090
|
-
var
|
|
4009
|
+
var backstopCosts = (report) => {
|
|
4010
|
+
const samples = report.results.flatMap((result5) => result5.backstopMs !== void 0 && Number.isFinite(result5.backstopMs) ? [result5.backstopMs] : []).sort((a, b) => a - b);
|
|
4011
|
+
if (!samples.length) return "";
|
|
4012
|
+
const percentile = (p) => samples[Math.max(0, Math.ceil(samples.length * p) - 1)].toFixed(1);
|
|
4013
|
+
return `; backstop per mutant p50 ${percentile(0.5)} ms, p90 ${percentile(0.9)} ms (${samples.length} measured)`;
|
|
4014
|
+
};
|
|
4015
|
+
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
4016
|
var cell = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\\", "\\\\").replaceAll("|", "\\|").replaceAll("`", "`").replace(/[\r\n]+/g, " ");
|
|
2092
4017
|
var markdownSummary = (options) => {
|
|
2093
4018
|
const { report, path } = options;
|
|
2094
|
-
const rows = report.results.filter((
|
|
4019
|
+
const rows = report.results.filter((result5) => result5.outcome === "missed" || result5.outcome === "timeout" || result5.outcome === "untested" || result5.outcome === "unreliable");
|
|
2095
4020
|
const exit = report.failure?.startsWith("BaselineFailed") ? 4 : reportExitCode(report);
|
|
2096
4021
|
return [
|
|
2097
4022
|
options.marker,
|
|
@@ -2114,27 +4039,28 @@ var shortType = (text) => {
|
|
|
2114
4039
|
return line.length > 80 ? line.slice(0, 79) + "\u2026" : line;
|
|
2115
4040
|
};
|
|
2116
4041
|
var outcomes = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
2117
|
-
var jsonReport =
|
|
2118
|
-
var logText = (
|
|
2119
|
-
..."output" in
|
|
2120
|
-
...
|
|
4042
|
+
var jsonReport = Schema12.encodeEffect(Schema12.fromJsonString(RunReport));
|
|
4043
|
+
var logText = (result5) => [
|
|
4044
|
+
..."output" in result5 && typeof result5.output === "string" ? [result5.output] : [],
|
|
4045
|
+
...result5.diagnostics
|
|
2121
4046
|
].join("\n");
|
|
2122
|
-
var makeReporter =
|
|
2123
|
-
const fs = yield*
|
|
2124
|
-
const path = yield*
|
|
4047
|
+
var makeReporter = Effect10.fn("makeReporter")(function* (options) {
|
|
4048
|
+
const fs = yield* FileSystem11.FileSystem;
|
|
4049
|
+
const path = yield* Path11.Path;
|
|
2125
4050
|
const dir = path.resolve(options.root, options.outDir);
|
|
2126
|
-
const started = yield*
|
|
2127
|
-
const semaphore = yield*
|
|
4051
|
+
const started = yield* Clock5.currentTimeMillis;
|
|
4052
|
+
const semaphore = yield* Semaphore2.make(1);
|
|
2128
4053
|
const results = [];
|
|
2129
4054
|
let pendingError;
|
|
2130
4055
|
let summarized = false;
|
|
4056
|
+
const telemetryWarned = /* @__PURE__ */ new Set();
|
|
2131
4057
|
const writeError = (error3) => new ReportWriteError({ path: dir, message: String(error3) });
|
|
2132
4058
|
const ids = /* @__PURE__ */ new Set();
|
|
2133
4059
|
for (const mutant of options.mutants) {
|
|
2134
4060
|
if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
|
|
2135
4061
|
ids.add(mutant.id);
|
|
2136
4062
|
}
|
|
2137
|
-
yield*
|
|
4063
|
+
yield* Effect10.gen(function* () {
|
|
2138
4064
|
const relative2 = path.relative(dir, path.resolve(options.root));
|
|
2139
4065
|
if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
|
|
2140
4066
|
return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
|
|
@@ -2149,101 +4075,106 @@ var makeReporter = Effect7.fn("makeReporter")(function* (options) {
|
|
|
2149
4075
|
}
|
|
2150
4076
|
yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
|
|
2151
4077
|
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(
|
|
4078
|
+
}).pipe(Effect10.mapError(writeError));
|
|
4079
|
+
const encodedMutants = yield* Schema12.encodeEffect(Schema12.fromJsonString(Schema12.Array(Mutant)))(options.mutants).pipe(Effect10.mapError(writeError));
|
|
4080
|
+
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect10.mapError(writeError));
|
|
2155
4081
|
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*
|
|
4082
|
+
`).join("")).pipe(Effect10.mapError(writeError));
|
|
4083
|
+
yield* Effect10.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect10.mapError(writeError));
|
|
2158
4084
|
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(
|
|
4085
|
+
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect10.mapError(writeError));
|
|
4086
|
+
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(Effect10.mapError(writeError));
|
|
2161
4087
|
}
|
|
2162
|
-
const writeLists = (items) =>
|
|
2163
|
-
const lines2 = items.filter((
|
|
4088
|
+
const writeLists = (items) => Effect10.forEach(outcomes, (outcome) => {
|
|
4089
|
+
const lines2 = items.filter((result5) => result5.outcome === outcome).map((result5) => mutantLine(result5.mutant, options.root, path));
|
|
2164
4090
|
return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines2.length === 0 ? "" : lines2.join("\n") + "\n");
|
|
2165
4091
|
}, { discard: true });
|
|
2166
4092
|
const service = Reporter.of({
|
|
2167
|
-
progress: (
|
|
2168
|
-
results.push(
|
|
2169
|
-
if (!options.markdown?.stdout) yield*
|
|
2170
|
-
yield*
|
|
2171
|
-
if (!ids.has(
|
|
4093
|
+
progress: (result5) => semaphore.withPermit(Effect10.gen(function* () {
|
|
4094
|
+
results.push(result5);
|
|
4095
|
+
if (!options.markdown?.stdout) yield* Console6.log(`${result5.outcome} ${mutantLine(result5.mutant, options.root, path)} (${result5.durationMs}ms)`);
|
|
4096
|
+
yield* Effect10.gen(function* () {
|
|
4097
|
+
if (!ids.has(result5.mutant.id)) return yield* writeError("Progress result does not belong to this report");
|
|
2172
4098
|
yield* writeLists(results);
|
|
2173
|
-
yield* fs.writeFileString(path.join(dir, "logs", `${
|
|
2174
|
-
}).pipe(
|
|
4099
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result5.mutant.id}.log`), logText(result5));
|
|
4100
|
+
}).pipe(Effect10.catch((error3) => Effect10.gen(function* () {
|
|
2175
4101
|
if (pendingError === void 0) {
|
|
2176
4102
|
pendingError = writeError(error3);
|
|
2177
|
-
yield*
|
|
4103
|
+
yield* Console6.warn(`Report write failed: ${pendingError.message}`);
|
|
2178
4104
|
}
|
|
2179
4105
|
})));
|
|
2180
4106
|
})),
|
|
2181
|
-
write: (report) => semaphore.withPermit(
|
|
4107
|
+
write: (report) => semaphore.withPermit(Effect10.gen(function* () {
|
|
2182
4108
|
if (pendingError !== void 0) return yield* pendingError;
|
|
2183
4109
|
const notMutated = [...new Map([...options.notMutated ?? [], ...report.notMutated ?? []].map((item) => [JSON.stringify(item), item])).values()];
|
|
2184
4110
|
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(
|
|
4111
|
+
`).join("")).pipe(Effect10.mapError(writeError));
|
|
4112
|
+
const telemetry = sanitizeReportTelemetry(report);
|
|
2186
4113
|
const counted = {
|
|
2187
|
-
...report,
|
|
4114
|
+
...telemetry.report,
|
|
2188
4115
|
notMutated,
|
|
2189
4116
|
selected: options.selected ?? options.mutants.length,
|
|
2190
4117
|
run: report.results.length,
|
|
2191
4118
|
budgetSkipped: options.budgetSkipped ?? 0
|
|
2192
4119
|
};
|
|
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", `${
|
|
4120
|
+
const encoded = yield* jsonReport(counted).pipe(Effect10.mapError(writeError));
|
|
4121
|
+
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect10.mapError(writeError));
|
|
4122
|
+
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect10.mapError(writeError));
|
|
4123
|
+
yield* writeLists(report.results).pipe(Effect10.mapError(writeError));
|
|
4124
|
+
for (const result5 of report.results) {
|
|
4125
|
+
if (!ids.has(result5.mutant.id)) return yield* writeError("Final result does not belong to this report");
|
|
4126
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result5.mutant.id}.log`), logText(result5)).pipe(Effect10.mapError(writeError));
|
|
4127
|
+
}
|
|
4128
|
+
for (const warning of telemetry.warnings) if (!telemetryWarned.has(warning)) {
|
|
4129
|
+
telemetryWarned.add(warning);
|
|
4130
|
+
yield* Console6.warn(warning);
|
|
2200
4131
|
}
|
|
2201
4132
|
if (options.markdown !== void 0) {
|
|
2202
4133
|
const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: notMutated.length });
|
|
2203
4134
|
for (const file of new Set(options.markdown.files)) {
|
|
2204
|
-
yield* fs.writeFileString(file, markdown).pipe(
|
|
4135
|
+
yield* fs.writeFileString(file, markdown).pipe(Effect10.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) })));
|
|
2205
4136
|
}
|
|
2206
|
-
if (!summarized && options.markdown.stdout) yield*
|
|
4137
|
+
if (!summarized && options.markdown.stdout) yield* Console6.log(markdown);
|
|
2207
4138
|
}
|
|
2208
4139
|
if (summarized) return;
|
|
2209
4140
|
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*
|
|
4141
|
+
if (report.results.some((result5) => result5.outcome === "unreliable")) yield* Console6.warn("Unreliable: the configured Vitest run cannot see all tests. See unreliable.txt and per-mutant diagnostics; these are not missed mutants.");
|
|
4142
|
+
const elapsed = (yield* Clock5.currentTimeMillis) - started;
|
|
4143
|
+
if (!options.markdown?.stdout) yield* Console6.log(countsLine(counted, notMutated.length) + `; ${(elapsed / 1e3).toFixed(2)}s`);
|
|
4144
|
+
if (options.markdown === void 0 && report.failure !== void 0) yield* Console6.warn(report.failure);
|
|
2214
4145
|
}))
|
|
2215
4146
|
});
|
|
2216
4147
|
return service;
|
|
2217
4148
|
});
|
|
2218
4149
|
|
|
2219
4150
|
// packages/cli/src/Git.ts
|
|
2220
|
-
import * as
|
|
2221
|
-
import * as
|
|
2222
|
-
import * as
|
|
2223
|
-
import * as
|
|
2224
|
-
import * as
|
|
2225
|
-
import * as
|
|
2226
|
-
var UsageError = class extends
|
|
4151
|
+
import * as Effect11 from "effect/Effect";
|
|
4152
|
+
import * as FileSystem13 from "effect/FileSystem";
|
|
4153
|
+
import * as Path13 from "effect/Path";
|
|
4154
|
+
import * as Schema13 from "effect/Schema";
|
|
4155
|
+
import * as Stream6 from "effect/Stream";
|
|
4156
|
+
import * as ChildProcess5 from "effect/process/ChildProcess";
|
|
4157
|
+
var UsageError = class extends Schema13.TaggedError()("UsageError", { message: Schema13.String }) {
|
|
2227
4158
|
};
|
|
2228
|
-
var git =
|
|
4159
|
+
var git = Effect11.fn("git")(function* (root, args) {
|
|
2229
4160
|
const command = `git ${args.join(" ")}`;
|
|
2230
|
-
return yield*
|
|
2231
|
-
const handle = yield*
|
|
2232
|
-
const [stdout, stderr, code] = yield*
|
|
2233
|
-
|
|
2234
|
-
|
|
4161
|
+
return yield* Effect11.scoped(Effect11.gen(function* () {
|
|
4162
|
+
const handle = yield* ChildProcess5.make("git", args, { cwd: root });
|
|
4163
|
+
const [stdout, stderr, code] = yield* Effect11.all([
|
|
4164
|
+
Stream6.mkString(Stream6.decodeText(handle.stdout)),
|
|
4165
|
+
Stream6.mkString(Stream6.decodeText(handle.stderr)),
|
|
2235
4166
|
handle.exitCode
|
|
2236
4167
|
], { concurrency: "unbounded" });
|
|
2237
4168
|
if (Number(code) !== 0) return yield* new UsageError({ message: `${command}:
|
|
2238
4169
|
${stderr}` });
|
|
2239
4170
|
return stdout;
|
|
2240
|
-
})).pipe(
|
|
4171
|
+
})).pipe(Effect11.mapError((error3) => error3._tag === "UsageError" ? error3 : new UsageError({ message: `${command}: ${String(error3)}` })));
|
|
2241
4172
|
});
|
|
2242
|
-
var repositoryRoot =
|
|
2243
|
-
const path = yield*
|
|
2244
|
-
const fs = yield*
|
|
4173
|
+
var repositoryRoot = Effect11.fn("repositoryRoot")(function* (root) {
|
|
4174
|
+
const path = yield* Path13.Path;
|
|
4175
|
+
const fs = yield* FileSystem13.FileSystem;
|
|
2245
4176
|
const top = (yield* git(root, ["rev-parse", "--show-toplevel"])).trim();
|
|
2246
|
-
const physical = yield* fs.realPath(root).pipe(
|
|
4177
|
+
const physical = yield* fs.realPath(root).pipe(Effect11.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
2247
4178
|
return path.resolve(root, path.relative(physical, top));
|
|
2248
4179
|
});
|
|
2249
4180
|
|
|
@@ -2260,17 +4191,21 @@ var flags = {
|
|
|
2260
4191
|
include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
|
|
2261
4192
|
exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
|
|
2262
4193
|
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")),
|
|
4194
|
+
warm: Flag.Boolean("warm").pipe(Flag.withDefault(false), Flag.withDescription("Force a persistent Vitest instance instead of automatic selection")),
|
|
4195
|
+
cold: Flag.Boolean("cold").pipe(Flag.withDefault(false), Flag.withDescription("Start a fresh Vitest process for each test execution")),
|
|
2263
4196
|
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")),
|
|
4197
|
+
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds, including startup")),
|
|
4198
|
+
baselineTimeout: Flag.Finite("baseline-timeout").pipe(Flag.optional, Flag.withDescription("Overall baseline deadline in seconds, including selection and startup; default 1800 (30 minutes)")),
|
|
2265
4199
|
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional, Flag.withDescription("Baseline duration multiplier; default 5")),
|
|
2266
4200
|
minimumTimeout: Flag.Finite("minimum-test-timeout").pipe(Flag.optional, Flag.withDescription("Minimum test timeout in seconds")),
|
|
2267
4201
|
output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
|
|
2268
4202
|
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
|
|
2269
4203
|
};
|
|
2270
|
-
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) =>
|
|
2271
|
-
const fs = yield*
|
|
2272
|
-
const path = yield*
|
|
4204
|
+
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect12.gen(function* () {
|
|
4205
|
+
const fs = yield* FileSystem15.FileSystem;
|
|
4206
|
+
const path = yield* Path15.Path;
|
|
2273
4207
|
const root = path.resolve(options.root);
|
|
4208
|
+
if (input.cold && input.warm) return yield* new UsageError({ message: "--warm and --cold are mutually exclusive" });
|
|
2274
4209
|
const range = Option.getOrUndefined(input.inDiffRange);
|
|
2275
4210
|
const inDiff = Option.getOrUndefined(input.inDiff);
|
|
2276
4211
|
const maxMutants = Option.getOrUndefined(input.maxMutants);
|
|
@@ -2282,15 +4217,15 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2282
4217
|
if (maxMutants !== void 0 && (!Number.isSafeInteger(maxMutants) || maxMutants < 0)) return yield* new UsageError({ message: "--max-mutants must be a nonnegative safe integer" });
|
|
2283
4218
|
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
4219
|
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(
|
|
4220
|
+
const gitRoot = range !== void 0 ? yield* repositoryRoot(root) : yield* repositoryRoot(root).pipe(Effect12.catch(() => Effect12.succeed(root)));
|
|
2286
4221
|
const diffText = range === void 0 ? void 0 : yield* git(gitRoot, ["diff", "--no-ext-diff", "--no-color", range, "--"]);
|
|
2287
4222
|
const configPath = path.join(root, "mutants.config.json");
|
|
2288
4223
|
const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
|
|
2289
|
-
|
|
2290
|
-
|
|
4224
|
+
Effect12.flatMap(Schema14.decodeEffect(Schema14.fromJsonString(ConfigFile))),
|
|
4225
|
+
Effect12.mapError((error3) => new UsageError({ message: `Invalid mutants.config.json: ${String(error3)}` }))
|
|
2291
4226
|
) : {};
|
|
2292
4227
|
const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
|
|
2293
|
-
const config = yield*
|
|
4228
|
+
const config = yield* Schema14.decodeEffect(RunConfig)({
|
|
2294
4229
|
root,
|
|
2295
4230
|
tsconfig: input.tsconfig,
|
|
2296
4231
|
exportedOnly: input.exportedOnly,
|
|
@@ -2298,31 +4233,37 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2298
4233
|
exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
|
|
2299
4234
|
functionFilter: fileConfig.functionFilter ?? [],
|
|
2300
4235
|
...inDiff === void 0 ? {} : { inDiff },
|
|
4236
|
+
cold: input.cold,
|
|
4237
|
+
warm: input.warm,
|
|
2301
4238
|
jobs: Option.getOrElse(input.jobs, () => fileConfig.jobs ?? 1),
|
|
2302
4239
|
...Option.isSome(timeoutMs) ? { timeoutMs: timeoutMs.value } : {},
|
|
4240
|
+
baselineTimeoutMs: Option.match(input.baselineTimeout, { onNone: () => fileConfig.baselineTimeoutMs ?? DEFAULT_BASELINE_TIMEOUT_MS, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
2303
4241
|
timeoutMultiplier: Option.getOrElse(input.timeoutMultiplier, () => fileConfig.timeoutMultiplier ?? 5),
|
|
2304
4242
|
minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
2305
4243
|
neverTimeoutMs: 1e3,
|
|
2306
4244
|
outDir: input.output
|
|
2307
|
-
}).pipe(
|
|
2308
|
-
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
|
|
4245
|
+
}).pipe(Effect12.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
4246
|
+
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
4247
|
return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
|
|
2310
4248
|
}
|
|
2311
4249
|
const source = yield* MutantSource;
|
|
2312
|
-
const generated = yield*
|
|
2313
|
-
|
|
4250
|
+
const generated = yield* Stream7.runCollect(source.generate(config)).pipe(
|
|
4251
|
+
Effect12.mapError((error3) => error3.reason === "selection" ? new UsageError({ message: error3.diagnostics.join("\n") }) : error3)
|
|
2314
4252
|
);
|
|
2315
4253
|
const skipped2 = yield* source.notMutated(config);
|
|
2316
4254
|
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 });
|
|
4255
|
+
const scratch = yield* Scratch;
|
|
4256
|
+
const roots = selected.mutants.length && scratch.inspect ? yield* scratch.inspect(root) : [];
|
|
4257
|
+
const eligible = yield* excludeLinkedCandidates(root, selected.mutants, roots);
|
|
2317
4258
|
const relative2 = (mutant) => path.relative(gitRoot, path.resolve(root, mutant.file)).replaceAll("\\", "/");
|
|
2318
4259
|
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2319
|
-
const ordered = [...
|
|
4260
|
+
const ordered = [...eligible.mutants].sort((a, b) => compare(relative2(a), relative2(b)) || a.span.start.line - b.span.start.line || a.span.start.column - b.span.start.column || compare(a.id, b.id));
|
|
2320
4261
|
const mutants = ordered.slice(0, maxMutants);
|
|
2321
|
-
const notMutated = selected.notMutated;
|
|
4262
|
+
const notMutated = [...new Map([...selected.notMutated, ...eligible.notMutated].map((entry) => [JSON.stringify(entry), entry])).values()];
|
|
2322
4263
|
const counts = { selected: ordered.length, run: 0, budgetSkipped: ordered.length - mutants.length };
|
|
2323
4264
|
if (mutants.length === 0) {
|
|
2324
|
-
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*
|
|
4265
|
+
const cause = ordered.length > 0 ? "budget" : eligible.notMutated.length > 0 ? "linked ignored trees" : range !== void 0 ? "range" : inDiff !== void 0 || diffText !== void 0 ? "diff" : config.functionFilter.length || config.exportedOnly ? "filter" : "file selection";
|
|
4266
|
+
yield* Console7.error(`0 mutants selected (${counts.selected} before budget); cause: ${cause}. Baseline skipped.`);
|
|
2326
4267
|
}
|
|
2327
4268
|
const markdown = input.format === "github" || summaryMd !== void 0 ? {
|
|
2328
4269
|
gitRoot,
|
|
@@ -2343,33 +4284,33 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2343
4284
|
report: { schemaVersion: 2, tool: "mutant.cafe", root, baseline: { durationMs: 0, testCommand: [] }, timeoutMs: 0, results: [], ...counts }
|
|
2344
4285
|
});
|
|
2345
4286
|
for (const file of new Set(markdown.files)) yield* fs.writeFileString(file, text).pipe(
|
|
2346
|
-
|
|
4287
|
+
Effect12.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) }))
|
|
2347
4288
|
);
|
|
2348
4289
|
if (markdown.stdout) {
|
|
2349
|
-
yield*
|
|
4290
|
+
yield* Console7.log(text);
|
|
2350
4291
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2351
4292
|
return;
|
|
2352
4293
|
}
|
|
2353
4294
|
}
|
|
2354
4295
|
if (input.list && input.format === "json") {
|
|
2355
|
-
yield*
|
|
4296
|
+
yield* Console7.log(yield* Schema14.encodeEffect(Schema14.fromJsonString(MutantList))({ schemaVersion: 2, tool: "mutant.cafe", mutants, notMutated, counts }));
|
|
2356
4297
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2357
4298
|
return;
|
|
2358
4299
|
}
|
|
2359
4300
|
if (input.list) {
|
|
2360
|
-
for (const mutant of mutants) yield*
|
|
4301
|
+
for (const mutant of mutants) yield* Console7.log(mutantLine(mutant, config.root, path));
|
|
2361
4302
|
const perFile = /* @__PURE__ */ new Map();
|
|
2362
4303
|
for (const mutant of mutants) {
|
|
2363
4304
|
const file = path.relative(root, path.resolve(root, mutant.file));
|
|
2364
4305
|
perFile.set(file, (perFile.get(file) ?? 0) + 1);
|
|
2365
4306
|
}
|
|
2366
|
-
for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield*
|
|
2367
|
-
yield*
|
|
4307
|
+
for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield* Console7.log(`${file}: ${count} mutants`);
|
|
4308
|
+
yield* Console7.log(`${mutants.length} mutants total; ${notMutated.length} not mutated; ${counts.selected} selected, 0 run, ${counts.budgetSkipped} budget-skipped`);
|
|
2368
4309
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2369
4310
|
return;
|
|
2370
4311
|
}
|
|
2371
4312
|
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 ?
|
|
4313
|
+
const report = yield* (mutants.length === 0 ? Effect12.succeed({
|
|
2373
4314
|
schemaVersion: 2,
|
|
2374
4315
|
tool: "mutant.cafe",
|
|
2375
4316
|
root,
|
|
@@ -2377,8 +4318,8 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2377
4318
|
timeoutMs: 0,
|
|
2378
4319
|
results: []
|
|
2379
4320
|
}) : options.run(config, mutants)).pipe(
|
|
2380
|
-
|
|
2381
|
-
|
|
4321
|
+
Effect12.provideService(Reporter, reporter),
|
|
4322
|
+
Effect12.catchTag("BaselineFailed", (error3) => Effect12.gen(function* () {
|
|
2382
4323
|
const failed = {
|
|
2383
4324
|
schemaVersion: 2,
|
|
2384
4325
|
tool: "mutant.cafe",
|
|
@@ -2386,31 +4327,45 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
2386
4327
|
baseline: { durationMs: 0, testCommand: error3.command },
|
|
2387
4328
|
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
2388
4329
|
results: [],
|
|
2389
|
-
failure: `BaselineFailed: ${error3.command
|
|
4330
|
+
failure: `BaselineFailed: ${formatTestCommand(error3.command)}
|
|
2390
4331
|
${error3.output.slice(-8e3)}`
|
|
2391
4332
|
};
|
|
2392
4333
|
yield* reporter.write(failed);
|
|
2393
4334
|
if (!input.advisory) return yield* error3;
|
|
2394
|
-
if (markdown === void 0) yield*
|
|
4335
|
+
if (markdown === void 0) yield* Console7.log("Advisory: baseline failed; would exit 4 without --advisory.");
|
|
2395
4336
|
return failed;
|
|
4337
|
+
})),
|
|
4338
|
+
Effect12.catchTag("BaselineTimedOut", (error3) => Effect12.gen(function* () {
|
|
4339
|
+
const timedOut = {
|
|
4340
|
+
schemaVersion: 2,
|
|
4341
|
+
tool: "mutant.cafe",
|
|
4342
|
+
root,
|
|
4343
|
+
baseline: { durationMs: 0, testCommand: error3.command },
|
|
4344
|
+
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
4345
|
+
results: [],
|
|
4346
|
+
failure: `BaselineTimedOut: ${error3.message}`
|
|
4347
|
+
};
|
|
4348
|
+
yield* reporter.write(timedOut);
|
|
4349
|
+
if (!input.advisory) return yield* error3;
|
|
4350
|
+
return timedOut;
|
|
2396
4351
|
}))
|
|
2397
4352
|
);
|
|
2398
|
-
if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield*
|
|
4353
|
+
if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield* Console7.log(`Advisory: would exit ${reportExitCode(report)} without --advisory.`);
|
|
2399
4354
|
yield* reporter.write(report);
|
|
2400
4355
|
if (options.onExit !== void 0) yield* options.onExit(input.advisory ? 0 : reportExitCode(report));
|
|
2401
4356
|
}));
|
|
2402
|
-
var runCli =
|
|
4357
|
+
var runCli = Effect12.fn("runCli")(function* (options) {
|
|
2403
4358
|
const code = yield* Ref.make(0);
|
|
2404
4359
|
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
|
|
4360
|
+
yield* Command.runWith(command, { version: "0.1.7" })(options.args).pipe(
|
|
4361
|
+
Effect12.catch((error3) => Effect12.gen(function* () {
|
|
4362
|
+
yield* Console7.error(error3._tag === "ProgramLoadError" ? `${error3.tsconfig}:
|
|
4363
|
+
${error3.diagnostics.join("\n")}` : error3._tag === "TestSpawnError" && error3.kind === "vitest-version" ? error3.message : error3._tag === "BaselineTimedOut" ? error3.message : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${formatTestCommand(error3.command)}
|
|
2409
4364
|
${error3.output.slice(-8e3)}` : String(error3));
|
|
2410
4365
|
yield* Ref.set(code, errorExitCode(error3));
|
|
2411
4366
|
})),
|
|
2412
|
-
|
|
2413
|
-
yield*
|
|
4367
|
+
Effect12.catchDefect((defect) => Effect12.gen(function* () {
|
|
4368
|
+
yield* Console7.error(`Internal error: ${String(defect)}`);
|
|
2414
4369
|
yield* Ref.set(code, 70);
|
|
2415
4370
|
}))
|
|
2416
4371
|
);
|
|
@@ -2418,15 +4373,15 @@ ${error3.output.slice(-8e3)}` : String(error3));
|
|
|
2418
4373
|
});
|
|
2419
4374
|
|
|
2420
4375
|
// packages/cli/src/bin.ts
|
|
2421
|
-
var run = (config, mutants) => runMutants(config,
|
|
4376
|
+
var run = (config, mutants) => runMutants(config, Stream8.fromIterable(mutants));
|
|
2422
4377
|
var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
|
|
2423
4378
|
Layer5.provideMerge(NodeServices.layer)
|
|
2424
4379
|
);
|
|
2425
|
-
var main =
|
|
4380
|
+
var main = Effect13.gen(function* () {
|
|
2426
4381
|
const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
|
|
2427
|
-
yield*
|
|
4382
|
+
yield* Effect13.sync(() => {
|
|
2428
4383
|
process.exitCode = code;
|
|
2429
4384
|
});
|
|
2430
|
-
}).pipe(
|
|
4385
|
+
}).pipe(Effect13.provide(live));
|
|
2431
4386
|
NodeRuntime.runMain(main);
|
|
2432
4387
|
//# sourceMappingURL=bin.js.map
|