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